Skip to main content

agentmux_srv/server/service/
window_create_steps.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The steps of `CreateWindow`, in the order the handler runs them. A step that can refuse the
5//! call answers `Err` with the reply that ends it.
6
7#![allow(clippy::result_large_err)]
8
9use super::*;
10
11type Events = Vec<agentmux_common::ipc::Event>;
12
13/// What a window's restore request came to, and the lock that keeps the next opener behind it.
14pub(super) struct RestoreRequest {
15    pub(super) restore_if_available: bool,
16    /// Held until this window is registered, so the next opener sees it.
17    _election: Option<tokio::sync::MutexGuard<'static, ()>>,
18}
19
20/// The workspace the window shows, and what building it did.
21pub(super) struct WorkspaceChoice {
22    pub(super) ws_id: String,
23    /// Events of a workspace made for this window, unpublished (empty for an existing one).
24    pub(super) fresh_workspace_events: Events,
25    /// Set when a restore actually replays the last snapshot — gates clearing
26    /// it (see `created_reply`) so a genuinely successful restore
27    /// can't be replayed again by a later call, while a crash mid-restore
28    /// (this flag set, but the function never reaches that final clear)
29    /// leaves the snapshot intact for the next launch to retry.
30    pub(super) did_restore: bool,
31    /// What that restore loaded, and from which copy: the open workspace keeps
32    /// it as its last clean load once this window is up (`user_workspace`).
33    pub(super) restored_copy: Option<(serde_json::Value, super::super::user_workspace::LoadedFrom)>,
34}
35
36/// Whether this call restores the last session, deciding it under the restore election.
37pub(super) async fn restore_request(state: &AppState, args: &[serde_json::Value]) -> RestoreRequest {
38    let store = &state.mstore;
39    // Restore-on-relaunch (SPEC_SESSION_RESTORE_AND_SAVED_LAYOUTS_2026_08_13
40    // Feature 1) — arg 3 is set only by the frontend's genuine cold-start
41    // call site (`Client.windowids` was empty). Every other caller
42    // (tear-off, "Open New Window", the workspace-missing error-recovery
43    // fallback) omits it and gets the pre-existing default-seed behavior,
44    // completely unchanged.
45    //
46    // The client's own claim isn't trusted alone (reagentx P2 on PR #2560):
47    // re-check `Client.windowids` server-side too, so a stray/duplicate/
48    // misused call with `restoreIfAvailable: true` mid-session (when other
49    // windows are legitimately still open) can't resurrect the last snapshot
50    // into a spurious extra workspace.
51    let windowids_empty = || {
52        store.get_all::<Client>().ok().and_then(|cs| cs.into_iter().next()).map(|c| c.windowids.is_empty()).unwrap_or(true)
53    };
54    let wants_restore: bool = service::get_arg(args, 3).unwrap_or(false);
55    let mut client_windowids_empty = windowids_empty();
56    // Held until this window is registered, so the next opener sees it.
57    let mut _election = None;
58    if wants_restore {
59        let elected = RESTORE_ELECTION.lock().await;
60        client_windowids_empty = windowids_empty();
61        let restored_at = store
62            .get_all::<Client>()
63            .ok()
64            .and_then(|cs| cs.into_iter().next())
65            .and_then(|c| c.meta.get(RESTORED_AT_META_KEY).and_then(|v| v.as_i64()));
66        // The host saw another window still opening (arg 7): the window srv
67        // lists is that concurrent opener's, not a restored window closing
68        // again, which this waits for like any close (#5363).
69        let another_opening: bool = service::get_optional_arg(args, 7).unwrap_or(None).unwrap_or(false);
70        let just_restored =
71            another_opening && restored_at.is_some_and(|at| agentmux_common::time::now_ms() - at < JUST_RESTORED_MS);
72        // A window the tray opens right after the last one closed can arrive
73        // before that close does (the host sends it on its own thread): wait
74        // briefly for it, rather than open the default panes and lose the
75        // window it closed (#5363).
76        if !client_windowids_empty && !just_restored {
77            let deadline = std::time::Instant::now() + RESTORE_WAITS_FOR_CLOSE;
78            while !client_windowids_empty && std::time::Instant::now() < deadline {
79                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
80                client_windowids_empty = windowids_empty();
81            }
82        }
83        if client_windowids_empty {
84            super::super::session_windows::set_client_meta(
85                store,
86                RESTORED_AT_META_KEY,
87                Some(serde_json::json!(agentmux_common::time::now_ms())),
88            );
89        }
90        _election = Some(elected);
91    }
92    let restore_if_available: bool = wants_restore && client_windowids_empty;
93    RestoreRequest { restore_if_available, _election }
94}
95
96/// The workspace for the window: the one asked for, a restored one, or a new one with the default panes.
97pub(super) async fn resolve_workspace(
98    state: &AppState,
99    requested_ws_id: String,
100    restore_if_available: bool,
101    seed_view: Option<String>,
102    seed_meta: Option<serde_json::Value>,
103) -> Result<WorkspaceChoice, WebReturnType> {
104    let store = &state.mstore;
105    let mut did_restore = false;
106    let mut restored_copy = None;
107    // Resolve / create the workspace.
108    let (ws_id, fresh_workspace_events): (String, Events) =
109        if requested_ws_id.is_empty() {
110            let restored_from_last_session = if restore_if_available {
111                // The newer of the session record and the open workspace's
112                // record, then that workspace's older copies.
113                match super::super::user_workspace::restore_at_launch(state).await {
114                    Ok(Some(restored)) => {
115                        restored_copy = Some((restored.loaded, restored.from));
116                        Some(restored.main)
117                    }
118                    Ok(None) => None,
119                    Err(e) => {
120                        tracing::warn!(
121                            error = %e,
122                            "CreateWindow: session restore failed — falling back to default seed"
123                        );
124                        None
125                    }
126                }
127            } else {
128                None
129            };
130            if let Some(result) = restored_from_last_session {
131                did_restore = true;
132                result
133            } else {
134                match create_default_contents(state, seed_view, seed_meta, restore_if_available).await {
135                    Ok(made) => made,
136                    Err(e) => return Err(WebReturnType::error(e)),
137                }
138            }
139        } else {
140            // Existing workspace — verify it's in the reducer
141            // (or SQLite), but no creation needed.
142            let exists_in_sqlite = match store.get::<Workspace>(&requested_ws_id) {
143                Ok(opt) => opt.is_some(),
144                Err(e) => {
145                    return Err(WebReturnType::error(format!(
146                        "CreateWindow: workspace lookup failed: {}",
147                        e
148                    )));
149                }
150            };
151            if !exists_in_sqlite {
152                return Err(WebReturnType::error(format!(
153                    "CreateWindow: workspace not found: {}",
154                    requested_ws_id
155                )));
156            }
157            (requested_ws_id, Vec::new())
158        };
159    Ok(WorkspaceChoice { ws_id, fresh_workspace_events, did_restore, restored_copy })
160}
161
162/// Registers the window in the reducer for `ws_id` and marks its row new. On a refusal the workspace
163/// made for it is deleted again. Returns the window's id and the events to publish.
164pub(super) async fn register_window(state: &AppState, ws_id: &str, fresh_workspace_events: &Events) -> Result<(String, Events), WebReturnType> {
165    let store = &state.mstore;
166    // Step 3: register the window in the reducer.
167    let window_id = uuid::Uuid::new_v4().to_string();
168    let win_events = dispatch_to_reducer(
169        state,
170        agentmux_common::ipc::Command::CreateWindow {
171            window_id: window_id.clone(),
172            workspace_id: ws_id.to_string(),
173        },
174    )
175    .await;
176    if let Some(err_msg) = win_events.iter().find_map(|e| match e {
177        agentmux_common::ipc::Event::Error { message, .. } => Some(message.clone()),
178        _ => None,
179    }) {
180        // Compensate the fresh workspace if we created one.
181        if !fresh_workspace_events.is_empty() {
182            let comp = dispatch_to_reducer(
183                state,
184                agentmux_common::ipc::Command::DeleteWorkspace {
185                    workspace_id: ws_id.to_string(),
186                    // Internal compensation path (Step 5 PR 2).
187                    force: false,
188                },
189            )
190            .await;
191            for ev in &comp {
192                let _ = crate::persist_subscriber::apply_event_to_mstore(ev, store);
193            }
194            publish_events(state, &comp);
195        }
196        return Err(WebReturnType::error(err_msg));
197    }
198    for ev in &win_events {
199        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
200            return Err(WebReturnType::error(format!(
201                "CreateWindow: SQLite write failed: {}",
202                e
203            )));
204        }
205    }
206    // Mark the window as `isnew` so the host's first-paint
207    // signaling logic still applies — wcore::create_window_full
208    // set this; the subscriber's default is `isnew: false`.
209    if let Ok(mut win) = store.must_get::<Window>(&window_id) {
210        if !win.isnew {
211            win.isnew = true;
212            let _ = store.update(&mut win);
213        }
214    }
215    Ok((window_id, win_events))
216}
217
218/// The host window label as a meta crumb on the new row. Returns the events to publish.
219pub(super) async fn write_label_crumb(state: &AppState, window_id: &str, host_label: &str) -> Events {
220    let store = &state.mstore;
221    // SPEC_POOL_ADOPTION_AND_WINDOW_ROW_CRUMB_2026_07_11 Residual 2 —
222    // persist the caller's host window label as a meta crumb,
223    // atomically with row creation (optional arg 2; old callers send
224    // two args and skip this). The crumb exists so cleanup paths can
225    // resolve label → window row WITHOUT the host-side registration
226    // chain (`register_backend_window` → launcher shadow), which is
227    // exactly what's missing in the early-close race shape (#2088)
228    // and after a host crash. It is a HINT, not an identity — labels
229    // recur across host restarts — so consumers must treat a miss or
230    // duplicate as "fall back to current behavior," never delete on
231    // crumb evidence alone. Non-fatal on failure: an unattributed
232    // row is the pre-crumb status quo.
233    if host_label.is_empty() {
234        Vec::new()
235    } else {
236        let evs = dispatch_to_reducer(
237            state,
238            agentmux_common::ipc::Command::UpdateWindowMeta {
239                window_id: window_id.to_string(),
240                meta_patch: serde_json::json!({ "host:label": host_label }),
241            },
242        )
243        .await;
244        for ev in &evs {
245            if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
246                tracing::warn!(
247                    window_id = %window_id,
248                    error = %e,
249                    "CreateWindow: host:label crumb write failed — row stays unattributed"
250                );
251            }
252        }
253        evs
254    }
255}
256
257/// A window a session restore rebuilt gets back its name, theme and opacity. Returns the events to publish.
258pub(super) async fn restored_name_events(state: &AppState, window_id: &str, ws_id: &str) -> Events {
259    let store = &state.mstore;
260    // A window a session restore rebuilt gets back the name, theme and opacity
261    // it had (session_windows.rs): the main one, and each reopened beside it.
262    // They are forgotten only once written.
263    super::super::session_windows::restored_window_opened(store, ws_id);
264    // A closed window reopening (`TakeClosedWindow`) is open now.
265    super::super::session_closed::forget(store, ws_id);
266    let restored_meta = super::super::session_windows::restored_window_meta(store, ws_id);
267    match (!restored_meta.is_empty()).then_some(restored_meta) {
268        None => Vec::new(),
269        Some(patch) => {
270            let evs = dispatch_to_reducer(
271                state,
272                agentmux_common::ipc::Command::UpdateWindowMeta {
273                    window_id: window_id.to_string(),
274                    meta_patch: serde_json::Value::Object(patch),
275                },
276            )
277            .await;
278            let mut written = !evs.iter().any(|e| matches!(e, agentmux_common::ipc::Event::Error { .. }));
279            for ev in &evs {
280                if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
281                    tracing::warn!(window_id = %window_id, error = %e, "CreateWindow: restored window name write failed");
282                    written = false;
283                }
284            }
285            if written {
286                super::super::session_windows::forget_restored_window_meta(store, ws_id);
287            }
288            evs
289        }
290    }
291}
292
293/// What this window takes from another: the appearance and name of the row it replaces (on a reload, or
294/// recreated after a crash), and the appearance of a window whose opener asked for it by host label.
295/// Returns the events to publish.
296pub(super) async fn inherited_events(state: &AppState, args: &[serde_json::Value], window_id: &str, host_label: &str) -> Events {
297    // SPEC_PER_WINDOW_THEME_AND_OPACITY_2026_10_12 §4.6 — a reloaded window
298    // other than the main one gets a new row each load (optional arg 6 is
299    // the row it had before), so its own theme and opacity come across. Its
300    // name too: nothing else keeps it once the old row is closed.
301    let previous_window_id: Option<String> = service::get_optional_arg(args, 6).unwrap_or(None);
302    let mut reload_events = match previous_window_id.filter(|p| !p.is_empty() && *p != window_id) {
303        Some(prev) => super::super::window_inherit::apply_replacement(state, &prev, window_id).await,
304        None => Vec::new(),
305    };
306    // SPEC_PER_WINDOW_THEME_AND_OPACITY_2026_10_12 §6 — the window that
307    // opened this one may already have asked for its appearance to be
308    // copied here (`InheritWindowAppearance`, keyed by host label). Taken
309    // only after the row is recorded, so a request arriving in between
310    // finds the row instead (see window_inherit.rs).
311    let inherit_events = match (!host_label.is_empty())
312        .then(|| {
313            let row_seq = super::super::window_inherit::record_created(host_label, window_id);
314            super::super::window_inherit::take_pending(host_label, row_seq)
315        })
316        .flatten()
317    {
318        Some(source) => super::super::window_inherit::apply_inheritance(state, &source, window_id).await,
319        None => Vec::new(),
320    };
321    reload_events.extend(inherit_events);
322    reload_events
323}
324
325/// The window row as the reply, once the snapshot a restore replayed is cleared.
326pub(super) fn created_reply(state: &AppState, window_id: &str, choice: &WorkspaceChoice) -> WebReturnType {
327    let store = &state.mstore;
328    match store.must_get::<Window>(window_id) {
329        Ok(win) => {
330            // Restore-on-relaunch (SPEC_SESSION_RESTORE_AND_SAVED_LAYOUTS_2026_08_13
331            // Feature 1) — only clear the snapshot once the restore it
332            // produced has fully, successfully completed (this read-back is
333            // the last step of that path). A crash between
334            // `restore_last_session` returning and reaching this line never
335            // executes this clear, so the next launch's `Client.windowids`
336            // is still empty and retries against the same intact snapshot —
337            // deliberately not cleared any earlier than this. Reviewer-caught
338            // (reagentx P2 on PR #2560): without this, a stray repeat call
339            // could replay the same snapshot into a second duplicate
340            // workspace even after a genuinely successful restore.
341            if choice.did_restore {
342                super::super::session_restore::clear_last_session_snapshot(store);
343                if let Some((loaded, from)) = &choice.restored_copy {
344                    super::super::user_workspace::after_clean_load(store, loaded, *from);
345                }
346            }
347            created_window_reply(store, &win)
348        }
349        Err(e) => WebReturnType::error(format!(
350            "CreateWindow: window read-back failed: {}",
351            e
352        )),
353    }
354}