Skip to main content

agentmux_srv/server/app_api/
mod.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! MuxAPI — high-level commands for programmatic control of AgentMux.
5//!
6//! These commands orchestrate multiple low-level operations (CreateBlock, SetMeta,
7//! ControllerResync) behind stable, intent-based interfaces. Callers express what
8//! they want ("open an agent pane with AgentX"), not how to do it.
9
10use std::sync::Arc;
11
12use base64::Engine;
13use serde_json::json;
14
15use crate::backend::blockcontroller;
16use crate::backend::obj::{self, Block, Tab, Workspace, MetaMapType};
17use crate::backend::providers;
18use crate::backend::rpc::engine::WshRpcEngine;
19use crate::backend::rpc_types::*;
20use crate::backend::session_archive;
21use crate::backend::storage::store::{Store, AgentContent, AgentDefinition, AgentInstance};
22use crate::backend::storage::identities::IdentityAccount;
23use crate::backend::storage::bundles::Bundle;
24
25use super::AppState;
26
27pub(crate) mod agent_attach;
28mod editor_pick;
29#[cfg(test)]
30mod agent_config_parity_tests;
31pub(crate) mod agent_lifecycle;
32pub(crate) mod agent_mute_quiet;
33pub(crate) mod agent_watch;
34#[cfg(test)]
35mod agent_attach_tests;
36#[cfg(test)]
37mod agent_one_pane_tests;
38pub(crate) mod agent_block;
39pub(crate) mod agent_reconcile;
40pub(crate) mod agent_config_render;
41pub(crate) mod agent_open;
42mod agent_open_steps;
43#[cfg(test)]
44#[path = "tests/agent_open_steps_tests.rs"]
45mod agent_open_steps_tests;
46#[cfg(test)]
47#[path = "tests/agent_open_shared_folder_tests.rs"]
48mod agent_open_shared_folder_tests;
49pub(crate) mod agent_open_many;
50pub(crate) mod agent_open_remote;
51/// Re-exported for `server/mod.rs`'s `POST /api/v1/agent/open` handler (the
52/// `OpenAgent` MCP tool's backing route) — the HTTP surface must share the
53/// RPC path's exact implementation, including its AGENT_OPEN_LOCKS TOCTOU
54/// serialization. See REPORT_AGENT_OPEN_API_GAP_2026_09_06.md.
55pub(crate) use agent_open::open_agent_impl;
56/// The `Agents` `spawn` action's route (SPEC_AGENT_WORKERS_2026_10_15.md).
57pub(crate) mod agent_migrate_ids;
58pub(crate) mod agent_rotate_token;
59pub(crate) mod agent_seats;
60pub(crate) mod agent_export;
61pub(crate) mod agent_handover;
62pub(crate) mod agent_move;
63pub(crate) mod agent_rename;
64pub(crate) mod agent_definition;
65pub(crate) mod agent_model;
66mod agent_runtime_pick;
67pub(crate) mod agent_spend;
68pub(crate) mod agent_routes;
69pub(crate) mod agent_history_reclaim;
70pub(crate) mod workspace_stop;
71pub(crate) mod agent_spawn;
72// pub(crate): `server/mod.rs`'s `/agentmux/agent/stop` handler (the
73// cross-channel bulk-stop forward target,
74// SPEC_FLEET_BULK_STOP_CROSS_CHANNEL_2026_08_22.md) calls
75// `stop_one_agent_block` directly — same function `fleet_bulk_stop_impl`
76// already uses for a LOCAL target, reused rather than duplicated for a
77// forwarded one.
78pub(crate) mod agent_context;
79pub(crate) mod agent_env;
80pub(crate) mod agent_io;
81mod agent_define;
82pub(crate) mod container_caches;
83pub(crate) mod container_limits;
84pub(crate) mod container_update;
85/// Re-exported so the human-facing creation/edit RPC handlers
86/// (`server::agent_handlers::template`/`core`) can reuse the same
87/// vendor-base-url validation `agent.define` already uses, instead of
88/// duplicating it.
89pub(crate) use agent_define::{check_provider_unchanged, check_volumes, validate_vendor_base_url};
90// pub(crate): `server/mod.rs`'s `POST /api/v1/agent/pane/close` handler (the
91// `ClosePane` MCP tool's backing route) calls `pane::handle_close_pane`
92// directly, same as `fleet`'s exposure just below.
93pub(crate) mod pane;
94pub(crate) mod floater_place;
95pub(crate) mod agent_tab_default;
96pub(crate) mod agent_own_tab;
97#[cfg(test)]
98#[path = "tests/agent_tab_default_tests.rs"]
99mod agent_tab_default_tests;
100mod pane_open_tab;
101mod open_updates;
102mod pane_open_steps;
103#[cfg(test)]
104#[path = "tests/pane_open_steps_tests.rs"]
105mod pane_open_steps_tests;
106#[cfg(test)]
107#[path = "tests/pane_meta_tests.rs"]
108mod pane_meta_tests;
109mod pane_singleton;
110// pub(crate): `server/mod.rs`'s `POST /api/v1/agent/dev_server/register`
111// handler (the `RegisterDevServer` MCP tool's backing route) calls
112// `dev_server::handle_register_dev_server` directly, same pattern as
113// `pane`'s `handle_close_pane` just above.
114pub(crate) mod dev_server;
115// pub(crate): `agentmux-mcp doctor`'s routes, in `routes.rs`.
116pub(crate) mod mcp_health;
117// pub(crate): the viewer feed reads transcripts through `read_range`.
118pub(crate) mod blockfile;
119mod open_tail;
120pub(crate) mod session;
121mod identity;
122pub(crate) mod bundle;
123mod memory;
124pub(crate) mod dream_exec;
125pub(crate) mod dream_run;
126mod global_memory;
127// MuxAPI bodies live with the submodule that registers them; these
128// re-exports keep every `app_api::…` path unchanged.
129pub use pane::{open_pane};
130mod pane_tabs;
131pub(crate) use pane_tabs::{activate_tab, move_tab, move_tabs, remove_tab};
132pub use agent_define::{allocate_agent_workdir};
133pub(crate) use agent_define::{agent_define_core};
134pub(crate) use identity::{identity_self_accounts_impl, identity_account_validate_stored_impl};
135pub(crate) use bundle::{bundle_list_impl, bundle_get_impl, bundle_self_get_impl};
136pub(crate) use bundle::SelfOwner;
137pub(crate) use global_memory::GlobalMemoryWriteProvenance;
138pub(crate) use memory::MemoryWriteProvenance;
139pub(crate) use memory::{memory_list_impl, memory_read_impl, memory_write_impl, memory_history_impl, memory_diff_impl, memory_revert_impl};
140pub(crate) use global_memory::{append_to_global_order, removed_global_entries, global_memory_write_impl, global_memory_write_inner, global_memory_write_with_reach_impl, global_memory_reach_impl, global_memory_reaches, global_memory_list_impl, global_memory_read_impl, global_memory_remove_impl, global_memory_history_impl, global_memory_diff_impl, bundle_version_diff, global_memory_revert_impl};
141mod skill;
142mod mcp;
143mod mcp_actor;
144mod bookmarks;
145mod browser_profiles;
146mod browser_grants;
147mod pins;
148pub(crate) mod workspace_import;
149pub(crate) use browser_profiles::ensure_agent_profile as browser_ensure_agent_profile;
150pub(crate) use browser_profiles::list as browser_profiles_list;
151mod layout;
152mod other_build_layouts;
153mod browser_start_page;
154mod voice;
155pub(crate) mod fleet;
156mod fleet_check_limits;
157mod fleet_forward;
158mod fleet_pacing;
159mod fleet_result;
160mod supervisor;
161mod attachments;
162pub(crate) mod connections;
163pub(crate) mod aws_credentials;
164pub(crate) mod aws_grants;
165pub(crate) mod github_token;
166pub(crate) mod pr_merge;
167pub(crate) mod push_scan;
168pub(crate) mod app_update;
169pub(crate) mod desktop;
170pub(crate) mod desktop_group;
171pub(crate) mod viewer;
172mod input_history;
173mod presence;
174pub(crate) mod client_terms;
175pub(crate) mod folder_overlap;
176pub(crate) mod folder_overlap_ask;
177pub(crate) mod pin_ask;
178pub(crate) mod agent_quit;
179pub(crate) mod remote_pane_view;
180pub(crate) mod remote_panes;
181pub(crate) mod tower_pane;
182mod gpu_panel;
183pub(crate) mod record_read;
184mod blockstats;
185mod history_agents;
186pub(in crate::server) mod audit_query;
187mod history_usage;
188mod shells;
189pub(crate) mod kanban;
190mod kanban_tokens;
191mod kanban_rollup;
192mod jobs;
193mod jobs_edit;
194pub(crate) mod connectivity;
195pub(crate) mod layout_intent;
196
197/// Register all MuxAPI handlers on the RPC engine.
198pub fn register_app_api_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
199    agent_open::register(engine, state);
200    agent_io::register(engine, state);
201    agent_define::register(engine, state);
202    pane::register(engine, state);
203    blockfile::register(engine, state);
204    open_tail::register(engine, state);
205    session::register(engine, state);
206    identity::register(engine, state);
207    bundle::register(engine, state);
208    memory::register(engine, state);
209    skill::register(engine, state);
210    mcp::register(engine, state);
211    bookmarks::register(engine, state);
212    browser_profiles::register(engine, state);
213    crate::server::browser_signin_offer::register(engine, state);
214    crate::server::browser_signin_fill::register(engine, state);
215    crate::server::browser_signin_list::register(engine, state);
216    crate::server::browser_signup::register(engine, state);
217    crate::server::browser_signin::register(engine);
218    pins::register(engine, state);
219    workspace_import::register(engine, state);
220    browser_grants::register(engine, state);
221    layout::register(engine, state);
222    other_build_layouts::register(engine, state);
223    layout_intent::register(engine, state);
224    browser_start_page::register(engine, state);
225    voice::register(engine, state);
226    fleet::register(engine, state);
227    supervisor::register(engine, state);
228    attachments::register(engine, state);
229    connections::register(engine, state);
230    viewer::register(engine, state);
231    input_history::register(engine, state);
232    app_update::register(engine, state);
233    desktop::register(engine, state);
234    presence::register(engine, state);
235    client_terms::register(engine, state);
236    folder_overlap::register(engine, state);
237    agent_quit::register(engine, state);
238    tower_pane::register(engine, state);
239    remote_panes::register(engine, state);
240    gpu_panel::register(engine, state);
241    blockstats::register(engine, state);
242    history_agents::register(engine, state);
243    audit_query::register(engine, state);
244    history_usage::register(engine, state);
245    shells::register(engine, state);
246    kanban::register(engine, state);
247    jobs::register(engine, state);
248    jobs_edit::register(engine, state);
249    crate::server::account_episodes::register(engine, state);
250    crate::server::jekt_held_summary::register(engine, state);
251    crate::server::prep::register(engine, state);
252    agent_model::register(engine, state);
253    agent_spend::register(engine, state);
254    connectivity::register(engine);
255}
256
257#[cfg(test)]
258#[path = "tests/global_memory_impl_tests.rs"]
259mod global_memory_impl_tests;
260#[cfg(test)]
261#[path = "tests/global_memory_version_impl_tests.rs"]
262mod global_memory_version_impl_tests;
263#[cfg(test)]
264#[path = "tests/memory_version_impl_tests.rs"]
265mod memory_version_impl_tests;
266#[cfg(test)]
267#[path = "tests/memory_error_kind_tests.rs"]
268mod memory_error_kind_tests;
269#[cfg(test)]
270#[path = "tests/global_memory_error_kind_tests.rs"]
271mod global_memory_error_kind_tests;
272#[cfg(test)]
273#[path = "tests/owner_error_kind_tests.rs"]
274mod owner_error_kind_tests;
275#[cfg(test)]
276#[path = "tests/accounts_error_kind_tests.rs"]
277mod accounts_error_kind_tests;
278
279// ---------------------------------------------------------------------------
280// Shared helpers used by submodules (via `use super::*`)
281// ---------------------------------------------------------------------------
282/// If the agent's GLOBAL transcript zone (`agent:<defId>:current`) has
283/// `output`, return `(global_store, agent_zone)` — preferred even when this
284/// channel's local `output` is non-empty. Returns `None` when the block isn't
285/// agent-anchored or is archived, there's no global store, or the global zone
286/// is empty — callers then read the per-channel store keyed by `block_id`.
287///
288/// Only the agent `output` stream is globalized; every other file stays local.
289pub(super) fn global_output_source(
290    _per_channel: &Arc<crate::backend::storage::filestore::FileStore>,
291    global: &Option<Arc<crate::backend::storage::filestore::FileStore>>,
292    mstore: &Arc<crate::backend::storage::store::Store>,
293    block_id: &str,
294    filename: &str,
295) -> Option<(Arc<crate::backend::storage::filestore::FileStore>, String)> {
296    if filename != crate::backend::agent_session::OUTPUT_FILE {
297        return None;
298    }
299    let gfs = global.as_ref()?;
300    let block = mstore.get::<Block>(block_id).ok().flatten()?;
301    let archived = block
302        .meta
303        .get(crate::backend::session_archive::META_SESSION_ARCHIVED_AT)
304        .and_then(|v| v.as_i64())
305        .map(|v| v > 0)
306        .unwrap_or(false);
307    if archived {
308        return None;
309    }
310    let zone = crate::backend::agent_session::agent_zone_for_block_meta(&block.meta)?;
311    // A zone found corrupt is not read again in this process: the per-channel
312    // copy answers (`damage`).
313    if crate::backend::transcript::damage::is_damaged(&zone) {
314        return None;
315    }
316    match gfs.stat(&zone, filename) {
317        Ok(Some(ref wf)) if wf.size > 0 => Some((gfs.clone(), zone)),
318        Err(e) => {
319            crate::backend::transcript::damage::note_corrupt(&zone, "tail read", &e);
320            None
321        }
322        _ => None,
323    }
324}
325
326/// Whether the shared-store zone of the agent `block_id` belongs to was found corrupt in this
327/// process. The block's history reads then come from its own copy, which holds only what this
328/// block wrote, so the pane tells the user earlier history may be missing.
329pub(super) fn history_damaged(mstore: &Arc<crate::backend::storage::store::Store>, block_id: &str) -> bool {
330    let Some(block) = mstore.get::<Block>(block_id).ok().flatten() else { return false };
331    let archived = block
332        .meta
333        .get(crate::backend::session_archive::META_SESSION_ARCHIVED_AT)
334        .and_then(|v| v.as_i64())
335        .is_some_and(|v| v > 0);
336    !archived
337        && crate::backend::agent_session::agent_zone_for_block_meta(&block.meta)
338            .is_some_and(|zone| crate::backend::transcript::damage::is_damaged(&zone))
339}
340
341/// Exact non-blank line count of the `output` file in `zone`, computed via the
342/// same streaming index builder `read_range` uses (so the two endpoints always
343/// agree). Returns `Some(0)` for an empty file, `None` on read failure.
344///
345/// Reuses `output.idx` when its `covered_size` header already matches the
346/// current `output` size — same freshness check
347/// `register_blockfile_read_range` (`blockfile.rs`) already does — instead of
348/// unconditionally rescanning the entire history on every call. Without this,
349/// every pane open for an agent with any global-zone history pays a full
350/// O(history size) rescan even when nothing has changed since the index was
351/// last built.
352pub(super) fn global_zone_line_count(
353    gfs: &Arc<crate::backend::storage::filestore::FileStore>,
354    zone: &str,
355) -> Option<u64> {
356    use crate::backend::blockcontroller::shell::{extend_output_idx, output_index};
357
358    // `output` and its index from one database snapshot: sizes, header and
359    // generation label of the same moment, whatever another srv instance is
360    // writing to this shared zone (Codex on #3634).
361    let view = output_index(gfs, zone)?;
362    if view.output_size == 0 {
363        return Some(0);
364    }
365    if let Some(lines) = view.fresh_lines {
366        return Some(lines);
367    }
368
369    // Stale or missing. `extend_output_idx` scans only the appended bytes when
370    // it can anchor on the existing index, and falls back to a full rebuild
371    // when it can't (missing, unreadable, no entries, another generation's, or
372    // `output` shrank).
373    //
374    // The count must stay EXACT. Returning a stale one instead was tried and
375    // is wrong: this feeds `useHistoryPagination`'s tail window
376    // (`offset = total - PAGE_SIZE`), so an undercount silently drops the most
377    // recent history on reopen — codex P1 on PR #2838. Only the COST of
378    // keeping it exact was ever negotiable, which is what the incremental scan
379    // buys: `output` grows continuously for a live agent, so "stale" is the
380    // steady state, and a 30-second line-count poll was driving a full
381    // O(file-size) rescan every time — 37 rebuilds in 19 minutes on a 759 MB
382    // transcript, mean 3168 ms, ~10% permanent duty cycle. See
383    // docs/reports/REPORT_AGENT_PANE_LOAD_RENDER_ARCHITECTURE_2026_08_27.md §5.
384    extend_output_idx(gfs, zone)
385}
386
387/// Resolve a tab ID: use the provided one, or fall back to the first workspace's active tab.
388pub(super) fn resolve_tab_id(mstore: &Store, explicit: Option<&str>) -> Result<String, String> {
389    if let Some(tid) = explicit {
390        return Ok(tid.to_string());
391    }
392
393    // Fall back to first workspace's active tab
394    let workspaces: Vec<Workspace> = mstore.get_all::<Workspace>()
395        .map_err(|e| format!("agent.open: list workspaces: {e}"))?;
396
397    for ws in &workspaces {
398        if !ws.activetabid.is_empty() {
399            return Ok(ws.activetabid.clone());
400        }
401        if let Some(first_tab) = ws.tabids.first() {
402            return Ok(first_tab.clone());
403        }
404    }
405
406    Err("no tabs found in any workspace".to_string())
407}
408
409/// Find an existing agent block in a tab by agent ID.
410pub(super) fn find_agent_block(mstore: &Store, tab_id: &str, agent_id: &str) -> Result<Option<Block>, String> {
411    let tab: Tab = mstore.must_get(tab_id)
412        .map_err(|e| format!("TAB_NOT_FOUND: {e}"))?;
413
414    for block_id in &tab.blockids {
415        if let Ok(Some(block)) = mstore.get::<Block>(block_id) {
416            let block_agent_id = obj::meta_get_string(&block.meta, "agentId", "");
417            // The agent's history reader carries its `agentId` but is not its pane.
418            if block_agent_id == agent_id && !obj::is_history_reader(&block.meta) {
419                return Ok(Some(block));
420            }
421        }
422    }
423    Ok(None)
424}
425
426/// Find which tab a given block currently belongs to, by scanning every
427/// tab's `blockids`. Needed because `resolve_tab_id` only resolves an
428/// explicit tab_id or "the active tab" — neither answers "which tab is MY
429/// OWN block in," which a caller passing its own block id (e.g. an MCP
430/// tool's `split_reference_block_id`) actually needs.
431pub(super) fn resolve_tab_id_for_block(mstore: &Store, block_id: &str) -> Result<String, String> {
432    let tabs: Vec<Tab> = mstore.get_all::<Tab>()
433        .map_err(|e| format!("resolve_tab_id_for_block: list tabs: {e}"))?;
434    for tab in tabs {
435        if tab.blockids.iter().any(|b| b == block_id) {
436            return Ok(tab.oid);
437        }
438    }
439    Err(format!("resolve_tab_id_for_block: block {block_id} not found in any tab"))
440}
441
442/// An Editor pane found in a tab for an agent's open to reuse.
443pub(super) struct EditorFound {
444    pub block: Block,
445    /// It is a background tab of a multi-tab pane: srv switches the pane to it before queueing the
446    /// file, because a tab that is not showing is not mounted and so would never take the file.
447    pub needs_activation: bool,
448    /// Why this one, for the log.
449    pub why: &'static str,
450}
451
452/// An Editor the open names, `block_id` (the `Pane` open `target_id`), in `tab_id`: it must be an Editor on
453/// `connection` that the tab holds.
454pub(super) fn editor_block_named(mstore: &Store, tab_id: &str, block_id: &str, connection: &str) -> Result<EditorFound, String> {
455    let tab: Tab = mstore.must_get(tab_id).map_err(|e| format!("TAB_NOT_FOUND: {e}"))?;
456    let block = mstore
457        .get::<Block>(block_id)
458        .ok()
459        .flatten()
460        .filter(|b| obj::meta_get_string(&b.meta, "view", "") == "editor")
461        .ok_or_else(|| format!("INVALID_ARG: {block_id} is not an Editor pane; target_id takes a block_id from layout whose view is editor"))?;
462    if !same_pane_connection(&obj::meta_get_string(&block.meta, "connection", ""), connection) {
463        return Err(format!("INVALID_ARG: {block_id} is an Editor on another connection than the file's"));
464    }
465    let layout = mstore.must_get::<obj::LayoutState>(&tab.layoutstate).map_err(|e| format!("TAB_NOT_FOUND: {e}"))?;
466    Ok(EditorFound { needs_activation: editor_pick::needs_activation(&layout, block_id), block, why: "named by the caller" })
467}
468
469/// Find the Editor-view block in `tab_id` an agent's open should reuse, on `connection` (its meta
470/// `connection`; absent and `local` are this computer), if any. Direct sibling of `find_agent_block`
471/// above, checking `meta.view == "editor"` instead of `meta.agentId`. An editor on another
472/// connection is never it: its reads and saves go there (remote terminals spec §6.3).
473///
474/// With several, [`editor_pick::choose`] decides, from the pane that asked (`caller`): one the tab
475/// shows ([`shown_block_ids`]) wins, then the nearest to the caller. When none is on screen, any
476/// Editor the tab holds does: a minimized pane, a background tab of a pane stack, or a pane behind a
477/// magnified one. The open then shows it (`showBlockWithoutFocus`, when the editor takes the file),
478/// instead of making a second Editor pane because the first was out of sight.
479pub(super) fn find_editor_block(mstore: &Store, tab_id: &str, connection: &str, caller: Option<&str>) -> Result<Option<EditorFound>, String> {
480    let tab: Tab = mstore.must_get(tab_id)
481        .map_err(|e| format!("TAB_NOT_FOUND: {e}"))?;
482    let Ok(layout) = mstore.must_get::<obj::LayoutState>(&tab.layoutstate) else {
483        return Ok(None);
484    };
485    let Some(root) = &layout.rootnode else { return Ok(None) };
486    let editors: Vec<Block> = member_block_ids(root)
487        .iter()
488        .filter_map(|id| mstore.get::<Block>(id).ok().flatten())
489        .filter(|block| {
490            obj::meta_get_string(&block.meta, "view", "") == "editor"
491                && same_pane_connection(&obj::meta_get_string(&block.meta, "connection", ""), connection)
492        })
493        .collect();
494    let ids: Vec<String> = editors.iter().map(|b| b.oid.clone()).collect();
495    let Some(pick) = editor_pick::choose(&layout, caller, &ids) else { return Ok(None) };
496    Ok(editors.into_iter().find(|b| b.oid == pick.block_id).map(|block| EditorFound {
497        needs_activation: editor_pick::needs_activation(&layout, &block.oid),
498        block,
499        why: pick.why,
500    }))
501}
502
503/// Every block a layout holds: each pane's whole stack, shown or not.
504fn member_block_ids(root: &agentmux_common::LayoutNode) -> Vec<String> {
505    fn walk(node: &agentmux_common::LayoutNode, out: &mut Vec<String>) {
506        if node.children.is_empty() {
507            if let Some(data) = &node.data {
508                if data.block_stack.is_empty() {
509                    if !data.block_id.is_empty() {
510                        out.push(data.block_id.clone());
511                    }
512                } else {
513                    out.extend(data.block_stack.iter().cloned());
514                }
515            }
516            return;
517        }
518        for child in &node.children {
519            walk(child, out);
520        }
521    }
522    let mut out = Vec::new();
523    walk(root, &mut out);
524    out
525}
526
527/// The blocks a tab's layout shows: each pane's active member (the tab
528/// in front of its stack), leaving out minimized panes, and every pane
529/// but the magnified one while one is magnified. A file pushed into an
530/// editor the user can't see would look like nothing happened
531/// (SPEC_AGENT_PANE_TOOL_PEEK_ON_LINE_AND_MD_OPEN_IN_EDITOR_2026_10_11.md §2.2).
532pub(super) fn shown_block_ids(layout: &obj::LayoutState) -> Vec<String> {
533    fn walk(node: &agentmux_common::LayoutNode, magnified: &str, out: &mut Vec<String>) {
534        if crate::backend::layout::is_effectively_minimized(node) {
535            return;
536        }
537        if node.children.is_empty() {
538            if let Some(data) = &node.data {
539                if !data.block_id.is_empty() && (magnified.is_empty() || magnified == node.id) {
540                    out.push(data.block_id.clone());
541                }
542            }
543            return;
544        }
545        for child in &node.children {
546            walk(child, magnified, out);
547        }
548    }
549    let mut out = Vec::new();
550    if let Some(root) = &layout.rootnode {
551        walk(root, &layout.magnifiednodeid, &mut out);
552    }
553    out
554}
555
556/// Whether two panes' connections are one: absent and `local` are this
557/// computer; otherwise the same host however it is spelled.
558pub(super) fn same_pane_connection(a: &str, b: &str) -> bool {
559    let norm = |c: &str| {
560        let c = c.trim();
561        if c.is_empty() || c == "local" { String::new() } else { c.to_string() }
562    };
563    let (a, b) = (norm(a), norm(b));
564    if a.is_empty() || b.is_empty() {
565        return a == b;
566    }
567    crate::backend::remote::conn::same_connection(&a, &b)
568}
569
570// ---------------------------------------------------------------------------
571// S1 enforcement helper
572// ---------------------------------------------------------------------------
573
574/// S1: the caller may only act on itself.
575///
576/// `ctx.agent_id` is stamped at `bus:register` and is the agent's slug;
577/// `req_agent_id` is whatever the request named. Both are compared **as
578/// canonical `db_agents.id`s** when they are not already byte-identical, so a
579/// caller that authenticates with its slug and names itself by id (or by a
580/// differently-cased slug) is recognised as itself.
581///
582/// **Both sides resolve, or neither does.** Phase 4 of
583/// `SPEC_CANONICAL_AGENT_ID_MIGRATION_2026_09_21.md` §6 proposed stamping the
584/// resolved id into `RpcContext` at registration instead, and flags the hazard
585/// itself: resolving one side of this equality while the other stays a slug
586/// silently denies **every** caller, turning an authz boundary into a
587/// permanent outage that no test of the allow path would catch. Resolving both
588/// here, at the single point of comparison, has no such window — there is no
589/// deploy ordering in which one side has migrated and the other has not.
590///
591/// The byte-equality fast path is deliberate and load-bearing: it is the
592/// overwhelmingly common case, it costs no store lookup, and it makes this
593/// function's behaviour for existing callers *identical* to the pre-migration
594/// version. Resolution only ever runs where the old code would already have
595/// returned `FORBIDDEN`, so this can admit calls that used to be rejected but
596/// can never reject one that used to be admitted.
597///
598/// Admitting more is safe here precisely because resolution is per-input and
599/// fails closed: two different inputs resolve to one id only when they name
600/// one agent, and an ambiguous slug (two agents, one slug) resolves to
601/// `Err` on both sides — so a collision denies rather than granting.
602///
603/// A failed resolution is reported as `agent_id mismatch`, never "no such
604/// agent": whether some other agent exists is not something an unauthorised
605/// caller should be able to probe through this boundary.
606/// Takes the store rather than `&AppState` because the handlers do not agree
607/// on what they capture — some clone the whole state into the closure, others
608/// clone `mstore` alone — and a borrowed `&AppState` cannot escape into a
609/// `'static` future.
610pub(crate) fn check_s1(
611    store: &crate::backend::storage::store::Store,
612    ctx: &RpcContext,
613    req_agent_id: &str,
614) -> Result<(), String> {
615    check_s1_resolved(store, &ctx.agent_id, req_agent_id)
616}
617
618/// `check_s1`'s decision over plain strings, so it can be tested without
619/// constructing an `RpcContext`.
620fn check_s1_resolved(
621    store: &crate::backend::storage::store::Store,
622    ctx_agent_id: &str,
623    req_agent_id: &str,
624) -> Result<(), String> {
625    if ctx_agent_id.is_empty() {
626        return Err("FORBIDDEN: unauthenticated agent connection".to_string());
627    }
628    if ctx_agent_id == req_agent_id {
629        return Ok(());
630    }
631    let mismatch = || "FORBIDDEN: agent_id mismatch".to_string();
632    let caller = crate::backend::agent_resolve::resolve_agent_id(store, ctx_agent_id)
633        .map_err(|_| mismatch())?;
634    let target =
635        crate::backend::agent_resolve::resolve_agent_id(store, req_agent_id).map_err(|_| mismatch())?;
636    if caller != target {
637        return Err(mismatch());
638    }
639    Ok(())
640}
641
642/// Resolve an S1-authenticated agent id (the slug — AGENTMUX_AGENT_ID /
643/// bus:register id, e.g. "Agent3") to the agent's DEFINITION id, which is
644/// what `db_agent_identity_links.agent_id` stores (== `AgentDefinition.id`;
645/// see `identity/resolver/inject.rs::resolve_bindings_for_instance`).
646///
647/// Every link-table operation reached from MuxAPI must go through
648/// this: MuxAPI callers authenticate with the slug, but writing the slug
649/// into the link table either trips the per-channel schema's
650/// `FOREIGN KEY (agent_id) REFERENCES db_agents(id)` (v30, #3088 — was
651/// `db_agent_definitions(id)`; a definition id still always satisfies it,
652/// since every definition has a `db_agents` mirror at the same id) (loud
653/// "FOREIGN KEY constraint failed" — the id_store fallback path when the
654/// 0011 shared-store backfill hasn't applied), or — on the shared store,
655/// whose links table carries no agent_id FK — silently writes a row keyed
656/// by slug that the resolver (which reads by definition id) can never
657/// match. Reads have the mirror-image bug: listing links by slug always
658/// returns empty, so ownership checks reject and unlinks no-op.
659///
660/// A caller that already holds a definition id passes through unchanged
661/// (verified against `agent_def_get`), so internal non-S1 callers of the
662/// shared `*_impl` helpers stay valid.
663pub(super) fn resolve_agent_definition_id(
664    state: &AppState,
665    agent_id: &str,
666) -> Result<String, String> {
667    // The three tiers this used to spell out inline (db_agents by slug, then
668    // by id, then the registry) are now `agent_resolve`'s, shared with
669    // `resolve_agent_uuid`. The registry tier in particular is load-bearing and
670    // was won the hard way — reagentx P1 on PR #2428 (round 4): the common case
671    // is a live agent with no `db_agents` row at all (launching an agent does
672    // not create one), so `identity.self.accounts`/`IdentityAccounts` stayed
673    // live-broken for registry-only agents even after `instance_get_by_slug`
674    // existed. See `agent_resolve::resolve_agent_id`.
675    crate::backend::agent_resolve::resolve_agent_id(&state.mstore, agent_id)
676}
677
678// Current unix time in milliseconds (0 if the clock is before the epoch).
679pub(super) use agentmux_common::time::now_ms;
680
681/// Parse + validate a saved per-agent `ui:zoom` content blob for seeding a new
682/// agent block's `term:zoom`. Returns `Some(z)` only for a parseable,
683/// non-default (≠ 1.0), in-[0.5, 2.0] zoom (the range the frontend enforces in
684/// term.tsx); anything else (default, out of range, garbage) returns `None` so
685/// the new block opens at the default 1.0. See SPEC_AGENT_ZOOM_PERSISTENCE §4.2.
686pub(super) fn parse_seed_zoom(raw: &str) -> Option<f64> {
687    let z = raw.trim().parse::<f64>().ok()?;
688    if (z - 1.0).abs() > f64::EPSILON && (0.5..=2.0).contains(&z) {
689        Some(z)
690    } else {
691        None
692    }
693}
694
695#[cfg(test)]
696#[path = "tests/cross_channel_tests.rs"]
697mod cross_channel_tests;
698
699
700#[cfg(test)]
701#[path = "tests/pane_open_reducer_tests.rs"]
702mod pane_open_reducer_tests;
703
704#[cfg(test)]
705#[path = "tests/floater_open_tests.rs"]
706mod floater_open_tests;
707
708#[cfg(test)]
709#[path = "tests/open_updates_tests.rs"]
710mod open_updates_tests;
711
712#[cfg(test)]
713#[path = "tests/stop_agents_tests.rs"]
714mod stop_agents_tests;
715
716#[cfg(test)]
717#[path = "tests/agent_zoom_seed_tests.rs"]
718mod agent_zoom_seed_tests;
719
720#[cfg(test)]
721#[path = "tests/bundle_upsert_input_tests.rs"]
722mod bundle_upsert_input_tests;
723
724// SPEC_AGENT_PANE_HISTORY_ALIGNMENT_2026_08_05.md follow-up: `PresetGet`
725// self-mode (backed by `bundle_self_get_impl`) only ever checked the local
726// `db_agents` table via `instance_get_by_slug`. A live agent that only
727// exists in the global named-agent registry (the common case — launching
728// an agent does not create a `db_agents` row, see issue #1836, already
729// handled the same way by `native_memory_handlers::memory_dir_for_agent`)
730// fell through to `instance: None` and silently returned the generic
731// blank/vanilla preset, with nothing to distinguish it from an agent that
732// genuinely has no bundle bound. Confirmed live against a real registry-only
733// agent named "AgentY": `PresetGet` returned `is_blank: true` even though
734// the registry's own `memory_id` was set.
735#[cfg(test)]
736#[path = "tests/bundle_self_get_registry_fallback_tests.rs"]
737mod bundle_self_get_registry_fallback_tests;
738
739#[cfg(test)]
740#[path = "tests/identity_self_accounts_tests.rs"]
741mod identity_self_accounts_tests;
742
743#[cfg(test)]
744#[path = "tests/s1_tests.rs"]
745mod s1_tests;
746
747#[cfg(test)]
748#[path = "tests/self_owner_tests.rs"]
749mod self_owner_tests;
750
751#[cfg(test)]
752#[path = "tests/agent_io_open_wire_tests.rs"]
753mod agent_io_open_wire_tests;
754
755#[cfg(test)]
756#[path = "tests/agent_send_tests.rs"]
757mod agent_send_tests;
758
759#[cfg(test)]
760#[path = "tests/block_transcript_write_tests.rs"]
761mod block_transcript_write_tests;