Skip to main content

agentmux_srv/server/
muxspect_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! HTTP handlers backing the `muxspect` CLI — Phase 1 of
5//! `docs/specs/SPEC_MUXSPECT_LIVE_INTROSPECTION_TOOL_2026_08_01.md`, plus
6//! the `dock`/`dock clear` extension from
7//! `docs/specs/SPEC_MUXSPECT_DOCK_DIAGNOSIS_AND_REMEDIATION_2026_08_06.md`.
8//!
9//! Diagnostic-only surface: a thin read composition over `ProcessBroker`
10//! (Phase A of the process-tracking consolidation,
11//! `crates/srv-core/src/broker/process.rs`) and its sibling registries — never
12//! a new independent snapshot of process/turn state (spec §5.1/§3 point 8).
13//! Reached the same way `agentmux-mcp` already reaches every other
14//! `/api/v1/*` route: plain HTTP, `X-AuthKey` header, `$AGENTMUX_LOCAL_URL`/
15//! `$AGENTMUX_AUTH_KEY` inherited from the caller's own environment (spec
16//! §5.2) — no new IPC mechanism, no new auth scheme. `dock clear` is this
17//! module's first MUTATING route — see the 2026-08-06 spec §2 for why that
18//! scope call is narrow and deliberate, not a reversal of the read-only
19//! design generally.
20
21use axum::extract::{Query, State};
22use axum::http::StatusCode;
23use axum::response::{IntoResponse, Json};
24use serde_json::json;
25
26use crate::backend::storage::filestore::FileStore;
27
28use super::AppState;
29
30/// Bounded tail window read from a block's own persisted `output` file
31/// when looking for a trailing `error_during_execution` frame — see
32/// [`last_error_frame`]. Large enough to comfortably hold the frame itself
33/// (a single JSON line, typically well under 1KB) plus whatever partial
34/// line/chunking noise might precede it; small enough to stay O(1) and not
35/// turn `muxspect` into a log-walker (that's `muxlog`'s job, not this
36/// tool's — see the tool's own design spec §1).
37const LAST_ERROR_TAIL_BYTES: i64 = 8192;
38
39/// The most recent persisted `error_during_execution` frame at the tail of
40/// a block's own `output` file — populated ONLY when the very last
41/// non-blank line IS one (a block that errored once and then kept
42/// producing normal output afterward must NOT be flagged; only "the last
43/// thing that happened to this block was an unrecovered error" counts).
44///
45/// This reads a signal that already exists and is already durable: per
46/// `agent_handlers/input.rs`'s own comment, this exact frame shape is
47/// deliberately persisted to the block file (not just live-broadcast) so
48/// it survives pane reload — the same source the frontend itself renders
49/// as the pane's error bubble. Composing a second reader over that
50/// existing store, rather than adding a new independent tracker, follows
51/// this module's own design constraint (spec §5.1/§3 pt. 8).
52///
53/// See `docs/reports/REPORT_MUXSPECT_SPAWN_REFUSAL_DIAGNOSIS_EXTENSION_2026_08_03.md`
54/// for the incident this closes the diagnostic gap on: a block whose spawn
55/// was refused before any controller/process ever existed showed up as
56/// featureless "no controller, no processes" — indistinguishable from a
57/// healthy idle block — even though the actual, actionable reason was
58/// already sitting in this exact file.
59#[derive(serde::Serialize)]
60pub struct LastErrorFrame {
61    /// The frame's `error.message` verbatim (includes the `[AgentMux] `
62    /// prefix every construction site already writes).
63    pub message: String,
64    /// Best-effort tag for which pre-spawn failure path wrote the frame —
65    /// see [`classify_last_error_source`]. NOT a stable/tested taxonomy
66    /// like `agents::failure::FailureClass` (which only classifies
67    /// POST-spawn exit failures); building that properly for pre-spawn
68    /// refusals is real, separate follow-up work (report §3.3), not
69    /// attempted here.
70    pub source: &'static str,
71    /// Epoch ms the `output` file was last written — i.e. when this frame
72    /// (being the file's last line) was appended. Deliberately a raw
73    /// timestamp, not a precomputed "age," matching `last_computed_ms`'s
74    /// existing convention elsewhere in this response so `--json`
75    /// consumers get a stable value and the CLI renderer computes age the
76    /// same way it already does for every other timestamp.
77    pub written_ms: u64,
78}
79
80/// Best-effort classification of which pre-spawn failure path wrote a
81/// persisted `error_during_execution` frame, inferred from the message
82/// text itself (each construction site's message is distinct and stable —
83/// see `identity/resolver/errors.rs`'s `SpawnGateError::Display`,
84/// `subprocess/container_spawn.rs`, `subprocess/host_spawn.rs`, and
85/// `agent_handlers/input.rs`'s container `ensure_running` path, the only
86/// four call sites that build this frame today). `message` should have
87/// the `[AgentMux] ` prefix already stripped.
88///
89/// codex P2, PR #2802: `SpawnGateError::AmbientHomeDirNotAllowed`'s wording
90/// starts with "this agent's", not either prefix this function originally
91/// recognized — without this branch every ambient-home refusal reported
92/// `unknown` instead of `identity`, regressing this diagnostic for exactly
93/// the pre-spawn refusal case it exists to classify.
94///
95/// ReAgent P2, PR #2854: same regression again for
96/// `SpawnGateError::ClaudeMdSeedFailed` (a newer variant, wording starts
97/// with "could not isolate this agent's") — this function needs a new
98/// branch every time a `SpawnGateError` variant with distinct wording is
99/// added, since it infers the source from message text rather than the
100/// error's own type. A future variant will hit the same gap again unless
101/// this doc comment (and the parallel test below) are kept in sync.
102fn classify_last_error_source(message: &str) -> &'static str {
103    if message.starts_with("no credentials for")
104        || message.starts_with("credential injection could not run")
105        || message.starts_with("this agent's")
106        // ReAgent P2 on PR #2854: SpawnGateError::ClaudeMdSeedFailed's own
107        // Display prefix — same regression this function's doc history
108        // already covers for AmbientHomeDirNotAllowed (codex P2, PR #2802),
109        // recurring for a newer SpawnGateError variant this function wasn't
110        // updated for when it was added.
111        || message.starts_with("could not isolate this agent's")
112    {
113        "identity"
114    } else if message.starts_with("container exec failed")
115        || message.starts_with("container ensure_running failed")
116        || message.starts_with("Couldn't start the container")
117    {
118        "container_spawn"
119    } else if message.starts_with("queued message could not be sent") {
120        "host_spawn"
121    } else {
122        "unknown"
123    }
124}
125
126/// Read the bounded tail of `block_id`'s `output` file and return the
127/// parsed [`LastErrorFrame`] if its last non-blank line is one. `None`
128/// covers every other case (no such block, empty file, last line is
129/// normal output, last line doesn't parse as this exact frame shape) —
130/// deliberately not distinguished further, since all of them mean the
131/// same thing to a caller: nothing actionable to surface here.
132fn last_error_frame(source: &crate::backend::transcript::source::TranscriptSource<'_>) -> Option<LastErrorFrame> {
133    let tail = source.tail(LAST_ERROR_TAIL_BYTES)?;
134    let text = String::from_utf8_lossy(&tail.bytes);
135    let last_line = text.lines().rev().find(|l| !l.trim().is_empty())?;
136
137    let value: serde_json::Value = serde_json::from_str(last_line).ok()?;
138    if value.get("type").and_then(|v| v.as_str()) != Some("result")
139        || value.get("is_error").and_then(|v| v.as_bool()) != Some(true)
140        || value.get("subtype").and_then(|v| v.as_str()) != Some("error_during_execution")
141    {
142        return None;
143    }
144    let message = value.get("error")?.get("message")?.as_str()?.to_string();
145    let source = classify_last_error_source(message.strip_prefix("[AgentMux] ").unwrap_or(&message));
146
147    Some(LastErrorFrame {
148        message,
149        source,
150        written_ms: tail.modts.max(0) as u64,
151    })
152}
153
154/// `GET /api/v1/muxspect/list` — every controller-backed block's current
155/// `ProcessStatus`, full detail (unlike `agent.tracked-blocks`, which
156/// intentionally returns only `block_ids` for its Swarm-pane contract).
157/// Each row also carries `is_agent` — `ProcessStatus::is_agent()`'s complete
158/// classification rule (subprocess/persistent/acp are ALWAYS agents
159/// regardless of `is_agent_pane`, which only applies to shell/cmd) — so
160/// consumers don't reimplement that rule themselves (codex P2 on PR #2380:
161/// the CLI's own naive `is_agent_pane`-only rendering mislabeled exactly
162/// those three controller types).
163pub async fn handle_muxspect_list(State(state): State<AppState>) -> impl IntoResponse {
164    let blocks: Vec<serde_json::Value> = state
165        .process_broker
166        .list()
167        .into_iter()
168        .map(|status| {
169            let is_agent = status.is_agent();
170            let last_error = last_error_frame(&crate::backend::transcript::source::TranscriptSource::resolve(&state.filestore, &state.mstore, &status.block_id));
171            let mut value = serde_json::to_value(&status).unwrap_or_default();
172            if let Some(obj) = value.as_object_mut() {
173                obj.insert("is_agent".to_string(), json!(is_agent));
174                obj.insert("last_error".to_string(), json!(last_error));
175            }
176            value
177        })
178        .collect();
179    Json(json!({ "blocks": blocks })).into_response()
180}
181
182#[derive(serde::Deserialize)]
183pub struct MuxspectDescribeQuery {
184    pub block_id: String,
185}
186
187/// `GET /api/v1/muxspect/describe?block_id=X` — composes `ProcessBroker`
188/// status, the coarse `BlockControllerRuntimeStatus`, and the OS-process
189/// tree for one block into a single response. This is the "describe
190/// everything about block X" query
191/// `REPORT_PROCESS_ARCHITECTURE_STATE_AND_RETHINK_2026_07_22.md` §5.4 named
192/// as missing — getting this picture today takes 2-3 separate, uncomposed
193/// RPC round-trips.
194pub async fn handle_muxspect_describe(
195    State(state): State<AppState>,
196    Query(q): Query<MuxspectDescribeQuery>,
197) -> impl IntoResponse {
198    if q.block_id.is_empty() {
199        return (
200            StatusCode::BAD_REQUEST,
201            Json(json!({ "error": "missing block_id" })),
202        )
203            .into_response();
204    }
205
206    // `process_status` (via `ProcessBroker::compute_status`) already reads
207    // BOTH the process-tracker registry (for `processes`/
208    // `liveness_confidence`) AND the controller's `BlockControllerRuntimeStatus`
209    // (carried on `process_status.controller_status`) in one pass. A second,
210    // independent read of either would risk a process starting/exiting or a
211    // turn starting/finishing between the two calls, returning two
212    // contradictory snapshots in one response (codex P2 on PR #2380, twice —
213    // once for the process list, once for the controller status). Derive
214    // everything from this one snapshot instead of reading twice.
215    let process_status = state.process_broker.status(&q.block_id);
216    let is_agent = process_status.is_agent();
217    // Read unconditionally, not gated on "no live controller" — cheap
218    // (bounded tail read), and gating it would mean re-deriving exactly
219    // the liveness logic `process_status` already computes just to decide
220    // whether to bother. In practice this is only ever non-null for
221    // exactly the case it exists for: nothing has appended to this
222    // block's output since an unrecovered pre-spawn failure.
223    let last_error = last_error_frame(&crate::backend::transcript::source::TranscriptSource::resolve(&state.filestore, &state.mstore, &q.block_id));
224
225    Json(json!({
226        "block_id": q.block_id,
227        "process_status": &process_status,
228        "is_agent": is_agent,
229        "controller_status": &process_status.controller_status,
230        "processes": &process_status.processes,
231        "tracking_confidence": process_status.liveness_confidence,
232        "last_error": last_error,
233    }))
234    .into_response()
235}
236
237#[derive(serde::Deserialize)]
238pub struct MuxspectFindQuery {
239    pub block_id: Option<String>,
240    pub agent: Option<String>,
241}
242
243/// `GET /api/v1/muxspect/find?block_id=X` or `?agent=X` — Ext 4 of
244/// `docs/reports/REPORT_MUXSPECT_MUXLOG_CROSS_CHANNEL_INSPECTION_2026_08_22.md`:
245/// "which running instance(s), if any, have a controller or subagent
246/// dispatch matching block_id/agent X" — the query that debugging session
247/// needed and had no tool for, ending in manual filesystem/env-var
248/// archaeology across every channel by hand.
249///
250/// Checks THIS instance first (host tier, no network) via the same
251/// `ProcessBroker::list()` `handle_muxspect_list` uses (so "found" here
252/// means the same thing `muxspect list` would show, not a different
253/// existence check invented for this endpoint) and, for an `agent` query,
254/// `reactive_handler.list_agents()` (same source `handle_muxspect_conversations`'s
255/// host tier and `verify-sender` use).
256///
257/// Then checks every OTHER channel via the shared reactive registry
258/// (`resolve_shared_reactive_dir` + `list_all_shared` — the exact mechanism
259/// `handle_muxspect_conversations`'s cross-channel tier already uses, see
260/// that handler's own doc comment for the security rationale) WITHOUT any
261/// network call at all for basic existence: `AgentEntry` already carries
262/// `block_id`/`agent_id`/`channel`/`local_url`, so a match there already
263/// answers "which channel" before any forwarding happens. Only a MATCHED
264/// cross-channel entry gets a forwarded `describe` call (same
265/// single-forwarded-hop / timeout discipline as the conversations handler)
266/// to fill in process/controller detail — unmatched channels cost nothing.
267///
268/// Always 200 — zero results is a legitimate answer ("not found on this
269/// host, in any known channel"), not an error, same posture as every other
270/// handler in this file. `results` can have more than one entry only if the
271/// same block_id/agent name somehow exists in more than one place at once
272/// (a real, worth-surfacing anomaly, not something to silently collapse to
273/// the first match).
274///
275/// **Cross-channel `block_id` scope (reagent P2 on PR #2745):** the
276/// cross-channel tier only searches the shared `AgentEntry` registry —
277/// agent-registered blocks. A plain shell/terminal block, or any other
278/// non-agent controller, in a DIFFERENT channel is not findable by
279/// `block_id` here (the host tier above has no such limit — it searches
280/// this instance's FULL `ProcessBroker::list()`, any controller type).
281/// Reaching a non-agent controller cross-channel would need a remote
282/// `/api/v1/muxspect/list`-style forward-and-filter, not just a registry
283/// lookup — out of scope for this change; see
284/// `SPEC_MUXSPECT_CROSS_INSTANCE_FIND_2026_08_22.md`'s Non-goals.
285///
286/// True when a forwarded `describe` response's `process_status.lifecycle`
287/// reads `"unknown"` — `broker::process::Lifecycle::Unknown`'s own doc
288/// comment: "no controller found for this block_id at all." A `None`
289/// input (the forward itself failed/timed out) is NOT the same as this —
290/// deliberately returns `false` for that case, since "we couldn't ask" is
291/// not the same claim as "we asked and it's confirmed gone." Pure
292/// (extracted from the async handler above) for direct unit testing —
293/// reagent P1 on PR #2745 found the un-extracted inline version reported
294/// "found": true unconditionally, with no test coverage of the "gone but
295/// still registered" case at all.
296fn describe_lifecycle_is_unknown(describe: Option<&serde_json::Value>) -> bool {
297    describe
298        .and_then(|d| d.get("process_status"))
299        .and_then(|ps| ps.get("lifecycle"))
300        .and_then(|l| l.as_str())
301        == Some("unknown")
302}
303
304pub async fn handle_muxspect_find(
305    State(state): State<AppState>,
306    Query(q): Query<MuxspectFindQuery>,
307) -> impl IntoResponse {
308    if q.block_id.as_deref().unwrap_or("").is_empty() && q.agent.as_deref().unwrap_or("").is_empty() {
309        return (
310            StatusCode::BAD_REQUEST,
311            Json(json!({ "error": "provide block_id or agent" })),
312        )
313            .into_response();
314    }
315
316    let mut results: Vec<serde_json::Value> = Vec::new();
317    let own_channel = std::env::var("AGENTMUX_CHANNEL").unwrap_or_else(|_| "stable".to_string());
318
319    // Host tier — no network, same source handle_muxspect_list/
320    // handle_muxspect_conversations already use. list_agents() (mutex lock +
321    // full clone of the agent map) is fetched ONCE here, not once per block
322    // inside the loop below — reagent P2 on PR #2745 caught the original
323    // version paying that cost per block, unnecessary repeated
324    // locking/cloning that scaled with block count, matching how
325    // handle_muxspect_conversations's own host tier already does it.
326    let agents = state.reactive_handler.list_agents();
327    for status in state.process_broker.list() {
328        let block_matches = q.block_id.as_deref().is_some_and(|b| b == status.block_id);
329        let agent_matches = q.agent.as_deref().is_some_and(|name| {
330            agents
331                .iter()
332                .any(|r| r.block_id == status.block_id && r.agent_id.eq_ignore_ascii_case(name))
333        });
334        if !block_matches && !agent_matches {
335            continue;
336        }
337        results.push(json!({
338            "tier": "host",
339            "channel": own_channel,
340            "block_id": status.block_id,
341            "found": true,
342            "process_status": &status,
343        }));
344    }
345
346    // Cross-channel tier — AgentEntry already carries block_id/agent_id, so
347    // matching costs zero network calls; only a match gets forwarded.
348    //
349    // reagent P1 on PR #2745: an earlier version unconditionally reported
350    // "found": true for any registry match, even a possibly-stale one whose
351    // owning agent/block already exited but hasn't been evicted from the
352    // shared registry yet — reported as a successful match with CLI exit
353    // code 0. Two checks now guard against that, mirroring the sibling
354    // handle_muxspect_verify_sender's staleness handling in this same file:
355    //   1. should_evict_on_forward_failure(&entry) (reused verbatim from
356    //      backend::reactive::registry — the exact function the registry's
357    //      OWN eviction logic uses, checking both real PID liveness and
358    //      FORWARD_FAILURE_GRACE_MS age) filters out entries already known
359    //      to be stale, before wasting a network call on them.
360    //   2. Even a fresh-looking entry can point at a block the remote
361    //      ProcessBroker no longer knows about (lifecycle: "unknown" — see
362    //      broker::process::Lifecycle's doc comment: "No controller found
363    //      for this block_id at all"). A successful forward with that
364    //      lifecycle is reported with "found": false, not true.
365    if let Some(shared_dir) = crate::registry::resolve_shared_reactive_dir() {
366        let local_url = state.local_web_url.clone();
367        let matches: Vec<_> = crate::backend::reactive::registry::list_all_shared(&shared_dir)
368            .into_iter()
369            .filter(|e| e.channel != own_channel && e.local_url != local_url)
370            .filter(|e| {
371                q.block_id.as_deref().is_some_and(|b| b == e.block_id)
372                    || q.agent.as_deref().is_some_and(|name| e.agent_id.eq_ignore_ascii_case(name))
373            })
374            .filter(|e| !crate::backend::reactive::registry::should_evict_on_forward_failure(e))
375            .collect();
376
377        let mut join_set = tokio::task::JoinSet::new();
378        for entry in matches {
379            let http_client = state.http_client.clone();
380            join_set.spawn(async move {
381                let fetch = http_client
382                    .get(format!("{}/api/v1/muxspect/describe", entry.local_url))
383                    .header(agentmux_common::AUTH_KEY_HEADER, &entry.auth_key)
384                    .query(&[("block_id", entry.block_id.as_str())])
385                    .send();
386
387                let describe = match tokio::time::timeout(
388                    std::time::Duration::from_millis(CROSS_CHANNEL_PREVIEW_TIMEOUT_MS),
389                    fetch,
390                )
391                .await
392                {
393                    Ok(Ok(resp)) if resp.status().is_success() => resp.json::<serde_json::Value>().await.ok(),
394                    _ => None, // timeout/connect/parse failure: still report the match, just without detail
395                };
396
397                let lifecycle_unknown = describe_lifecycle_is_unknown(describe.as_ref());
398
399                json!({
400                    "tier": "cross-channel",
401                    "channel": entry.channel,
402                    "block_id": entry.block_id,
403                    "agent_id": entry.agent_id,
404                    "found": !lifecycle_unknown,
405                    "describe": describe,
406                })
407            });
408        }
409        while let Some(res) = join_set.join_next().await {
410            if let Ok(value) = res {
411                results.push(value);
412            }
413        }
414    }
415
416    Json(json!({
417        "query": { "block_id": q.block_id, "agent": q.agent },
418        "results": results,
419    }))
420    .into_response()
421}
422
423/// A `ToolNode`'s status stays `"running"` this long (matches the
424/// frontend's own `TOOL_PROMOTION_MS`, `frontend/app/view/agent/activity/
425/// tool-adapter.ts`) before it's eligible to be flagged `stuck` here — a
426/// tool call that's merely taking a while must not be flagged the instant
427/// it starts. No shared constant exists between the two languages; keep
428/// this value in sync with the frontend's if either changes.
429const DOCK_STUCK_THRESHOLD_MS: i64 = 30_000;
430
431#[derive(serde::Deserialize)]
432pub struct MuxspectDockQuery {
433    pub block_id: String,
434}
435
436#[derive(serde::Serialize)]
437pub struct DockNodeView {
438    pub node_id: String,
439    pub tool_name: String,
440    pub status: String,
441    pub age_ms: i64,
442    /// `true` when `status == "running"`, past `DOCK_STUCK_THRESHOLD_MS`,
443    /// AND the block's own `ProcessBroker` lifecycle is not `Running` —
444    /// i.e. nothing srv-side is actively backing this block's turn at
445    /// all. Coarse: this is block-level, not node-level, liveness (a
446    /// block mid-turn on a LATER tool call would still read `Running` and
447    /// suppress the flag for an earlier stuck node in the same block) —
448    /// see spec §3.1's own framing of this as "the same signal a human
449    /// would manually cross-reference today, automated," not a perfect
450    /// per-node liveness oracle.
451    ///
452    /// Does NOT cover a backgrounded call stuck in the actual dock UI
453    /// (issue #2518): `status` here is the RAW `ToolNode` status, which is
454    /// terminal ("success") for an accepted background launch within ~a
455    /// second — this field can never go `true` for that case no matter how
456    /// long the real dock row has been showing `running`, because the
457    /// server has no visibility into whether a `<task-notification>` ever
458    /// arrived (that reclassification is entirely client-side, in
459    /// `tool-adapter.ts`). See `run_in_background` below: a `true` there
460    /// combined with a long `age_ms` is worth checking by hand even when
461    /// `stuck` reads `false`.
462    pub stuck: bool,
463    /// `params.run_in_background === true` on the pushing client's own
464    /// `ToolNode`, if it's a Bash call and the renderer reported it.
465    /// `None` for every non-Bash tool and for older clients that predate
466    /// this field. See `stuck`'s doc comment above for why this exists.
467    #[serde(skip_serializing_if = "Option::is_none")]
468    pub run_in_background: Option<bool>,
469}
470
471/// `GET /api/v1/muxspect/dock?block_id=X` — the cached `ToolNode` status
472/// snapshot for one block, cross-referenced against `ProcessBroker` to
473/// flag entries that look stuck. See
474/// `docs/specs/SPEC_MUXSPECT_DOCK_DIAGNOSIS_AND_REMEDIATION_2026_08_06.md` §3.1.
475pub async fn handle_muxspect_dock(
476    State(state): State<AppState>,
477    Query(q): Query<MuxspectDockQuery>,
478) -> impl IntoResponse {
479    if q.block_id.is_empty() {
480        return (
481            StatusCode::BAD_REQUEST,
482            Json(json!({ "error": "missing block_id" })),
483        )
484            .into_response();
485    }
486
487    let now_ms = agentmux_common::time::now_ms();
488
489    // One process_broker read, reused for every node — same rationale as
490    // handle_muxspect_describe: derive from one snapshot, not N reads that
491    // could observe N different, mutually-contradictory states.
492    let lifecycle = state.process_broker.status(&q.block_id).lifecycle;
493    let backed = lifecycle == crate::broker::process::Lifecycle::Running;
494
495    let nodes = dock_node_views(state.dock_snapshots.get(&q.block_id, now_ms), now_ms, backed);
496
497    // `DockSnapshotCache` is intentionally ephemeral (see its own doc
498    // comment) and evicts any entry — including a genuinely-still-running
499    // `bg: true` one — after MAX_NODE_AGE_MS (1 hour). A `task dev`
500    // session in this repo's own retros has run 12+ hours, so this CLI's
501    // output would go dark on it long before it actually finishes.
502    // `db_background_tasks` (Phase A/B) has no such eviction — merge in
503    // anything it still shows `Running` that the cache no longer has,
504    // rather than changing the cache's own eviction semantics (which are
505    // correct for what it's actually for — see dock_snapshot.rs's doc
506    // comment). See docs/specs/SPEC_BACKGROUND_TASK_DASHBOARD_INTELLIGENCE_2026_08_20.md §3.4.
507    let background_tasks = state.mstore.background_task_list_for_block(&q.block_id).unwrap_or_default();
508    let nodes = merge_background_tasks(nodes, background_tasks, now_ms);
509
510    Json(json!({ "block_id": q.block_id, "nodes": nodes })).into_response()
511}
512
513/// Append a synthetic `DockNodeView` for every `Running` `db_background_tasks`
514/// row not already represented in `nodes` (by id — `db_background_tasks.id`
515/// mirrors the dock's own `node_id`, see `background_tasks.rs`'s module doc
516/// comment). Pure, unit-testable like `dock_node_views` above. A task
517/// still present in `nodes` is left as-is — the live cache's own status is
518/// more specific (carries `tool_name`, real `stuck` computation) than
519/// anything this synthesizes from the registry alone.
520fn merge_background_tasks(
521    mut nodes: Vec<DockNodeView>,
522    background_tasks: Vec<crate::backend::storage::background_tasks::BackgroundTask>,
523    now_ms: i64,
524) -> Vec<DockNodeView> {
525    use std::collections::HashSet;
526    let existing: HashSet<String> = nodes.iter().map(|n| n.node_id.clone()).collect();
527    for task in background_tasks {
528        if task.status != crate::backend::storage::background_tasks::BackgroundTaskStatus::Running {
529            continue;
530        }
531        if existing.contains(&task.id) {
532            continue;
533        }
534        nodes.push(DockNodeView {
535            node_id: task.id,
536            tool_name: task.label,
537            status: "running".to_string(),
538            age_ms: (now_ms - task.started_at_ms).max(0),
539            // Not computed the same way as a live cache entry's `stuck`
540            // (no ProcessBroker cross-reference here, and a durable
541            // registry row surviving this long is expected, not
542            // suspicious, for a declared-background task) — false rather
543            // than guessing.
544            stuck: false,
545            run_in_background: Some(true),
546        });
547    }
548    nodes
549}
550
551/// Pure computation behind `handle_muxspect_dock` — separated out so the
552/// stuck-flagging logic (the actual diagnostic value of this endpoint) is
553/// unit-testable without constructing a full `AppState`/axum request, same
554/// discipline as `last_error_frame`/`classify_last_error_source` above.
555fn dock_node_views(
556    nodes: Vec<crate::backend::dock_snapshot::DockNodeSnapshot>,
557    now_ms: i64,
558    backed: bool,
559) -> Vec<DockNodeView> {
560    nodes
561        .into_iter()
562        .map(|n| {
563            let age_ms = (now_ms - n.observed_at).max(0);
564            let stuck = n.status == "running" && age_ms >= DOCK_STUCK_THRESHOLD_MS && !backed;
565            DockNodeView {
566                node_id: n.node_id,
567                tool_name: n.tool_name,
568                status: n.status,
569                age_ms,
570                stuck,
571                run_in_background: n.run_in_background,
572            }
573        })
574        .collect()
575}
576
577#[derive(serde::Deserialize, Default)]
578pub struct MuxspectBackgroundTasksQuery {
579    /// Omit to list every still-running declared-background task across
580    /// every block on this instance (the Swarm/fleet-view case); pass to
581    /// scope to one block's own history (including terminal tasks, unlike
582    /// the global list).
583    #[serde(default)]
584    pub block_id: Option<String>,
585}
586
587#[derive(serde::Serialize, ts_rs::TS)]
588#[ts(export, export_to = "../../../frontend/types/rpc/")]
589pub struct BackgroundTaskView {
590    pub id: String,
591    pub block_id: String,
592    pub label: String,
593    /// Always present, carries null when unknown -- no skip_serializing_if.
594    #[ts(type = "number | null")]
595    pub pid: Option<i64>,
596    #[ts(type = "number")]
597    pub started_at_ms: i64,
598    /// A closed set the frontend branches on; ts-rs would emit a bare
599    /// `string` for a `&'static str` and drop the union the hand-written
600    /// declaration carried.
601    #[ts(type = "\"running\" | \"done\" | \"error\" | \"stopped\"")]
602    pub status: &'static str,
603    #[ts(type = "number")]
604    pub last_seen_ms: i64,
605    #[ts(type = "number | null")]
606    pub ended_at_ms: Option<i64>,
607    /// The Agent call (`tool_use_id`) whose subagent launched this task —
608    /// the same id as that subagent's `tool_use_id` in Swarm. Null for the
609    /// agent's own tasks. Always present, like `pid`.
610    #[ts(type = "string | null")]
611    pub owner_tool_use_id: Option<String>,
612}
613
614impl From<crate::backend::storage::background_tasks::BackgroundTask> for BackgroundTaskView {
615    fn from(t: crate::backend::storage::background_tasks::BackgroundTask) -> Self {
616        BackgroundTaskView {
617            id: t.id,
618            block_id: t.block_id,
619            label: t.label,
620            pid: t.pid,
621            started_at_ms: t.started_at_ms,
622            status: t.status.as_str(),
623            last_seen_ms: t.last_seen_ms,
624            ended_at_ms: t.ended_at_ms,
625            owner_tool_use_id: t.owner_tool_use_id,
626        }
627    }
628}
629
630/// `GET /api/v1/muxspect/migrations` — the migration doctor for THIS
631/// instance's data dir: every registry migration with its applied/pending
632/// state and, for applied ones, the same post-condition verdict
633/// `agentmux-srv migrate --verify` prints
634/// (`SPEC_MIGRATION_SYSTEM_HARDENING_2026_08_03.md` Phase 1c). Built by the
635/// one producer both share (`migrations::doctor_report_for_instance`), so an
636/// operator inside a running instance gets exactly the answer the CLI would
637/// give against a stopped one — without hunting for the srv binary or the
638/// data dir. The incident the hardening spec was written about (§1.6: a
639/// migration "recorded as applied that wrote nothing") is exactly a "why did
640/// this agent fail to start" question, which is `muxspect`'s job.
641///
642/// Read-only, like `--verify`: opens both tracking stores with
643/// `SQLITE_OPEN_READ_ONLY`, never opens a `Store`, never creates a file.
644/// Runs on the blocking pool — it is a handful of SQLite reads, but they
645/// are synchronous. `exit_code` in the body is what `--verify` would exit
646/// with (0 or 3), so the CLI can mirror it.
647pub async fn handle_muxspect_migrations() -> impl IntoResponse {
648    let data_dir = crate::backend::base::get_mux_data_dir();
649    let report = tokio::task::spawn_blocking(move || crate::migrations::doctor_report_for_instance(&data_dir))
650        .await
651        .map_err(|e| format!("doctor task panicked: {e}"))
652        .and_then(|r| r);
653    match report {
654        Ok(report) => Json(report).into_response(),
655        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e }))).into_response(),
656    }
657}
658
659/// `GET /api/v1/muxspect/background-tasks[?block_id=X]` — the durable
660/// declared-background task registry (`db_background_tasks`), the source
661/// of truth `handle_muxspect_dock`'s ephemeral, 1-hour-evicted
662/// `DockSnapshotCache` deliberately isn't (see
663/// docs/status/STATUS_ATTACHED_TASK_AXIS_AND_DEV_LOOP_2026_08_15.md). A
664/// task still shows up here after the dock cache has evicted it, and
665/// survives a pane reload — it's backed by SQLite, not an in-memory cache.
666pub async fn handle_muxspect_background_tasks(
667    State(state): State<AppState>,
668    Query(q): Query<MuxspectBackgroundTasksQuery>,
669) -> impl IntoResponse {
670    let result = match q.block_id.as_deref() {
671        Some(block_id) if !block_id.is_empty() => state.mstore.background_task_list_for_block(block_id),
672        _ => state.mstore.background_task_list_running(),
673    };
674    match result {
675        Ok(tasks) => {
676            let views: Vec<BackgroundTaskView> = tasks.into_iter().map(Into::into).collect();
677            Json(json!({ "tasks": views })).into_response()
678        }
679        Err(e) => (
680            StatusCode::INTERNAL_SERVER_ERROR,
681            Json(json!({ "error": e.to_string() })),
682        )
683            .into_response(),
684    }
685}
686
687#[derive(serde::Deserialize)]
688pub struct MuxspectDockClearRequest {
689    pub block_id: String,
690    pub node_id: String,
691}
692
693/// `POST /api/v1/muxspect/dock/clear` — validates `node_id` is a currently
694/// tracked node for `block_id` (per the cache — see
695/// `docs/specs/SPEC_MUXSPECT_DOCK_DIAGNOSIS_AND_REMEDIATION_2026_08_06.md`
696/// §3.2), then publishes `EVENT_DOCK_CLEAR` scoped to `block:<id>`. Only a
697/// renderer currently displaying that block and still holding that node
698/// ever receives or acts on it (real server-side scope routing, not
699/// client-side self-filtering — same mechanism `EVENT_SHELL_NODE_CREATE`
700/// already uses). Returns 404 if the node isn't in the cache — either it
701/// was never pushed, or it already resolved/was already cleared; either
702/// way there's nothing to do.
703pub async fn handle_muxspect_dock_clear(
704    State(state): State<AppState>,
705    Json(req): Json<MuxspectDockClearRequest>,
706) -> impl IntoResponse {
707    if req.block_id.is_empty() || req.node_id.is_empty() {
708        return (
709            StatusCode::BAD_REQUEST,
710            Json(json!({ "error": "missing block_id or node_id" })),
711        )
712            .into_response();
713    }
714
715    if !state.dock_snapshots.has_node(&req.block_id, &req.node_id) {
716        return (
717            StatusCode::NOT_FOUND,
718            Json(json!({ "error": "no such node in this block's dock snapshot", "cleared": false })),
719        )
720            .into_response();
721    }
722
723    state.broker.publish_event::<crate::backend::mps_events::DockClear>(&crate::backend::mps_events::DockClearEvent { node_id: req.node_id.clone() }, vec![format!("block:{}", req.block_id)], 0);
724    state.dock_snapshots.remove_node(&req.block_id, &req.node_id);
725
726    Json(json!({ "cleared": true, "block_id": req.block_id, "node_id": req.node_id })).into_response()
727}
728
729#[derive(serde::Deserialize)]
730pub struct MuxspectVerifySenderQuery {
731    pub name: String,
732}
733
734/// **Not a security/trust primitive.** This reports registry LIVENESS only
735/// (does an agent named X currently exist in the discovery data at all) —
736/// it performs NO cryptographic check and must not be confused with the
737/// actual JEKT sender-authentication mechanism, which is per-message,
738/// automatic, and already computes a real `TRUST=`/`SIG=` value on every
739/// delivered jekt via HMAC-SHA256 (host tier) / Ed25519 (LAN, cross-channel
740/// and same-account WAN) / a pinned Ed25519 key (reagent WAN) — see the jekt
741/// protocol specification, https://docs.agentmux.ai/internals/jekt-protocol/.
742/// Earlier drafts of this route reused that exact vocabulary
743/// (`host-verified`/`network-claimed`) for a mere presence check, which
744/// collided with — and could be mistaken for — that real, stronger
745/// guarantee (reagentx-workflow review on PR #2702, P1). Deliberately no
746/// `trust`/`verified` field here at all: `status` + `tier` fully describe
747/// what was actually checked (presence, not authenticity), with nothing
748/// that could be misread as more than that.
749#[derive(serde::Serialize, Debug, PartialEq, Eq)]
750pub struct VerifySenderVerdict {
751    pub name: String,
752    /// `"found"` | `"not_found"` | `"stale"`.
753    pub status: &'static str,
754    #[serde(skip_serializing_if = "Option::is_none")]
755    pub tier: Option<&'static str>,
756    #[serde(skip_serializing_if = "Option::is_none")]
757    pub last_seen_ms: Option<i64>,
758    #[serde(skip_serializing_if = "Option::is_none")]
759    pub channel: Option<String>,
760    #[serde(skip_serializing_if = "Option::is_none")]
761    pub local_url: Option<String>,
762}
763
764/// One already-fetched candidate, tagged with the tier it was found on.
765/// Keeps [`classify_sender`] pure and independent of `AgentRegistration`/
766/// `AgentEntry`/`LanInstance`'s actual (differently-shaped) types — the
767/// handler below does the field mapping once, at the IO boundary, same
768/// discipline as `dock_node_views`/`last_error_frame` above.
769struct SenderCandidate {
770    name: String,
771    /// `"host"` | `"cross-channel"` | `"lan"` | `"wan"` — NOT `"spawner"`;
772    /// that tier is checked entirely client-side by `muxspect.mjs` before
773    /// this route is ever called (it depends on the CALLER's own
774    /// environment, which this handler has no way to observe). See
775    /// `docs/specs/SPEC_MUXSPECT_VERIFY_SENDER_2026_08_21.md`.
776    tier: &'static str,
777    last_seen_ms: Option<i64>,
778    /// Whether `last_seen_ms` is a genuinely-refreshed heartbeat this
779    /// candidate's tier can be judged stale by. `false` for host tier —
780    /// `ReactiveHandler::list_agents()` is synchronously accurate (an
781    /// agent is removed from it on unregister, not aged out by timestamp;
782    /// see `bootstrap/network.rs`'s 20s heartbeat task's own doc comment:
783    /// "always accurate, with no staleness window of its own") and nothing in
784    /// this codebase currently calls `update_last_seen` to refresh
785    /// `AgentRegistration.last_seen` after registration — applying a
786    /// staleness cutoff to it would eventually flag every healthy,
787    /// long-running host-tier agent as stale (#2702). `false` for WAN too (`last_seen_ms` is always `None` there —
788    /// `cloud_subscriber` doesn't track a per-agent heartbeat). `true` for
789    /// cross-channel (the same 20s heartbeat task above re-writes the
790    /// shared registry's `updated_at` for every live host-tier agent) and
791    /// LAN (mDNS peers re-announce and bump `last_seen` on every
792    /// `ServiceResolved`).
793    stale_eligible: bool,
794    channel: Option<String>,
795    local_url: Option<String>,
796}
797
798/// Pure verdict computation over already-fetched discovery data — see
799/// [`handle_muxspect_verify_sender`] for the IO/fetch boundary this
800/// composes with. `candidates` must already be in tier-priority order
801/// (host, then cross-channel, then lan, then wan — most-trusted first).
802///
803/// Among all case-insensitive name matches (a name can legitimately appear
804/// on more than one tier, or more than once within cross-channel if
805/// several channels registered it), prefers the first NON-stale match in
806/// tier-priority order; only falls back to a stale match if every match is
807/// stale. Picking the literal first match regardless of staleness (an
808/// earlier version of this function) could report `stale` even when a
809/// later, live entry for the same sender existed (codex review on PR
810/// #2702, P2).
811fn classify_sender(name: &str, candidates: &[SenderCandidate], now_ms: i64) -> VerifySenderVerdict {
812    let needle = name.to_lowercase();
813    let is_stale = |c: &&SenderCandidate| {
814        c.stale_eligible
815            && c.last_seen_ms
816                .is_some_and(|ls| now_ms - ls >= crate::backend::reactive::registry::FORWARD_FAILURE_GRACE_MS as i64)
817    };
818    let matches: Vec<&SenderCandidate> = candidates.iter().filter(|c| c.name.to_lowercase() == needle).collect();
819    let chosen = matches.iter().find(|c| !is_stale(c)).or_else(|| matches.first());
820
821    match chosen {
822        None => VerifySenderVerdict {
823            name: name.to_string(),
824            status: "not_found",
825            tier: None,
826            last_seen_ms: None,
827            channel: None,
828            local_url: None,
829        },
830        Some(c) => VerifySenderVerdict {
831            name: name.to_string(),
832            status: if is_stale(c) { "stale" } else { "found" },
833            tier: Some(c.tier),
834            last_seen_ms: c.last_seen_ms,
835            channel: c.channel.clone(),
836            local_url: c.local_url.clone(),
837        },
838    }
839}
840
841/// `GET /api/v1/muxspect/verify-sender?name=X` — answers "is an agent named
842/// X currently registered, and via what tier" in one call, so an agent
843/// that just received a `[JEKT:FROM=X ...]` marker doesn't have to fall
844/// back to manual filesystem/process archaeology to sanity-check the
845/// claimed sender exists at all. See [`VerifySenderVerdict`]'s doc comment
846/// for the important caveat this is NOT the JEKT protocol's own
847/// cryptographic sender verification. See `docs/retro/RETRO_JEKT_CROSS_
848/// CHANNEL_TRUST_SELF_DECLARED_2026_08_21.md` for the incident this closes
849/// the liveness-lookup gap on, and `docs/specs/SPEC_MUXSPECT_VERIFY_
850/// SENDER_2026_08_21.md` for the full design.
851///
852/// Composes the same four sources `handle_discovery` (`GET
853/// /agentmux/discovery`) already aggregates — host-tier
854/// `AgentRegistration`, the host-global cross-channel shared registry, LAN
855/// mDNS peers, and the WAN cloud subscriber — into a verdict instead of
856/// raw discovery data. Always 200 (matching `list`/`dock`/`describe`'s own
857/// convention of encoding "nothing found" in the body rather than the HTTP
858/// status — a `not_found` verdict is a legitimate query result, not a
859/// caller error) — `apiGet`'s fail-on-non-2xx contract in `muxspect.mjs`
860/// would otherwise turn a normal "no such sender" answer into a hard CLI
861/// failure.
862pub async fn handle_muxspect_verify_sender(
863    State(state): State<AppState>,
864    Query(q): Query<MuxspectVerifySenderQuery>,
865) -> impl IntoResponse {
866    if q.name.is_empty() {
867        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "missing name" }))).into_response();
868    }
869
870    let mut candidates: Vec<SenderCandidate> = Vec::new();
871
872    candidates.extend(state.reactive_handler.list_agents().into_iter().map(|a| SenderCandidate {
873        name: a.agent_id,
874        tier: "host",
875        last_seen_ms: Some(a.last_seen as i64),
876        stale_eligible: false,
877        channel: None,
878        local_url: None,
879    }));
880
881    // Mirrors handle_discovery's own cross_channel derivation exactly
882    // (same exclusion of this instance's own channel/URL) — kept as a
883    // separate read here rather than refactored into a shared helper, to
884    // avoid touching handle_discovery's existing, already-tested behavior
885    // for an unrelated new route.
886    let own_channel = std::env::var("AGENTMUX_CHANNEL").unwrap_or_else(|_| "stable".to_string());
887    let local_url = state.local_web_url.clone();
888    if let Some(shared_dir) = crate::registry::resolve_shared_reactive_dir() {
889        candidates.extend(
890            crate::backend::reactive::registry::list_all_shared(&shared_dir)
891                .into_iter()
892                .filter(|e| e.channel != own_channel && e.local_url != local_url)
893                .map(|e| SenderCandidate {
894                    name: e.agent_id,
895                    tier: "cross-channel",
896                    last_seen_ms: Some(e.updated_at as i64),
897                    stale_eligible: true,
898                    channel: Some(e.channel),
899                    local_url: Some(e.local_url),
900                }),
901        );
902    }
903
904    for lan_instance in state.lan_discovery.get_instances() {
905        let peer_url = format!("{}:{}", lan_instance.address, lan_instance.port);
906        // LanInstance.last_seen is UNIX SECONDS (lan/discovery.rs stamps it
907        // via `.as_secs()`), not milliseconds like every other timestamp in
908        // this handler — multiplying is required or every LAN candidate
909        // reads as ~1970 and is immediately (wrongly) flagged stale (codex
910        // review on PR #2702, P1).
911        candidates.extend(lan_instance.agents.iter().map(|agent_name| SenderCandidate {
912            name: agent_name.clone(),
913            tier: "lan",
914            last_seen_ms: Some((lan_instance.last_seen as i64).saturating_mul(1000)),
915            stale_eligible: true,
916            channel: None,
917            local_url: Some(peer_url.clone()),
918        }));
919    }
920
921    if let Some(subscriber) = crate::muxbus::cloud_subscriber::get_global_subscriber() {
922        candidates.extend(subscriber.subscribed_agents().into_iter().map(|agent_name| SenderCandidate {
923            name: agent_name,
924            tier: "wan",
925            last_seen_ms: None,
926            stale_eligible: false,
927            channel: None,
928            local_url: None,
929        }));
930    }
931
932    let now_ms = agentmux_common::time::now_ms();
933
934    Json(classify_sender(&q.name, &candidates, now_ms)).into_response()
935}
936
937/// Truncation length for a `last_message_preview` — keeps `conversations`'
938/// response small even when the tail line is a long tool-call/result frame;
939/// this is a liveness-glance preview, not a transcript reader (that's
940/// `GetAgentTranscript`/`muxspect conversation <agent>`'s job). Applied to
941/// BOTH the host-tier read ([`last_line_preview_and_activity`]) and the
942/// cross-channel forwarded read — codex P2 on PR #2715 caught the
943/// cross-channel path skipping this entirely, which let one huge remote
944/// tool-call/result line inflate an otherwise-bounded response.
945const PREVIEW_MAX_CHARS: usize = 200;
946
947/// Bounded tail window read directly off the live FileStore file in
948/// [`last_line_preview_and_activity`]'s fast path — deliberately small
949/// relative to a whole session (which can be many MB): only needs to
950/// comfortably contain the single last non-blank line, not search for a
951/// specific frame shape the way [`LAST_ERROR_TAIL_BYTES`]'s window does.
952const PREVIEW_TAIL_BYTES: i64 = 4096;
953
954/// Short per-forward timeout for cross-channel preview fetches in
955/// [`handle_muxspect_conversations`] — a single dead/unresponsive channel
956/// must not stall the whole listing; best-effort, matches this file's
957/// diagnostic (never authoritative) posture elsewhere.
958const CROSS_CHANNEL_PREVIEW_TIMEOUT_MS: u64 = 1500;
959
960/// Truncate a preview line to [`PREVIEW_MAX_CHARS`], appending an ellipsis
961/// when it was actually cut. Shared by the host-tier and cross-channel
962/// preview paths so they can't drift out of sync again (codex P2 on
963/// PR #2715 — the cross-channel path originally didn't call this at all).
964fn truncate_preview(line: &str) -> String {
965    if line.chars().count() > PREVIEW_MAX_CHARS {
966        line.chars().take(PREVIEW_MAX_CHARS).collect::<String>() + "…"
967    } else {
968        line.to_string()
969    }
970}
971
972/// Last non-blank line of a block's own transcript, truncated for preview
973/// display, plus a real "when was this last written" timestamp — `None`
974/// for either if the block has no session output yet (e.g. an agent
975/// registered but no turn has produced output) — missing is not an error,
976/// same "encode absence in the body, not the status" posture as the rest
977/// of this file.
978///
979/// Fast path: a bounded tail read straight off the live FileStore file
980/// (`stat` + a small `read_at`, not a full read) — covers the overwhelming
981/// common case (an active or recently-active, non-archived block) without
982/// loading/decompressing full session history just to preview one line
983/// (codex P2 on PR #2715: the original version called
984/// `session_archive::read_session_output`, a full-session-export
985/// primitive, for every host agent on every `conversations` call). The
986/// file's own `modts` doubles as a REAL last-activity timestamp — unlike
987/// `AgentRegistration::last_seen`, which nothing in this codebase updates
988/// after registration (codex P2 on PR #2715: using it as
989/// `last_activity_ms` made a long-lived, actively-working agent look
990/// hours-stale). Falls back to the full-read primitive (which also
991/// handles archived/gzip sessions) only when the fast path finds nothing —
992/// no live file yet, or genuinely archived — at the cost of no cheap
993/// activity timestamp in that fallback case (`None`, not a guessed value).
994fn last_line_preview_and_activity(
995    mstore: &std::sync::Arc<crate::backend::storage::store::Store>,
996    filestore: &std::sync::Arc<FileStore>,
997    block_id: &str,
998) -> (Option<String>, Option<u64>) {
999    if let Some(tail) = crate::backend::transcript::source::TranscriptSource::resolve(filestore, mstore, block_id).tail(PREVIEW_TAIL_BYTES) {
1000        let text = String::from_utf8_lossy(&tail.bytes);
1001        if let Some(last) = text.lines().rev().find(|l| !l.trim().is_empty()) {
1002            return (Some(truncate_preview(last)), Some(tail.modts.max(0) as u64));
1003        }
1004    }
1005
1006    match crate::backend::session_archive::read_session_output(mstore, filestore, block_id) {
1007        Ok((raw_bytes, _)) => {
1008            let text = String::from_utf8_lossy(&raw_bytes);
1009            let preview = text
1010                .lines()
1011                .rev()
1012                .find(|l| !l.trim().is_empty())
1013                .map(truncate_preview);
1014            (preview, None)
1015        }
1016        Err(_) => (None, None),
1017    }
1018}
1019
1020/// `GET /api/v1/muxspect/conversations` — a single-call, all-tier glance at
1021/// every agent's most recent activity, so an agent (or a human via `muxspect
1022/// conversations`) doesn't have to compose `DiscoverAgents` +
1023/// N×`GetAgentTranscript` calls by hand. See
1024/// `docs/specs/SPEC_MUXSPECT_CROSS_TIER_CONVERSATION_VISIBILITY_2026_08_21.md`
1025/// Phase A.
1026///
1027/// Host and cross-channel entries carry a `last_message_preview` (the tail
1028/// non-blank transcript line) and `turn_active`, read directly for host
1029/// (this instance's own `mstore`/`filestore`) and via a single best-effort
1030/// forwarded HTTP call per channel for cross-channel (same auth/loopback
1031/// pattern `handle_reactive_inject`'s Tier 2b and this instance's own
1032/// `handle_muxspect_verify_sender` already use — see those for the security
1033/// rationale; not repeated here). LAN and WAN entries carry no preview
1034/// (`remote_fetch_required: true`) — Phase A deliberately does not invent a
1035/// remote-read protocol for those tiers; see the spec's Phase B/C.
1036///
1037/// Always 200 — an empty `agents` list is a legitimate result, not an
1038/// error, matching every other handler in this file.
1039pub async fn handle_muxspect_conversations(State(state): State<AppState>) -> impl IntoResponse {
1040    let mut agents: Vec<serde_json::Value> = Vec::new();
1041    let work_facts = super::work_facts_handlers::start_conversation_facts(&state); // beside the previews below
1042
1043    // Host tier — direct local read, no network.
1044    for reg in state.reactive_handler.list_agents() {
1045        let (m, f, b) = (state.mstore.clone(), state.filestore.clone(), reg.block_id.clone());
1046        let (preview, activity_ms) = super::transcript_tail::off_worker(move || last_line_preview_and_activity(&m, &f, &b)).await;
1047        let turn_active = crate::backend::blockcontroller::get_block_controller_status(&reg.block_id).map(|s| s.turn_active).unwrap_or(false);
1048        let (agent_state, unavailable) = crate::backend::agent_state::state_and_unavailable(&state.mstore, &reg.block_id);
1049        agents.push(json!({
1050            "name": reg.agent_id,
1051            "tier": "host",
1052            "block_id": reg.block_id,
1053            "turn_active": turn_active,
1054            "state": agent_state, "unavailable": unavailable, // never its account: other hosts receive this
1055            // Transcript-write time (last_line_preview_and_activity), else registration time.
1056            "last_activity_ms": activity_ms.unwrap_or(reg.last_seen),
1057            "last_message_preview": preview,
1058        }));
1059    }
1060
1061    // Cross-channel tier — one best-effort forwarded call per channel, ALL
1062    // concurrent (codex P2 on PR #2715: sequential fetches meant a single
1063    // dead/slow channel added its full CROSS_CHANNEL_PREVIEW_TIMEOUT_MS to
1064    // TOTAL latency instead of every channel paying it once, in parallel).
1065    // `forwarded=true` caps each of these at the same single-hop guard
1066    // `handle_reactive_transcript`'s own cross-channel fallback uses (see
1067    // TranscriptQuery::forwarded's doc comment) — this call IS a forward,
1068    // from the target instance's point of view, exactly like that one.
1069    let own_channel = std::env::var("AGENTMUX_CHANNEL").unwrap_or_else(|_| "stable".to_string());
1070    let local_url = state.local_web_url.clone();
1071    if let Some(shared_dir) = crate::registry::resolve_shared_reactive_dir() {
1072        let cross_channel_entries: Vec<_> =
1073            crate::backend::reactive::registry::list_all_shared(&shared_dir)
1074                .into_iter()
1075                .filter(|e| e.channel != own_channel && e.local_url != local_url)
1076                .collect();
1077
1078        let mut join_set = tokio::task::JoinSet::new();
1079        for entry in cross_channel_entries {
1080            let http_client = state.http_client.clone();
1081            join_set.spawn(async move {
1082                let mut preview: Option<String> = None;
1083                let mut turn_active: Option<bool> = None;
1084
1085                let fetch = http_client
1086                    .get(format!("{}/agentmux/reactive/transcript", entry.local_url))
1087                    .header(agentmux_common::AUTH_KEY_HEADER, &entry.auth_key)
1088                    .query(&[
1089                        ("agent", entry.agent_id.as_str()),
1090                        ("max_lines", "1"),
1091                        ("forwarded", "true"),
1092                    ])
1093                    .send();
1094
1095                if let Ok(Ok(resp)) = tokio::time::timeout(
1096                    std::time::Duration::from_millis(CROSS_CHANNEL_PREVIEW_TIMEOUT_MS),
1097                    fetch,
1098                )
1099                .await
1100                {
1101                    if resp.status().is_success() {
1102                        if let Ok(body) = resp.json::<serde_json::Value>().await {
1103                            turn_active = body.get("turn_active").and_then(|v| v.as_bool());
1104                            preview = body
1105                                .get("lines")
1106                                .and_then(|v| v.as_array())
1107                                .and_then(|arr| arr.last())
1108                                .and_then(|v| v.as_str())
1109                                .map(truncate_preview);
1110                        }
1111                    }
1112                }
1113                // Timeout/connection/parse failure: list the agent anyway
1114                // with no preview — best-effort, same as every other tier
1115                // here.
1116
1117                json!({
1118                    "name": entry.agent_id,
1119                    "tier": "cross-channel",
1120                    "channel": entry.channel,
1121                    "block_id": entry.block_id,
1122                    "turn_active": turn_active,
1123                    "last_activity_ms": entry.updated_at,
1124                    "last_message_preview": preview,
1125                })
1126            });
1127        }
1128        while let Some(res) = join_set.join_next().await {
1129            // A panicked/cancelled task just doesn't contribute a row —
1130            // best-effort, matching this whole tier's posture elsewhere.
1131            if let Ok(value) = res {
1132                agents.push(value);
1133            }
1134        }
1135    }
1136
1137    // LAN tier — liveness only, no remote-read protocol in Phase A.
1138    for lan_instance in state.lan_discovery.get_instances() {
1139        for agent_name in &lan_instance.agents {
1140            agents.push(json!({
1141                "name": agent_name,
1142                "tier": "lan",
1143                "host": format!("{}:{}", lan_instance.address, lan_instance.port),
1144                "remote_fetch_required": true,
1145            }));
1146        }
1147    }
1148
1149    // WAN tier — liveness only, no remote-read protocol in Phase A.
1150    if let Some(subscriber) = crate::muxbus::cloud_subscriber::get_global_subscriber() {
1151        for agent_name in subscriber.subscribed_agents() {
1152            agents.push(json!({
1153                "name": agent_name,
1154                "tier": "wan",
1155                "remote_fetch_required": true,
1156            }));
1157        }
1158    }
1159
1160    super::work_facts_handlers::annotate_conversations(work_facts, &mut agents).await; // their `work`
1161    Json(json!({ "agents": agents })).into_response()
1162}
1163
1164/// Flatten one layout tree into a compact, renderable node list.
1165///
1166/// Deliberately a FLAT list carrying a `depth`, not nested JSON: the CLI
1167/// renders an indented outline, and a flat list keeps both the wire shape and
1168/// the renderer trivial.
1169fn flatten_layout_nodes(
1170    node: &agentmux_common::LayoutNode,
1171    depth: usize,
1172    index_path: &str,
1173    out: &mut Vec<serde_json::Value>,
1174) {
1175    let is_branch = !node.children.is_empty();
1176    out.push(json!({
1177        "id": node.id,
1178        "depth": depth,
1179        "path": index_path,
1180        "kind": if is_branch { "branch" } else { "leaf" },
1181        "flex_direction": match node.flex_direction {
1182            agentmux_common::FlexDirection::Row => "row",
1183            agentmux_common::FlexDirection::Column => "column",
1184        },
1185        "size": node.size,
1186        // `minimized` round-trips through the untyped `extra` catch-all on
1187        // this side, not as a typed field — same access the reducer's own
1188        // `is_node_locked` uses. Reported as "locked" rather than raw
1189        // `minimized` because legacy pre-display-mode markers
1190        // (`minimizedSize`/`slipMinimize`/`columnDissolve`) count too, and an
1191        // unmigrated tree on disk is exactly the case this route should show.
1192        "locked": crate::backend::layout::is_node_locked(node),
1193        // A branch is "effectively minimized" when every leaf under it is —
1194        // the state that drives chip geometry. Surfaced explicitly because it
1195        // is NOT visible from the `minimized` flag alone on a branch.
1196        "effectively_minimized": crate::backend::layout::is_effectively_minimized(node),
1197        "block_id": node.data.as_ref().map(|d| d.block_id.clone()),
1198        "child_count": node.children.len(),
1199    }));
1200    for (i, child) in node.children.iter().enumerate() {
1201        let child_path = if index_path.is_empty() {
1202            i.to_string()
1203        } else {
1204            format!("{index_path}.{i}")
1205        };
1206        flatten_layout_nodes(child, depth + 1, &child_path, out);
1207    }
1208}
1209
1210/// `GET /api/v1/muxspect/layout[?tab_id=X]` — the persisted layout tree for
1211/// every tab (or one), plus the layout doctor's verdict on each.
1212///
1213/// Why this exists: layout state was previously only inspectable by reading
1214/// `db_layout` out of SQLite by hand and walking the JSON, which is what
1215/// diagnosing the cross-split minimize bugs (#2848, #2850, #2855) actually
1216/// required. This applies `muxspect`'s existing "what is this instance doing
1217/// right now" contract to layout.
1218///
1219/// It reports the PERSISTED tree, a genuinely different question from what
1220/// the frontend currently renders: `validate_layout_invariants` normally runs
1221/// at reducer write-time, so running it on demand here also catches
1222/// corruption already sitting on disk, including trees written by older
1223/// versions that never ran the check.
1224///
1225/// Read-only, like every route in this module except `dock clear`.
1226pub async fn handle_muxspect_layout(
1227    State(state): State<AppState>,
1228    Query(q): Query<MuxspectLayoutQuery>,
1229) -> impl IntoResponse {
1230    let tabs = match state.mstore.get_all::<crate::backend::obj::Tab>() {
1231        Ok(t) => t,
1232        Err(e) => {
1233            // 200 with an `error` field, not a 4xx/5xx — muxspect.mjs's
1234            // apiGet() treats a non-2xx as a transport failure and prints a
1235            // connection error, which would misattribute a store-read problem
1236            // as "srv is unreachable".
1237            return Json(json!({ "error": format!("failed to list tabs: {e}") })).into_response();
1238        }
1239    };
1240
1241    let mut layouts = Vec::new();
1242    for tab in tabs {
1243        if let Some(want) = q.tab_id.as_deref() {
1244            if tab.oid != want {
1245                continue;
1246            }
1247        }
1248        let ls = match state
1249            .mstore
1250            .must_get::<crate::backend::obj::LayoutState>(&tab.layoutstate)
1251        {
1252            Ok(ls) => ls,
1253            Err(e) => {
1254                // A tab pointing at a missing layoutstate is itself a finding
1255                // worth surfacing rather than skipping silently.
1256                layouts.push(json!({
1257                    "tab_id": tab.oid,
1258                    "tab_name": tab.name,
1259                    "layoutstate_oid": tab.layoutstate,
1260                    "error": format!("layoutstate unreadable: {e}"),
1261                }));
1262                continue;
1263            }
1264        };
1265
1266        let violations = crate::backend::layout::validate_layout_invariants(&ls.rootnode);
1267        let mut nodes = Vec::new();
1268        if let Some(root) = ls.rootnode.as_ref() {
1269            flatten_layout_nodes(root, 0, "", &mut nodes);
1270        }
1271        let leaf_count = nodes.iter().filter(|n| n["kind"] == "leaf").count();
1272        let minimized_leaves = nodes
1273            .iter()
1274            .filter(|n| n["kind"] == "leaf" && n["locked"] == true)
1275            .count();
1276
1277        layouts.push(json!({
1278            "tab_id": tab.oid,
1279            "tab_name": tab.name,
1280            "layoutstate_oid": ls.oid,
1281            "magnified_node_id": ls.magnifiednodeid,
1282            "node_count": nodes.len(),
1283            "leaf_count": leaf_count,
1284            "minimized_leaf_count": minimized_leaves,
1285            "violations": violations,
1286            "healthy": violations.is_empty(),
1287            "nodes": nodes,
1288        }));
1289    }
1290
1291    // An explicit tab_id that matched nothing is a FAILED LOOKUP, not an
1292    // empty result. Returning `{"layouts": []}` made a stale or mistyped id
1293    // indistinguishable from a successful run over a tab with no panes --
1294    // the CLI printed "no layouts found" and exited 0, which is exactly the
1295    // wrong answer for a targeted diagnostic in a script (codex P2 on
1296    // PR #2856). Same 200-with-`error` shape as the store-read failure above,
1297    // for the same reason: a non-2xx would be reported by muxspect.mjs's
1298    // apiGet() as "srv is unreachable".
1299    if let Some(want) = q.tab_id.as_deref() {
1300        if layouts.is_empty() {
1301            return Json(json!({ "error": format!("no tab with id '{want}' in this instance") }))
1302                .into_response();
1303        }
1304    }
1305
1306    Json(json!({ "layouts": layouts })).into_response()
1307}
1308
1309#[derive(serde::Deserialize)]
1310pub struct MuxspectLayoutQuery {
1311    /// Restrict to one tab. Omitted = every tab in this instance.
1312    pub tab_id: Option<String>,
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317    use super::*;
1318    use crate::backend::storage::filestore::{FileMeta, FileOpts};
1319
1320    fn error_frame_line(message: &str) -> String {
1321        json!({
1322            "type": "result",
1323            "is_error": true,
1324            "subtype": "error_during_execution",
1325            "error": {"message": message}
1326        })
1327        .to_string()
1328    }
1329
1330    // reagent P1 on PR #2745 — pins describe_lifecycle_is_unknown, the
1331    // pure piece extracted from handle_muxspect_find's cross-channel
1332    // staleness check.
1333    #[test]
1334    fn describe_lifecycle_is_unknown_true_for_lifecycle_unknown() {
1335        let describe = json!({ "process_status": { "lifecycle": "unknown" } });
1336        assert!(describe_lifecycle_is_unknown(Some(&describe)));
1337    }
1338
1339    #[test]
1340    fn describe_lifecycle_is_unknown_false_for_a_real_lifecycle() {
1341        for lifecycle in ["running", "idle", "done", "error"] {
1342            let describe = json!({ "process_status": { "lifecycle": lifecycle } });
1343            assert!(!describe_lifecycle_is_unknown(Some(&describe)), "lifecycle={lifecycle}");
1344        }
1345    }
1346
1347    #[test]
1348    fn describe_lifecycle_is_unknown_false_when_the_forward_itself_failed() {
1349        // None (the describe call timed out/errored) is NOT the same claim
1350        // as "confirmed gone" — "we couldn't ask" must not read as "unknown".
1351        assert!(!describe_lifecycle_is_unknown(None));
1352    }
1353
1354    #[test]
1355    fn describe_lifecycle_is_unknown_false_for_malformed_or_missing_fields() {
1356        assert!(!describe_lifecycle_is_unknown(Some(&json!({}))));
1357        assert!(!describe_lifecycle_is_unknown(Some(&json!({ "process_status": {} }))));
1358        assert!(!describe_lifecycle_is_unknown(Some(&json!({ "process_status": { "lifecycle": 123 } }))));
1359    }
1360
1361    #[test]
1362    fn classify_last_error_source_matches_every_known_construction_site() {
1363        // The exact message text each of the four call sites builds today
1364        // (identity/resolver/errors.rs, container_spawn.rs, host_spawn.rs,
1365        // agent_handlers/input.rs) — with the `[AgentMux] ` prefix already
1366        // stripped, as the real caller does before classifying.
1367        assert_eq!(
1368            classify_last_error_source("no credentials for claude: the bound account was deleted or is unresolvable. Bind an account for this provider in Connectors → Accounts."),
1369            "identity"
1370        );
1371        assert_eq!(
1372            classify_last_error_source("credential injection could not run (task join failed); the spawn was refused rather than falling back to the global CLI login. Retry, and check `muxlog auth` if it persists."),
1373            "identity"
1374        );
1375        // codex P2, PR #2802: SpawnGateError::AmbientHomeDirNotAllowed.
1376        assert_eq!(
1377            classify_last_error_source("this agent's claude identity points directly at your personal claude config directory (C:\\Users\\user\\.claude) instead of an isolated AgentMux account — AgentMux no longer allows spawning an agent against your own global CLI login. Re-bind this identity to an isolated account in Connectors \u{2192} Accounts (delete the current claude account and log in again to create a fresh, isolated one), then retry."),
1378            "identity"
1379        );
1380        // ReAgent P2, PR #2854: SpawnGateError::ClaudeMdSeedFailed.
1381        assert_eq!(
1382            classify_last_error_source("could not isolate this agent's claude config directory (C:\\Users\\user\\.agentmux\\shared\\identities\\id-1\\claude): permission denied. Refusing to spawn with an unprotected config dir — retry, and check the directory's permissions if it persists."),
1383            "identity"
1384        );
1385        assert_eq!(
1386            classify_last_error_source("container exec failed: no such container"),
1387            "container_spawn"
1388        );
1389        assert_eq!(
1390            classify_last_error_source("container ensure_running failed: image not found"),
1391            "container_spawn"
1392        );
1393        assert_eq!(
1394            classify_last_error_source("Couldn't start the container for this agent: the registry refused access to x."),
1395            "container_spawn"
1396        );
1397        assert_eq!(
1398            classify_last_error_source("queued message could not be sent: lease held by another process"),
1399            "host_spawn"
1400        );
1401        assert_eq!(classify_last_error_source("something nobody wrote yet"), "unknown");
1402        // #3577: SpawnGateError::AgentDeleted — its Display starts
1403        // "this agent's", so it files under identity with the other gate
1404        // refusals.
1405        assert_eq!(
1406            classify_last_error_source(
1407                &crate::identity::resolver::SpawnGateError::AgentDeleted {
1408                    agent_id: "uid-x".to_string()
1409                }
1410                .to_string()
1411            ),
1412            "identity"
1413        );
1414    }
1415
1416    #[test]
1417    fn last_error_frame_none_for_missing_block() {
1418        let filestore = FileStore::open_in_memory().unwrap();
1419        assert!(last_error_frame(&crate::backend::transcript::source::TranscriptSource::own(&filestore, "no-such-block")).is_none());
1420    }
1421
1422    #[test]
1423    fn last_error_frame_none_for_empty_output() {
1424        let filestore = FileStore::open_in_memory().unwrap();
1425        filestore
1426            .make_file("block-1", "output", FileMeta::new(), FileOpts::default())
1427            .unwrap();
1428        assert!(last_error_frame(&crate::backend::transcript::source::TranscriptSource::own(&filestore, "block-1")).is_none());
1429    }
1430
1431    #[test]
1432    fn last_error_frame_found_when_last_line_is_the_frame() {
1433        let filestore = FileStore::open_in_memory().unwrap();
1434        filestore
1435            .make_file("block-1", "output", FileMeta::new(), FileOpts::default())
1436            .unwrap();
1437        let mut content = String::new();
1438        content.push_str("{\"type\":\"assistant\",\"text\":\"normal turn output\"}\n");
1439        content.push_str(&error_frame_line(
1440            "[AgentMux] no credentials for claude: bind an account in Connectors → Accounts.",
1441        ));
1442        content.push('\n');
1443        filestore.write_file("block-1", "output", content.as_bytes()).unwrap();
1444
1445        let found = last_error_frame(&crate::backend::transcript::source::TranscriptSource::own(&filestore, "block-1")).expect("last line is an error frame");
1446        assert_eq!(
1447            found.message,
1448            "[AgentMux] no credentials for claude: bind an account in Connectors → Accounts."
1449        );
1450        assert_eq!(found.source, "identity");
1451        assert!(found.written_ms > 0);
1452    }
1453
1454    /// An agent's error frame is read from the agent's zone; the block's own store holds nothing.
1455    #[test]
1456    fn last_error_frame_is_read_from_the_agents_zone() {
1457        use crate::backend::transcript::source::TranscriptSource;
1458        let (own, global, zone) = (FileStore::open_in_memory().unwrap(), FileStore::open_in_memory().unwrap(), "agent:error-frame-global:current");
1459        global.make_file(zone, "output", FileMeta::new(), FileOpts::default()).unwrap();
1460        global.append_lines(zone, "output", format!("{}\n", error_frame_line("[AgentMux] no credentials for claude: bind an account in Connectors → Accounts.")).as_bytes()).unwrap();
1461        let found = last_error_frame(&TranscriptSource { fs: &global, zone: zone.to_string(), global: true, own: None }).expect("the frame in the agent zone");
1462        assert_eq!(found.source, "identity");
1463        assert!(last_error_frame(&TranscriptSource::own(&own, "blk")).is_none());
1464    }
1465
1466    /// Pins the "only the LAST non-blank line counts" rule (see the
1467    /// function's own doc comment): a block that errored once and then
1468    /// recovered — kept producing normal output afterward — must NOT be
1469    /// flagged. Only "the last thing that happened was an unrecovered
1470    /// error" is what this exists to surface.
1471    #[test]
1472    fn last_error_frame_none_when_normal_output_follows_an_earlier_error() {
1473        let filestore = FileStore::open_in_memory().unwrap();
1474        filestore
1475            .make_file("block-1", "output", FileMeta::new(), FileOpts::default())
1476            .unwrap();
1477        let mut content = String::new();
1478        content.push_str(&error_frame_line("[AgentMux] container exec failed: transient"));
1479        content.push('\n');
1480        content.push_str("{\"type\":\"assistant\",\"text\":\"turn resumed fine after the retry\"}\n");
1481        filestore.write_file("block-1", "output", content.as_bytes()).unwrap();
1482
1483        assert!(last_error_frame(&crate::backend::transcript::source::TranscriptSource::own(&filestore, "block-1")).is_none());
1484    }
1485
1486    #[test]
1487    fn last_error_frame_ignores_a_result_frame_that_is_not_an_error() {
1488        let filestore = FileStore::open_in_memory().unwrap();
1489        filestore
1490            .make_file("block-1", "output", FileMeta::new(), FileOpts::default())
1491            .unwrap();
1492        let normal_result = json!({"type": "result", "is_error": false, "subtype": "success"}).to_string();
1493        filestore
1494            .write_file("block-1", "output", format!("{normal_result}\n").as_bytes())
1495            .unwrap();
1496
1497        assert!(last_error_frame(&crate::backend::transcript::source::TranscriptSource::own(&filestore, "block-1")).is_none());
1498    }
1499
1500    fn dock_node(id: &str, status: &str, observed_at: i64) -> crate::backend::dock_snapshot::DockNodeSnapshot {
1501        crate::backend::dock_snapshot::DockNodeSnapshot {
1502            node_id: id.to_string(),
1503            tool_name: "Bash".to_string(),
1504            status: status.to_string(),
1505            timestamp: Some(observed_at),
1506            observed_at,
1507            run_in_background: None,
1508        }
1509    }
1510
1511    #[test]
1512    fn dock_node_views_flags_stuck_running_node_past_threshold_when_unbacked() {
1513        let now_ms = 100_000;
1514        let views = dock_node_views(vec![dock_node("n1", "running", 50_000)], now_ms, false);
1515        assert_eq!(views.len(), 1);
1516        assert_eq!(views[0].age_ms, 50_000);
1517        assert!(views[0].stuck, "running, 50s old, unbacked — must be flagged stuck");
1518    }
1519
1520    #[test]
1521    fn dock_node_views_does_not_flag_running_node_within_threshold() {
1522        let now_ms = 100_000;
1523        // Only 10s old — well under DOCK_STUCK_THRESHOLD_MS (30s), even unbacked.
1524        let views = dock_node_views(vec![dock_node("n1", "running", 90_000)], now_ms, false);
1525        assert!(!views[0].stuck, "a tool merely taking a while must not be flagged instantly");
1526    }
1527
1528    #[test]
1529    fn dock_node_views_does_not_flag_running_node_when_backed_by_a_live_process() {
1530        let now_ms = 100_000;
1531        // Old enough to qualify on age alone, but `backed=true` (block lifecycle
1532        // is Running) — something IS actively going on for this block.
1533        let views = dock_node_views(vec![dock_node("n1", "running", 50_000)], now_ms, true);
1534        assert!(!views[0].stuck, "backed by a live process — not stuck, just slow");
1535    }
1536
1537    #[test]
1538    fn dock_node_views_does_not_flag_non_running_nodes_regardless_of_age() {
1539        let now_ms = 100_000;
1540        for status in ["success", "failed", "canceled", "denied"] {
1541            let views = dock_node_views(vec![dock_node("n1", status, 0)], now_ms, false);
1542            assert!(!views[0].stuck, "status={status} already resolved, must never be flagged stuck");
1543        }
1544    }
1545
1546    #[test]
1547    fn dock_node_views_preserves_every_input_node() {
1548        let now_ms = 100_000;
1549        let views = dock_node_views(
1550            vec![dock_node("n1", "running", 99_000), dock_node("n2", "success", 80_000)],
1551            now_ms,
1552            false,
1553        );
1554        assert_eq!(views.len(), 2);
1555        assert_eq!(views[0].node_id, "n1");
1556        assert_eq!(views[1].node_id, "n2");
1557    }
1558
1559    #[test]
1560    fn dock_node_views_surfaces_run_in_background_even_though_status_is_terminal() {
1561        // Issue #2518: an accepted background launch is terminal
1562        // ("success") within ~a second server-side, so `stuck` can never
1563        // catch it — this is the one signal that lets a human tell "this
1564        // success might actually still be running in the real dock" apart
1565        // from an ordinary finished call, without the server having to
1566        // duplicate the client's <task-notification> cross-referencing.
1567        let now_ms = 100_000;
1568        let mut bg_node = dock_node("n1", "success", 0);
1569        bg_node.run_in_background = Some(true);
1570        let views = dock_node_views(vec![bg_node], now_ms, false);
1571        assert_eq!(views[0].run_in_background, Some(true));
1572        assert!(!views[0].stuck, "status is terminal — the raw heuristic correctly stays quiet");
1573    }
1574
1575    fn bg_task(
1576        id: &str,
1577        status: crate::backend::storage::background_tasks::BackgroundTaskStatus,
1578        started_at_ms: i64,
1579    ) -> crate::backend::storage::background_tasks::BackgroundTask {
1580        crate::backend::storage::background_tasks::BackgroundTask {
1581            id: id.to_string(),
1582            block_id: "block-1".to_string(),
1583            label: "task dev".to_string(),
1584            pid: Some(4242),
1585            started_at_ms,
1586            status,
1587            last_seen_ms: started_at_ms,
1588            ended_at_ms: None,
1589            owner_tool_use_id: None,
1590        }
1591    }
1592
1593    #[test]
1594    fn merge_background_tasks_adds_a_running_task_the_cache_evicted() {
1595        // The exact §3.4 scenario: DockSnapshotCache's 1-hour TTL evicted
1596        // the entry, but db_background_tasks still knows it's running.
1597        use crate::backend::storage::background_tasks::BackgroundTaskStatus;
1598        let now_ms = 100_000_000;
1599        let merged = merge_background_tasks(vec![], vec![bg_task("bg-1", BackgroundTaskStatus::Running, 1_000)], now_ms);
1600        assert_eq!(merged.len(), 1);
1601        assert_eq!(merged[0].node_id, "bg-1");
1602        assert_eq!(merged[0].status, "running");
1603        assert_eq!(merged[0].age_ms, now_ms - 1_000);
1604        assert_eq!(merged[0].run_in_background, Some(true));
1605        assert!(!merged[0].stuck);
1606    }
1607
1608    #[test]
1609    fn merge_background_tasks_skips_a_task_the_cache_still_has() {
1610        use crate::backend::storage::background_tasks::BackgroundTaskStatus;
1611        let now_ms = 100_000;
1612        let existing = dock_node_views(vec![dock_node("bg-1", "running", 90_000)], now_ms, false);
1613        let merged = merge_background_tasks(existing, vec![bg_task("bg-1", BackgroundTaskStatus::Running, 1_000)], now_ms);
1614        assert_eq!(merged.len(), 1, "must not duplicate a node the live cache already has");
1615        assert_eq!(merged[0].tool_name, "Bash", "the live cache's own entry wins, not a synthesized one");
1616    }
1617
1618    #[test]
1619    fn merge_background_tasks_ignores_non_running_tasks() {
1620        use crate::backend::storage::background_tasks::BackgroundTaskStatus;
1621        let now_ms = 100_000;
1622        for status in [BackgroundTaskStatus::Done, BackgroundTaskStatus::Error, BackgroundTaskStatus::Stopped] {
1623            let merged = merge_background_tasks(vec![], vec![bg_task("bg-1", status, 1_000)], now_ms);
1624            assert!(merged.is_empty(), "status={status:?} is terminal — must not be synthesized as a live dock row");
1625        }
1626    }
1627
1628    #[test]
1629    fn merge_background_tasks_on_no_tasks_is_a_true_no_op() {
1630        let now_ms = 100_000;
1631        let existing = dock_node_views(vec![dock_node("n1", "running", 90_000)], now_ms, false);
1632        let expected_len = existing.len();
1633        let merged = merge_background_tasks(existing, vec![], now_ms);
1634        assert_eq!(merged.len(), expected_len);
1635        assert_eq!(merged[0].node_id, "n1");
1636    }
1637
1638    #[tokio::test]
1639    async fn handle_muxspect_dock_rejects_empty_block_id() {
1640        let state = crate::server::tests::test_state();
1641        let resp = handle_muxspect_dock(
1642            State(state),
1643            Query(MuxspectDockQuery { block_id: String::new() }),
1644        )
1645        .await
1646        .into_response();
1647        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1648    }
1649
1650    #[tokio::test]
1651    async fn handle_muxspect_dock_clear_rejects_empty_ids() {
1652        let state = crate::server::tests::test_state();
1653        let resp = handle_muxspect_dock_clear(
1654            State(state),
1655            Json(MuxspectDockClearRequest { block_id: String::new(), node_id: "n1".to_string() }),
1656        )
1657        .await
1658        .into_response();
1659        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1660    }
1661
1662    #[tokio::test]
1663    async fn handle_muxspect_dock_clear_404s_on_unknown_node() {
1664        let state = crate::server::tests::test_state();
1665        let resp = handle_muxspect_dock_clear(
1666            State(state),
1667            Json(MuxspectDockClearRequest { block_id: "block-1".to_string(), node_id: "no-such-node".to_string() }),
1668        )
1669        .await
1670        .into_response();
1671        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1672    }
1673
1674    #[tokio::test]
1675    async fn handle_muxspect_dock_clear_succeeds_and_removes_from_cache() {
1676        let state = crate::server::tests::test_state();
1677        state.dock_snapshots.push_delta("block-1", dock_node("n1", "running", 0));
1678        assert!(state.dock_snapshots.has_node("block-1", "n1"));
1679
1680        let resp = handle_muxspect_dock_clear(
1681            State(state.clone()),
1682            Json(MuxspectDockClearRequest { block_id: "block-1".to_string(), node_id: "n1".to_string() }),
1683        )
1684        .await
1685        .into_response();
1686        assert_eq!(resp.status(), StatusCode::OK);
1687        assert!(
1688            !state.dock_snapshots.has_node("block-1", "n1"),
1689            "a cleared node must not still be reported by a subsequent `dock` read"
1690        );
1691    }
1692
1693    async fn json_body(resp: axum::response::Response) -> serde_json::Value {
1694        let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
1695        serde_json::from_slice(&body).unwrap()
1696    }
1697
1698    #[tokio::test]
1699    async fn handle_muxspect_background_tasks_scoped_to_block_includes_terminal_tasks() {
1700        let state = crate::server::tests::test_state();
1701        state.mstore.background_task_observe("t1", "block-1", "task dev", 0, 0).unwrap();
1702        state.mstore.background_task_observe("t2", "block-1", "finished build", 0, 0).unwrap();
1703        state
1704            .mstore
1705            .background_task_complete(
1706                "t2",
1707                crate::backend::storage::background_tasks::BackgroundTaskStatus::Done,
1708                500,
1709            )
1710            .unwrap();
1711        // Different block — must not leak into a block-scoped query.
1712        state.mstore.background_task_observe("t3", "block-2", "other pane", 0, 0).unwrap();
1713
1714        let resp = handle_muxspect_background_tasks(
1715            State(state),
1716            Query(MuxspectBackgroundTasksQuery { block_id: Some("block-1".to_string()) }),
1717        )
1718        .await
1719        .into_response();
1720        assert_eq!(resp.status(), StatusCode::OK);
1721        let body = json_body(resp).await;
1722        let ids: Vec<&str> = body["tasks"].as_array().unwrap().iter().map(|t| t["id"].as_str().unwrap()).collect();
1723        assert_eq!(ids, vec!["t1", "t2"], "block-scoped query includes terminal tasks for that block");
1724    }
1725
1726    #[tokio::test]
1727    async fn handle_muxspect_background_tasks_without_block_id_lists_running_globally() {
1728        let state = crate::server::tests::test_state();
1729        state.mstore.background_task_observe("t1", "block-1", "still running", 0, 0).unwrap();
1730        state.mstore.background_task_observe("t2", "block-2", "also running", 0, 0).unwrap();
1731        state.mstore.background_task_observe("t3", "block-1", "finished", 0, 0).unwrap();
1732        state
1733            .mstore
1734            .background_task_complete(
1735                "t3",
1736                crate::backend::storage::background_tasks::BackgroundTaskStatus::Done,
1737                500,
1738            )
1739            .unwrap();
1740
1741        let resp = handle_muxspect_background_tasks(
1742            State(state),
1743            Query(MuxspectBackgroundTasksQuery { block_id: None }),
1744        )
1745        .await
1746        .into_response();
1747        assert_eq!(resp.status(), StatusCode::OK);
1748        let body = json_body(resp).await;
1749        let ids: Vec<&str> = body["tasks"].as_array().unwrap().iter().map(|t| t["id"].as_str().unwrap()).collect();
1750        assert_eq!(ids, vec!["t1", "t2"], "global query is running-only, across every block");
1751    }
1752
1753    fn candidate(name: &str, tier: &'static str, last_seen_ms: Option<i64>, stale_eligible: bool) -> SenderCandidate {
1754        SenderCandidate { name: name.to_string(), tier, last_seen_ms, stale_eligible, channel: None, local_url: None }
1755    }
1756
1757    #[test]
1758    fn classify_sender_not_found_on_empty_candidates() {
1759        let verdict = classify_sender("AgentA", &[], 1_000_000);
1760        assert_eq!(verdict.status, "not_found");
1761        assert_eq!(verdict.tier, None);
1762    }
1763
1764    #[test]
1765    fn classify_sender_found_on_host_tier() {
1766        let candidates = [candidate("AgentA", "host", Some(999_000), false)];
1767        let verdict = classify_sender("AgentA", &candidates, 1_000_000);
1768        assert_eq!(verdict.status, "found");
1769        assert_eq!(verdict.tier, Some("host"));
1770    }
1771
1772    #[test]
1773    fn classify_sender_found_on_cross_channel_tier() {
1774        let candidates = [candidate("AgentA", "cross-channel", Some(999_000), true)];
1775        let verdict = classify_sender("AgentA", &candidates, 1_000_000);
1776        assert_eq!(verdict.status, "found");
1777        assert_eq!(verdict.tier, Some("cross-channel"));
1778    }
1779
1780    #[test]
1781    fn classify_sender_found_on_lan_or_wan_tier() {
1782        let lan = classify_sender("Peer", &[candidate("Peer", "lan", Some(999_000), true)], 1_000_000);
1783        assert_eq!(lan.status, "found");
1784        let wan = classify_sender("Peer", &[candidate("Peer", "wan", None, false)], 1_000_000);
1785        assert_eq!(wan.status, "found");
1786    }
1787
1788    #[test]
1789    fn classify_sender_name_match_is_case_insensitive() {
1790        let candidates = [candidate("agenta", "host", Some(999_000), false)];
1791        let verdict = classify_sender("AgentA", &candidates, 1_000_000);
1792        assert_eq!(verdict.status, "found");
1793    }
1794
1795    /// Host tier must NEVER be flagged stale, no matter how old
1796    /// `last_seen_ms` is — `ReactiveHandler::list_agents()` is
1797    /// synchronously accurate (removed on unregister, not aged out), and
1798    /// nothing in this codebase refreshes `AgentRegistration.last_seen`
1799    /// after registration. Applying a staleness cutoff here would flag
1800    /// every long-running, perfectly healthy host-tier agent as stale
1801    /// (codex review on PR #2702, P1 — this pins the fix).
1802    #[test]
1803    fn classify_sender_host_tier_never_stale_regardless_of_age() {
1804        let now_ms = 1_000_000;
1805        let ancient = now_ms - 10 * crate::backend::reactive::registry::FORWARD_FAILURE_GRACE_MS as i64;
1806        let candidates = [candidate("AgentA", "host", Some(ancient), false)];
1807        let verdict = classify_sender("AgentA", &candidates, now_ms);
1808        assert_eq!(verdict.status, "found", "host tier is stale_eligible: false — age must never matter");
1809    }
1810
1811    /// Cross-channel and LAN entries DO get a real, periodically-refreshed
1812    /// timestamp (the 20s heartbeat task for cross-channel, mDNS
1813    /// re-announce for LAN) — pins that a hit past the real
1814    /// `FORWARD_FAILURE_GRACE_MS` threshold (reused from `registry.rs`,
1815    /// not a separately-invented constant) downgrades to `stale` rather
1816    /// than being silently dropped to `not_found`.
1817    #[test]
1818    fn classify_sender_stale_when_last_seen_past_the_real_grace_threshold() {
1819        let now_ms = 1_000_000;
1820        let stale_ts = now_ms - crate::backend::reactive::registry::FORWARD_FAILURE_GRACE_MS as i64;
1821        let candidates = [candidate("AgentA", "cross-channel", Some(stale_ts), true)];
1822        let verdict = classify_sender("AgentA", &candidates, now_ms);
1823        assert_eq!(verdict.status, "stale");
1824        assert_eq!(verdict.tier, Some("cross-channel"), "still reports which tier it was found on");
1825    }
1826
1827    #[test]
1828    fn classify_sender_wan_tier_has_no_last_seen_and_is_never_stale() {
1829        // WAN candidates carry no last_seen_ms (cloud_subscriber doesn't
1830        // track a per-agent heartbeat) — must not be misclassified as
1831        // stale just because the field is absent.
1832        let candidates = [candidate("AgentA", "wan", None, false)];
1833        let verdict = classify_sender("AgentA", &candidates, 1_000_000);
1834        assert_eq!(verdict.status, "found");
1835    }
1836
1837    /// Priority (non-stale case): a name present on multiple tiers reports
1838    /// the FIRST match — callers push candidates in tier-priority order
1839    /// (host, cross-channel, lan, wan) — so a host hit wins over a later
1840    /// cross-channel entry for the same name.
1841    #[test]
1842    fn classify_sender_reports_first_matching_tier_when_present_on_multiple() {
1843        let candidates = [
1844            candidate("AgentA", "host", Some(999_000), false),
1845            candidate("AgentA", "cross-channel", Some(999_000), true),
1846        ];
1847        let verdict = classify_sender("AgentA", &candidates, 1_000_000);
1848        assert_eq!(verdict.tier, Some("host"));
1849    }
1850
1851    /// Priority (staleness case): a STALE earlier-tier match must not win
1852    /// over a LIVE later-tier match for the same name — picking the
1853    /// literal first match regardless of staleness could report `stale`
1854    /// even though a live entry for the same sender existed elsewhere in
1855    /// the candidate list (codex review on PR #2702, P2 — this pins the
1856    /// fix). Only when EVERY match is stale does the first (most-trusted)
1857    /// one win as a fallback.
1858    #[test]
1859    fn classify_sender_prefers_a_live_candidate_over_an_earlier_stale_one() {
1860        let now_ms = 1_000_000;
1861        let stale_ts = now_ms - crate::backend::reactive::registry::FORWARD_FAILURE_GRACE_MS as i64;
1862        let candidates = [
1863            candidate("AgentA", "cross-channel", Some(stale_ts), true), // stale, but tier-priority first
1864            candidate("AgentA", "lan", Some(999_000), true),            // live, lower tier-priority
1865        ];
1866        let verdict = classify_sender("AgentA", &candidates, now_ms);
1867        assert_eq!(verdict.status, "found");
1868        assert_eq!(verdict.tier, Some("lan"));
1869    }
1870
1871    #[test]
1872    fn classify_sender_falls_back_to_first_stale_match_when_all_are_stale() {
1873        let now_ms = 1_000_000;
1874        let stale_ts = now_ms - crate::backend::reactive::registry::FORWARD_FAILURE_GRACE_MS as i64;
1875        let candidates = [
1876            candidate("AgentA", "cross-channel", Some(stale_ts), true),
1877            candidate("AgentA", "lan", Some(stale_ts), true),
1878        ];
1879        let verdict = classify_sender("AgentA", &candidates, now_ms);
1880        assert_eq!(verdict.status, "stale");
1881        assert_eq!(verdict.tier, Some("cross-channel"), "falls back to the most-trusted tier among stale matches");
1882    }
1883
1884    #[tokio::test]
1885    async fn handle_muxspect_verify_sender_rejects_empty_name() {
1886        let state = crate::server::tests::test_state();
1887        let resp = handle_muxspect_verify_sender(State(state), Query(MuxspectVerifySenderQuery { name: String::new() }))
1888            .await
1889            .into_response();
1890        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1891    }
1892
1893    #[tokio::test]
1894    async fn handle_muxspect_verify_sender_not_found_is_still_200() {
1895        // A "no such sender" verdict is a legitimate query result, not a
1896        // caller error — must stay 200 so muxspect.mjs's apiGet() (which
1897        // treats any non-2xx as fatal) doesn't turn it into a hard failure.
1898        let state = crate::server::tests::test_state();
1899        let resp = handle_muxspect_verify_sender(
1900            State(state),
1901            Query(MuxspectVerifySenderQuery { name: "NoSuchAgent".to_string() }),
1902        )
1903        .await
1904        .into_response();
1905        assert_eq!(resp.status(), StatusCode::OK);
1906        let body = json_body(resp).await;
1907        assert_eq!(body["status"], "not_found");
1908    }
1909
1910    #[tokio::test]
1911    async fn handle_muxspect_conversations_empty_state_is_still_200() {
1912        // No agents registered at all is a legitimate result, not an error —
1913        // same "encode absence in the body, not the status" posture as the
1914        // rest of this file's handlers.
1915        let state = crate::server::tests::test_state();
1916        let resp = handle_muxspect_conversations(State(state)).await.into_response();
1917        assert_eq!(resp.status(), StatusCode::OK);
1918        let body = json_body(resp).await;
1919        assert!(body["agents"].is_array());
1920    }
1921
1922    #[tokio::test]
1923    async fn handle_muxspect_conversations_includes_a_registered_host_agent() {
1924        let state = crate::server::tests::test_state();
1925        let unique = uuid::Uuid::new_v4();
1926        let agent_id = format!("conversations-test-agent-{unique}");
1927        let block_id = format!("conversations-test-block-{unique}");
1928        state
1929            .reactive_handler
1930            .register_agent(&agent_id, &block_id, None)
1931            .unwrap();
1932
1933        let resp = handle_muxspect_conversations(State(state)).await.into_response();
1934        assert_eq!(resp.status(), StatusCode::OK);
1935        let body = json_body(resp).await;
1936        let agents = body["agents"].as_array().expect("agents array");
1937        let entry = agents
1938            .iter()
1939            .find(|a| a["name"] == agent_id)
1940            .expect("registered agent should appear in the listing");
1941        assert_eq!(entry["tier"], "host");
1942        // No filestore content written for this block in this test — a
1943        // missing preview is the correct, non-error result (see
1944        // last_line_preview's own doc comment), not something this test
1945        // should treat as a failure.
1946        assert_eq!(entry["last_message_preview"], serde_json::Value::Null);
1947    }
1948
1949    /// Minimal, non-archived `Block` row so `read_session_output` takes its
1950    /// FileStore-read path — matches the pattern
1951    /// `session_archive.rs`'s own tests use, just without the extra
1952    /// archival-specific meta this module's read path never inspects.
1953    fn insert_bare_block(
1954        mstore: &std::sync::Arc<crate::backend::storage::store::Store>,
1955        block_id: &str,
1956    ) {
1957        use crate::backend::obj::Block;
1958        let mut block = Block {
1959            oid: block_id.to_string(),
1960            parentoref: String::new(),
1961            version: 1,
1962            runtimeopts: None,
1963            stickers: None,
1964            meta: Default::default(),
1965            subblockids: None,
1966        };
1967        mstore.insert(&mut block).expect("mstore insert");
1968    }
1969
1970    #[test]
1971    fn last_line_preview_and_activity_returns_last_non_blank_line() {
1972        let filestore = std::sync::Arc::new(FileStore::open_in_memory().unwrap());
1973        let mstore = std::sync::Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
1974        let block_id = uuid::Uuid::new_v4().to_string();
1975        filestore
1976            .make_file(&block_id, "output", crate::backend::storage::filestore::FileMeta::default(), crate::backend::storage::filestore::FileOpts::default())
1977            .expect("make_file");
1978        filestore
1979            .append_data(&block_id, "output", b"first line\n\nlast line\n")
1980            .expect("append_data");
1981        insert_bare_block(&mstore, &block_id);
1982
1983        let (preview, activity_ms) = last_line_preview_and_activity(&mstore, &filestore, &block_id);
1984        assert_eq!(preview, Some("last line".to_string()));
1985        // Fast path (live FileStore file present) — a real write timestamp
1986        // must come back, not None, per codex P2 on PR #2715.
1987        assert!(activity_ms.is_some());
1988    }
1989
1990    #[test]
1991    fn last_line_preview_and_activity_truncates_long_lines() {
1992        let filestore = std::sync::Arc::new(FileStore::open_in_memory().unwrap());
1993        let mstore = std::sync::Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
1994        let block_id = uuid::Uuid::new_v4().to_string();
1995        let long_line = "x".repeat(PREVIEW_MAX_CHARS + 50);
1996        filestore
1997            .make_file(&block_id, "output", crate::backend::storage::filestore::FileMeta::default(), crate::backend::storage::filestore::FileOpts::default())
1998            .expect("make_file");
1999        filestore
2000            .append_data(&block_id, "output", format!("{long_line}\n").as_bytes())
2001            .expect("append_data");
2002        insert_bare_block(&mstore, &block_id);
2003
2004        let (preview, _) = last_line_preview_and_activity(&mstore, &filestore, &block_id);
2005        let preview = preview.unwrap();
2006        assert_eq!(preview.chars().count(), PREVIEW_MAX_CHARS + 1); // +1 for the trailing "…"
2007        assert!(preview.ends_with('…'));
2008    }
2009
2010    #[test]
2011    fn last_line_preview_and_activity_returns_none_for_missing_block() {
2012        let filestore = std::sync::Arc::new(FileStore::open_in_memory().unwrap());
2013        let mstore = std::sync::Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
2014        let (preview, activity_ms) = last_line_preview_and_activity(&mstore, &filestore, "no-such-block");
2015        assert_eq!(preview, None);
2016        assert_eq!(activity_ms, None);
2017    }
2018
2019    /// `flatten_layout_nodes` is what `muxspect layout` renders from, so its
2020    /// shape is the contract. Covers the cross-split arrangement the layout
2021    /// fixes (#2848/#2850/#2855) came from: a Row nested inside a Column.
2022    #[test]
2023    fn flatten_layout_nodes_reports_depth_path_and_effective_minimize() {
2024        use agentmux_common::{FlexDirection, LayoutNode, LayoutNodeData};
2025
2026        fn leaf(id: &str, block: &str, minimized: bool) -> LayoutNode {
2027            let mut n = LayoutNode {
2028                id: id.to_string(),
2029                flex_direction: FlexDirection::Row,
2030                size: 10.0,
2031                children: Vec::new(),
2032                data: Some(LayoutNodeData {
2033                    block_id: block.to_string(),
2034                    ..Default::default()
2035                }),
2036                ..Default::default()
2037            };
2038            n.minimized = minimized;
2039            n
2040        }
2041
2042        // Column[ top, Row[ A(min), B(min) ], bottom ]
2043        let inner = LayoutNode {
2044            id: "inner".into(),
2045            flex_direction: FlexDirection::Row,
2046            size: 10.0,
2047            children: vec![leaf("a", "blk-a", true), leaf("b", "blk-b", true)],
2048            data: None,
2049            ..Default::default()
2050        };
2051        let root = LayoutNode {
2052            id: "root".into(),
2053            flex_direction: FlexDirection::Column,
2054            size: 10.0,
2055            children: vec![leaf("top", "blk-top", false), inner, leaf("bot", "blk-bot", false)],
2056            data: None,
2057            ..Default::default()
2058        };
2059
2060        let mut out = Vec::new();
2061        flatten_layout_nodes(&root, 0, "", &mut out);
2062
2063        // Flat, pre-order, one entry per node.
2064        assert_eq!(out.len(), 6);
2065        assert_eq!(out[0]["id"], "root");
2066        assert_eq!(out[0]["depth"], 0);
2067        assert_eq!(out[0]["kind"], "branch");
2068        assert_eq!(out[0]["flex_direction"], "column");
2069
2070        // Index path is positional, so a reader can locate a node in the tree.
2071        assert_eq!(out[1]["path"], "0");
2072        assert_eq!(out[2]["path"], "1");
2073        assert_eq!(out[3]["path"], "1.0");
2074        assert_eq!(out[3]["depth"], 2);
2075
2076        // The inner Row is a BRANCH with no minimized flag of its own, but is
2077        // effectively minimized because every leaf under it is — the state
2078        // that drives chip geometry, and invisible from `locked` alone. This
2079        // is the distinction the cross-split bugs turned on.
2080        assert_eq!(out[2]["id"], "inner");
2081        assert_eq!(out[2]["locked"], false);
2082        assert_eq!(out[2]["effectively_minimized"], true);
2083        assert_eq!(out[2]["child_count"], 2);
2084
2085        // Leaves carry their block id; the minimized ones report locked.
2086        assert_eq!(out[3]["block_id"], "blk-a");
2087        assert_eq!(out[3]["locked"], true);
2088        assert_eq!(out[1]["locked"], false);
2089        assert_eq!(out[1]["effectively_minimized"], false);
2090    }
2091
2092    #[test]
2093    fn truncate_preview_is_shared_by_host_and_cross_channel_paths() {
2094        // Pins the fix for codex P2 on PR #2715 (cross-channel previews
2095        // originally skipped truncation entirely) at the unit-test level
2096        // — the handler-level concurrent-fetch behavior itself needs a
2097        // live second instance to exercise end-to-end, out of reach for
2098        // this module's test harness.
2099        let long = "y".repeat(PREVIEW_MAX_CHARS + 10);
2100        let truncated = truncate_preview(&long);
2101        assert_eq!(truncated.chars().count(), PREVIEW_MAX_CHARS + 1);
2102        assert!(truncated.ends_with('…'));
2103
2104        let short = "short line";
2105        assert_eq!(truncate_preview(short), short);
2106    }
2107}