agentmux_launcher/reducer/mod.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Phase B.3 — pure reducer.
5//
6// Shares its DISCIPLINE with `agentmux_srv::reducer` — pure, total,
7// deterministic, no I/O — and its wire types: both import the same
8// `agentmux_common::ipc::{Command, Event}`. What differs is `State` (each
9// crate's own) and the command/event variants each `update` actually
10// handles — this one drives the window/process state machine, not
11// workspaces/tabs/blocks. Two reducers by design; see
12// docs/architecture/DECISION_SAGA_REDUCER_TWO_FRAMEWORKS_2026_09_07.md.
13//
14// Per `docs/specs/SPEC_WINDOW_PROCESS_STATE_MACHINE_2026_04_27.md` §5.1:
15//
16// pub fn update(state: &State, cmd: Command) -> (State, Vec<Event>);
17//
18// We deviate slightly: the function takes `&mut State` (mutating in
19// place rather than returning a new value) because cloning a HashMap
20// per-command in the IPC hot path is wasteful and not needed for
21// the testability properties we want — `proptest` works equally well
22// against a mutating-reducer (apply commands one by one, assert
23// invariants hold after each).
24//
25// Strict properties of `update`:
26// 1. **Total**. Every (cmd, state) combination produces a result;
27// never panics on input. (Panics ARE used to enforce internal
28// invariants — those are bugs in the reducer or upstream code,
29// not user input. See spec §7 / §8.)
30// 2. **Deterministic**. Same (state, cmd, conn) → same (state',
31// events). No clocks, no UUIDs, no env reads inside update —
32// injected via the `Reducer` context if needed (B.4 will need
33// it for spawned_at timestamps; for B.3 the conn carries one).
34// 3. **No I/O**. update never blocks or awaits. Mutex is held for
35// the duration of update — must stay sub-millisecond. That includes
36// logging: `crate::log` opens, rotates and appends to a file, so an
37// arm that wants a log line pushes it onto `Reduced::diagnostics`
38// and the caller writes it after releasing the lock.
39//
40// Connection context: every command arrives over a specific
41// connection and the resulting events that are *replies* (Registered,
42// Pong) belong to that connection only, while *broadcasts*
43// (ProcessSpawned, LifecyclePhaseChanged) belong to all subscribers.
44// Phase B.3 ships in a simplified model where every event goes over
45// the originating connection; B.4 splits the routing.
46//
47// Invariants checked:
48// * Register on a PID that's already registered → AlreadyRegistered
49// error. (Connection-level enforcement that "Register sent twice"
50// also lives in the server; this is the cross-connection guard.)
51// * Lifecycle transitions: Starting → Running on first Host
52// register. Running → Quitting on Quit (B.3 placeholder).
53// Quitting → Dead on cleanup-done (B.3 placeholder). No skipping.
54
55use agentmux_common::ipc::{Command, DriftKind, ErrorCode, Event};
56
57use crate::state::State;
58
59/// Context the reducer needs but can't read from State (clocks,
60/// connection identity). Passed in per-call so update remains pure.
61#[derive(Debug, Clone)]
62pub struct Ctx {
63 /// RFC3339 timestamp to stamp on new ProcessRecords. Injected
64 /// (rather than read from chrono::Utc::now() inside update) to
65 /// keep the function deterministic for tests.
66 pub now_rfc3339: String,
67 /// The connection on which this command arrived. Currently
68 /// just used for log correlation; B.4+ will use it to route
69 /// per-connection replies.
70 pub conn_id: u64,
71 /// PID the connection has Registered under, if any. The server
72 /// tracks this server-side and passes it on every command after
73 /// the initial Register so the reducer can mark the right
74 /// process Exited on Goodbye. None for the very first command
75 /// on a connection (which MUST be Register, enforced server-
76 /// side). (codex P1 + gemini HIGH PR #574 round-1.)
77 pub registered_pid: Option<u32>,
78 /// Phase B.9.1 — monotonic milliseconds since some reference
79 /// epoch (the IPC server uses launcher start as the epoch).
80 /// Used by the WRR arm for per-window observability timestamps
81 /// (`last_foreground_at_ms`, `pending_hwnds[hwnd].arrived_at_ms`).
82 /// Distinct from `now_rfc3339` (wall clock) because operators
83 /// reading `--diag wrr` want age, not absolute time.
84 pub now_ms: u64,
85}
86
87mod pool;
88mod window;
89mod saga;
90mod connection;
91
92/// What one `update` call produced.
93#[derive(Debug, Default)]
94pub struct Reduced {
95 /// Events to log, broadcast and reply with.
96 pub events: Vec<Event>,
97 /// Log lines for `crate::log`. The reducer does no I/O; the caller
98 /// writes these after releasing the state lock.
99 pub diagnostics: Vec<String>,
100}
101
102/// Apply one Command to State, returning the resulting Events and any
103/// diagnostic log lines. State is mutated in place. Total function —
104/// never panics on input (panics are reserved for internal invariant
105/// violations).
106pub fn update(state: &mut State, cmd: Command, ctx: &Ctx) -> Reduced {
107 let _ = ctx.conn_id; // reserved for B.4 routing
108 let mut diagnostics: Vec<String> = Vec::new();
109
110 let mut cmd_events = match cmd {
111 Command::Register {
112 kind,
113 pid,
114 version,
115 } => connection::handle_register(state, ctx, kind, pid, version),
116 Command::Ping { nonce } => {
117 let v = state.bump_version();
118 vec![Event::Pong { nonce, version: v }]
119 }
120 // SPEC_LAUNCHER_TEARDOWN_BACKSTOP Phase 1 — UI-liveness telemetry is
121 // recorded at the transport layer (`ipc/server.rs` →
122 // `crate::ui_liveness`), NOT here: it's thread/process telemetry
123 // about the host, not domain state this reducer owns. This arm
124 // exists only for match exhaustiveness — a defensive no-op.
125 Command::ReportUiThreadAlive { .. } => Vec::new(),
126 // The launcher SENDS ProbeUiThread (over the host pipe); receiving
127 // one on its own IPC server is a wrong-direction message — ignore
128 // (the reducer is pure and does not log; the pre-Register table in
129 // ipc/server.rs already names this case for unregistered senders).
130 Command::ProbeUiThread { .. } => Vec::new(),
131 // Launcher → host only, like ProbeUiThread; a client sending it is a no-op.
132 Command::NotifySrvLatency { .. } => Vec::new(),
133 Command::QuitApp => Vec::new(),
134 Command::Goodbye => connection::handle_goodbye(state, ctx.registered_pid.unwrap_or(0)),
135 Command::ReportWindowOpened {
136 label,
137 kind,
138 parent_label,
139 } => {
140 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportWindowOpened") {
141 return Reduced { events: vec![err], diagnostics };
142 }
143 window::handle_report_window_opened(state, ctx, label, kind, parent_label)
144 }
145 Command::ReportWindowClosed { label } => {
146 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportWindowClosed") {
147 return Reduced { events: vec![err], diagnostics };
148 }
149 window::handle_report_window_closed(state, label)
150 }
151 Command::ReportBackgroundServiceEnabled { enabled } => {
152 if let Some(err) =
153 connection::enforce_host_only(state, ctx, "ReportBackgroundServiceEnabled")
154 {
155 return Reduced { events: vec![err], diagnostics };
156 }
157 window::handle_report_background_service_enabled(state, enabled)
158 }
159 Command::ReportPoolWindowAdded { label, saga_id } => {
160 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportPoolWindowAdded") {
161 return Reduced { events: vec![err], diagnostics };
162 }
163 pool::handle_report_pool_window_added(state, label, saga_id)
164 }
165 Command::ReportPoolWindowRemoved { label } => {
166 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportPoolWindowRemoved") {
167 return Reduced { events: vec![err], diagnostics };
168 }
169 pool::handle_report_pool_window_removed(state, label)
170 }
171 // Phase F.5 — host-only signal that a pool→window promote is
172 // happening. Sent BETWEEN the matching `ReportPoolWindowRemoved`
173 // and `ReportWindowOpened` so the launcher can disambiguate
174 // promote from pre-promote destroy. Pure-reducer arm: emits
175 // the typed event; saga side-effect (start the pool-respawn
176 // saga) lives in the saga coordinator's bus subscription.
177 Command::ReportPoolWindowPromoted { label } => {
178 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportPoolWindowPromoted") {
179 return Reduced { events: vec![err], diagnostics };
180 }
181 pool::handle_report_pool_window_promoted(state, label)
182 }
183 // Phase F.5 — `SpawnPoolWindow` is a launcher→host direction
184 // command, NOT a host→launcher report. If a registered client
185 // sends it to the launcher pipe by mistake, return a non-fatal
186 // error so the client knows the dispatch was wrong (vs silently
187 // appearing successful with no reply). Same misrouted-error
188 // pattern as the srv-pipe commands below.
189 Command::SpawnPoolWindow { .. } => host_pipe_only(state, "SpawnPoolWindow"),
190 // Phase F.6 — host-only signal that all browser-pane HWNDs
191 // belonging to a closing top-level window have been reaped.
192 // Pure-reducer arm: emits the typed event so the
193 // window-cleanup-cascade saga can advance from Step 1
194 // (ReapingPanes) to Step 2 (DrainingPool). State is
195 // unchanged — pane bookkeeping lives in the host's session
196 // structures (lifecycle entries, pane HWND map), not the
197 // launcher's mirror; the launcher just narrates the
198 // transition for subscribers.
199 Command::ReportPanesReaped { label, saga_id } => {
200 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportPanesReaped") {
201 return Reduced { events: vec![err], diagnostics };
202 }
203 saga::handle_report_panes_reaped(state, label, saga_id)
204 }
205 // Phase F.6 — host reports the result of the post-close
206 // drain-pool-if-last decision. `was_last == true` →
207 // `Event::PoolDrained`; `was_last == false` →
208 // `Event::PoolNotLast`. Both are terminal alternatives for
209 // the window-cleanup-cascade saga's Step 2.
210 Command::ReportPoolDrainDecision {
211 label,
212 was_last,
213 saga_id,
214 } => {
215 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportPoolDrainDecision") {
216 return Reduced { events: vec![err], diagnostics };
217 }
218 pool::handle_report_pool_drain_decision(state, label, was_last, saga_id)
219 }
220 // Phase F.6 — `ReapPanes` and `DrainPoolIfLast` are
221 // launcher→host direction commands, NOT host→launcher
222 // reports. Same misrouted-error pattern as `SpawnPoolWindow`
223 // above.
224 Command::ReapPanes { .. } => host_pipe_only(state, "ReapPanes"),
225 Command::DrainPoolIfLast { .. } => host_pipe_only(state, "DrainPoolIfLast"),
226 // Phase CPD-1 — host-emitted report that a saga-issued action
227 // failed. Pure pass-through arm: translates the wire command
228 // into `Event::SagaActionFailed`. The saga coordinator's bus
229 // loop (CPD-3) will treat this as a terminal signal for the
230 // matching `saga_id` and emit `Event::SagaFailed`. Host-only
231 // gate same as other Report* arms.
232 Command::ReportSagaActionFailed { saga_id, reason } => {
233 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportSagaActionFailed") {
234 return Reduced { events: vec![err], diagnostics };
235 }
236 saga::handle_report_saga_action_failed(state, saga_id, reason)
237 }
238 // Startup-stage telemetry is NOT mirrored State — it's forwarded
239 // directly into the launcher's StartupEventSink by a short-circuit
240 // in ipc/server.rs BEFORE the command ever reaches this reducer
241 // (same pattern as GetEvents). These arms exist only to satisfy
242 // exhaustiveness; they are unreachable at runtime.
243 Command::ReportStartupStageBegin { .. } | Command::ReportStartupStageEnd { .. } => {
244 vec![]
245 }
246 Command::ReportHostCounts { windows, pool } => {
247 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportHostCounts") {
248 return Reduced { events: vec![err], diagnostics };
249 }
250 handle_report_host_counts(state, windows, pool)
251 }
252 Command::ReportHostPoolCount { count } => {
253 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportHostPoolCount") {
254 return Reduced { events: vec![err], diagnostics };
255 }
256 pool::handle_report_host_pool_count(state, count)
257 }
258 Command::ReportBackendWindowIdRegistered { label, window_id } => {
259 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportBackendWindowIdRegistered") {
260 return Reduced { events: vec![err], diagnostics };
261 }
262 window::handle_report_backend_window_id_registered(state, label, window_id)
263 }
264 Command::ReportBackendWindowIdUnregistered { label } => {
265 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportBackendWindowIdUnregistered") {
266 return Reduced { events: vec![err], diagnostics };
267 }
268 window::handle_report_backend_window_id_unregistered(state, label)
269 }
270 // Phase B.9.1 (WRR) — Win32 reality events. Host-only
271 // because only the host installs the SetWinEventHook /
272 // wndproc wrapper. Same enforce-host pattern as the other
273 // observability reports.
274 Command::ReportHwndOpened { hwnd, class_name, title, label_hint } => {
275 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportHwndOpened") {
276 return Reduced { events: vec![err], diagnostics };
277 }
278 crate::wrr::apply_hwnd_opened(
279 state,
280 hwnd,
281 class_name,
282 title,
283 label_hint,
284 ctx.now_ms,
285 &mut diagnostics,
286 )
287 }
288 Command::ReportHwndDestroyed { hwnd } => {
289 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportHwndDestroyed") {
290 return Reduced { events: vec![err], diagnostics };
291 }
292 let host_running = connection::host_is_running(state);
293 crate::wrr::apply_hwnd_destroyed(state, hwnd, host_running)
294 }
295 Command::ReportHwndVisibilityChanged { hwnd, visible } => {
296 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportHwndVisibilityChanged") {
297 return Reduced { events: vec![err], diagnostics };
298 }
299 crate::wrr::apply_hwnd_visibility_changed(state, hwnd, visible, ctx.now_ms)
300 }
301 Command::ReportHwndForegroundChanged { hwnd } => {
302 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportHwndForegroundChanged") {
303 return Reduced { events: vec![err], diagnostics };
304 }
305 crate::wrr::apply_hwnd_foreground_changed(state, hwnd, ctx.now_ms)
306 }
307 Command::ReportHwndIconicChanged { hwnd, iconic } => {
308 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportHwndIconicChanged") {
309 return Reduced { events: vec![err], diagnostics };
310 }
311 crate::wrr::apply_hwnd_iconic_changed(state, hwnd, iconic)
312 }
313 Command::ReportHwndPositionChanged { hwnd, rect } => {
314 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportHwndPositionChanged") {
315 return Reduced { events: vec![err], diagnostics };
316 }
317 crate::wrr::apply_hwnd_position_changed(state, hwnd, rect, &mut diagnostics)
318 }
319 Command::ReportMonitorTopologyChanged { rects } => {
320 if let Some(err) = connection::enforce_host_only(state, ctx, "ReportMonitorTopologyChanged") {
321 return Reduced { events: vec![err], diagnostics };
322 }
323 crate::wrr::apply_monitor_topology_changed(state, rects)
324 }
325 // Phase D.1 — read-only snapshot of canonical state. Any
326 // registered client can ask; no host-only gate. Reducer state
327 // is unchanged by this command (it's a query, not a mutation),
328 // but we still bump `event_version` so the snapshot's version
329 // is monotonically distinct from prior events — a subscriber
330 // applying snapshot + delta events knows the snapshot's
331 // version is the "as-of" point.
332 Command::GetSnapshot => connection::handle_get_snapshot(state),
333 // Phase D.3 — `GetEvents` is intercepted by the IPC server's
334 // dispatch path BEFORE reaching the reducer (it's a non-
335 // mutating read against the event log, which is I/O-adjacent
336 // — keeping it out of the pure reducer preserves the
337 // "reducer never blocks" invariant). This arm exists only
338 // to satisfy the exhaustive match; in practice it's
339 // unreachable. Returning empty Vec is the safe no-op.
340 Command::GetEvents { .. } => Vec::new(),
341 // Phase E.2 — srv-pipe domain commands routed to launcher
342 // pipe by mistake.
343 Command::CreateWorkspace { .. } => srv_pipe_only(state, "CreateWorkspace"),
344 Command::DeleteWorkspace { .. } => srv_pipe_only(state, "DeleteWorkspace"),
345 // Phase E.2b — Tab arms are also srv-pipe commands.
346 Command::CreateTab { .. } => srv_pipe_only(state, "CreateTab"),
347 Command::DeleteTab { .. } => srv_pipe_only(state, "DeleteTab"),
348 Command::SetActiveTab { .. } => srv_pipe_only(state, "SetActiveTab"),
349 Command::ReorderTab { .. } => srv_pipe_only(state, "ReorderTab"),
350 // Phase E.5 — window↔workspace mapping commands are srv-pipe.
351 Command::CreateWindow { .. } => srv_pipe_only(state, "CreateWindow"),
352 Command::CloseWindowInternal { .. } => srv_pipe_only(state, "CloseWindowInternal"),
353 Command::SwitchWorkspace { .. } => srv_pipe_only(state, "SwitchWorkspace"),
354 // Phase E.5.3 — atomic single-step domain commands are srv-pipe.
355 Command::ReorderTabsBulk { .. } => srv_pipe_only(state, "ReorderTabsBulk"),
356 Command::RenameWorkspace { .. } => srv_pipe_only(state, "RenameWorkspace"),
357 Command::RenameTab { .. } => srv_pipe_only(state, "RenameTab"),
358 Command::UpdateWorkspaceMeta { .. } => srv_pipe_only(state, "UpdateWorkspaceMeta"),
359 Command::UpdateTabMeta { .. } => srv_pipe_only(state, "UpdateTabMeta"),
360 Command::UpdateBlockMeta { .. } => srv_pipe_only(state, "UpdateBlockMeta"),
361 // Phase E.3 — Block arms are also srv-pipe commands.
362 Command::CreateBlock { .. } => srv_pipe_only(state, "CreateBlock"),
363 Command::DeleteBlock { .. } => srv_pipe_only(state, "DeleteBlock"),
364 // Phase E.5.5 — saga-driven move commands are srv-pipe.
365 Command::MoveTab { .. } => srv_pipe_only(state, "MoveTab"),
366 Command::MoveBlock { .. } => srv_pipe_only(state, "MoveBlock"),
367 Command::PinBlock { .. } | Command::UnpinBlock { .. } => srv_pipe_only(state, "PinBlock"),
368 Command::ParkBlock { .. } => srv_pipe_only(state, "ParkBlock"),
369 Command::AttachBlock { .. } => srv_pipe_only(state, "AttachBlock"),
370 // Phase E.4 (Option A) — layout-focused/magnified setters are
371 // srv-pipe commands. Misrouted to the launcher pipe, return
372 // a non-fatal error so the client knows the dispatch was wrong.
373 Command::SetFocusedNode { .. } => srv_pipe_only(state, "SetFocusedNode"),
374 Command::SetMagnifiedNode { .. } => srv_pipe_only(state, "SetMagnifiedNode"),
375 // Phase E.1b — `GetSrvSnapshot` is a srv-pipe command. If a
376 // registered client misroutes it to the launcher pipe, return
377 // an explicit error so the client knows the dispatch was
378 // wrong (vs silently appearing successful with no reply).
379 // Pre-Register, `enforce_register_first` already returns a
380 // soft error. (codex P2 #610.)
381 Command::GetSrvSnapshot => srv_pipe_only(state, "GetSrvSnapshot"),
382 // Phase E.4.B — layout-tree commands are srv-pipe only; same
383 // soft-error treatment as GetSrvSnapshot above.
384 Command::LayoutDeleteNode { .. }
385 | Command::LayoutDeleteNodeByBlock { .. }
386 | Command::LayoutStackPush { .. }
387 | Command::LayoutStackActivate { .. }
388 | Command::CreateBlockInStack { .. }
389 | Command::LayoutStackMove { .. }
390 | Command::LayoutStackMoveMany { .. }
391 | Command::LayoutApplyIntent { .. }
392 | Command::LayoutQueueBackendActions { .. }
393 | Command::LayoutSetTree { .. }
394 | Command::UpdateWindowMeta { .. } => misrouted(
395 state,
396 "Srv-pipe command (Layout/UpdateWindowMeta) sent to launcher pipe by mistake".to_string(),
397 ),
398 };
399
400 // Heartbeat-via-traffic: drain any deferred hidden-since-open
401 // drifts AFTER the command processes. Running this AFTER (not
402 // before) is critical — the command itself may legitimately clear
403 // the deferred state (visible=true / foreground / window closed),
404 // and a pre-command drain would fire spurious drift on an event
405 // whose own purpose is the recovery (codex P2 PR #725 round 2).
406 //
407 // Catches windows that hid during placement and produced no
408 // further visibility events: any subsequent unrelated command
409 // past the grace promotes the deferred state to a fired drift.
410 let mut deferred = crate::wrr::drain_deferred_hidden_since_open(state, ctx.now_ms);
411 cmd_events.append(&mut deferred);
412 Reduced { events: cmd_events, diagnostics }
413}
414
415/// A command that belongs on another pipe reached the launcher's. Reply
416/// with a non-fatal error so the client knows its dispatch was wrong,
417/// rather than seeing no reply at all.
418fn misrouted(state: &mut State, message: String) -> Vec<Event> {
419 let v = state.bump_version();
420 vec![Event::Error {
421 code: ErrorCode::InvalidCommand,
422 message,
423 fatal: false,
424 version: v,
425 }]
426}
427
428/// `misrouted` for a command only srv's pipe handles.
429fn srv_pipe_only(state: &mut State, command: &str) -> Vec<Event> {
430 misrouted(
431 state,
432 format!("{command} is a srv-pipe command; sent to launcher pipe by mistake"),
433 )
434}
435
436/// `misrouted` for a command the launcher sends to the host, never receives.
437fn host_pipe_only(state: &mut State, command: &str) -> Vec<Event> {
438 misrouted(
439 state,
440 format!("{command} is a launcher→host command; sent to launcher pipe by mistake"),
441 )
442}
443
444/// Phase B.4 follow-up — drift check. Compares host-reported counts
445/// to launcher mirror counts; emits `DriftDetected` for each
446/// disagreeing dimension. Returns `[]` when both counts match (the
447/// happy path; mirrors are in sync).
448///
449/// Two events possible (windows + pool) when both diverge in the
450/// same report — emitted in a stable order (windows first) so test
451/// assertions don't depend on HashSet iteration order.
452fn handle_report_host_counts(state: &mut State, host_windows: u32, host_pool: u32) -> Vec<Event> {
453 let mut out = Vec::new();
454 let mirror_windows = state.windows.len() as u32;
455 let mirror_pool = state.pool.len() as u32;
456 if mirror_windows != host_windows {
457 let v = state.bump_version();
458 out.push(Event::DriftDetected {
459 kind: DriftKind::Windows,
460 host_count: host_windows,
461 mirror_count: mirror_windows,
462 version: v,
463 });
464 }
465 if mirror_pool != host_pool {
466 let v = state.bump_version();
467 out.push(Event::DriftDetected {
468 kind: DriftKind::Pool,
469 host_count: host_pool,
470 mirror_count: mirror_pool,
471 version: v,
472 });
473 }
474 out
475}
476
477#[cfg(test)]
478mod tests;