Skip to main content

agentmux_common/ipc/
command.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The commands a client sends to the launcher, and the connection kinds that send them.
5
6use super::*;
7use serde::{Deserialize, Serialize};
8
9/// Stable identifier for a connected client. Tagged so the launcher
10/// can route replies + log who said what.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(rename_all = "lowercase")]
13pub enum ClientKind {
14    /// The CEF host process (one per launcher run).
15    Host,
16    /// A frontend renderer (proxied via the host's CEF JS bridge — Phase B.7).
17    Renderer,
18    /// The agentmux-srv backend (proxy connection used for Quit ack
19    /// + process-tree facts; the workspace data path stays on
20    /// HTTP/WS through host).
21    Srv,
22    /// External tooling (`agentmux.exe --diag` etc.).
23    Tool,
24}
25
26/// Commands flow client → launcher.
27#[derive(Debug, Clone, Serialize, Deserialize)]
28#[serde(tag = "cmd", rename_all = "snake_case")]
29pub enum Command {
30    /// Identifies the connection. MUST be the first command on every
31    /// new connection. Server enforces.
32    Register {
33        kind: ClientKind,
34        /// PID of the connecting process — used for cross-checking
35        /// against the launcher's `ProcessRecord` map and for
36        /// log correlation.
37        pid: u32,
38        /// Free-form version string of the client binary, for log
39        /// correlation across version skew.
40        version: String,
41    },
42    /// Health probe — server replies with `Event::Pong` carrying the
43    /// same nonce. NOT a polling heartbeat (per spec §4.3) — sent
44    /// only on demand by clients that need round-trip confirmation.
45    Ping {
46        nonce: u64,
47    },
48    /// SPEC_LAUNCHER_TEARDOWN_BACKSTOP_2026_07_11 Phase 1 — launcher → host
49    /// (over the host pipe, like the saga `IssueCmd::Host` commands): probe
50    /// whether the host's CEF **UI thread** is actually pumping. The host
51    /// replies with `ReportUiThreadAlive { nonce }` from a posted UI task —
52    /// NEVER from the pipe-reader thread (a wedged host's tokio reader keeps
53    /// answering; only a UI-thread round-trip is liveness evidence). A host
54    /// whose UI thread is hung, or not yet pumping (the known pre-ready
55    /// `post_task` silent drop), simply never replies — silence is the
56    /// signal; there is no host-side timeout.
57    ProbeUiThread {
58        nonce: u64,
59    },
60    /// Reply to `ProbeUiThread`, sent host → launcher via the `Report*`
61    /// path once the probe's posted UI task actually executes. Echoes the
62    /// nonce; the launcher treats ANY receipt as "UI thread pumped after
63    /// the matching probe was sent" (staleness bounded by the probe
64    /// interval, which is all the Phase-2 rule consumes).
65    ReportUiThreadAlive {
66        nonce: u64,
67    },
68    /// Launcher → host: the level of srv's health-probe latency changed —
69    /// the rolling average of the launcher's probe round-trip times crossed a
70    /// threshold. The host shows it through the memory-pressure banner system
71    /// as kind `"backend"`. `level` is `"normal" | "warn" | "critical"`.
72    /// See docs/analysis/ANALYSIS_SRV_HTTP_STALL_IO_DRIVER_STARVATION_2026_09_26.md §8.2.
73    NotifySrvLatency {
74        level: String,
75        avg_ms: u64,
76    },
77    /// Launcher → host: quit gracefully, as the host's `quit_app` command does (tray Quit, agreed upgrade restart).
78    QuitApp,
79    /// Graceful disconnect. Server logs and closes the connection.
80    /// In B.3+ this becomes `Quit { reason }` with shutdown semantics;
81    /// for B.2 it's just a polite goodbye.
82    Goodbye,
83    /// Phase B.4: host reports that a real window has been created
84    /// (CEF `on_after_created` fired). Launcher records it in its
85    /// read-only mirror and broadcasts `Event::WindowOpened` to other
86    /// subscribers. Pool windows do NOT report via this command —
87    /// they get their own `ReportPool*` commands in a follow-up so
88    /// the mirror can distinguish user-visible windows from pool
89    /// inventory.
90    ReportWindowOpened {
91        /// Stable label assigned by the host (e.g. "main", "window-{uuid}").
92        label: String,
93        kind: WindowKind,
94        /// For `Subwindow` only: label of the `FullInstance` parent.
95        /// `None` for `FullInstance`.
96        parent_label: Option<String>,
97    },
98    /// Phase B.4: host reports a window is closing (`on_before_close`).
99    /// Launcher removes from mirror, broadcasts `Event::WindowClosed`.
100    /// Idempotent: a missing label is logged but not an error (covers
101    /// the close-before-launcher-saw-the-open race).
102    ReportWindowClosed {
103        label: String,
104    },
105    /// Workstream 0 Phase 1 (`SPEC_TRAY_OPTIONAL_BACKGROUND_SERVICE_2026_09_04.md`
106    /// §7) — host reports whether background-service mode
107    /// (`AGENTMUX_BACKGROUND_SERVICE`) is enabled for this process. Sent
108    /// once, right after connecting (mirrors `GetSnapshot`'s
109    /// once-per-connect timing). The launcher's own last-window
110    /// orphan-drift detection and the teardown backstop it arms must not
111    /// treat an intentionally-resting host (zero windows, by design, for
112    /// however long the user leaves it) as a stuck/orphaned one — see
113    /// PR #2983 review (Codex P2). Host-only.
114    ReportBackgroundServiceEnabled {
115        enabled: bool,
116    },
117    /// Phase B.4 follow-up — host reports a pre-warmed pool window
118    /// being added (`spawn_pool_window`). Pool windows live in a
119    /// SEPARATE map from the user-visible window mirror; the host
120    /// transitions them out of the pool with `ReportPoolWindowRemoved`
121    /// + `ReportWindowOpened` on promote, or just
122    /// `ReportPoolWindowRemoved` on pre-promote destroy.
123    ReportPoolWindowAdded {
124        label: String,
125        /// Phase CPD-1 (cross-process dispatch) — saga correlation
126        /// echo. `Some(N)` when the host is replying to a saga-issued
127        /// `Command::SpawnPoolWindow { saga_id: N }`; `None` for
128        /// organic refills (e.g. host's implicit `spawn_pool_window`
129        /// inside `promote_pool_window`). The launcher reducer
130        /// passes the value through to `Event::PoolWindowAdded` so
131        /// per-saga correlation (CPD-4) can match the response to
132        /// the originating saga.
133        ///
134        /// `#[serde(default)]` for forward-compat with hosts running
135        /// pre-CPD-1 builds — they emit no `saga_id` field, which
136        /// deserializes as `None` (organic). Removed once CPD-1+CPD-3
137        /// have soaked one release cycle.
138        #[serde(default)]
139        saga_id: Option<u64>,
140    },
141    /// Phase B.4 follow-up — host reports a pool window leaving the
142    /// pool (promote, destroy, or app exit).
143    ReportPoolWindowRemoved {
144        label: String,
145    },
146    /// Phase B.4 follow-up — drift detection (full snapshot). Host
147    /// sends its own post-mutation counts after each window-level
148    /// transition; the launcher reducer compares both dimensions to
149    /// its mirror counts and emits `Event::DriftDetected` per
150    /// disagreeing dimension. Sent in a separate command (rather
151    /// than embedded in each Report*) so the existing wire shapes
152    /// stay unchanged.
153    ///
154    /// Known limitation (B.4 observe-only): emissions originate
155    /// from multiple execution contexts (CEF UI thread for
156    /// `on_after_created`/`on_before_close`, IPC handler thread
157    /// for `promote_pool_window`). Cross-thread interleaving in
158    /// the outbound channel can produce a snapshot whose counts
159    /// were taken at a moment that doesn't match the channel
160    /// order seen by the reducer, occasionally emitting a
161    /// transient false `DriftDetected`. Acceptable for B.4
162    /// (drift is diagnostic — false positives are ephemeral and
163    /// self-correct on the next stable state). B.5 will tighten
164    /// with a transition-ID protocol once the launcher is
165    /// authoritative. (codex P2 PR #578 round-4 — accepted as
166    /// known limitation.)
167    ReportHostCounts {
168        /// User-visible top-level windows in the host's
169        /// authoritative store (`browsers` minus browser-pane
170        /// children minus unpromoted pool labels).
171        windows: u32,
172        /// Pre-promote pool inventory size.
173        pool: u32,
174    },
175    /// Phase B.4 follow-up — pool-dimension-only drift check. Used
176    /// by `spawn_pool_window` (pool transitions) where snapshotting
177    /// the windows dimension would produce transient false drift:
178    /// pool refill is triggered DURING `on_before_close` BEFORE the
179    /// matching `ReportWindowClosed` lands, so the host's window
180    /// count is mid-flight relative to the launcher mirror. Pool
181    /// count IS stable at that moment (the new pool label was just
182    /// added), so checking pool alone preserves the "check every
183    /// transition" guarantee for the dimension that actually
184    /// changed. (codex P2 PR #578 round-3.)
185    ReportHostPoolCount {
186        count: u32,
187    },
188    /// Phase B.5 (window_id_map step a) — host reports the
189    /// frontend's `register_backend_window` call: a window's label
190    /// → backend window ID (a srv-side UUID the frontend resolves
191    /// via `MOS.makeORef`). The launcher mirrors it for the same
192    /// reasons it mirrors `instance_registry`: host's authoritative
193    /// copy will be retired through the a→b→c→d→e ratchet.
194    ReportBackendWindowIdRegistered {
195        label: String,
196        window_id: String,
197    },
198    /// Phase B.5 (window_id_map step a) — host reports a window
199    /// closing, so the launcher should drop the label→window_id
200    /// mapping. Sent from the same close path that emits
201    /// `ReportWindowClosed`.
202    ReportBackendWindowIdUnregistered {
203        label: String,
204    },
205    /// Phase B.9.1 (WRR — Window Reality Reconciliation) — host
206    /// reports a Win32 top-level window was created. Hooked off
207    /// `EVENT_OBJECT_CREATE` (objid=`OBJID_WINDOW`) via
208    /// `SetWinEventHook(WINEVENT_OUTOFCONTEXT)`. The host filters
209    /// CEF subprocess HWNDs (renderer, GPU, plugin) at the hook
210    /// callback so the launcher only sees plausible app windows.
211    /// `label_hint` is the host's best guess from
212    /// `pending_window_creations` if it can disambiguate; `None`
213    /// when the create event arrives before the host has linked
214    /// the HWND back to a label (caught up later by the reducer's
215    /// pending_hwnds).
216    ReportHwndOpened {
217        hwnd: u64,
218        class_name: String,
219        title: String,
220        label_hint: Option<String>,
221    },
222    /// Phase B.9.1 — host reports a Win32 top-level window was
223    /// destroyed. Hooked off `EVENT_OBJECT_DESTROY`.
224    ReportHwndDestroyed {
225        hwnd: u64,
226    },
227    /// Phase B.9.1 — `EVENT_OBJECT_SHOW` / `EVENT_OBJECT_HIDE`.
228    ReportHwndVisibilityChanged {
229        hwnd: u64,
230        visible: bool,
231    },
232    /// Phase B.9.1 — `EVENT_SYSTEM_FOREGROUND`. Tells the launcher
233    /// the user actually saw this window (not just opened it).
234    /// Used to distinguish "opened but never foregrounded" (drift)
235    /// from "opened and shown".
236    ReportHwndForegroundChanged {
237        hwnd: u64,
238    },
239    /// Phase B.9.1 — `EVENT_SYSTEM_MINIMIZESTART` /
240    /// `EVENT_SYSTEM_MINIMIZEEND`.
241    ReportHwndIconicChanged {
242        hwnd: u64,
243        iconic: bool,
244    },
245    /// Phase B.9.1 — `WM_WINDOWPOSCHANGED` from the host's wndproc
246    /// wrapper. The host coalesces bursts (50ms debounce per HWND)
247    /// before sending so the wire stays light during topology
248    /// changes. Reducer compares `rect` against `state.monitors` to
249    /// classify off-monitor drift.
250    ReportHwndPositionChanged {
251        hwnd: u64,
252        rect: Rect,
253    },
254    /// Phase B.9.1 — `WM_DISPLAYCHANGE`. Replaces the launcher's
255    /// `state.monitors` wholesale; reducer re-evaluates every
256    /// known window's last_rect against the new topology and
257    /// emits `OffMonitor` drift for any that newly fall off.
258    ReportMonitorTopologyChanged {
259        rects: Vec<Rect>,
260    },
261    /// Phase D.1 — request a `Event::Snapshot` reply containing the
262    /// reducer's current canonical state. Used by `--diag wrr` for
263    /// state-now visibility, by the frontend reducer for mid-session
264    /// resync after disconnect, and by future Tool clients that need
265    /// to bootstrap without observing every prior event.
266    GetSnapshot,
267    /// Phase E.1b — srv-side equivalent of `GetSnapshot`. Routed to
268    /// the srv pipe; reducer replies with `Event::SrvSnapshot`.
269    /// Separate from `GetSnapshot` (launcher) per spec §4.3 — each
270    /// reducer is canonical for its domain and replies on its own
271    /// pipe.
272    ///
273    /// Reply contents grow with each phase: E.1b had lifecycle +
274    /// version only; E.2 added `workspaces`; E.2b+ will add tabs /
275    /// blocks / layouts. See `Event::SrvSnapshot` for the current
276    /// shape.
277    GetSrvSnapshot,
278    /// Phase E.2 — create a new workspace and emit
279    /// `Event::WorkspaceCreated`. Its `oid` is minted by the dispatcher
280    /// (srv's `reducer::Ctx::new_id`), not the reducer.
281    CreateWorkspace {
282        name: String,
283    },
284    /// Phase E.2 — delete a workspace. Reducer removes from canonical
285    /// state and emits `Event::WorkspaceDeleted`. Cascade-to-tabs +
286    /// SQLite write happen via wcore today (RPC path); migrating to
287    /// reducer-driven persistence is E.2c.
288    DeleteWorkspace {
289        workspace_id: String,
290        /// Step 5 PR 2 — provenance marker for the `delete_workspace`
291        /// saga. `true` means the dispatch is being driven by the
292        /// saga coordinator (per-tab DeleteTab dispatches already
293        /// happened in saga steps; this final cascade is just the
294        /// workspace row + window mappings). `false` for legacy /
295        /// internal compensation paths (e.g. `tear_off_tab` /
296        /// `tear_off_block` rolling back a freshly-created empty
297        /// workspace) which keep the existing cascade behaviour.
298        ///
299        /// The reducer's `handle_delete_workspace` cascades regardless
300        /// of `force` — the reducer is a pure mutator and the cascade
301        /// must always execute to keep state consistent. The flag is
302        /// recorded in the saga log purely for provenance, mirroring
303        /// the saga-as-narrator pattern documented in
304        /// `docs/retro/phase-fg-roadmap-2026-05-01.md`.
305        ///
306        /// Defaults to `false` via `#[serde(default)]` so all existing
307        /// producers (RPC, internal compensation) keep working.
308        #[serde(default)]
309        force: bool,
310    },
311    /// Phase E.2b — create a tab inside an existing workspace, append it
312    /// to the workspace's ordered tab list, and emit `Event::TabCreated`.
313    /// Its `tab_id` is minted by the dispatcher (srv's
314    /// `reducer::Ctx::new_id`). Returns `Event::Error` if the parent
315    /// workspace doesn't exist.
316    CreateTab {
317        workspace_id: String,
318        name: String,
319    },
320    /// Phase E.2b — delete a tab from a workspace. Reducer removes the
321    /// tab from canonical state, removes its id from the workspace's
322    /// ordered tab list, and emits `Event::TabDeleted`. If the deleted
323    /// tab was the active tab, also emits `Event::ActiveTabChanged`
324    /// pointing at the new active (next-or-prev tab, or empty if the
325    /// workspace has no tabs left).
326    DeleteTab {
327        workspace_id: String,
328        tab_id: String,
329        /// (codex P2 PR #633 round 4 + codex P1 round 2.) Bypass the
330        /// reducer's atomic last-tab guard. `false` for user-facing
331        /// flows (close button, keyboard shortcut) — reducer rejects
332        /// last-tab deletes to keep workspaces non-empty. `true` for
333        /// internal compensation paths (`CreateTab` rollback,
334        /// `PromoteBlockToTab` compensation) where rolling back a
335        /// just-created tab requires deleting the only tab.
336        ///
337        /// Defaults to `false` via `#[serde(default)]` for backwards
338        /// compatibility — pre-existing producers that don't set the
339        /// field get the safe (guarded) behavior.
340        #[serde(default)]
341        force: bool,
342    },
343    /// Phase E.2b — set a workspace's active tab. No-op if already
344    /// active. Errors if the workspace doesn't exist or the tab isn't
345    /// in that workspace's tab list.
346    SetActiveTab {
347        workspace_id: String,
348        tab_id: String,
349    },
350    /// Phase E.2c.3b — reorder a tab within its workspace's
351    /// `tab_ids`. `new_index` is clamped to the list length; no-op
352    /// if the tab is already at that position. Errors if the
353    /// workspace doesn't exist or the tab isn't in its tab list.
354    ReorderTab {
355        workspace_id: String,
356        tab_id: String,
357        new_index: u32,
358    },
359    /// Phase E.5 — record a new window in the srv reducer's
360    /// `state.windows` map. Caller pre-assigns `window_id` (sagas
361    /// use a fresh UUID; RPC migration in PR 4 will likewise mint
362    /// the id at the RPC boundary). Validates the parent workspace
363    /// exists; errors otherwise. Used by CreateWindow + TearOff
364    /// sagas to track window↔workspace association.
365    CreateWindow {
366        window_id: String,
367        workspace_id: String,
368    },
369    /// Phase E.5 — remove a window's workspace mapping from the
370    /// reducer. Called by CloseWindow sagas after the host's CEF
371    /// window-close completes. Idempotent silent no-op on missing.
372    CloseWindowInternal {
373        window_id: String,
374    },
375    /// Phase E.5 — switch which workspace a window points at.
376    /// Errors if the window or destination workspace is unknown.
377    SwitchWorkspace {
378        window_id: String,
379        workspace_id: String,
380    },
381    /// Phase E.5.3 — replace a workspace's `tab_ids` with the given
382    /// list. The new list must be a permutation of the current set
383    /// (same elements, possibly different order); reducer errors
384    /// otherwise. Used by the drag-reorder UI's bulk-reorder path
385    /// (replaces wcore-direct `UpdateTabIds`).
386    ReorderTabsBulk {
387        workspace_id: String,
388        tab_ids: Vec<String>,
389    },
390    /// Phase E.5.3 — rename a workspace. Errors if the workspace
391    /// doesn't exist; no-op if the name is identical.
392    RenameWorkspace {
393        workspace_id: String,
394        name: String,
395    },
396    /// Phase E.5.3 — rename a tab. Errors if the tab doesn't exist;
397    /// no-op if identical.
398    RenameTab {
399        tab_id: String,
400        name: String,
401    },
402    /// Phase E.5.3 — apply a meta-patch to a workspace. The reducer
403    /// validates the entity exists and emits `Event::WorkspaceMetaUpdated`
404    /// with the patch payload; the persist subscriber performs the
405    /// actual merge against mstore. Reducer state does NOT track meta
406    /// in E.5.3 — pass-through preserves the reducer's small footprint
407    /// without losing the migration property (every mutation goes
408    /// through the reducer's broadcast bus).
409    UpdateWorkspaceMeta {
410        workspace_id: String,
411        meta_patch: serde_json::Value,
412    },
413    /// Phase E.5.3 — apply a meta-patch to a tab. Same pass-through
414    /// shape as `UpdateWorkspaceMeta`.
415    UpdateTabMeta {
416        tab_id: String,
417        meta_patch: serde_json::Value,
418    },
419    /// Phase E.5.3 — apply a meta-patch to a block. Same pass-through
420    /// shape as `UpdateWorkspaceMeta`.
421    UpdateBlockMeta {
422        block_id: String,
423        meta_patch: serde_json::Value,
424    },
425    /// Phase E.5.x — apply a meta-patch to a window's `meta` map.
426    /// Same pass-through shape as `UpdateWorkspaceMeta`. Migrated
427    /// through the reducer per issue #855 so `Event::WindowMetaUpdated`
428    /// lands on `srv_events_tx` and the MuxObjUpdate broadcast bridge
429    /// picks it up — replaces the wcore-direct fallback that bypassed
430    /// reducer + bridge entirely.
431    UpdateWindowMeta {
432        window_id: String,
433        meta_patch: serde_json::Value,
434    },
435    /// Phase E.5.5 — move a tab from one workspace to another.
436    /// Reducer:
437    /// * Removes `tab_id` from `src_workspace_id.tab_ids`.
438    /// * Updates `tab.workspace_id = dst_workspace_id`.
439    /// * Inserts `tab_id` at `dst_index` in `dst_workspace_id.tab_ids`,
440    ///   clamping to the dst list length.
441    /// * If `tab_id` was the source workspace's `active_tab_id`, the
442    ///   source's active reverts to its first remaining tab (or
443    ///   `None` if the source becomes empty).
444    ///
445    /// Errors if the source, dest or tab is missing, the tab isn't in the
446    /// source, or it is the source's last tab and `allow_empty_source` is
447    /// false. Used by TearOffTab, MoveTabToWorkspace and RestoreTornOffTab.
448    MoveTab {
449        tab_id: String,
450        src_workspace_id: String,
451        dst_workspace_id: String,
452        dst_index: u32,
453        /// Bypass the last-tab guard, for flows that drain a workspace and
454        /// then delete it. Defaults to `false`, like `DeleteTab.force`.
455        #[serde(default)]
456        allow_empty_source: bool,
457    },
458    /// Phase E.5.5 — move a block from one tab to another (or to a
459    /// different position in the same tab).
460    /// Reducer:
461    /// * Removes `block_id` from `src_tab_id.block_ids`.
462    /// * Updates `block.tab_id = dst_tab_id`.
463    /// * Inserts `block_id` at `dst_index` in `dst_tab_id.block_ids`,
464    ///   clamping to the dst list length.
465    /// Errors if source tab, dest tab, or block is missing, or if
466    /// `block.tab_id != src_tab_id`. Used by TearOffBlock and the
467    /// MoveBlockToTab saga.
468    MoveBlock {
469        block_id: String,
470        src_tab_id: String,
471        dst_tab_id: String,
472        dst_index: u32,
473    },
474    /// Pin a pane to its window (`agentmux_common::pin`): `block_id`, a pane of one of the workspace's tabs, joins
475    /// the workspace's `pins`. Nothing moves: the block stays in its tab and in its layout. Refused past `MAX_PINS`.
476    PinBlock { workspace_id: String, block_id: String },
477    /// Unpin a pane: `block_id` leaves the workspace's `pins`. Nothing moves.
478    UnpinBlock { workspace_id: String, block_id: String },
479    /// Phase E.3 — create a block inside an existing tab, append it to
480    /// the tab's `block_ids`, and emit `Event::BlockCreated`. Its
481    /// `block_id` is minted by the dispatcher (srv's
482    /// `reducer::Ctx::new_id`). Returns `Event::Error` if the parent tab
483    /// doesn't exist.
484    CreateBlock {
485        tab_id: String,
486        /// Phase E.2c.4 — block metadata (`view`, layout hints, etc.)
487        /// passed through to the persisted Block row. The reducer
488        /// itself doesn't track meta — it forwards it untouched into
489        /// `Event::BlockCreated` so the persist subscriber writes
490        /// the Block with the correct meta map. `#[serde(default)]`
491        /// for forward-compat with old log entries that pre-date the
492        /// meta field.
493        #[serde(default)]
494        meta: serde_json::Value,
495    },
496    /// Take an agent's block out of `tab_id` and keep it, in no tab. No-op when it isn't in that
497    /// tab. The layout node goes separately (`LayoutDeleteNodeByBlock`).
498    ParkBlock {
499        tab_id: String,
500        block_id: String,
501    },
502    /// Put a parked block into `dst_tab_id` at `dst_index` (clamped); errors when it is in a tab.
503    AttachBlock {
504        block_id: String,
505        dst_tab_id: String,
506        dst_index: u32,
507    },
508    /// Phase E.3 — delete a block from a tab. Idempotent silent no-op
509    /// on missing tab or missing block.
510    DeleteBlock {
511        tab_id: String,
512        block_id: String,
513    },
514    /// Phase E.4 (Option A) — set a tab's `focusednodeid`. Errors if
515    /// the tab is unknown to the reducer; no-op short-circuit when the
516    /// value is already current. Empty `node_id` clears the field.
517    /// Routes through the reducer so the persist subscriber writes the
518    /// new value into `LayoutState.focusednodeid` for the tab. The
519    /// rest of `LayoutState` (rootnode/pendingbackendactions)
520    /// keeps its existing wcore-direct path until Option B lands.
521    SetFocusedNode {
522        tab_id: String,
523        node_id: String,
524    },
525    /// Phase E.4 (Option A) — set a tab's `magnifiednodeid`. Same
526    /// shape as `SetFocusedNode`; empty `node_id` clears (toggle-off).
527    SetMagnifiedNode {
528        tab_id: String,
529        node_id: String,
530    },
531
532    // ── Phase E.4.B — Layout tree commands ──────────────────────────────
533    //
534    // The frontend's own tree edits arrive as `LayoutApplyIntent`; the
535    // rest are srv's (deletes by block, pane tabs, seeding, the queue).
536    // See docs/specs/srv-phase-e4b-formal-spec-2026-05-03.md §5.
537
538    /// Remove a node by id; collapse empty parents.
539    LayoutDeleteNode {
540        tab_id: String,
541        node_id: String,
542        correlation_id: String,
543    },
544    /// Remove the node holding `block_id`; collapse empty parents.
545    /// SPEC_864 site #6 — the block→node resolution happens in the
546    /// reducer arm (the reducer owns the tree), so callers that only
547    /// know a block id (the `delete_block` saga) don't need tree
548    /// access. Resolving to no node is a silent idempotent no-op:
549    /// blocks may legitimately have no layout node (already removed by a
550    /// layout intent, or never laid out).
551    LayoutDeleteNodeByBlock {
552        tab_id: String,
553        block_id: String,
554        correlation_id: String,
555    },
556    /// Add `block_id` to the tab stack of the pane holding
557    /// `target_block_id`, optionally as the visible tab.
558    /// SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.2.
559    LayoutStackPush {
560        tab_id: String,
561        target_block_id: String,
562        block_id: String,
563        activate: bool,
564        correlation_id: String,
565    },
566    /// Make `block_id` the visible tab of the pane whose stack holds it.
567    LayoutStackActivate {
568        tab_id: String,
569        block_id: String,
570        correlation_id: String,
571    },
572    /// Create a block AND place it in the tab stack of the pane holding
573    /// `target_block_id`, in one reducer step — the block never exists
574    /// without a pane (the two-step `pane.open { skip_placement }` + frontend
575    /// push could be interrupted in between, orphaning it).
576    /// SPEC_PANE_TABS_REDUCER_COMMANDS_2026_09_18.md §3.2.
577    CreateBlockInStack {
578        tab_id: String,
579        target_block_id: String,
580        #[serde(default)]
581        meta: serde_json::Value,
582        activate: bool,
583    },
584    /// Move `block_id` to `position` relative to `target_block_id` — a
585    /// same-leaf reorder when both are already members of the same pane's
586    /// stack, otherwise a cross-pane move (removed from its current leaf,
587    /// placed into `target_block_id`'s leaf, promoting a single-block leaf
588    /// into a stack if needed). Refuses (silent no-op-with-error) if
589    /// `block_id` is its source leaf's only member — removing the last
590    /// member is "close the pane," a different command. A same-leaf reorder
591    /// never changes which member is visible unless `activate` is set,
592    /// even when the reordered member was already the visible one.
593    /// SPEC_PANE_TAB_DRAG_AND_DROP_2026_09_19.md §4.1.
594    LayoutStackMove {
595        tab_id: String,
596        block_id: String,
597        target_block_id: String,
598        position: crate::StackMovePosition,
599        activate: bool,
600        correlation_id: String,
601    },
602    /// Move several Pane Tabs into ONE pane in a single edit: every block in
603    /// `block_ids` not already in the pane holding `target_block_id` is
604    /// appended to it, in the order given, as `LayoutStackMove` with
605    /// `position: End` would for each. `activate_block_id`, when present,
606    /// becomes that pane's visible tab. All or nothing: a block or target
607    /// that is not in the tree leaves the tree untouched. A pane emptied by
608    /// the move is removed, as for `LayoutStackMove`.
609    /// SPEC_PANE_TAB_MULTI_SELECT_MOVE_AND_COLLAPSED_EXPAND_2026_10_24.md §5.
610    LayoutStackMoveMany {
611        tab_id: String,
612        block_ids: Vec<String>,
613        target_block_id: String,
614        #[serde(default)]
615        activate_block_id: Option<String>,
616        correlation_id: String,
617    },
618    /// Apply a layout intent to the tab's tree: the frontend's own tree
619    /// action, computed and normalized by the reducer.
620    /// SPEC_STRONG_REDUCER_AUTHORITY_LAYOUT_2026_06_30.md §4.
621    ///
622    /// `action_id` names it: branches it creates get ids derived from it,
623    /// and a repeat of a recent id is a no-op. `view` is the sender's
624    /// focused and magnified pane after the intent (`None`: the intent's own
625    /// `focused`/`magnified` flags decide, as for srv's own placements).
626    LayoutApplyIntent {
627        tab_id: String,
628        intent: crate::LayoutIntent,
629        action_id: String,
630        #[serde(default, skip_serializing_if = "Option::is_none")]
631        view: Option<crate::LayoutViewState>,
632    },
633    /// Bulk-replace the tree. Used during Phase 7a writer migration and
634    /// for tear-off where the whole subtree changes atomically.
635    ///
636    /// `slices` (srv's seeders) carries the rest of the `LayoutState` row
637    /// (focus / magnify / pendingbackendactions) with REPLACE
638    /// semantics. `slices: None` (tree-only callers) leaves those columns
639    /// untouched.
640    LayoutSetTree {
641        tab_id: String,
642        new_tree: Option<crate::LayoutNode>,
643        correlation_id: String,
644        #[serde(default, skip_serializing_if = "Option::is_none")]
645        slices: Option<crate::LayoutClientSlices>,
646    },
647    /// SPEC_864 Phase 4 — append actions to a tab's
648    /// `pendingbackendactions` queue through the reducer. `actions` is a
649    /// JSON array of `LayoutActionData` objects (raw-value pass-through;
650    /// the reducer does not model the queue — see
651    /// `Event::LayoutBackendActionsQueued`).
652    LayoutQueueBackendActions {
653        tab_id: String,
654        actions: serde_json::Value,
655        correlation_id: String,
656    },
657
658    /// Phase D.3 — request an `Event::EventList` reply containing the
659    /// events the launcher has emitted with version > `since`. Used
660    /// by subscribers that hold a snapshot at version V and want to
661    /// catch up to the live stream by replaying missed events.
662    ///
663    /// Typical resync flow:
664    ///   1. `Register` → `Registered { version: V0 }`
665    ///   2. `GetSnapshot` → `Snapshot { version: V1 }` (V1 > V0)
666    ///      — apply the snapshot
667    ///   3. `GetEvents { since: V1 }` → `EventList { events, version: V2 }`
668    ///      — apply replay events to catch up to V2
669    ///   4. live broadcast events flow with version > V2
670    ///
671    /// Replay is best-effort: the launcher's in-memory ring is
672    /// bounded; if `since` is older than the oldest retained event,
673    /// the reply still contains all retained events but the
674    /// subscriber may have missed some. Caller should treat the
675    /// result as "everything I have for you" and re-fetch a snapshot
676    /// if state inconsistency is detected.
677    GetEvents {
678        /// Exclusive lower bound — events with `version > since` are
679        /// returned, in ascending order.
680        since: u64,
681    },
682    /// Phase F.5 — host explicitly reports that a pool window was
683    /// promoted to a user-visible top-level window (the
684    /// `promote_pool_window` flow in `agentmux-cef`). Sent BETWEEN the
685    /// `ReportPoolWindowRemoved` + `ReportWindowOpened` pair so the
686    /// launcher reducer has unambiguous evidence the transition was a
687    /// promote (vs a destroy followed by an unrelated open) and can
688    /// emit `Event::PoolWindowPromoted`. The pool-respawn saga
689    /// consumes the event to bracket the implicit refill in
690    /// `SagaStarted`/`SagaCompleted`.
691    ///
692    /// Host-only — same gate as `ReportPoolWindowRemoved`.
693    ReportPoolWindowPromoted {
694        label: String,
695    },
696    /// Phase F.5 — launcher-side saga coordinator asks the host to
697    /// spawn a fresh pool window (refill after promote).
698    ///
699    /// **Status: live.** Cross-process dispatch (CPD-1 through CPD-5)
700    /// shipped; the saga coordinator's `apply_action` for
701    /// `PipeTarget::Host` writes this command through `host_pipe`
702    /// (`crates/launcher/src/host_pipe/`) and waits on the
703    /// `Event::PoolWindowAdded { saga_id: Some(N) }` echo. Host's
704    /// implicit `spawn_pool_window` call inside `promote_pool_window`
705    /// remains the organic refill path for non-saga-driven
706    /// promotions (with `saga_id: None`).
707    ///
708    /// `saga_id`: every host-bound command carries the originating
709    /// saga's id so the host can echo it on the corresponding
710    /// `Report*` reply. `0` is reserved as "no saga" and treated as a
711    /// non-saga dispatch. `#[serde(default)]` retained for
712    /// forward-compat with any pre-CPD-1 deserializers (no real-world
713    /// consumer today; portable runtime is bundled per release).
714    SpawnPoolWindow {
715        #[serde(default)]
716        saga_id: u64,
717    },
718    /// Phase F.6 — host reports that all browser-pane HWNDs belonging
719    /// to a closing top-level window have been reaped. Emitted from
720    /// `client.rs::on_before_close` after the subwindow cascade and
721    /// pane lifecycle drain finish for the closing window.
722    ///
723    /// Distinct from `ReportWindowClosed` — that event marks the
724    /// CEF browser leaving the host's `browsers` map; this one marks
725    /// the host's pane bookkeeping (lifecycle entries, pane HWND map)
726    /// for that label being fully drained. Today both happen in the
727    /// same `on_before_close` body so the events arrive back-to-back,
728    /// but the saga distinguishes them so future fine-grained
729    /// reapers (e.g. async pane teardown for embedded browsers) can
730    /// land without rewriting the saga.
731    ///
732    /// Host-only — same gate as `ReportWindowClosed`.
733    ReportPanesReaped {
734        label: String,
735        /// Phase CPD-1 — saga correlation echo. `Some(N)` when the
736        /// host is replying to a saga-issued
737        /// `Command::ReapPanes { saga_id: N }`; `None` for organic
738        /// reports (e.g. host's existing implicit pane drain inside
739        /// `on_before_close` that wasn't saga-driven).
740        ///
741        /// `#[serde(default)]` for forward-compat with pre-CPD-1
742        /// hosts.
743        #[serde(default)]
744        saga_id: Option<u64>,
745    },
746    /// Phase F.6 — host reports the result of the post-close
747    /// drain-pool-if-last decision. `was_last == true` when the
748    /// closing window was the last user-visible window and the host
749    /// just kicked off the warm-pool drain (Stage 1 of the two-stage
750    /// close cascade in `client.rs::on_before_close`); `false` when
751    /// other user-visible windows remain and the pool stays warm.
752    ///
753    /// The launcher's window-cleanup-cascade saga uses this to close
754    /// out its bracket regardless of which branch fires (both are
755    /// terminal for the saga).
756    ///
757    /// Host-only.
758    ReportPoolDrainDecision {
759        label: String,
760        was_last: bool,
761        /// Phase CPD-1 — saga correlation echo. `Some(N)` when the
762        /// host is replying to a saga-issued
763        /// `Command::DrainPoolIfLast { saga_id: N }`; `None` for
764        /// organic reports.
765        ///
766        /// `#[serde(default)]` for forward-compat with pre-CPD-1
767        /// hosts.
768        #[serde(default)]
769        saga_id: Option<u64>,
770    },
771    /// Phase F.6 — launcher-side saga coordinator asks the host to
772    /// reap all browser-pane HWNDs for a window that just closed.
773    ///
774    /// **Status: live.** Wired through `host_pipe` post-CPD-3. The
775    /// saga issues this with `target = PipeTarget::Host`; the
776    /// coordinator's `apply_action` writes it through the host pipe
777    /// and waits for the `Event::PanesReaped { saga_id: Some(N) }`
778    /// echo. Host's organic pane drain inside `on_before_close` still
779    /// emits the same Report with `saga_id: None` for non-saga-driven
780    /// closes.
781    ///
782    /// `saga_id`: mandatory on the wire (host echoes back on
783    /// `ReportPanesReaped`). `#[serde(default)]` retained for
784    /// forward-compat (see `SpawnPoolWindow` for rationale).
785    ReapPanes {
786        label: String,
787        #[serde(default)]
788        saga_id: u64,
789    },
790    /// Phase F.6 — launcher-side saga coordinator asks the host to
791    /// drain the warm pool if the just-closed window was the last
792    /// user-visible window (i.e. trigger Stage 1 of the close
793    /// cascade).
794    ///
795    /// **Status: live** (same shipping path as `ReapPanes`). Wired
796    /// through `host_pipe` post-CPD-3; saga waits on
797    /// `Event::PoolDrained { saga_id: Some(N) }` /
798    /// `Event::PoolNotLast { saga_id: Some(N) }` echo. Host's
799    /// `on_before_close` still runs the equivalent inline check
800    /// organically (with `saga_id: None`).
801    ///
802    /// `saga_id`: mandatory on the wire. `#[serde(default)]` retained
803    /// for forward-compat.
804    DrainPoolIfLast {
805        label: String,
806        #[serde(default)]
807        saga_id: u64,
808    },
809    /// Phase CPD-1 — host-emitted report that a saga-issued action
810    /// failed (e.g. window not found, IPC error). Carries the
811    /// originating `saga_id` and a human-readable `reason`. The
812    /// launcher reducer translates this into `Event::SagaActionFailed`
813    /// so the saga coordinator can terminate the matching saga as
814    /// `SagaFailed`.
815    ///
816    /// Schema-only in CPD-1: hosts don't yet read commands from the
817    /// pipe (CPD-2 wires that), so no producer for this command
818    /// exists yet. The shape is added now so launcher reducer arms
819    /// + saga coordinator wiring can soak before CPD-3 makes the
820    /// dispatch live.
821    ReportSagaActionFailed {
822        saga_id: u64,
823        reason: String,
824    },
825    /// Host reports the start of a named startup phase, forwarded by
826    /// the launcher into its `StartupEventSink` so it renders live in
827    /// the splash telemetry panel — same stage/label shape as the
828    /// launcher's own internal `saga`/`backend`/`host` stages
829    /// (`crates/launcher/src/startup_events.rs`), just sourced from
830    /// inside the host process instead.
831    ///
832    /// The host can only send this AFTER `connect_to_launcher`
833    /// succeeds, so phases that finish before the IPC connection
834    /// exists (e.g. the CEF framework `dlopen` on macOS, which
835    /// happens before the connection is even opened) can't be
836    /// reported live — the host times those with a local `Instant`
837    /// and sends both `ReportStartupStageBegin` + `ReportStartupStageEnd`
838    /// back-to-back once connected, with the already-elapsed duration
839    /// on the `End` message. Phases that start after the connection
840    /// exists (CEF `cef::initialize`, first-paint) are reported live.
841    ReportStartupStageBegin {
842        /// Stable machine-readable stage key (e.g. `"dlopen"`,
843        /// `"cef_init"`, `"first_paint"`) — matches
844        /// `StartupEvent::StageBegin`'s `stage` field on the launcher
845        /// side.
846        stage: String,
847        /// Human-readable label shown in the splash panel.
848        label: String,
849    },
850    /// Companion to `ReportStartupStageBegin` — see its doc comment.
851    ReportStartupStageEnd {
852        stage: String,
853        duration_ms: u64,
854        /// `"ok"` | `"warn"` | `"error"` — kept as a plain string on
855        /// the wire rather than importing `agentmux-launcher`'s
856        /// `StartupStatus` (which lives in the launcher binary crate,
857        /// not a shared crate); the launcher's IPC handler maps it to
858        /// `StartupStatus` when forwarding into the sink.
859        status: String,
860        detail: Option<String>,
861    },
862}