Skip to main content

agentmux_srv/server/
state.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Shared server state: AppState and HostIpc.
5//! Split out of server/mod.rs unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.1).
6
7use super::*;
8
9/// The paired CEF host's CDP-automation credentials, pushed once via
10/// `host_ipc.Register` — see `AppState::host_ipc`.
11#[derive(Clone, Debug)]
12pub struct HostIpc {
13    pub port: u16,
14    pub token: String,
15}
16
17#[derive(Clone)]
18pub struct AppState {
19    pub auth_key: String,
20    /// LAN peer-discovery credential — see `Config::lan_key`'s doc comment.
21    /// Accepted only by `lan_or_full_auth_middleware`'s three routes, never
22    /// the general `auth_middleware` gating everything else.
23    pub lan_key: String,
24    /// Random identifier generated once per process boot — NOT the
25    /// `--instance` channel name (`config.instance_id`), which is
26    /// stable across restarts and shared by every process on the same
27    /// channel. Used as the owner id for cross-process session leases
28    /// (`registry::LeaseStore`) so two live processes can be told
29    /// apart even when they're the same channel/version.
30    /// See `docs/retro/RETRO_DEV_BUILD_SHARED_AGENT_SESSION_COLLISION_2026_07_29.md`.
31    pub boot_id: Arc<str>,
32    pub version: String,
33    /// OS hostname of the machine this instance runs on (e.g. "narko").
34    /// Already computed at boot for LAN discovery's mDNS TXT records; kept
35    /// here so `/agentmux/discovery` can name its own host too — `local_url`
36    /// is always loopback, so without this a client has no way to say which
37    /// machine it is talking to.
38    pub hostname: String,
39    pub app_path: String,
40    pub mstore: Arc<Store>,
41    /// GLOBAL shared store (`~/.agentmux/shared/store.db`). Holds durable
42    /// user content that must survive version upgrades: accounts,
43    /// bundles, drone definitions, and MuxBus credentials.
44    /// `None` when the shared root can't be resolved (CI / unusual envs).
45    /// See `docs/specs/SPEC_GLOBAL_IDENTITY_MEMORY_DRONE_2026_06_24.md`.
46    pub shared_store: Option<Arc<Store>>,
47    /// The destination's staging area for agents moved here from another computer (`agent_move::staging`).
48    pub move_staging: Option<Arc<crate::backend::agent_move::staging::Staging>>,
49    /// Effective identity/memory/drone/muxbus store — `shared_store` when
50    /// available, otherwise `mstore`. Handlers capture this instead of
51    /// `mstore` for any operation that must survive across version upgrades.
52    ///
53    /// Deprecated for everything except `db_accounts` reads/writes as of
54    /// `docs/specs/SPEC_IDENTITY_STORE_SPLIT_2026_08_17.md` — new call sites
55    /// for agent→account links, bundles, drone definitions, muxbus
56    /// creds, native memory, or cron jobs should use `identity_store`
57    /// instead, which (unlike this field) is never redirected by
58    /// `isolated_auth_enabled()`. `id_store` itself stays because
59    /// `db_accounts` still legitimately needs an isolatable path (account
60    /// testing) — see the spec's §3.2 for the account-specific split, not
61    /// yet implemented.
62    pub id_store: Arc<Store>,
63    /// Permanently-global identity store — see `identity_store`'s own doc
64    /// comment on `bootstrap::Stores` for the full explanation. Never
65    /// `None`: falls back to `mstore` on the same best-effort terms as
66    /// `id_store` if the shared root can't be resolved.
67    pub identity_store: Arc<Store>,
68    /// The Kanban queue (cards, events, dependencies, PRs), Presence claims,
69    /// coordination posts and the Jobs run ledger. The identity store, except in
70    /// a `task dev` build (or with `AGENTMUX_ISOLATED_WORK=1`), which has a
71    /// `work-store.db` of its own so it never touches the operator's real queue
72    /// (`crate::registry::work_store`). Use this, not `identity_store`, for those.
73    pub work_store: Arc<Store>,
74    /// Scheduled jobs (`db_cron_jobs`): `shared_store`, or `work_store` in a build
75    /// that has its own, so a dev build neither fires nor edits the
76    /// operator's real jobs.
77    pub cron_store: Option<Arc<Store>>,
78    pub filestore: Arc<FileStore>,
79    /// GLOBAL, channel-independent transcript store backing the
80    /// `agent:<defId>:current` zone. `None` when the shared root can't be
81    /// resolved (global transcripts disabled — falls back to per-channel
82    /// `filestore`). Lets an agent's conversation load when opened from any
83    /// build/channel, finishing the cross-channel arc started by #1387–#1396.
84    /// See `docs/analysis/ANALYSIS_CROSS_CHANNEL_CONVERSATION_HISTORY_2026_06_14.md`.
85    pub global_transcript_store: Option<Arc<FileStore>>,
86    pub event_bus: Arc<EventBus>,
87    pub broker: Arc<Broker>,
88    pub reactive_handler: &'static ReactiveHandler,
89    pub poller: Arc<Poller>,
90    pub config_watcher: Arc<wconfig::ConfigState>,
91    pub messagebus: Arc<MessageBus>,
92    pub subagent_watcher: Arc<SubagentWatcher>,
93    pub history_service: Arc<HistoryService>,
94    /// Tracks every OS-level process each agent CLI has spawned, via
95    /// platform-specific mechanisms (Windows Job Objects, Linux cgroups; a
96    /// stub on macOS). Surfaces the tree to the agent pane and
97    /// provides kill-tree on pane close / host exit.
98    /// See `backend::process_tracker`.
99    pub process_tracker: Arc<crate::backend::process_tracker::registry::AgentProcessRegistry>,
100    /// Process Broker (Phase A) — unified `ProcessStatus` per block, read
101    /// through instead of composing `blockcontroller`/`process_tracker`
102    /// directly at each call site. See `crate::broker::process` and
103    /// `docs/specs/REPORT_PROCESS_ARCHITECTURE_STATE_AND_RETHINK_2026_07_22.md`.
104    pub process_broker: Arc<crate::broker::ProcessBroker>,
105    /// In-memory, latest-per-block cache of Activity Dock `ToolNode` status
106    /// deltas pushed by the frontend. Backs `muxspect dock`/`muxspect dock
107    /// clear`. Never persisted — see
108    /// `docs/specs/SPEC_MUXSPECT_DOCK_DIAGNOSIS_AND_REMEDIATION_2026_08_06.md`.
109    pub dock_snapshots: Arc<crate::backend::dock_snapshot::DockSnapshotCache>,
110    /// Which events have already produced an ambient narration. Process-wide
111    /// and bounded — a per-connection set is reset by every reconnect, which is
112    /// precisely when the frontend re-emits nodes and would narrate them twice.
113    /// See `backend::narrated_events`.
114    pub narrated_events: Arc<crate::backend::narrated_events::NarratedEvents>,
115    /// Live controller for mDNS-based LAN/host peer discovery. The controller
116    /// owns a swappable daemon slot so the `network:lan_discovery` setting can
117    /// be toggled at runtime without restarting the process.
118    /// See `docs/specs/lan-discovery-toggle.md`.
119    pub lan_discovery: Arc<LanDiscoveryController>,
120    /// Owns the LAN-facing HTTP listeners. Paired with `lan_discovery`: that
121    /// one controls whether we ADVERTISE on the LAN, this one controls whether
122    /// we are actually REACHABLE there. Both must be driven from the same
123    /// place — advertising without listening is the "discovered but
124    /// unreachable" state described in `backend::lan::listeners`.
125    pub lan_listeners: Arc<crate::backend::lan::listeners::LanListenerSupervisor>,
126    /// The names-only fleet feed behind `/agentmux/fleet` and
127    /// `/agentmux/fleet/events` (`backend::fleet_feed`). Its change-detection
128    /// task is started by `main.rs` once the shutdown token exists.
129    pub fleet_feed: Arc<crate::backend::fleet_feed::FleetFeed>,
130    /// Paired devices' read-only view: pairing codes, the certificate, the
131    /// feed hub and the feed caps (`backend::viewer`). Its routes are served
132    /// only by the viewer listener (`server::build_viewer_router`).
133    pub viewer: Arc<crate::backend::viewer::ViewerService>,
134    /// Language Server Protocol supervisor — owns the lifecycle of LSP
135    /// server child processes (one per workspace/language) and proxies
136    /// LSP messages between the editor pane and the server.
137    /// Spec: `docs/specs/SPEC_EDITOR_LSP_AND_THEMES_2026-05-26.md`.
138    pub lsp_supervisor: Arc<LspSupervisor>,
139    /// Local HTTP URL of this instance (e.g. "http://127.0.0.1:PORT").
140    /// Used for cross-instance inject forwarding and file registry entries.
141    pub local_web_url: String,
142    /// Shared HTTP client for cross-instance inject forwarding.
143    pub http_client: reqwest::Client,
144    /// This instance's paired CEF host's `ipc_port` + `ipc_token`
145    /// (`/agentmux/browser/*` on the host's own IPC server — CDP-based
146    /// screenshot/click/query automation). `None` until the host calls
147    /// `host_ipc.Register` once at its own startup (there is no way to
148    /// know these values before then — the host generates `ipc_token`
149    /// for itself and is the sole source of truth, see
150    /// `crates/cef/src/client/helpers.rs::register_ipc_with_backend`).
151    /// Backs the `/api/v1/ui/{screenshot,click,query}` proxy routes.
152    /// See `docs/specs/SPEC_AGENT_UI_AUTOMATION_CLICK_SCREENSHOT_2026_08_18.md`.
153    pub host_ipc: Arc<tokio::sync::Mutex<Option<HostIpc>>>,
154    /// Shared secret only the paired host (never an agent) is given —
155    /// gates `host_ipc.Register` so an agent process can't spoof the
156    /// host's own credential push (both share the general `auth_key`
157    /// already, so that alone can't distinguish them). `None` if nobody
158    /// configured one, in which case `handle_register` rejects every
159    /// registration. See `Config::host_reg_secret`'s doc comment.
160    pub host_reg_secret: Option<String>,
161    /// Phase E.2c.2 — srv reducer's canonical state. Workspace HTTP/WS
162    /// RPC handlers route through the reducer (dispatch
163    /// `Command::Create/Delete/...Workspace` and read out of
164    /// `state.workspaces`); the persist subscriber mirrors emitted
165    /// events back to SQLite. Tab/Block RPC migrations land in
166    /// E.2c.3 / E.2c.4.
167    pub srv_state: std::sync::Arc<tokio::sync::Mutex<crate::state::State>>,
168    /// Phase E.2c.2 — broadcast bus for srv reducer events. RPC
169    /// handlers publish reducer-emitted events here so the persist
170    /// subscriber writes them back to SQLite. Pipe IPC server (when
171    /// bound) shares the same bus.
172    pub srv_events_tx: tokio::sync::broadcast::Sender<agentmux_common::ipc::Event>,
173    /// Phase E.5.5 — monotonic saga-id allocator. Each saga
174    /// (TearOffTab, TearOffBlock, RestoreTornOffTab, etc.) calls
175    /// `fetch_add` to claim a unique id; the id is stamped onto
176    /// `Event::SagaStarted/Completed/Failed` so subscribers can
177    /// correlate. Per-instance scope (no cross-process sharing — see
178    /// `docs/retro/saga-coordinator-location-analysis-2026-04-30.md`).
179    pub saga_id_alloc: std::sync::Arc<std::sync::atomic::AtomicU64>,
180    /// Saga durability — durable on-disk log of saga lifecycle.
181    /// Written by `SagaCtx::dispatch` / `compensate` (per-step) and
182    /// `emit_terminal` (per-saga) so a srv crash mid-saga leaves a
183    /// recoverable trail. PR 1 ships the log + instrumentation; PR 2
184    /// adds resume-on-startup + `--diag sagas`.
185    /// See `docs/specs/SPEC_SAGA_DURABILITY_2026-05-01.md`.
186    pub saga_log: std::sync::Arc<crate::sagas::log::SagaLog>,
187    /// Provider login session state — one entry per in-flight
188    /// `auth.start` login. See
189    /// `docs/specs/SPEC_PRE_LAUNCH_OAUTH_FLOW_2026_05_14.md`.
190    pub auth_session_manager: std::sync::Arc<crate::identity::auth_session::AuthSessionManager>,
191
192    /// In-flight `install.start` sessions. Frontend subscribes to
193    /// `install_chunk` MPS events scoped by session id; the registry
194    /// holds per-session cancel handles so `install.cancel` can abort
195    /// an install mid-flight.
196    /// See `SPEC_AGENT_INSTALL_STAGE_2026_05_17.md` §9.
197    pub install_sessions: std::sync::Arc<crate::server::install_handlers::InstallSessionRegistry>,
198    /// Docker container runtime handle for container-type agent panes
199    /// (Phase 2). Self-healing — `.get()`/`.is_available()` retry the
200    /// Docker connection on demand rather than being fixed at process
201    /// boot, so a daemon that starts after AgentMux launched is picked up
202    /// without an app restart. See `ContainerRuntimeHandle` and
203    /// docs/retro/RETRO_DOCKER_DETECTION_DIVERGENCE_2026_07_04.md.
204    pub container_manager: std::sync::Arc<crate::backend::container::ContainerRuntimeHandle>,
205    /// Native dev-proxy routing table (`"<project>-<agent_id>"` →
206    /// container-internal `ip:port`) — backs the `RegisterDevServer` MCP
207    /// tool and the standalone dev-proxy HTTP server spawned in `main.rs`.
208    /// Cheap to clone (one `Arc` inside); `container_manager` also holds a
209    /// clone (wired via `ContainerRuntimeHandle::set_dev_proxy_registry`
210    /// in `bootstrap::build_app_state`) so `stop`/`remove` can clear a
211    /// dead container's routes. See
212    /// docs/specs/SPEC_NATIVE_CONTAINER_DEV_PROXY_2026_09_19.md.
213    pub dev_proxy: crate::backend::dev_proxy::DevProxyRegistry,
214    /// Phase 3 — per-shell stop handles so `ShellStop` (MCP tool) and the UI
215    /// stop button can tree-kill a running persistent shell node. See
216    /// `docs/specs/SPEC_PERSISTENT_SHELL_PHASE3_STOP_2026_06_14.md`.
217    pub shell_sessions: std::sync::Arc<crate::backend::shell_node::ShellSessionRegistry>,
218    /// Persistent cron scheduler — loaded from `db_cron_jobs` at startup.
219    /// Creates/cancels tokio tasks that fire on the specified UTC schedule and
220    /// POST to `/agentmux/reactive/inject`. See
221    /// `docs/specs/SPEC_CRON_LOOP_ROBUSTNESS_2026_06_25.md §3.2`.
222    pub cron_scheduler: std::sync::Arc<crate::backend::cron::CronScheduler>,
223    /// Filesystem watcher for files open in editor/preview panes — publishes
224    /// `EVENT_EDITOR_FILE_CHANGED` (scoped per-block) when a watched path
225    /// changes on disk, so panes can refresh instead of silently going
226    /// stale. Migrated onto the shared `fs_watch_pool` below
227    /// (SPEC_SHARED_FS_WATCHER_FRAMEWORK_2026_08_07.md) — always constructs
228    /// successfully now (a construction-time failure degrades into
229    /// `fs_watch_pool.health()`'s `degraded_paths` instead of `None`), so
230    /// unlike before this field is no longer optional.
231    /// See docs/specs/SPEC_EDITOR_LIVE_FILE_RELOAD_2026_07_18.md.
232    pub editor_file_watcher: std::sync::Arc<crate::backend::editor_file_watcher::EditorFileWatcher>,
233    /// Filesystem watcher for directories a Media pane is pointed at —
234    /// publishes `EVENT_MEDIA_FILE_CHANGED` (scoped per-block) when a
235    /// matching-extension file is created/modified. Same migration and
236    /// no-longer-optional note as `editor_file_watcher` above.
237    /// See docs/specs/SPEC_MEDIA_PANE_2026_07_26.md.
238    pub media_file_watcher: std::sync::Arc<crate::backend::media_file_watcher::MediaFileWatcher>,
239    /// Directory watcher behind `fs.watch` for Files panes — publishes
240    /// `files:changed` (scoped per-block) when a watched folder's listing
241    /// changes. Process-wide rather than per connection, so a watch outlives
242    /// the WebSocket that made it, like the two watchers above.
243    /// See docs/specs/SPEC_FILE_BROWSER_PANE_2026_10_01.md §6.3.
244    pub files_watcher: std::sync::Arc<crate::backend::files_watcher::FilesWatcher>,
245    /// Shared filesystem-watcher framework (retry/fallback/self-healing on
246    /// top of `notify`) that `editor_file_watcher`/`media_file_watcher`
247    /// above are built on. See
248    /// docs/specs/SPEC_SHARED_FS_WATCHER_FRAMEWORK_2026_08_07.md.
249    pub fs_watch_pool: std::sync::Arc<crate::backend::fs_watch::FsWatchPool>,
250}