Skip to main content

agentmux_common/ipc/
event.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The events the launcher sends to clients, and the frame that wraps either direction on the
5//! host pipe.
6
7use super::*;
8use serde::{Deserialize, Serialize};
9
10/// Events flow launcher → client. Versioned per spec §5.2 — every
11/// event carries a monotonic `version: u64` per launcher run, used
12/// by Phase D's resync protocol.
13///
14/// Phase B.3 introduces the first non-handshake events
15/// (ProcessSpawned, ProcessExited, LifecyclePhaseChanged) emitted
16/// by the launcher's reducer when commands transition state. B.4+
17/// adds the window-state events (WindowAdded, WindowStateChanged,
18/// WindowRemoved) per spec §5.2.
19/// Note: `Eq` is not derived because layout variants carry `LayoutNode`
20/// which contains `f32` (not `Eq`). `PartialEq` is sufficient for all
21/// current use-sites.
22#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
23#[serde(tag = "event", rename_all = "snake_case")]
24pub enum Event {
25    /// Reply to `Command::Register`. Acknowledges the client kind +
26    /// confirms the launcher's view of the world.
27    Registered {
28        client_id: u64,
29        launcher_pid: u32,
30        launcher_version: String,
31        version: u64,
32    },
33    /// Reply to `Command::Ping`. Echoes the nonce.
34    Pong {
35        nonce: u64,
36        version: u64,
37    },
38    /// Sent when an incoming command can't be parsed or violates an
39    /// invariant (e.g. Command before Register). Connection stays
40    /// open unless `fatal: true`.
41    Error {
42        code: ErrorCode,
43        message: String,
44        fatal: bool,
45        version: u64,
46    },
47    /// A process joined the launcher's canonical registry. Emitted
48    /// when a client first Registers (B.3) and, in B.4+, when the
49    /// launcher itself spawns a child.
50    ProcessSpawned {
51        pid: u32,
52        kind: ClientKind,
53        client_version: String,
54        version: u64,
55    },
56    /// A process exited or disconnected gracefully. Emitted on
57    /// Goodbye (B.3) and, in B.4+, on detected child exit.
58    ProcessExited {
59        pid: u32,
60        /// Exit code. 0 = clean Goodbye; non-zero = OS-reported
61        /// exit code or synthetic value for crashes.
62        code: i32,
63        version: u64,
64    },
65    /// The launcher's lifecycle phase changed. Spec §4 defines the
66    /// valid transitions: Starting → Running → Quitting → Dead.
67    /// Emitted at most once per transition.
68    LifecyclePhaseChanged {
69        from: LifecyclePhase,
70        to: LifecyclePhase,
71        version: u64,
72    },
73    /// Phase B.4: a window joined the launcher's mirror. Emitted in
74    /// response to `Command::ReportWindowOpened` from the host. Other
75    /// subscribers (Tool clients, eventually srv) receive this to
76    /// keep their own views consistent.
77    WindowOpened {
78        label: String,
79        kind: WindowKind,
80        parent_label: Option<String>,
81        version: u64,
82    },
83    /// Phase B.4: a window left the launcher's mirror. Emitted on
84    /// `Command::ReportWindowClosed`. Cascades for FullInstance
85    /// closures are NOT modeled here yet (B.5 tightens) — for now
86    /// the host emits one ReportWindowClosed per window even on
87    /// cascade closes, so subscribers see the same N events.
88    WindowClosed {
89        label: String,
90        version: u64,
91        /// (codex P1 PR #637.) `true` when the close was detected by
92        /// `wrr::apply_hwnd_destroyed` after a host/renderer crash —
93        /// no clean `on_before_close` ran, so the host did NOT send
94        /// the `ReportPanesReaped` / `ReportPoolDrainDecision` reports
95        /// the F.6 saga waits for. Subscribers that drive
96        /// cleanup-cascade sagas must filter on `!crash_detected` to
97        /// avoid spawning an in-flight saga that can never reach a
98        /// terminal state.
99        ///
100        /// `#[serde(default)]` so pre-existing producers default to
101        /// `false` (clean close).
102        #[serde(default)]
103        crash_detected: bool,
104    },
105    /// Phase B.4 follow-up — pool inventory transitioned. Emitted in
106    /// response to `ReportPoolWindow{Added,Removed}`. Subscribers
107    /// (Tool clients) use this to track pool warmth without polling.
108    PoolWindowAdded {
109        label: String,
110        version: u64,
111        /// Phase CPD-1 — saga correlation. Mirrors the `saga_id` that
112        /// arrived on the originating
113        /// `Command::ReportPoolWindowAdded { saga_id }`. `None` for
114        /// organic refills (no saga in flight). Subscribers (CPD-4
115        /// per-saga correlation) match on this to scope events to the
116        /// originating saga.
117        ///
118        /// `#[serde(default)]` for forward-compat with old
119        /// `launcher-events.log` entries that pre-date CPD-1.
120        #[serde(default)]
121        saga_id: Option<u64>,
122    },
123    PoolWindowRemoved {
124        label: String,
125        version: u64,
126    },
127    /// Phase F.5 — emitted by the launcher when the host explicitly
128    /// reports a pool window was promoted to a user-visible
129    /// top-level window (i.e. the pool→window handoff inside
130    /// `agentmux-cef::commands::window_pool::promote_pool_window`).
131    /// The pool-respawn saga (launcher-side coordinator) starts on
132    /// this event, brackets the implicit refill in
133    /// `SagaStarted`/`SagaCompleted`, and waits for the matching
134    /// `PoolWindowAdded` for a fresh pool label.
135    ///
136    /// Distinct from `PoolWindowRemoved` because that event also
137    /// fires on pre-promote destroy (closing without promoting), where
138    /// no refill saga should run.
139    PoolWindowPromoted {
140        label: String,
141        version: u64,
142    },
143    /// Phase F.6 — emitted by the launcher when the host reports that
144    /// all browser-pane HWNDs belonging to a closing top-level window
145    /// have been reaped (`Command::ReportPanesReaped`). Step-1
146    /// terminal signal for the window-cleanup-cascade saga.
147    PanesReaped {
148        label: String,
149        version: u64,
150        /// Phase CPD-1 — saga correlation. Mirrors `saga_id` from the
151        /// originating `ReportPanesReaped`. `None` for organic
152        /// reports (non-saga-driven pane drains).
153        ///
154        /// `#[serde(default)]` for forward-compat with pre-CPD-1
155        /// log entries.
156        #[serde(default)]
157        saga_id: Option<u64>,
158    },
159    /// Phase F.6 — emitted by the launcher when the host reports it
160    /// kicked off Stage 1 of the close-cascade pool drain (i.e. the
161    /// just-closed window was the last user-visible window).
162    /// Step-2 terminal signal (success branch) for the
163    /// window-cleanup-cascade saga.
164    ///
165    /// "Drained" here means "drain initiated"; the actual pool
166    /// teardown is async and surfaces as a series of
167    /// `PoolWindowRemoved` events as each pool browser's
168    /// `on_before_close` fires. The saga doesn't wait for those —
169    /// the bracket closes when drain is *decided*, not when it
170    /// completes.
171    PoolDrained {
172        label: String,
173        version: u64,
174        /// Phase CPD-1 — saga correlation. Mirrors `saga_id` from the
175        /// originating `ReportPoolDrainDecision`. `None` for organic
176        /// reports.
177        #[serde(default)]
178        saga_id: Option<u64>,
179    },
180    /// Phase F.6 — emitted by the launcher when the host reports a
181    /// close that did NOT trigger a pool drain (other user-visible
182    /// windows remain). Step-2 terminal signal (no-op branch) for
183    /// the window-cleanup-cascade saga; the bracket closes
184    /// successfully because nothing further is needed.
185    PoolNotLast {
186        label: String,
187        version: u64,
188        /// Phase CPD-1 — saga correlation. Mirrors `saga_id` from the
189        /// originating `ReportPoolDrainDecision`. `None` for organic
190        /// reports.
191        #[serde(default)]
192        saga_id: Option<u64>,
193    },
194    /// Phase B.5 (window_id_map step a) — launcher recorded the
195    /// label → backend window ID mapping. Subscribers (host's
196    /// shadow, eventually srv-side consumers) update their
197    /// projections.
198    BackendWindowIdRegistered {
199        label: String,
200        window_id: String,
201        version: u64,
202    },
203    /// Phase B.5 (window_id_map step a) — launcher dropped the
204    /// label → backend window ID mapping (window closed).
205    BackendWindowIdUnregistered {
206        label: String,
207        window_id: String,
208        version: u64,
209    },
210    /// Phase B.5 — sequential instance number assigned to a window
211    /// by the launcher's authoritative registry. Numbers start at 1
212    /// for "main" and increment for each subsequent open. Never
213    /// reused within a launcher run. The host caches these to
214    /// display window titles; B.5 step 2 will retire host's own
215    /// `WindowInstanceRegistry` in favor of this stream.
216    WindowInstanceAssigned {
217        label: String,
218        num: u32,
219        version: u64,
220    },
221    /// Phase B.5 — instance number released (window closed). The
222    /// launcher's authoritative registry drops the label; the slot
223    /// is NOT reused (numbers monotonic per spec invariant: stable
224    /// instance# across promotions / unregisters).
225    WindowInstanceReleased {
226        label: String,
227        num: u32,
228        version: u64,
229    },
230    /// Phase B.4 follow-up — emitted when the launcher's mirror
231    /// disagrees with the host's reported counts. Logged at WARN
232    /// level so operators see drift immediately. Drift in B.4 is
233    /// a CONTRACT BUG (the host should report every state change);
234    /// B.5 will turn drift into a hard failure once the mirror is
235    /// authoritative.
236    DriftDetected {
237        kind: DriftKind,
238        host_count: u32,
239        mirror_count: u32,
240        version: u64,
241    },
242    /// Phase B.9.1 (WRR) — emitted when the launcher's reducer
243    /// detects a divergence between CEF browser identity (tracked
244    /// in `state.windows` / `state.pool` via `ReportWindow*`) and
245    /// Win32 reality (newly tracked via `ReportHwnd*`). Each variant
246    /// of `kind` is emitted at the moment the OS event that
247    /// surfaces it is dispatched through the reducer — there is no
248    /// timer / heartbeat. See `docs/retro/wrr-design-2026-04-28.md`
249    /// for the full classification table.
250    HwndDriftDetected {
251        kind: HwndDriftKind,
252        /// Affected label, when known.
253        label: Option<String>,
254        /// Affected HWND, when known. `u64` to keep the wire format
255        /// stable across pointer-width differences.
256        hwnd: Option<u64>,
257        /// Human-readable description for the launcher log + `--diag`
258        /// output. Free-form; not parsed by any consumer.
259        detail: String,
260        severity: Severity,
261        version: u64,
262    },
263    /// Phase B.9.2 — pure-reducer self-heal. Emitted alongside an
264    /// `HwndDriftDetected` when the reducer is confident the bug
265    /// happened at OPEN TIME (not from later user action) and a
266    /// safe corrective rect is computable. The host's WRR
267    /// subscriber listens for this and applies `SetWindowPos` on
268    /// the UI thread. No timers — the trigger is the same OS
269    /// event tick that surfaced the bug, so the correction lands
270    /// before the user has time to notice the orphan window.
271    ///
272    /// Guard for emission (per the design, suppress over-correction):
273    /// - The window's `mirror.foregrounded_since_open == false`
274    ///   (we never auto-move a window the user has already
275    ///   touched).
276    /// - The reducer can compute a target rect from
277    ///   `state.monitors` (i.e., monitors are known).
278    CorrectiveWindowMove {
279        /// Win32 HWND to move.
280        hwnd: u64,
281        /// Reducer-computed target rect. Default policy:
282        /// primary-monitor-centered at default window size.
283        target_rect: Rect,
284        /// Why correction fired — surfaces in host log + audit.
285        reason: HwndDriftKind,
286        version: u64,
287    },
288    /// Phase B.9.3 — saga-style corrective. Reducer detected the
289    /// `OrphanInstance` transition (last user-visible label
290    /// removed from `state.windows`, host still Running). Host
291    /// subscriber handles by reaping the warm pool and calling
292    /// `quit_message_loop()`. ADVISORY, not a hard command —
293    /// the host's handler should re-check `state.browsers`
294    /// before actually quitting (the user could open a new
295    /// window in the same dispatch tick race window). Event is
296    /// idempotent: multiple emissions are safe; reaping pool +
297    /// quit are themselves idempotent.
298    HostShouldQuit {
299        version: u64,
300    },
301    /// Phase D.1 — reply to `Command::GetSnapshot`. Carries the
302    /// reducer's current canonical state (the projections subscribers
303    /// most commonly need). The `version` field is the reducer's
304    /// `event_version` at the moment the snapshot was taken; events
305    /// the subscriber receives AFTER this snapshot have monotonically
306    /// greater version numbers, letting the subscriber apply them as
307    /// deltas without missing or duplicating updates.
308    ///
309    /// What's included: lifecycle, windows (label + kind + parent +
310    /// HWND-observation axis), pool labels, instance numbers,
311    /// backend window IDs, monitor topology. What's intentionally
312    /// excluded: `processes` (PID metadata is launcher-internal),
313    /// `pending_hwnds` (transient reconciliation state), event log
314    /// (Phase D.2 adds a separate snapshot-with-replay variant).
315    Snapshot {
316        version: u64,
317        lifecycle: LifecyclePhase,
318        windows: Vec<WindowSnapshot>,
319        pool: Vec<String>,
320        instance_registry: Vec<(String, u32)>,
321        backend_window_ids: Vec<(String, String)>,
322        monitors: Vec<Rect>,
323    },
324    /// Phase D.3 — reply to `Command::GetEvents { since }`. Carries
325    /// the events the launcher has emitted with `version > since`,
326    /// in ascending version order. Subscribers apply them in order
327    /// to catch up to the launcher's live stream.
328    ///
329    /// The `version` field on this event is the launcher's
330    /// `event_version` at the moment the reply was assembled — not
331    /// the highest version inside `events`. A subscriber treating
332    /// this as the "as-of" point for subsequent events should use
333    /// `events.last().version` (or fall back to this `version` if
334    /// `events` is empty) to know where to resume the live stream.
335    ///
336    /// Replay is best-effort: if `since` predates the launcher's
337    /// in-memory ring, `events` contains everything still retained
338    /// but the subscriber should expect potential missed events
339    /// before the first one in this reply.
340    EventList {
341        events: Vec<Event>,
342        version: u64,
343    },
344    /// Phase E.1a — emitted by the saga coordinator when a new saga
345    /// starts. `name` is the saga's static name (e.g. "tear_off_block")
346    /// for `--diag` output. Subscribers (renderer especially) use
347    /// `saga_id` to start buffering subsequent events with that id
348    /// until the matching `SagaCompleted` or `SagaFailed` arrives.
349    ///
350    /// `saga_id` is monotonic per launcher run, allocated by the
351    /// coordinator. Persisting saga state across launcher restarts
352    /// is deferred (Phase F or beyond); restart abandons in-flight
353    /// sagas, and renderer-side timeouts handle the visible
354    /// consequence.
355    SagaStarted {
356        saga_id: u64,
357        name: String,
358        version: u64,
359    },
360    /// Phase E.1a — saga ended successfully. All events with this
361    /// `saga_id` have been emitted; subscribers can flush their
362    /// buffers and apply the changes atomically.
363    SagaCompleted {
364        saga_id: u64,
365        version: u64,
366    },
367    /// Phase E.1a — saga ended in failure. `reason` is operator-
368    /// readable; if compensation actions were issued, they appear
369    /// as ordinary commands/events on the bus before this event.
370    /// Renderers should discard their buffer for this `saga_id` —
371    /// no atomic apply.
372    SagaFailed {
373        saga_id: u64,
374        reason: String,
375        version: u64,
376    },
377    /// Phase E.1b — srv-side snapshot reply. Phase E.2 populates
378    /// `workspaces` (canonical Vec); subsequent sub-phases add
379    /// `tabs`, `blocks`, `layouts`, etc.
380    ///
381    /// `version` is the srv reducer's `event_version` at snapshot
382    /// time, monotonically distinct from prior srv events so
383    /// subscribers know the "as-of" point for delta application.
384    SrvSnapshot {
385        version: u64,
386        lifecycle: LifecyclePhase,
387        /// Phase E.2 — sorted list of workspaces in the reducer's
388        /// canonical state. (id, name) pairs for compactness; full
389        /// state available via per-event subscription. Empty before
390        /// E.2 lands.
391        ///
392        /// `#[serde(default)]` so old `srv-events.log` entries
393        /// written by E.1b (which had no `workspaces` field) still
394        /// deserialize when later sub-phases add bootstrap-replay
395        /// from the on-disk log. Same forward-compat treatment will
396        /// apply to E.3's `blocks`, etc. (reagent P2 #611.)
397        #[serde(default)]
398        workspaces: Vec<(String, String)>,
399        /// Phase E.2b — sorted list of tabs in the reducer's canonical
400        /// state. `(tab_id, workspace_id, name)` triples for
401        /// compactness. `#[serde(default)]` for forward-compat with
402        /// pre-E.2b log entries.
403        #[serde(default)]
404        tabs: Vec<(String, String, String)>,
405        /// Phase E.2b — sorted list of `(workspace_id, active_tab_id)`
406        /// pairs for workspaces that have an active tab set.
407        /// Workspaces with no active tab are omitted.
408        #[serde(default)]
409        active_tabs: Vec<(String, String)>,
410        /// Phase E.3 — sorted list of blocks in the reducer's
411        /// canonical state. `(block_id, tab_id)` pairs for
412        /// compactness. `#[serde(default)]` for forward-compat with
413        /// pre-E.3 log entries.
414        #[serde(default)]
415        blocks: Vec<(String, String)>,
416    },
417    /// Phase E.2 — workspace was created. Carries the assigned
418    /// `oid` and `name` so subscribers (renderer, persist) can
419    /// apply the change without further round-trips.
420    WorkspaceCreated {
421        workspace_id: String,
422        name: String,
423        version: u64,
424    },
425    /// Phase E.2 — workspace was deleted.
426    WorkspaceDeleted {
427        workspace_id: String,
428        /// Every block_id cascaded out with this workspace (every block in
429        /// every tab it contained) — `TabDeleted`/`WorkspaceDeleted` never
430        /// emitted per-block events (see `reducer/tab.rs::handle_delete_tab`),
431        /// so this is the host's only signal to tear down a browser-pane
432        /// renderer whose tab/workspace was deleted while unloaded/inactive
433        /// (issue #2218, B.4). `#[serde(default)]` so replaying an old
434        /// saga-log entry (predating this field) still deserializes.
435        #[serde(default)]
436        block_ids: Vec<String>,
437        version: u64,
438    },
439    /// Phase E.2b — tab was created inside a workspace. Carries the
440    /// assigned `tab_id` and parent `workspace_id` so subscribers can
441    /// place it in the correct workspace's tab list.
442    TabCreated {
443        workspace_id: String,
444        tab_id: String,
445        name: String,
446        version: u64,
447    },
448    /// Phase E.2b — tab was deleted from a workspace.
449    TabDeleted {
450        workspace_id: String,
451        tab_id: String,
452        /// Every block_id cascaded out with this tab. See `WorkspaceDeleted`'s
453        /// `block_ids` doc — same rationale (issue #2218, B.4).
454        #[serde(default)]
455        block_ids: Vec<String>,
456        version: u64,
457    },
458    /// Phase E.2b — a workspace's active tab changed. `tab_id: None`
459    /// means the workspace has no active tab (e.g., last tab deleted).
460    ActiveTabChanged {
461        workspace_id: String,
462        tab_id: Option<String>,
463        version: u64,
464    },
465    /// Phase E.2c.3b — a tab was reordered within its workspace's
466    /// `tab_ids`. Subscribers should rewrite the workspace's tab
467    /// order to match the reducer's authoritative list (which lives
468    /// in the snapshot's `tabs` field; subscribers can also recompute
469    /// from `tab_id` + `new_index` against their last-known order).
470    TabReordered {
471        workspace_id: String,
472        tab_id: String,
473        new_index: u32,
474        version: u64,
475    },
476    /// Phase E.5 — srv-side window→workspace mapping established.
477    /// Distinct from launcher's `WindowOpened` (which tracks CEF
478    /// window lifecycle). Subscribers update their view of "which
479    /// workspace is each window showing."
480    SrvWindowOpened {
481        window_id: String,
482        workspace_id: String,
483        version: u64,
484    },
485    /// Phase E.5 — srv-side window mapping removed. Distinct from
486    /// launcher's `WindowClosed`.
487    SrvWindowClosed {
488        window_id: String,
489        version: u64,
490    },
491    /// Phase E.5 — a window now points at a different workspace
492    /// (used by the SwitchWorkspace command + the CloseWindow saga
493    /// when reassigning during cleanup).
494    SrvWindowWorkspaceChanged {
495        window_id: String,
496        workspace_id: String,
497        version: u64,
498    },
499    /// Phase E.5.3 — workspace's `tab_ids` was replaced wholesale.
500    /// Subscribers should rewrite the persistent `Workspace.tabids`
501    /// to match the new list (preserving `pinnedtabids` separately —
502    /// pinning is a Waveterm legacy and not in scope here).
503    TabsReorderedBulk {
504        workspace_id: String,
505        tab_ids: Vec<String>,
506        version: u64,
507    },
508    /// Phase E.5.3 — workspace was renamed.
509    WorkspaceRenamed {
510        workspace_id: String,
511        name: String,
512        version: u64,
513    },
514    /// Phase E.5.3 — tab was renamed.
515    TabRenamed {
516        tab_id: String,
517        name: String,
518        version: u64,
519    },
520    /// Phase E.5.3 — meta-patch applied to a workspace. Carries the
521    /// patch (NOT the resolved meta map); subscribers merge against
522    /// the workspace's existing meta. This shape lets sagas inspect
523    /// what changed without needing the prior state.
524    WorkspaceMetaUpdated {
525        workspace_id: String,
526        meta_patch: serde_json::Value,
527        version: u64,
528    },
529    /// Phase E.5.x (issue #855) — meta-patch applied to a window's
530    /// `meta` map. Same shape as `WorkspaceMetaUpdated`. Persist
531    /// subscriber merges into mstore; MuxObjUpdate bridge translates
532    /// to a frontend `waveobj:update` broadcast.
533    WindowMetaUpdated {
534        window_id: String,
535        meta_patch: serde_json::Value,
536        version: u64,
537    },
538    /// Phase E.5.3 — meta-patch applied to a tab.
539    TabMetaUpdated {
540        tab_id: String,
541        meta_patch: serde_json::Value,
542        version: u64,
543    },
544    /// Phase E.5.3 — meta-patch applied to a block.
545    BlockMetaUpdated {
546        block_id: String,
547        meta_patch: serde_json::Value,
548        version: u64,
549    },
550    /// Phase E.5.5 — a tab was moved from one workspace to another.
551    /// Subscribers should rewrite both workspaces' `tabids` and the
552    /// tab's `parentoref`/`workspaceid` to match the reducer's view.
553    /// `dst_index` reflects the position in `dst_workspace_id.tab_ids`
554    /// AFTER insertion (already clamped by the reducer).
555    /// Carries enough information to re-derive the new state without
556    /// reading the reducer (subscribers replay events post-Lagged).
557    TabMoved {
558        tab_id: String,
559        src_workspace_id: String,
560        dst_workspace_id: String,
561        dst_index: u32,
562        /// The source workspace's new `active_tab_id` after the move,
563        /// or `None` if the source has no remaining tabs. Subscribers
564        /// rewrite the source's `activetabid` to match.
565        new_src_active_tab_id: Option<String>,
566        /// The destination workspace's new `active_tab_id` after the
567        /// move. Wcore behavior (`move_tab_to_workspace`) was to
568        /// always set the moved tab as dst's active; the reducer
569        /// mirrors that. `None` means "do not change dst.active_tab_id"
570        /// — reserved for future flows where the moved tab shouldn't
571        /// steal focus. Codex P2 #621.
572        ///
573        /// `#[serde(default)]` for forward-compat with pre-PR3
574        /// `srv-events.log` entries (none in production yet, but the
575        /// pattern is established).
576        #[serde(default)]
577        new_dst_active_tab_id: Option<String>,
578        version: u64,
579    },
580    /// Phase E.5.5 — a block was moved from one tab to another (or
581    /// repositioned within the same tab). Subscribers update both
582    /// tabs' `blockids` and the block's `parentoref`. `dst_index`
583    /// reflects post-insertion position.
584    BlockMoved {
585        block_id: String,
586        src_tab_id: String,
587        dst_tab_id: String,
588        dst_index: u32,
589        version: u64,
590    },
591    /// The workspace's pinned panes changed (`Command::PinBlock`, `UnpinBlock`, or a pinned pane that was closed,
592    /// parked or moved to another window); `pins` is the workspace's whole list now. No block moved.
593    PinsChanged {
594        workspace_id: String,
595        pins: Vec<crate::pin::PinRecord>,
596        version: u64,
597    },
598    /// A block left a tab and was kept (`Command::ParkBlock`); nothing was deleted.
599    BlockParked {
600        tab_id: String,
601        block_id: String,
602        version: u64,
603    },
604    /// A parked block went into a tab (`Command::AttachBlock`).
605    BlockAttached {
606        block_id: String,
607        dst_tab_id: String,
608        dst_index: u32,
609        version: u64,
610    },
611    /// Phase E.3 — block was created inside a tab.
612    BlockCreated {
613        tab_id: String,
614        block_id: String,
615        /// Phase E.2c.4 — meta carried through from
616        /// `Command::CreateBlock`. The persist subscriber writes
617        /// the Block row with this meta map. `#[serde(default)]` for
618        /// forward-compat with pre-E.2c.4 log entries.
619        #[serde(default)]
620        meta: serde_json::Value,
621        version: u64,
622    },
623    /// Phase E.3 — block was deleted from a tab.
624    BlockDeleted {
625        tab_id: String,
626        block_id: String,
627        version: u64,
628    },
629    /// Phase E.4 (Option A) — a tab's `focusednodeid` changed via the
630    /// reducer. Subscribers (persist, eventually the renderer's E.6
631    /// dispatcher) update the tab's layout view. Empty `node_id`
632    /// reflects a clear.
633    FocusedNodeChanged {
634        tab_id: String,
635        node_id: String,
636        version: u64,
637    },
638    /// Phase E.4 (Option A) — a tab's `magnifiednodeid` changed via
639    /// the reducer. Empty `node_id` reflects a clear (toggle-off).
640    MagnifiedNodeChanged {
641        tab_id: String,
642        node_id: String,
643        version: u64,
644    },
645
646    // ── Phase E.4.B — Layout tree events ───────────────────────────────
647    //
648    // Each carries the resulting tree (or the queue change), so the
649    // persist subscriber writes it without re-running the algebra.
650    // See docs/specs/srv-phase-e4b-formal-spec-2026-05-03.md §6.
651
652    LayoutNodeDeleted {
653        tab_id: String,
654        node_id: String,
655        /// The reducer's resulting tree (post-delete, post-collapse) for
656        /// the persist subscriber to write to `db_layout` — single-writer,
657        /// no algebra re-run (SPEC_STRONG_REDUCER_AUTHORITY_LAYOUT /
658        /// SPEC_864 site #6). Unlike the other structural events, a delete
659        /// CAN legitimately empty the tree (root-orphan case) — `None`
660        /// alone is ambiguous with a version-skewed pre-change sender, so
661        /// `tree_cleared` below disambiguates. `#[serde(default)]` for
662        /// forward-compat.
663        #[serde(default)]
664        new_tree: Option<crate::LayoutNode>,
665        /// True when the delete legitimately emptied the tree (the deleted
666        /// node WAS the root). The persist subscriber clears `db_layout`'s
667        /// rootnode only when `new_tree.is_none() && tree_cleared` — a bare
668        /// `None` (old sender / replayed pre-change JSON) is ignored rather
669        /// than erasing the persisted layout (same skew concern as codex
670        /// P2 on #1883). `#[serde(default)]` = false for old JSON.
671        #[serde(default)]
672        tree_cleared: bool,
673        /// True if the deleted node was the focused one (subscribers may
674        /// need to refocus).
675        was_focused: bool,
676        /// True if the deleted node was the magnified one (subscribers
677        /// may need to re-magnify or clear their magnification UI).
678        /// Reagent P1 PR #715 round 3: reducer was clearing
679        /// `magnified_node_id` internally but not reporting it.
680        ///
681        /// `#[serde(default)]` for forward-compat with replay /
682        /// version-skewed senders that emit pre-round-3
683        /// `LayoutNodeDeleted` JSON without this field (codex P2 PR
684        /// #715 round 5).
685        #[serde(default)]
686        was_magnified: bool,
687        correlation_id: String,
688        version: u64,
689    },
690    /// SPEC_864 Phase 2 — `slices` mirrors the command's field: when
691    /// present, the persist subscriber also writes focus /
692    /// magnify / pendingbackendactions (REPLACE semantics). `None` =
693    /// tree-only replace; those columns stay untouched.
694    LayoutTreeReplaced {
695        tab_id: String,
696        new_tree: Option<crate::LayoutNode>,
697        correlation_id: String,
698        #[serde(default, skip_serializing_if = "Option::is_none")]
699        slices: Option<crate::LayoutClientSlices>,
700        version: u64,
701    },
702
703    /// SPEC_864 Phase 4 — actions appended to a tab's
704    /// `pendingbackendactions` queue through the reducer: what srv did to
705    /// the tree, for the window showing the tab to mirror. `actions` is a
706    /// JSON array of `LayoutActionData` objects, carried as a raw value the
707    /// same way `LayoutClientSlices` carries the queue: the reducer does NOT
708    /// model the queue in `TabRecord` (pass-through), and the persist
709    /// subscriber APPENDS these to `LayoutState.pendingbackendactions`.
710    LayoutBackendActionsQueued {
711        tab_id: String,
712        actions: serde_json::Value,
713        correlation_id: String,
714        version: u64,
715    },
716
717    /// Phase CPD-1 (cross-process dispatch) — emitted by the launcher
718    /// when the host reports that a saga-issued action failed
719    /// (`Command::ReportSagaActionFailed { saga_id, reason }`). The
720    /// saga coordinator's bus loop will (in CPD-3) treat this as a
721    /// terminal signal for the matching saga, emitting
722    /// `Event::SagaFailed` and removing it from the in-flight
723    /// registry. CPD-1 ships the wire shape only; no producer
724    /// (host) and no consumer (saga coordinator) are wired yet.
725    SagaActionFailed {
726        saga_id: u64,
727        reason: String,
728        version: u64,
729    },
730}
731
732/// Phase CPD-1 (cross-process dispatch) — envelope enum for frames
733/// sent over the launcher → host pipe direction. Today the host's
734/// read loop only expects `Event` JSON; CPD-2 extends the read loop
735/// to recognize this tagged union and dispatch by `kind`:
736///
737/// * `event` → existing event-handling code (state sync from
738///   launcher reducer broadcasts).
739/// * `command` → new command-handling code (saga-issued actions).
740///
741/// Newline-delimited JSON, one frame per line. `#[serde(tag = "kind",
742/// rename_all = "snake_case")]` so the wire shape is e.g.
743/// `{"kind":"event","event":"pool_window_added",...}` or
744/// `{"kind":"command","cmd":"spawn_pool_window","saga_id":42}`.
745///
746/// Schema-only in CPD-1: introduced now so the launcher's host-pipe
747/// writer (CPD-2) and the host's read loop (CPD-2/CPD-3) can be
748/// built against a stable wire envelope without further schema
749/// churn.
750#[derive(Debug, Clone, Serialize, Deserialize)]
751#[serde(tag = "kind", rename_all = "snake_case")]
752pub enum HostFrame {
753    /// Wraps a launcher-emitted Event being pushed down to the host
754    /// (existing fanout path; CPD-2 refactors the writer to go
755    /// through this envelope).
756    Event(Event),
757    /// Wraps a saga-issued Command being dispatched from the launcher
758    /// to the host. Carries `saga_id` inside the Command payload.
759    Command(Command),
760}