Skip to main content

agentmux_srv/server/service/
mod.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! HTTP `/agentmux/service` dispatcher, split into concern-based submodules.
5//!
6//! * [`object`] / [`client`] / [`window`] / [`workspace`] / [`misc`] — the
7//!   per-service RPC handlers `dispatch_service` routes to.
8//! * [`introspect`] — agent-facing read-only tree snapshots + `AgentContext`
9//!   resolution (backs `/api/v1/self`, `/layout`, naming verbs).
10//! * [`object_helpers`] — wave-object read/update/meta primitives.
11//! * [`reducer_helpers`] — reducer dispatch / event publish / compensation.
12//! * [`layout_helpers`] — layout-tree + pending-action writers used by the
13//!   drag-and-drop / tear-off / redock handlers.
14//!
15//! `pub use` re-exports keep every external call site
16//! (`crate::server::service::…`, `super::service::…`) unchanged.
17
18mod client;
19mod credential;
20pub(crate) use credential::host_caller_allowed;
21mod host_ipc;
22mod introspect;
23pub(crate) mod layout_helpers;
24pub(crate) mod layout_intents;
25#[cfg(test)]
26mod layout_intents_tests;
27#[cfg(test)]
28mod pane_tab_command_tests;
29mod misc;
30pub(crate) mod pane_share;
31mod object;
32#[cfg(test)]
33mod object_tests;
34mod stop_requests;
35pub(crate) mod object_helpers;
36pub(crate) mod reducer_helpers;
37pub(crate) mod session_restore;
38pub(crate) mod session_other_builds;
39pub(crate) mod session_closed;
40pub(crate) mod session_slots;
41pub(crate) mod session_windows;
42pub(crate) use session_windows::{forget_windows_left_by_quit, live_windows, open_workspace_ids};
43pub(crate) mod user_workspace;
44pub(crate) mod user_workspace_files;
45mod user_workspace_switch;
46mod tab_lifecycle;
47pub(crate) mod pin;
48mod tab_move;
49mod redock_origin;
50mod tear_off;
51mod window;
52mod window_close;
53mod window_create;
54mod window_inherit;
55mod window_mutate;
56mod window_query;
57mod workspace;
58mod workspace_lifecycle;
59
60use axum::{extract::State, response::Json, Extension};
61
62use crate::backend::service::WebReturnType;
63
64use super::AppState;
65use crate::backend::service::WebCallType;
66
67// ---- Public surface re-exports (external call sites depend on these) ----
68
69pub(crate) use introspect::{
70    agent_layout, agent_tabs, agent_windows, agent_workspaces, resolve_agent_context,
71    workspace_id_for_tab, AgentContext,
72};
73pub(crate) use layout_helpers::setup_torn_off_block_layout;
74pub(crate) use object_helpers::{schedule_agent_zoom_mirror, update_object_meta};
75pub(crate) use reducer_helpers::{create_block_in_tab, create_via_reducer, dispatch_to_reducer, publish_events};
76pub(crate) use tab_lifecycle::handle_create_tab;
77pub(crate) use tear_off::{handle_redock_floating_pane, handle_tear_off_block};
78
79pub(super) async fn handle_service(
80    State(state): State<AppState>,
81    caller: Option<Extension<super::caller::Caller>>,
82    body: axum::body::Bytes,
83) -> Json<WebReturnType> {
84    let call: WebCallType = match serde_json::from_slice(&body) {
85        Ok(c) => c,
86        Err(e) => return Json(WebReturnType::error(format!("invalid request body: {e}"))),
87    };
88    let uid = caller.as_ref().and_then(|Extension(caller)| caller.uid());
89    Json(run_service_call_as(&state, &call, uid).await)
90}
91
92/// Dispatch a service call and broadcast any resulting `MuxObjUpdate`s to the
93/// event bus — the shared core of `handle_service`. Factored out so the typed
94/// first-class agent-API verbs (e.g. `/api/v1/window/name`) get byte-identical
95/// persistence + broadcast to a raw `/agentmux/service` call without
96/// re-implementing it. See SPEC_AGENT_API_FIRST_CLASS_SURFACE_2026_06_17.md.
97pub(crate) async fn run_service_call(state: &AppState, call: &WebCallType) -> WebReturnType {
98    run_service_call_as(state, call, None).await
99}
100
101/// [`run_service_call`] for a request whose agent token names `caller_uid` (`None`: no agent credential).
102pub(crate) async fn run_service_call_as(state: &AppState, call: &WebCallType, caller_uid: Option<&str>) -> WebReturnType {
103    let service_start = std::time::Instant::now();
104    let result = dispatch_service(state, call, caller_uid).await;
105    let elapsed = service_start.elapsed();
106    // debug, not info: fires on every HTTP /agentmux/service call — a
107    // meaningful slice (~10%+) of an unrotated 406 MB launcher-log mirror on
108    // a real machine (SPEC_WIN10_PAGEFILE_OOM_CRASH_2026_06_29 P1). Default
109    // production filter is info, so this is now suppressed unless
110    // RUST_LOG=debug is set; still there for perf debugging on demand.
111    tracing::debug!(
112        "[http-perf] {}.{}: {:.2}ms",
113        call.service,
114        call.method,
115        elapsed.as_secs_f64() * 1000.0,
116    );
117
118    // Broadcast every MuxObjUpdate the handler returned so other
119    // clients (additional windows, test harnesses, etc.) learn about
120    // changes they didn't initiate. The calling HTTP client also gets
121    // `updates` in the response body — this broadcast is for
122    // everybody else on the event bus. Before this, only a handful
123    // of handlers (agent.open, blockcontroller events) broadcast
124    // manually, so an external harness's CreateTab / UpdateObject
125    // were invisible to the frontend.
126    //
127    // One batched frame, not one frame per update: these WS frames also
128    // reach the CALLING renderer, and they land BEFORE the HTTP response
129    // body — so N individual frames repaint the UI in N unbatched steps
130    // and the response body's batched application (mos.ts
131    // `updateMuxObjects`) arrives too late to matter (version-guarded to
132    // a no-op). CloseTab's `[delete tab, update workspace]` pair sent as
133    // two frames is exactly the blank-tab flash of
134    // SPEC_TAB_CLOSE_BUTTON_SELECT_FLASH_2026_08_25.md §7.
135    if let Some(updates) = &result.updates {
136        state.event_bus.broadcast_mux_obj_updates(updates);
137    }
138
139    result
140}
141
142async fn dispatch_service(state: &AppState, call: &WebCallType, caller_uid: Option<&str>) -> WebReturnType {
143    match call.service.as_str() {
144        "object" => object::handle_object_service(state, call, caller_uid).await,
145        "client" => client::handle_client_service(state, call).await,
146        "credential" => credential::handle_credential_service(state, call).await,
147        "window" => window::handle_window_service(state, call).await,
148        "workspace" => workspace::handle_workspace_service(state, call).await,
149        "host_ipc" => host_ipc::handle_host_ipc_service(state, call).await,
150        _ => misc::handle_misc_service(state, call).await,
151    }
152}