Skip to main content

agentmux_srv_core/reducer/
window.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4use agentmux_common::ipc::Event;
5
6use crate::state::State;
7
8
9use crate::state::WindowRecord;
10
11use super::invalid_command;
12
13/// Phase E.5 — record a new window→workspace mapping. Validates
14/// the parent workspace exists; otherwise emits `Event::Error`
15/// (non-fatal). Idempotent on duplicate `window_id`: re-issuing
16/// for the same window updates the workspace pointer if it
17/// changed, or no-ops if identical.
18pub(super) fn handle_create_window(
19    state: &mut State,
20    window_id: String,
21    workspace_id: String,
22) -> Vec<Event> {
23    if !state.workspaces.contains_key(&workspace_id) {
24        return invalid_command(state, format!("CreateWindow: workspace not found: {}", workspace_id));
25    }
26    if let Some(existing) = state.windows.get(&window_id) {
27        if existing.workspace_id == workspace_id {
28            return Vec::new();
29        }
30    }
31    state.windows.insert(
32        window_id.clone(),
33        WindowRecord {
34            window_id: window_id.clone(),
35            workspace_id: workspace_id.clone(),
36        },
37    );
38    let v = state.bump_version();
39    vec![Event::SrvWindowOpened {
40        window_id,
41        workspace_id,
42        version: v,
43    }]
44}
45
46/// Phase E.5 — remove a window's workspace mapping. Idempotent
47/// silent no-op on missing.
48pub(super) fn handle_close_window_internal(state: &mut State, window_id: String) -> Vec<Event> {
49    if state.windows.remove(&window_id).is_none() {
50        return Vec::new();
51    }
52    let v = state.bump_version();
53    vec![Event::SrvWindowClosed {
54        window_id,
55        version: v,
56    }]
57}
58
59/// Phase E.5 — change which workspace a window points at. Errors
60/// (non-fatal) if the window or destination workspace is unknown.
61/// No-op if the window is already pointing at the destination.
62pub(super) fn handle_switch_workspace(
63    state: &mut State,
64    window_id: String,
65    workspace_id: String,
66) -> Vec<Event> {
67    if !state.workspaces.contains_key(&workspace_id) {
68        return invalid_command(
69            state,
70            format!("SwitchWorkspace: destination workspace not found: {}", workspace_id),
71        );
72    }
73    let Some(window) = state.windows.get_mut(&window_id) else {
74        return invalid_command(state, format!("SwitchWorkspace: window not found: {}", window_id));
75    };
76    if window.workspace_id == workspace_id {
77        return Vec::new();
78    }
79    window.workspace_id = workspace_id.clone();
80    let v = state.bump_version();
81    vec![Event::SrvWindowWorkspaceChanged {
82        window_id,
83        workspace_id,
84        version: v,
85    }]
86}
87
88/// Phase E.5.x (issue #855) — apply a meta-patch to a window. Pass-
89/// through to `Event::WindowMetaUpdated`; the persist subscriber
90/// performs the merge against mstore. Same shape as
91/// `handle_update_workspace_meta` — reducer state does NOT track
92/// window meta, the migration property is "every mutation goes
93/// through the reducer's broadcast bus" so the MuxObjUpdate bridge
94/// can fan out to the frontend.
95///
96/// Validates the window exists, matching its three sibling meta arms
97/// (`handle_update_workspace_meta` / `handle_update_tab_meta` /
98/// `handle_update_block_meta`) — this arm used to be the sole outlier
99/// with no guard, which made `POST /api/v1/window/name` report success
100/// for well-formed-but-nonexistent window ids (the persist subscriber's
101/// `apply_window_meta_updated` silently no-ops on a mstore miss, so
102/// nothing downstream caught it either). The guard is safe because
103/// `state.windows` reliably mirrors real windows: every runtime
104/// creation goes through `handle_create_window`, and
105/// `persist::bootstrap_state_from_mstore` hydrates pre-existing windows
106/// (including the wcore-seeded first-launch window, created before
107/// hydration runs) at startup. The old "wcore-direct paths won't appear
108/// here" caveat this comment used to carry predates that hydration.
109/// SPEC_WINDOW_NAME_API_HARDENING_2026_08_08.md §3.1.
110pub(super) fn handle_update_window_meta(
111    state: &mut State,
112    window_id: String,
113    meta_patch: serde_json::Value,
114) -> Vec<Event> {
115    if !state.windows.contains_key(&window_id) {
116        return invalid_command(state, format!("UpdateWindowMeta: window not found: {}", window_id));
117    }
118    let v = state.bump_version();
119    vec![Event::WindowMetaUpdated {
120        window_id,
121        meta_patch,
122        version: v,
123    }]
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use crate::reducer::test_support::*;
130    use crate::reducer::update;
131    use agentmux_common::ipc::Command;
132
133    #[test]
134    fn create_window_validates_workspace_exists() {
135        let mut state = State::default();
136        let events = update(
137            &mut state,
138            Command::CreateWindow {
139                window_id: "win-1".into(),
140                workspace_id: "no-such-ws".into(),
141            },
142            &ctx(1),
143        );
144        assert!(matches!(&events[0], Event::Error { .. }));
145        assert!(state.windows.is_empty());
146    }
147
148    #[test]
149    fn create_window_inserts_record_and_emits_event() {
150        let mut state = State::default();
151        let ws_id = create_workspace(&mut state, "w");
152        let events = update(
153            &mut state,
154            Command::CreateWindow {
155                window_id: "win-1".into(),
156                workspace_id: ws_id.clone(),
157            },
158            &ctx(2),
159        );
160        assert!(matches!(
161            &events[0],
162            Event::SrvWindowOpened { window_id, workspace_id, .. }
163                if window_id == "win-1" && *workspace_id == ws_id
164        ));
165        assert_eq!(state.windows["win-1"].workspace_id, ws_id);
166    }
167
168    #[test]
169    fn create_window_idempotent_on_same_workspace() {
170        let mut state = State::default();
171        let ws_id = create_workspace(&mut state, "w");
172        let _ = update(
173            &mut state,
174            Command::CreateWindow {
175                window_id: "win-1".into(),
176                workspace_id: ws_id.clone(),
177            },
178            &ctx(2),
179        );
180        let events = update(
181            &mut state,
182            Command::CreateWindow {
183                window_id: "win-1".into(),
184                workspace_id: ws_id,
185            },
186            &ctx(3),
187        );
188        assert!(events.is_empty());
189    }
190
191    #[test]
192    fn close_window_internal_removes_record() {
193        let mut state = State::default();
194        let ws_id = create_workspace(&mut state, "w");
195        let _ = update(
196            &mut state,
197            Command::CreateWindow {
198                window_id: "win-1".into(),
199                workspace_id: ws_id,
200            },
201            &ctx(2),
202        );
203        let events = update(
204            &mut state,
205            Command::CloseWindowInternal {
206                window_id: "win-1".into(),
207            },
208            &ctx(3),
209        );
210        assert!(matches!(&events[0], Event::SrvWindowClosed { .. }));
211        assert!(state.windows.is_empty());
212    }
213
214    #[test]
215    fn close_window_internal_silent_on_missing() {
216        let mut state = State::default();
217        let events = update(
218            &mut state,
219            Command::CloseWindowInternal {
220                window_id: "ghost".into(),
221            },
222            &ctx(1),
223        );
224        assert!(events.is_empty());
225    }
226
227    #[test]
228    fn update_window_meta_errors_on_unknown_window() {
229        // Regression for SPEC_WINDOW_NAME_API_HARDENING_2026_08_08.md §2.1:
230        // this arm used to emit WindowMetaUpdated unconditionally, so a
231        // well-formed-but-nonexistent window id sailed through to a silent
232        // persist no-op and POST /api/v1/window/name reported success.
233        let mut state = State::default();
234        let events = update(
235            &mut state,
236            Command::UpdateWindowMeta {
237                window_id: "00000000-dead-beef-0000-000000000000".into(),
238                meta_patch: serde_json::json!({ "window:displayname": "phantom" }),
239            },
240            &ctx(1),
241        );
242        assert!(
243            matches!(&events[0], Event::Error { message, .. } if message.contains("window not found")),
244            "expected window-not-found error, got {:?}",
245            events
246        );
247    }
248
249    #[test]
250    fn update_window_meta_emits_event_for_known_window() {
251        let mut state = State::default();
252        let ws_id = create_workspace(&mut state, "a");
253        let _ = update(
254            &mut state,
255            Command::CreateWindow {
256                window_id: "win-1".into(),
257                workspace_id: ws_id,
258            },
259            &ctx(2),
260        );
261        let events = update(
262            &mut state,
263            Command::UpdateWindowMeta {
264                window_id: "win-1".into(),
265                meta_patch: serde_json::json!({ "window:displayname": "named" }),
266            },
267            &ctx(3),
268        );
269        assert!(
270            matches!(&events[0], Event::WindowMetaUpdated { window_id, .. } if window_id == "win-1"),
271            "expected WindowMetaUpdated, got {:?}",
272            events
273        );
274    }
275
276    #[test]
277    fn switch_workspace_updates_window_pointer() {
278        let mut state = State::default();
279        let ws_a = create_workspace(&mut state, "a");
280        let ws_b = create_workspace(&mut state, "b");
281        let _ = update(
282            &mut state,
283            Command::CreateWindow {
284                window_id: "win-1".into(),
285                workspace_id: ws_a.clone(),
286            },
287            &ctx(2),
288        );
289        let events = update(
290            &mut state,
291            Command::SwitchWorkspace {
292                window_id: "win-1".into(),
293                workspace_id: ws_b.clone(),
294            },
295            &ctx(3),
296        );
297        assert!(matches!(
298            &events[0],
299            Event::SrvWindowWorkspaceChanged { workspace_id, .. } if *workspace_id == ws_b
300        ));
301        assert_eq!(state.windows["win-1"].workspace_id, ws_b);
302    }
303
304    #[test]
305    fn switch_workspace_validates_window_and_destination() {
306        let mut state = State::default();
307        let ws_id = create_workspace(&mut state, "a");
308        // Unknown window.
309        let events = update(
310            &mut state,
311            Command::SwitchWorkspace {
312                window_id: "ghost".into(),
313                workspace_id: ws_id.clone(),
314            },
315            &ctx(2),
316        );
317        assert!(matches!(&events[0], Event::Error { .. }));
318        // Known window, unknown workspace.
319        let _ = update(
320            &mut state,
321            Command::CreateWindow {
322                window_id: "win-1".into(),
323                workspace_id: ws_id,
324            },
325            &ctx(3),
326        );
327        let events = update(
328            &mut state,
329            Command::SwitchWorkspace {
330                window_id: "win-1".into(),
331                workspace_id: "no-such-ws".into(),
332            },
333            &ctx(4),
334        );
335        assert!(matches!(&events[0], Event::Error { .. }));
336    }
337
338    #[test]
339    fn switch_workspace_no_op_when_already_pointing() {
340        let mut state = State::default();
341        let ws_id = create_workspace(&mut state, "a");
342        let _ = update(
343            &mut state,
344            Command::CreateWindow {
345                window_id: "win-1".into(),
346                workspace_id: ws_id.clone(),
347            },
348            &ctx(2),
349        );
350        let events = update(
351            &mut state,
352            Command::SwitchWorkspace {
353                window_id: "win-1".into(),
354                workspace_id: ws_id,
355            },
356            &ctx(3),
357        );
358        assert!(events.is_empty());
359    }
360}