Skip to main content

agentmux_srv/bootstrap/
plumbing.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Split out of the single-file bootstrap module unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.3).
5
6use super::*;
7
8/// Output of [`spawn_reducer_plumbing`].
9pub struct ReducerPlumbing {
10    pub srv_state: Arc<tokio::sync::Mutex<state::State>>,
11    pub srv_events_tx: tokio::sync::broadcast::Sender<agentmux_common::ipc::Event>,
12    #[cfg(target_os = "windows")]
13    pub srv_event_log: Arc<event_log::EventLog>,
14}
15
16/// Phase E.2 / E.2c.2 — srv reducer plumbing, hoisted out of the
17/// (conditional) pipe-IPC bind block so HTTP/WS RPC handlers in
18/// dispatch_service can route through the reducer. State, event
19/// bus, event log, and persist subscriber all live unconditionally;
20/// the pipe IPC server is still conditional on
21/// `AGENTMUX_SRV_PIPE_PATH` being set (absent in `task dev` mode).
22///
23/// Bootstraps reducer state from SQLite, spawns the disk writer (forensic
24/// log of every reducer event), the persist subscriber (idempotent SQLite
25/// write-back), the MuxObjUpdate bridge, and the subagent-watcher block-delete
26/// cascade backstop.
27pub async fn spawn_reducer_plumbing(
28    mstore: &Arc<Store>,
29    event_bus: &Arc<EventBus>,
30    subagent_watcher: &Arc<backend::subagent_watcher::SubagentWatcher>,
31) -> ReducerPlumbing {
32    let mstore_for_persist = Arc::clone(mstore);
33    let srv_state = std::sync::Arc::new(tokio::sync::Mutex::new(state::State::default()));
34    let (srv_events_tx, _) =
35        tokio::sync::broadcast::channel::<agentmux_common::ipc::Event>(1024);
36    let srv_event_log = std::sync::Arc::new(event_log::EventLog::new(Some(
37        base::get_mux_data_dir().join("srv-events.log"),
38    )));
39
40    // Bootstrap reducer state from SQLite. Always runs (even in
41    // `task dev` where there's no pipe IPC server) so RPC handlers
42    // dispatching through the reducer see populated state.
43    persist::bootstrap_state_from_mstore(&srv_state, &mstore_for_persist).await;
44
45    // Spawn the disk writer (forensic log of every reducer event)
46    // and the persist subscriber (idempotent SQLite write-back).
47    let disk_writer_rx = srv_events_tx.subscribe();
48    let log_for_writer = std::sync::Arc::clone(&srv_event_log);
49    tokio::spawn(event_log::run_disk_writer(log_for_writer, disk_writer_rx));
50    let subscriber_rx = srv_events_tx.subscribe();
51    persist_subscriber::spawn_persist_subscriber(
52        subscriber_rx,
53        std::sync::Arc::clone(&mstore_for_persist),
54        std::sync::Arc::clone(&srv_state),
55    );
56
57    // Phase 1 of the MuxObjUpdate bridge: subscribe to srv_events_tx and
58    // translate workspace mutations into `waveobj:update` WS broadcasts.
59    // Fixes the workspace-rename reactivity gap where UpdateWorkspace
60    // returned `success_empty()` and the response loop had nothing to
61    // broadcast — see docs/specs/SPEC_OBJ_UPDATE_BRIDGE_2026-05-14.md.
62    //
63    // Watchdog: capture the JoinHandle and observe it from a sibling task
64    // so a panic in the bridge's loop scaffolding (vs. an inner
65    // dispatch_event panic, which is already caught per-event) is logged
66    // loudly. Without this, a silent bridge death would manifest as
67    // "renaming a workspace stopped propagating" with no log evidence.
68    // (Per ReAgent P2 follow-up on PR #852.)
69    let bridge_rx = srv_events_tx.subscribe();
70    let bridge_handle = server::mux_obj_bridge::spawn_mux_obj_bridge(
71        bridge_rx,
72        std::sync::Arc::clone(&mstore_for_persist),
73        std::sync::Arc::clone(event_bus),
74    );
75    tokio::spawn(async move {
76        match bridge_handle.await {
77            Ok(()) => tracing::info!(
78                target: "wave-obj-bridge",
79                "bridge task exited normally (events channel closed at srv shutdown)"
80            ),
81            Err(e) if e.is_panic() => tracing::error!(
82                target: "wave-obj-bridge",
83                "bridge task PANICKED at top level — frontend MOS will stop receiving updates until srv restart. Panic: {}",
84                e
85            ),
86            Err(e) => tracing::error!(
87                target: "wave-obj-bridge",
88                "bridge task terminated unexpectedly (non-panic JoinError): {}",
89                e
90            ),
91        }
92    });
93
94    // Block-delete cascade backstop for the subagent watcher: prunes a
95    // closed block's subagents/dispatches on Event::BlockDeleted/TabDeleted/
96    // WorkspaceDeleted, independent of whether the frontend's normal
97    // /agentmux/reactive/unregister teardown path fires for this close (see
98    // SubagentWatcher::prune_block's doc comment). Without this, closing an
99    // agent pane left a ghost row in the Swarm pane until srv restart.
100    let block_prune_rx = srv_events_tx.subscribe();
101    backend::subagent_watcher::spawn_block_prune_subscriber(subagent_watcher.clone(), block_prune_rx);
102
103    // A container agent's pane snapshots go with their panes; those left by a pane that is gone go now.
104    crate::server::container_pane_snapshot::spawn_sweeper(srv_events_tx.subscribe());
105    // A remote pane's feed goes with its pane, too (D4 of the remote panes spec).
106    crate::server::app_api::remote_panes::spawn_block_closer(srv_events_tx.subscribe());
107    crate::server::container_pane_snapshot::sweep(|block| mstore.get::<backend::obj::Block>(block).ok().flatten().is_some());
108
109    ReducerPlumbing {
110        srv_state,
111        srv_events_tx,
112        #[cfg(target_os = "windows")]
113        srv_event_log,
114    }
115}
116
117/// Assembles the final `AppState` from every bundle produced above, plus the
118/// handful of state pieces (auth session manager, install sessions, container
119/// manager, shell sessions, cron scheduler) that only ever existed inline in
120/// the `AppState` struct literal.
121pub fn build_app_state(
122    config: &config::Config,
123    version: String,
124    stores: Stores,
125    bg: BackgroundSubsystems,
126    net: &NetworkBundle,
127    reducer: &ReducerPlumbing,
128) -> AppState {
129    // Clone before move into AppState for cron_scheduler construction: jobs
130    // (`db_jobs`) live in the cron store (`server::cron::jobs_store`).
131    let jobs_store = stores.cron_store.clone();
132    // Live settings for the agent CPU-priority policy (process_tracker).
133    net.process_tracker.set_config(bg.config_watcher.clone());
134    let broker = bg.broker;
135
136    // Built before `container_manager` below so its constructor block can
137    // wire the two together (`set_dev_proxy_registry`) — `stop`/`remove`
138    // then clear an agent's routes when its container goes away. See
139    // docs/specs/SPEC_NATIVE_CONTAINER_DEV_PROXY_2026_09_19.md.
140    let dev_proxy = crate::backend::dev_proxy::DevProxyRegistry::new();
141
142    // The viewer (backend::viewer): its certificate lives in this instance's
143    // data directory, and its port is advertised on the fleet feed and the
144    // UDP replies while a viewer listener is up.
145    let viewer = crate::backend::viewer::ViewerService::new(Some(base::get_mux_data_dir()), &broker);
146    viewer.install_global(Arc::clone(&broker));
147
148    let fleet_feed = Arc::new(
149        crate::backend::fleet_feed::FleetFeed::new(
150            net.hostname.clone(),
151            crate::backend::reactive::registry::local_channel_id(),
152            version.clone(),
153        )
154        .with_install_id(crate::backend::fleet_source::install_id())
155        .with_viewer_port(viewer.advertised_port_handle()),
156    );
157
158    AppState {
159        auth_key: config.auth_key.clone(),
160        lan_key: config.lan_key.clone(),
161        boot_id: Arc::from(uuid::Uuid::new_v4().to_string()),
162        version,
163        hostname: net.hostname.clone(),
164        app_path: config.app_path.clone(),
165        mstore: stores.mstore,
166        shared_store: stores.shared_store, move_staging: open_move_staging(),
167        id_store: stores.id_store,
168        identity_store: stores.identity_store,
169        work_store: stores.work_store,
170        cron_store: stores.cron_store,
171        filestore: stores.filestore,
172        global_transcript_store: stores.global_transcript_store,
173        event_bus: bg.event_bus,
174        broker: broker.clone(),
175        reactive_handler: bg.reactive_handler,
176        poller: bg.poller,
177        config_watcher: bg.config_watcher,
178        messagebus: bg.messagebus,
179        subagent_watcher: bg.subagent_watcher,
180        history_service: bg.history_service,
181        lan_discovery: net.lan_discovery.clone(),
182        lan_listeners: net.lan_listeners.clone(),
183        fleet_feed,
184        viewer,
185        lsp_supervisor: net.lsp_supervisor.clone(),
186        local_web_url: net.local_web_url.clone(),
187        // Bounded request timeout: cross-instance reactive-inject forwards
188        // (Tier 2/2b/3) chain through this client, and an unbounded client
189        // combined with a forwarding cycle (two channels each holding a
190        // stale-but-PID-alive shared-registry entry pointing at the other)
191        // could otherwise hang a request indefinitely. The hop-count guard
192        // in server/reactive.rs bounds the CYCLE; this bounds each
193        // individual HOP (reagent P1 on PR #2350).
194        http_client: crate::http_client::builder()
195            .timeout(std::time::Duration::from_secs(10))
196            .build()
197            .unwrap_or_else(|e| {
198                tracing::warn!(error = %e, "failed to build http_client with timeout, using default");
199                crate::http_client::client()
200            }),
201        host_ipc: std::sync::Arc::new(tokio::sync::Mutex::new(None)),
202        host_reg_secret: config.host_reg_secret.clone(),
203        process_tracker: net.process_tracker.clone(),
204        process_broker: net.process_broker.clone(),
205        dock_snapshots: std::sync::Arc::new(crate::backend::dock_snapshot::DockSnapshotCache::new()),
206        narrated_events: Arc::new(crate::backend::narrated_events::NarratedEvents::new()),
207        // Phase E.2c.2 — reducer state + event bus exposed to HTTP/WS
208        // dispatch handlers. Workspace handlers route through the
209        // reducer and publish events to `srv_events_tx`; the persist
210        // subscriber writes back to SQLite asynchronously.
211        srv_state: std::sync::Arc::clone(&reducer.srv_state),
212        srv_events_tx: reducer.srv_events_tx.clone(),
213        // Phase E.5.5 — saga-id allocator. Seeded from
214        // `SagaLog::max_saga_id()` so restarts don't collide with
215        // prior runs' IDs. First new saga after restart gets
216        // `seed + 1`; on a fresh DB seed=0, first saga gets id 1.
217        saga_id_alloc: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(stores.saga_id_seed)),
218        saga_log: stores.saga_log,
219        auth_session_manager: {
220            let mgr = std::sync::Arc::new(crate::identity::auth_session::AuthSessionManager::new());
221            // Ends timed-out logins and drops finished ones, polled or not.
222            mgr.spawn_sweeper();
223            mgr
224        },
225        install_sessions: crate::server::install_handlers::InstallSessionRegistry::new(),
226        container_manager: {
227            // Self-healing: unlike a plain `Option<ContainerManager>` fixed at
228            // boot, `ContainerRuntimeHandle` retries the connect on demand, so
229            // a daemon that starts after this point is picked up by later
230            // calls without an app restart. See
231            // docs/retro/RETRO_DOCKER_DETECTION_DIVERGENCE_2026_07_04.md.
232            let handle = std::sync::Arc::new(
233                crate::backend::container::ContainerRuntimeHandle::connect_at_startup(),
234            );
235            handle.set_dev_proxy_registry(dev_proxy.clone());
236            let handle_check = handle.clone();
237            tokio::spawn(async move {
238                if handle_check.is_available().await {
239                    tracing::info!("Docker daemon available — container agent panes enabled");
240                } else {
241                    tracing::warn!(
242                        "Docker daemon not reachable at startup; container agent panes will \
243                         become available automatically once Docker is running"
244                    );
245                }
246            });
247            handle
248        },
249        dev_proxy,
250        shell_sessions: crate::backend::shell_node::ShellSessionRegistry::new(),
251        cron_scheduler: crate::backend::cron::CronScheduler::new(
252            jobs_store,
253            crate::http_client::client(),
254            net.local_web_url.clone(),
255            config.auth_key.clone(),
256            Arc::clone(&broker),
257        ),
258        editor_file_watcher: bg.editor_file_watcher,
259        media_file_watcher: bg.media_file_watcher,
260        files_watcher: bg.files_watcher,
261        fs_watch_pool: bg.fs_watch_pool,
262    }
263}
264
265/// Phase E.1b — srv pipe IPC server. Bound when launcher passes
266/// `AGENTMUX_SRV_PIPE_PATH`; absent in `task dev` mode (no
267/// launcher in the loop).
268///
269/// Bind happens BEFORE the AGENTMUXSRV-ESTART line so the
270/// launcher knows the pipe is ready when host starts. Non-fatal
271/// if the bind fails — srv keeps running with HTTP/WS only.
272#[cfg(target_os = "windows")]
273pub fn bind_srv_pipe_ipc(
274    version: &str,
275    srv_state: std::sync::Arc<tokio::sync::Mutex<state::State>>,
276    srv_events_tx: tokio::sync::broadcast::Sender<agentmux_common::ipc::Event>,
277    srv_event_log: std::sync::Arc<event_log::EventLog>,
278) {
279    if let Ok(srv_pipe_path) = std::env::var("AGENTMUX_SRV_PIPE_PATH") {
280        if !srv_pipe_path.is_empty() {
281            match crate::srv_ipc::server::bind_first_pipe_instance(&srv_pipe_path) {
282                Ok(first_pipe) => {
283                    // Phase E.2c.2 — pipe IPC server reuses the
284                    // hoisted srv_state / events_tx / event_log so
285                    // pipe-originated commands and HTTP/WS-originated
286                    // commands mutate the same canonical state.
287                    let srv_ctx = crate::srv_ipc::ServerCtx {
288                        srv_pid: std::process::id(),
289                        srv_version: version.to_string(),
290                        state: srv_state,
291                        events_tx: srv_events_tx,
292                        event_log: srv_event_log,
293                    };
294                    let _srv_ipc_handle = crate::srv_ipc::run_srv_ipc_server(
295                        srv_pipe_path.clone(),
296                        first_pipe,
297                        srv_ctx,
298                    );
299                    tracing::info!(
300                        target: "srv-ipc",
301                        "[srv-ipc] bound + spawned on {}",
302                        srv_pipe_path
303                    );
304                }
305                Err(e) => {
306                    tracing::error!(
307                        target: "srv-ipc",
308                        "[srv-ipc] bind failed on {}: {} — srv runs without pipe IPC",
309                        srv_pipe_path,
310                        e
311                    );
312                }
313            }
314        }
315    }
316}
317
318/// The staging area for agents moved here from another computer, under the data folder; swept of what has expired as it opens.
319fn open_move_staging() -> Option<Arc<crate::backend::agent_move::staging::Staging>> {
320    match crate::backend::agent_move::staging::Staging::open(base::get_mux_data_dir().join("move-staging"), Default::default()) {
321        Ok(staging) => {
322            staging.sweep(agentmux_common::time::now_ms());
323            Some(Arc::new(staging))
324        }
325        Err(e) => {
326            tracing::warn!(error = %e, "the staging area for incoming agents could not be opened");
327            None
328        }
329    }
330}