Skip to main content

agentmux_launcher/
srv_spawner.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Spawn the agentmux-srv backend sidecar from the LAUNCHER (Phase B.1).
5//
6// Today's flow (pre-Phase-B): launcher spawns host; host spawns srv;
7// host owns a Job Object J1 wrapping srv; renderers inherit launcher's
8// J0 via host. Result: when host crashes, J1 closes and srv dies.
9//
10// Phase B.1 flow: launcher spawns BOTH srv and host as siblings,
11// assigns BOTH to launcher's J0 directly. Host's J1 on srv is
12// deleted (it would actively defeat "srv survives host crash" if
13// kept). Renderers continue to inherit J0 via host as before.
14//
15// The launcher passes srv's endpoints to the host via env vars
16// (AGENTMUX_BACKEND_WS, _WEB, _PID). Host detects them and skips
17// its own spawn_backend path (which is preserved for `task dev`
18// fallback where launcher isn't in the loop).
19//
20// Adapted from `crates/cef/src/sidecar.rs::spawn_backend` —
21// kept structurally similar so divergence is auditable. Key
22// differences:
23//   * Tokio process API (not std::process)
24//   * CREATE_SUSPENDED + assign-to-job + ResumeThread (PR #570 race
25//     pattern, applied to srv too)
26//   * No separate Job Object on srv; launcher's J0 covers it
27//   * Auth key generated here, not consumed from a shared AppState
28//   * stderr ESTART parsing returns the result via tokio mpsc
29
30use std::path::{Path, PathBuf};
31use std::process::Stdio;
32
33use agentmux_common::srv_estart_wait::{wait_for_estart, EstartChannels, EstartWait};
34use tokio::io::{AsyncBufReadExt, BufReader};
35use tokio::process::{Child, Command};
36use tokio::sync::mpsc;
37
38use crate::data_dir::DataPaths;
39
40/// What the launcher learns about srv after it signals ready.
41/// Held by the launcher and used to populate env vars the host reads.
42#[derive(Debug, Clone)]
43pub struct SrvSpawnResult {
44    pub pid: u32,
45    pub ws_endpoint: String,
46    pub web_endpoint: String,
47    pub instance_id: String,
48    pub auth_key: String,
49    /// Shared secret proving to srv that a `host_ipc.Register` call really
50    /// comes from the paired host, not an agent process (agents share
51    /// `auth_key` too — see `crates/srv/src/server/service/host_ipc.rs`).
52    /// Minted once per `spawn_srv` call (same lifetime as `auth_key`) and
53    /// given to both host and srv's spawn env — see `host_spawn.rs`'s
54    /// `AGENTMUX_HOST_REG_SECRET` env line and this file's own
55    /// `AGENTMUX_HOST_REG_SECRET` env line below. Survives every host-only
56    /// crash-restart automatically, exactly like `auth_key` does (this
57    /// struct is held in the launcher's own stack frame across restarts —
58    /// see `SrvSpawnResult`'s own doc comment above).
59    pub host_reg_secret: String,
60    /// Number of data migrations still pending after the in-process startup run.
61    /// Counted by srv at ESTART time (`count_pending_migrations`). Since
62    /// SPEC_MIGRATION_SYSTEM_HARDENING Phase 1 a migration *failure* never
63    /// reaches ESTART at all (srv exits 1 with `MigrationFailed`), so a
64    /// non-zero value here means the count and the run disagree — e.g. the
65    /// fresh-install ordering case runner.rs documents — and the status-bar
66    /// shows its retry message for that.
67    pub pending_migrations: usize,
68    /// RFC3339 timestamp captured when ESTART arrived. Carried on the
69    /// result for `--diag` / debug observability; not currently
70    /// propagated into env. F.7 cleanup audit: keep with allow + this
71    /// note rather than delete — a future `--diag srv` printer is the
72    /// natural reader.
73    #[allow(dead_code)]
74    pub started_at: String,
75}
76
77/// Errors during srv spawn — granular enough that the launcher can
78/// log the right diagnostic.
79#[derive(Debug)]
80pub enum SrvSpawnError {
81    BinaryNotFound(String),
82    SpawnFailed(String),
83    #[cfg(target_os = "windows")]
84    JobAssignFailed(String),
85    #[cfg(target_os = "windows")]
86    ResumeFailed(String),
87    EstartTimeout,
88    EstartChannelClosed,
89    /// srv reported `AGENTMUXSRV-MIGRATION-FAILED` and exited 1 before ESTART
90    /// (SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03 Phase 1). Carries the
91    /// reason srv gave. Distinct from `EstartTimeout` so the supervisor can
92    /// show the user a real message instead of "timeout (30s)" — and so it
93    /// can do it immediately rather than 30s later.
94    MigrationFailed(String),
95    /// srv found data that needs `agentmux-srv migrate --prepare` and exited
96    /// before writing anything (`AGENTMUXSRV-NEEDS-PREPARE`). [`spawn_srv`]
97    /// handles it itself; it reaches a caller only if srv still asks after a
98    /// prepare, which `spawn_srv` turns into `MigrationFailed`.
99    NeedsPrepare(String),
100    /// Another srv already holds this data folder's `srv.lock`, and this one exited before starting
101    /// (`DATA_DIR_HELD_EXIT`): a desktop app opened while a headless server runs on the same channel, or
102    /// two servers started at once. The supervisor says so plainly instead of letting the splash fail.
103    DataDirHeld,
104}
105
106impl std::fmt::Display for SrvSpawnError {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        match self {
109            Self::BinaryNotFound(s) => write!(f, "srv binary not found: {}", s),
110            Self::SpawnFailed(s) => write!(f, "spawn failed: {}", s),
111            #[cfg(target_os = "windows")]
112            Self::JobAssignFailed(s) => write!(f, "AssignProcessToJobObject failed: {}", s),
113            #[cfg(target_os = "windows")]
114            Self::ResumeFailed(s) => write!(f, "ResumeThread failed: {}", s),
115            Self::EstartTimeout => write!(f, "timeout waiting for AGENTMUXSRV-ESTART (30s)"),
116            Self::EstartChannelClosed => {
117                write!(f, "ESTART channel closed before srv signalled ready")
118            }
119            Self::MigrationFailed(s) => write!(f, "database migration failed: {}", s),
120            Self::NeedsPrepare(s) => write!(f, "srv's data needs preparing: {}", s),
121            Self::DataDirHeld => write!(f, "another AgentMux server is already using this data folder"),
122        }
123    }
124}
125
126/// Title for the fatal dialog both supervisors show on `DataDirHeld`.
127pub const DATA_DIR_HELD_DIALOG_TITLE: &str = "AgentMux is already running";
128
129/// Body for that dialog: another server (a headless one, or another launch) holds this channel's data
130/// folder, and this one cannot start beside it. Kept here so Windows and Unix say the same words.
131pub fn data_dir_held_dialog_body(data_dir: &std::path::Path) -> String {
132    format!(
133        "AgentMux is already running for this channel on this computer, so this copy stopped.\n\n\
134         Its data folder is:\n{}\n\n\
135         If AgentMux has a window open, use that one. If it is running without a window, open it in your \
136         browser with `agentmux open`, or stop it with `agentmux stop` and then open AgentMux again. Only \
137         one AgentMux can use a data folder at a time.",
138        data_dir.display()
139    )
140}
141
142/// Title for the fatal dialog both supervisors show on `MigrationFailed`.
143pub const MIGRATION_FAILED_DIALOG_TITLE: &str = "AgentMux — database migration failed";
144
145/// Body for that dialog. Kept here (not in each supervisor) so Windows and
146/// Unix show the same words.
147///
148/// Every sentence is something the launcher actually knows:
149/// - Restart-to-retry: srv re-runs every unapplied migration on the next
150///   launch (`run_pending_migrations` filters on `migration_is_applied`).
151/// - The backup ordering: `runner.rs::run_pending_migrations` calls
152///   `backup_stores` (→ `~/.agentmux/shared/backups/pre-migration-<ver>-<ts>/`)
153///   BEFORE applying anything, and returns `Err("... backup failed: ...")`
154///   without running a migration if that copy fails. So the reason text
155///   itself tells the user which case they are in; we state the ordering
156///   and let it do so, rather than asserting a backup exists.
157///
158/// We deliberately do NOT claim "your data has not been changed" or "a
159/// snapshot was taken": the backup step is one of the things that can be
160/// the failure, and bootstrap/stores.rs's separate
161/// `maybe_snapshot_pre_migration` is best-effort (non-fatal on error,
162/// `Ok(None)` when it decides none is needed). An earlier revision of this
163/// text made that claim unconditionally (#3043).
164pub fn migration_failed_dialog_body(reason: &str) -> String {
165    format!(
166        "AgentMux could not update its data store and will not start.\n\n\
167         {}\n\n\
168         Restart AgentMux to retry. Migrations only run after a copy of the \
169         store is written to ~/.agentmux/shared/backups/pre-migration-*/ — \
170         if the error above is about writing that copy, nothing was changed. \
171         Run `muxlog srv` for the full log.",
172        reason
173    )
174}
175
176/// One of srv's progress lines (a data-preparation step or a migration, in
177/// the `agentmux_common::srv_stderr` protocol) as a splash sub-row of `stage`.
178/// `false` if `line` is not one. Shared by srv's own startup ("backend") and
179/// `migrate --prepare` ("prepare").
180fn forward_progress_line(line: &str, stage: &'static str, sink: &crate::startup_events::StartupEventSink) -> bool {
181    use agentmux_common::srv_stderr as p;
182    let ok = crate::startup_events::StartupStatus::Ok;
183    if let Some(b) = p::parse_step_begin_line(line) {
184        sink.sub_begin(stage, b.id, b.label);
185    } else if let Some(e) = p::parse_step_end_line(line) {
186        if e.ok {
187            sink.sub_end(stage, e.id, e.duration_ms, ok, None);
188        } else {
189            let failed = crate::startup_events::StartupStatus::Error;
190            sink.sub_end(stage, e.id, e.duration_ms, failed, Some("failed".to_string()));
191        }
192    } else if let Some(b) = p::parse_migration_begin_line(line) {
193        sink.sub_begin(stage, b.id, b.description);
194    } else if let Some(e) = p::parse_migration_end_line(line) {
195        sink.sub_end(stage, e.id, e.duration_ms, ok, None);
196    } else {
197        return false;
198    }
199    true
200}
201
202/// Spawn `cmd` (an srv process: the daemon, or `migrate --prepare`) so it
203/// lives and dies with the launcher, before any of its code runs. Returns the
204/// child and its pid.
205///
206/// - Windows: started suspended, assigned to the launcher's Job Object J0,
207///   then resumed (PR #570's race pattern): srv opens files and sockets only
208///   once it is in the job, so nothing it holds survives the launcher. With
209///   no J0 (the degraded mode `main.rs` logs) it is only resumed. A failure
210///   kills the suspended child, which `kill_on_drop(false)` would otherwise
211///   leave as a zombie holding the data dir's lockfile (#571).
212/// - Linux: `PR_SET_PDEATHSIG` → SIGKILL, so it is reaped even if the
213///   launcher dies abnormally (A0); async-signal-safe only, as for the host.
214/// - Unix: its own process group, for the teardown backstop's
215///   `kill_process_group_forcefully` (SPEC_LAUNCHER_TEARDOWN_BACKSTOP_2026_07_11).
216fn spawn_in_launcher_tree(
217    cmd: &mut Command,
218    #[cfg(target_os = "windows")] job_handle: windows_sys::Win32::Foundation::HANDLE,
219) -> Result<(Child, u32), SrvSpawnError> {
220    #[cfg(target_os = "windows")]
221    cmd.creation_flags(agentmux_common::win32::CREATE_SUSPENDED | agentmux_common::win32::CREATE_NO_WINDOW);
222    #[cfg(target_os = "linux")]
223    unsafe {
224        cmd.pre_exec(|| {
225            libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL, 0, 0, 0);
226            Ok(())
227        });
228    }
229    #[cfg(not(target_os = "windows"))]
230    cmd.process_group(0);
231
232    let mut child = cmd.spawn().map_err(|e| SrvSpawnError::SpawnFailed(e.to_string()))?;
233    let pid = child.id().ok_or_else(|| SrvSpawnError::SpawnFailed("child has no PID".to_string()))?;
234    #[cfg(target_os = "windows")]
235    {
236        if !job_handle.is_null() {
237            if let Err(e) = assign_pid_to_job(pid, job_handle) {
238                let _ = child.start_kill();
239                return Err(SrvSpawnError::JobAssignFailed(e));
240            }
241        }
242        if let Err(e) = agentmux_common::win32::resume_main_thread(pid) {
243            let _ = child.start_kill();
244            return Err(SrvSpawnError::ResumeFailed(e));
245        }
246    }
247    Ok((child, pid))
248}
249
250/// Run `agentmux-srv migrate --prepare` while srv is stopped, as the splash's
251/// "Updating data" stage: copy the previous version's data forward,
252/// back up, run the pending migrations, each a sub-row. The upgrade step of
253/// `docs/specs/SPEC_FAST_STARTUP_UPGRADE_OWNS_MIGRATIONS_AND_UPDATES_2026_09_15.md`
254/// §10, run by [`spawn_srv`] when srv reports `AGENTMUXSRV-NEEDS-PREPARE`.
255async fn run_prepare(
256    launcher_exe_dir: &Path,
257    paths: &DataPaths,
258    #[cfg(target_os = "windows")] job_handle: windows_sys::Win32::Foundation::HANDLE,
259    sink: &crate::startup_events::StartupEventSink,
260) -> Result<(), SrvSpawnError> {
261    sink.stage_begin("prepare", "Updating data");
262    let t = std::time::Instant::now();
263    let backend_path = resolve_srv_binary(launcher_exe_dir)?;
264    let mut cmd = Command::new(&backend_path);
265    cmd.args(["--wavedata", &paths.data_dir.to_string_lossy(), "migrate", "--prepare"])
266        .envs(paths.common.to_env_vars())
267        // Argument parsing wants an auth key; migrate never uses it.
268        .env("AGENTMUX_AUTH_KEY", "migrate-placeholder")
269        .stdin(Stdio::null())
270        .stdout(Stdio::piped())
271        .stderr(Stdio::piped())
272        .kill_on_drop(true);
273    // In the launcher's process tree like srv itself: a launcher that dies
274    // mid-update must not leave a migration writing the stores unsupervised.
275    let (mut child, _pid) = spawn_in_launcher_tree(
276        &mut cmd,
277        #[cfg(target_os = "windows")]
278        job_handle,
279    )
280    .map_err(|e| SrvSpawnError::SpawnFailed(format!("migrate --prepare: {e}")))?;
281
282    // stdout carries only the NDJSON summary: logged.
283    if let Some(stdout) = child.stdout.take() {
284        tokio::spawn(async move {
285            let mut lines = BufReader::new(stdout).lines();
286            while let Ok(Some(line)) = lines.next_line().await {
287                crate::log(&format!("[prepare] {line}"));
288            }
289        });
290    }
291    let mut failure = None;
292    let mut handle_line = |line: String| {
293        if let Some(reason) = agentmux_common::srv_stderr::parse_migration_failed_line(&line) {
294            failure = Some(reason);
295        } else if !forward_progress_line(&line, "prepare", sink) {
296            crate::log(&format!("[prepare stderr] {line}"));
297        }
298    };
299    // Wait for the process, not for stderr's EOF: a grandchild that inherited
300    // stderr would hold it open after migrate exits and leave the splash on
301    // "Updating data" forever (docs/analysis/ANALYSIS_MIGRATE_STDOUT_HANG_2026_06_26.md).
302    // The process itself gets no deadline: it may wait up to 30 minutes for
303    // another instance's migration lock, and the splash shows that wait.
304    let mut stderr = child.stderr.take().map(|s| BufReader::new(s).lines());
305    let status = loop {
306        tokio::select! {
307            status = child.wait() => break status,
308            line = async {
309                match stderr.as_mut() {
310                    Some(lines) => lines.next_line().await,
311                    None => std::future::pending().await,
312                }
313            } => match line {
314                Ok(Some(line)) => handle_line(line),
315                _ => stderr = None,
316            },
317        }
318    }
319    .map_err(|e| SrvSpawnError::SpawnFailed(format!("migrate --prepare wait: {e}")))?;
320    // What it wrote just before exiting, without waiting on a held-open pipe.
321    if let Some(mut lines) = stderr {
322        let drain = async {
323            while let Ok(Some(line)) = lines.next_line().await {
324                handle_line(line);
325            }
326        };
327        let _ = tokio::time::timeout(std::time::Duration::from_secs(2), drain).await;
328    }
329    let ms = t.elapsed().as_millis() as u64;
330    if status.success() {
331        sink.stage_end("prepare", ms, crate::startup_events::StartupStatus::Ok, None);
332        crate::log(&format!("prepare: done in {ms} ms"));
333        Ok(())
334    } else {
335        sink.stage_end("prepare", ms, crate::startup_events::StartupStatus::Error, Some("failed".into()));
336        Err(SrvSpawnError::MigrationFailed(
337            failure.unwrap_or_else(|| format!("agentmux-srv migrate --prepare exited with {status}")),
338        ))
339    }
340}
341
342/// Start srv and wait for it to be ready ([`spawn_srv_once`]). If srv finds
343/// data that needs preparing (a new version's first start, pending
344/// migrations), it exits before writing anything; this then runs
345/// `migrate --prepare` on the splash and starts srv once more. A second
346/// "needs preparing" is a failure, never a loop.
347pub async fn spawn_srv(
348    launcher_exe_dir: &Path,
349    paths: &DataPaths,
350    srv_pipe_path: &str,
351    #[cfg(target_os = "windows")] job_handle: windows_sys::Win32::Foundation::HANDLE,
352    sink: &crate::startup_events::StartupEventSink,
353    restart_id: Option<&str>,
354) -> Result<(SrvSpawnResult, Child), SrvSpawnError> {
355    #[cfg(target_os = "windows")]
356    let attempt = || spawn_srv_once(launcher_exe_dir, paths, srv_pipe_path, job_handle, sink, restart_id);
357    #[cfg(not(target_os = "windows"))]
358    let attempt = || spawn_srv_once(launcher_exe_dir, paths, srv_pipe_path, sink, restart_id);
359    let started = match attempt().await {
360        Err(SrvSpawnError::NeedsPrepare(reason)) => {
361            crate::log(&format!("srv: data needs preparing ({reason}); running migrate --prepare"));
362            #[cfg(target_os = "windows")]
363            run_prepare(launcher_exe_dir, paths, job_handle, sink).await?;
364            #[cfg(not(target_os = "windows"))]
365            run_prepare(launcher_exe_dir, paths, sink).await?;
366            match attempt().await {
367                Err(SrvSpawnError::NeedsPrepare(reason)) => Err(SrvSpawnError::MigrationFailed(format!(
368                    "the data still needs preparing after migrate --prepare: {reason}"
369                ))),
370                other => other,
371            }
372        }
373        other => other,
374    };
375    // The tray's Quit asks this srv who is working (`quit_ask`).
376    if let Ok((result, _)) = &started {
377        crate::quit_ask::srv_is_at(&result.web_endpoint, &result.auth_key);
378    }
379    started
380}
381
382/// Spawn srv as a child of the launcher, assigned to launcher's
383/// Job Object J0 so it dies cleanly with the launcher tree.
384///
385/// `launcher_exe_dir` is used to locate the srv binary alongside the
386/// launcher (or in `runtime/` for portable). `paths` carries the
387/// data + config dirs and is propagated to srv via env vars.
388/// `job_handle` is the launcher's Job Object so srv joins the same
389/// kill-on-job-close contract as the host. Returns once srv prints
390/// `AGENTMUXSRV-ESTART` (or the 30s timeout fires).
391///
392/// Caller keeps the returned `Child` alive — drop closes srv's
393/// stdin and srv's existing PPID death-watcher takes over (already
394/// part of agentmux-srv per `SPEC_BACKEND_LIFECYCLE.md`).
395// Phase E.1b — `srv_pipe_path` is the launcher-computed pipe path
396// (same data-dir hash as launcher's own pipe, different leaf name).
397// Passed via `AGENTMUX_SRV_PIPE_PATH` so srv doesn't have to
398// recompute the hash; launcher is the single source of truth.
399async fn spawn_srv_once(
400    launcher_exe_dir: &Path,
401    paths: &DataPaths,
402    srv_pipe_path: &str,
403    #[cfg(target_os = "windows")] job_handle: windows_sys::Win32::Foundation::HANDLE,
404    sink: &crate::startup_events::StartupEventSink,
405    // The incident the launcher records for this respawn (`incidents`), so srv's
406    // start-up count of the agents it stopped lands on that notice; `None` for a
407    // cold start.
408    restart_id: Option<&str>,
409) -> Result<(SrvSpawnResult, Child), SrvSpawnError> {
410    sink.stage_begin("backend", "Backend startup");
411    let srv_t = std::time::Instant::now();
412    let backend_path = resolve_srv_binary(launcher_exe_dir)?;
413
414    // Generate a fresh auth_key per run (UUID v4 — same as host did).
415    // This is the launcher's responsibility now; host receives it via
416    // AGENTMUX_AUTH_KEY env so srv + host + frontend agree on the key.
417    let auth_key = uuid::Uuid::new_v4().to_string();
418    // Minted alongside auth_key, same lifetime/reuse rules — see
419    // `SrvSpawnResult::host_reg_secret`'s doc comment.
420    let host_reg_secret = uuid::Uuid::new_v4().to_string();
421    let version = env!("CARGO_PKG_VERSION");
422    let instance_id = format!("v{}", version);
423
424    // app_path = launcher's exe dir (used by srv for finding bundled
425    // tooling like jq.exe / rg.exe). In portable mode this is the
426    // top of the portable folder; the runtime/tools/bin/ subdir
427    // lives under runtime/, but srv's app_path lookup is currently
428    // exe_dir-based per the host's code.
429    //
430    // For B.1 we keep parity: pass exe_dir of the LAUNCHER. If srv
431    // tooling lookup breaks, follow up — log it loudly.
432    let app_path_str = launcher_exe_dir.to_string_lossy().to_string();
433
434    let mut cmd = Command::new(&backend_path);
435    cmd.args([
436        "--wavedata",
437        &paths.data_dir.to_string_lossy(),
438        "--instance",
439        &instance_id,
440    ])
441    .env("AGENTMUX_AUTH_KEY", &auth_key)
442    .env("AGENTMUX_HOST_REG_SECRET", &host_reg_secret)
443    // Canonical AGENTMUX_* env vars (INSTANCE_DIR / DATA_DIR /
444    // CONFIG_DIR / LOG_DIR / CEF_CACHE_DIR / AGENTS_DIR / INSTANCE_
445    // RUNTIME_DIR / SHARED_DIR / RUNTIME_MODE). Replaces the old
446    // AGENTMUX_DATA_HOME / AGENTMUX_DEV / AGENTMUX_CONFIG_HOME /
447    // AGENTMUX_SETTINGS_DIR pre-unification names. srv reads them
448    // via `DataPaths::from_env()` (or the raw var names directly).
449    .envs(paths.common.to_env_vars())
450    .env("AGENTMUX_APP_PATH", &app_path_str)
451    .env("AGENTMUX_SRV_PIPE_PATH", srv_pipe_path)
452    // srv checks its data read-only and, if it needs preparing, exits for
453    // `spawn_srv` to run `migrate --prepare` (`srv_stderr::NEEDS_PREPARE_PREFIX`).
454    .env(agentmux_common::srv_stderr::SUPERVISOR_PREPARES_ENV, "1")
455    .stdin(Stdio::piped())
456    .stdout(Stdio::piped())
457    .stderr(Stdio::piped())
458    .kill_on_drop(false); // Job Object handles cleanup; tokio's kill-on-drop would force-kill.
459    if let Some(id) = restart_id {
460        cmd.env(agentmux_common::incidents::RESTART_ID_ENV, id);
461    }
462
463    let (mut child, pid) = spawn_in_launcher_tree(
464        &mut cmd,
465        #[cfg(target_os = "windows")]
466        job_handle,
467    )?;
468
469    let started_at = chrono::Utc::now().to_rfc3339();
470
471    // Forward srv stdout to our log (info level; the launcher's log
472    // file is the same one srv-logs end up in once we wire log
473    // forwarding properly).
474    if let Some(stdout) = child.stdout.take() {
475        let pid_for_log = pid;
476        tokio::spawn(async move {
477            let mut reader = BufReader::new(stdout).lines();
478            while let Ok(Some(line)) = reader.next_line().await {
479                crate::log(&format!("[srv {} stdout] {}", pid_for_log, line));
480            }
481        });
482    }
483
484    // Parse stderr for AGENTMUXSRV-ESTART (the readiness signal). srv
485    // writes other diagnostic lines too (AGENTMUXSRV-EVENT:..., plain
486    // text); for B.1 we just log them. Phase B sub-PR B.2 will
487    // forward AGENTMUXSRV-EVENT messages to subscribers via the IPC
488    // event stream.
489    let stderr = child
490        .stderr
491        .take()
492        .ok_or_else(|| SrvSpawnError::SpawnFailed("no stderr handle".to_string()))?;
493    let (tx, rx) = mpsc::channel::<SrvSpawnResult>(1);
494    // Separate channel so the stderr reader can signal that migrations are running.
495    // The ESTART waiter extends its deadline when it receives this ping so that a
496    // large-dataset migration that takes longer than the normal 30s boot window
497    // doesn't cause the launcher to kill srv prematurely.
498    let (migration_tx, migration_rx) = mpsc::channel::<()>(4);
499    // Third channel: srv reports a fatal migration failure on stderr and exits
500    // 1 without ESTART. Without this the waiter would only notice via the 30s
501    // timeout, and the user would see "timeout" instead of the actual error.
502    let (failure_tx, failure_rx) = mpsc::channel::<String>(1);
503    // srv's data needs `migrate --prepare`; srv exits right after the line.
504    let (prepare_tx, prepare_rx) = mpsc::channel::<String>(1);
505    let auth_key_for_estart = auth_key.clone();
506    let host_reg_secret_for_estart = host_reg_secret.clone();
507    let started_at_for_estart = started_at.clone();
508    let pid_for_log = pid;
509    let sink_for_migrations = sink.clone();
510    tokio::spawn(async move {
511        let mut reader = BufReader::new(stderr).lines();
512        let mut estart_sent = false;
513        while let Ok(Some(line)) = reader.next_line().await {
514            let estart = if estart_sent { None } else { agentmux_common::srv_stderr::parse_estart_line(&line) };
515            if let Some(parsed) = estart {
516                let result = SrvSpawnResult {
517                    pid: pid_for_log,
518                    ws_endpoint: parsed.ws_endpoint,
519                    web_endpoint: parsed.web_endpoint,
520                    instance_id: parsed.instance_id,
521                    auth_key: auth_key_for_estart.clone(),
522                    host_reg_secret: host_reg_secret_for_estart.clone(),
523                    pending_migrations: parsed.pending_migrations,
524                    started_at: started_at_for_estart.clone(),
525                };
526                crate::log(&format!(
527                    "srv {} ready: ws={} web={} instance={} pending_migrations={}",
528                    result.pid, result.ws_endpoint, result.web_endpoint, result.instance_id,
529                    result.pending_migrations
530                ));
531                let _ = tx.send(result).await;
532                estart_sent = true;
533            } else if let Some(reason) = agentmux_common::srv_stderr::parse_needs_prepare_line(&line) {
534                crate::log(&format!("[srv {} needs prepare] {}", pid_for_log, reason));
535                let _ = prepare_tx.send(reason).await;
536            } else if let Some(reason) =
537                agentmux_common::srv_stderr::parse_migration_failed_line(&line)
538            {
539                crate::log(&format!("[srv {} MIGRATION FAILED] {}", pid_for_log, reason));
540                let _ = failure_tx.send(reason).await;
541            } else if agentmux_common::srv_stderr::is_migrating_line(&line) {
542                crate::log(&format!("[srv {} migrating] {}", pid_for_log, line));
543                let _ = migration_tx.send(()).await;
544            } else if forward_progress_line(&line, "backend", &sink_for_migrations) {
545                // A migration, or a copy-forward / snapshot / lock wait / backup
546                // step: a sub-row of the already-open "backend" stage, not a
547                // stage of its own. See
548                // docs/reports/REPORT_SPLASH_SCREEN_ARCHITECTURE_RETHINK_2026_09_14.md
549                // §2.1/§4 Phase 3.1.
550            } else if let Some(req) = agentmux_common::srv_stderr::parse_upgrade_line(&line) {
551                crate::log(&format!("[srv {} upgrade] {}", pid_for_log, line));
552                crate::upgrade_restart::forward(req);
553            } else if agentmux_common::srv_stderr::parse_event_line(&line).is_some() {
554                crate::log(&format!("[srv {} event] {}", pid_for_log, line));
555                // Phase B.2 will forward these to subscribers.
556            } else {
557                crate::log(&format!("[srv {} stderr] {}", pid_for_log, line));
558            }
559        }
560        // EOF on stderr → srv exited (or its stderr closed). Logged
561        // by the wait-task in main; nothing else to do here.
562    });
563
564    // Wait for ESTART. Both error paths must explicitly start_kill
565    // the child before returning — same kill_on_drop(false) leak
566    // class as the assign/resume failures above. Without this, the
567    // 30s timeout in degraded mode (J0 absent) would leak a fully-
568    // running srv that keeps the data dir lockfile, blocking the
569    // next launch (#571).
570    //
571    let mut channels = EstartChannels { ready: rx, migrating: migration_rx, failed: failure_rx, needs_prepare: Some(prepare_rx) };
572    let recv = wait_for_estart(&mut channels, || {
573        crate::log("srv: migration in progress — ESTART deadline extended to 30 minutes")
574    })
575    .await;
576    match recv {
577        EstartWait::Timeout => {
578            let _ = child.start_kill();
579            sink.stage_end(
580                "backend",
581                srv_t.elapsed().as_millis() as u64,
582                crate::startup_events::StartupStatus::Error,
583                Some("timeout (30s)".into()),
584            );
585            Err(SrvSpawnError::EstartTimeout)
586        }
587        EstartWait::MigrationFailed(reason) => {
588            // srv exits itself right after the line; start_kill on an
589            // already-exited child is a harmless no-op and keeps this arm in
590            // the same shape as the other two failure paths.
591            let _ = child.start_kill();
592            sink.stage_end(
593                "backend",
594                srv_t.elapsed().as_millis() as u64,
595                crate::startup_events::StartupStatus::Error,
596                Some("migration failed".into()),
597            );
598            Err(SrvSpawnError::MigrationFailed(reason))
599        }
600        EstartWait::NeedsPrepare(reason) => {
601            // srv exits by itself right after the line; `migrate --prepare`
602            // must not start while it may still hold the data, so wait for
603            // the real exit, forcing it only if it hangs.
604            if tokio::time::timeout(std::time::Duration::from_secs(10), child.wait()).await.is_err() {
605                let _ = child.start_kill();
606                let _ = child.wait().await;
607            }
608            sink.stage_end(
609                "backend",
610                srv_t.elapsed().as_millis() as u64,
611                crate::startup_events::StartupStatus::Ok,
612                Some("data needs updating".into()),
613            );
614            Err(SrvSpawnError::NeedsPrepare(reason))
615        }
616        EstartWait::Ready(None) => Err(closed_before_ready(&mut child, &sink, srv_t.elapsed()).await),
617        EstartWait::Ready(Some(result)) => {
618            sink.stage_end(
619                "backend",
620                srv_t.elapsed().as_millis() as u64,
621                crate::startup_events::StartupStatus::Ok,
622                None,
623            );
624            Ok((result, child))
625        }
626    }
627}
628
629/// The error for an srv that exited before ESTART: another server holding this data folder has its own
630/// code, so the supervisor can say that plainly; anything else is the generic closed channel.
631fn failure_before_ready(code: Option<i32>) -> SrvSpawnError {
632    if code == Some(agentmux_common::srv_stderr::DATA_DIR_HELD_EXIT) {
633        SrvSpawnError::DataDirHeld
634    } else {
635        SrvSpawnError::EstartChannelClosed
636    }
637}
638
639/// Reap an srv that closed its ESTART channel before becoming ready, and say which refusal it was: a
640/// server already holding the data folder exits with `DATA_DIR_HELD_EXIT`, so the supervisor can show
641/// that plainly instead of a bare failed start.
642async fn closed_before_ready(
643    child: &mut tokio::process::Child,
644    sink: &crate::startup_events::StartupEventSink,
645    elapsed: std::time::Duration,
646) -> SrvSpawnError {
647    let code = match tokio::time::timeout(std::time::Duration::from_secs(2), child.wait()).await {
648        Ok(Ok(status)) => status.code(),
649        _ => {
650            let _ = child.start_kill();
651            let _ = child.wait().await;
652            None
653        }
654    };
655    let error = failure_before_ready(code);
656    let held = matches!(error, SrvSpawnError::DataDirHeld);
657    sink.stage_end(
658        "backend",
659        elapsed.as_millis() as u64,
660        crate::startup_events::StartupStatus::Error,
661        Some(if held { "another server holds this data folder".to_string() } else { "backend exited before it was ready".to_string() }),
662    );
663    error
664}
665
666/// Show the person why an srv spawn failed, in plain words, for the failures the launcher can explain:
667/// a migration that could not run, or another server already holding this channel's data folder. Other
668/// errors are the caller's to log, as before. Kept here so Windows and Unix say the same words.
669pub fn show_spawn_failure(e: &SrvSpawnError, data_dir: &std::path::Path) {
670    match e {
671        SrvSpawnError::MigrationFailed(reason) => {
672            // On Windows the launcher has no console in release, so the dialog is the only thing the
673            // person sees; on Unix `show_fatal_dialog` prints today. Same helper either way.
674            crate::show_fatal_dialog(MIGRATION_FAILED_DIALOG_TITLE, &migration_failed_dialog_body(reason));
675        }
676        SrvSpawnError::DataDirHeld => {
677            // Another server (a headless one, or another launch) holds this channel's data folder:
678            // say so plainly rather than let the splash end on a failed start (task #49109).
679            crate::show_fatal_dialog(DATA_DIR_HELD_DIALOG_TITLE, &data_dir_held_dialog_body(data_dir));
680        }
681        _ => {}
682    }
683}
684
685/// Resolve the agentmux-srv binary path from the LAUNCHER's vantage
686/// point.
687///
688/// Search order, mirroring the host's `resolve_backend_binary` in
689/// sidecar.rs (minus its workspace `dist/bin` fallback) but anchored at
690/// the launcher's exe dir:
691///   1. `<launcher_dir>/runtime/agentmux-srv-{ver}-{os}.{arch}.exe`
692///      (versioned portable layout)
693///   2. `<launcher_dir>/runtime/agentmux-srv.exe` (dev fallback)
694///   3. `<launcher_dir>/agentmux-srv-{ver}-{os}.{arch}.exe`
695///      (launcher in same dir as srv — should not happen in portable
696///      but covers cargo-built dev mode where launcher + srv both
697///      land in target/release/)
698///   4. `<launcher_dir>/agentmux-srv.exe` (dev fallback)
699fn resolve_srv_binary(launcher_exe_dir: &Path) -> Result<PathBuf, SrvSpawnError> {
700    use agentmux_common::srv_binary;
701    let backend_name = "agentmux-srv";
702    let runtime = launcher_exe_dir.join("runtime");
703    let candidates = srv_binary::candidates(&[&runtime, launcher_exe_dir], backend_name, srv_binary::EXE_SUFFIX);
704    if let Some(found) = candidates.iter().find(|p| p.exists()) {
705        return Ok(found.clone());
706    }
707
708    Err(SrvSpawnError::BinaryNotFound(format!(
709        "{} v{} not found. Searched:\n  {}",
710        backend_name,
711        srv_binary::VERSION,
712        candidates
713            .iter()
714            .map(|p| p.display().to_string())
715            .collect::<Vec<_>>()
716            .join("\n  ")
717    )))
718}
719
720/// Assign a process to the launcher's Job Object J0. Used by
721/// `spawn_srv` for srv and exported for `main.rs` to use for the
722/// host. Separated from job creation because both children join
723/// the SAME job (only one J0 ever exists per launcher run).
724#[cfg(target_os = "windows")]
725pub fn assign_pid_to_job(
726    pid: u32,
727    job: windows_sys::Win32::Foundation::HANDLE,
728) -> Result<(), String> {
729    use windows_sys::Win32::Foundation::CloseHandle;
730    use windows_sys::Win32::System::JobObjects::AssignProcessToJobObject;
731    use windows_sys::Win32::System::Threading::{
732        OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE,
733    };
734    unsafe {
735        let process = OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, 0, pid);
736        if process.is_null() {
737            return Err(format!("OpenProcess({}) returned null", pid));
738        }
739        let ok = AssignProcessToJobObject(job, process);
740        CloseHandle(process);
741        if ok == 0 {
742            return Err(format!(
743                "AssignProcessToJobObject failed for pid={}",
744                pid
745            ));
746        }
747        Ok(())
748    }
749}
750
751#[cfg(test)]
752mod migration_failed_tests {
753    use super::*;
754
755    #[test]
756    fn display_names_the_migration_and_carries_srv_reason() {
757        let e = SrvSpawnError::MigrationFailed("migration 0007 failed: disk I/O error".into());
758        assert_eq!(e.to_string(), "database migration failed: migration 0007 failed: disk I/O error");
759    }
760
761    #[test]
762    fn dialog_body_includes_reason_and_restart_guidance() {
763        let body = migration_failed_dialog_body("open shared store: database is locked");
764        assert!(body.contains("open shared store: database is locked"));
765        assert!(body.contains("Restart AgentMux to retry"));
766        assert!(body.contains("shared/backups/pre-migration-"), "must say where the pre-run copy lives");
767    }
768
769    #[test]
770    fn dialog_body_never_asserts_a_backup_exists() {
771        // reagent P1 on #3043: `backup_stores` failing is itself one of the
772        // error paths, so the body must not promise a snapshot/backup was
773        // taken. The wording states the ordering (copy first, then migrate)
774        // and lets the reason text — which names the backup step when that
775        // is what failed — carry the rest.
776        let body = migration_failed_dialog_body("run_pending_migrations: backup failed: disk full");
777        assert!(!body.contains("has not been changed:"), "unconditional data-safety claim");
778        assert!(!body.contains("a snapshot was taken"), "unconditional snapshot claim");
779        assert!(body.contains("if the error above is about writing that copy, nothing was changed"));
780    }
781
782    #[test]
783    fn stderr_line_from_srv_parses_into_the_reason_the_dialog_shows() {
784        // End-to-end over the shared protocol: what srv writes is what the
785        // launcher reads, without either side owning the literal.
786        let line = agentmux_common::srv_stderr::migration_failed_line("mark applied 0011: readonly db");
787        let reason = agentmux_common::srv_stderr::parse_migration_failed_line(&line).expect("tagged line");
788        assert_eq!(reason, "mark applied 0011: readonly db");
789        assert!(!line.starts_with("AGENTMUXSRV-MIGRATING"), "must not be swallowed by the MIGRATING branch");
790    }
791
792    #[test]
793    fn an_srv_refused_because_another_holds_the_data_folder_is_told_apart_from_a_closed_channel() {
794        assert!(matches!(
795            failure_before_ready(Some(agentmux_common::srv_stderr::DATA_DIR_HELD_EXIT)),
796            SrvSpawnError::DataDirHeld
797        ));
798        for code in [None, Some(1), Some(agentmux_common::srv_stderr::SHARED_FOLDER_HELD_EXIT)] {
799            assert!(matches!(failure_before_ready(code), SrvSpawnError::EstartChannelClosed), "{code:?}");
800        }
801        assert_eq!(SrvSpawnError::DataDirHeld.to_string(), "another AgentMux server is already using this data folder");
802    }
803
804    #[test]
805    fn the_second_servers_dialog_says_which_folder_and_what_to_do_and_never_interrupted() {
806        let body = data_dir_held_dialog_body(std::path::Path::new("/home/person/.agentmux/channels/stable/versions/0.60.53/data"));
807        assert!(body.contains("already running for this channel"), "{body}");
808        assert!(body.contains("0.60.53"), "names the folder: {body}");
809        assert!(body.contains("`agentmux open`") && body.contains("`agentmux stop`"), "{body}");
810        assert!(body.contains("Only one AgentMux can use a data folder at a time"), "{body}");
811        assert!(!body.to_lowercase().contains("interrupted"), "not the splash's bare word: {body}");
812        assert!(!body.contains("delete"), "never tell the person to delete the lock file: {body}");
813    }
814}