Skip to main content

agentmux_srv/server/service/
window_create.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `window` service handler — `CreateWindow`. Split out of `window.rs`;
5//! see that file's dispatcher for the full method list.
6
7use agentmux_common::ipc;
8use crate::backend::obj::*;
9use crate::backend::service::{self, WebCallType, WebReturnType};
10
11use super::super::AppState;
12use super::reducer_helpers::{dispatch_to_reducer, publish_events};
13
14/// How long a restore asks for waits for a window close still on its way.
15pub(crate) const RESTORE_WAITS_FOR_CLOSE: std::time::Duration = std::time::Duration::from_secs(3);
16
17/// Windows asking to restore decide one at a time, so exactly one restores
18/// when several open together (a double click on the tray icon) (#5363).
19static RESTORE_ELECTION: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
20
21/// When a window last asked for and got a restore (epoch ms, client meta).
22const RESTORED_AT_META_KEY: &str = "session:restored_at_ms";
23
24/// An opener arriving this soon after a restore, beside another window still
25/// opening, opens the default panes at once: the window it would wait for is
26/// the one just restored, not one closing.
27const JUST_RESTORED_MS: i64 = 10_000;
28
29/// The reply for a window that was made. Every window has a slot in the panel's list from the day it is
30/// made: the next one, at the end.
31fn created_window_reply(store: &crate::backend::storage::store::Store, win: &Window) -> WebReturnType {
32    super::session_slots::place(store, std::slice::from_ref(&win.workspaceid));
33    WebReturnType::success(serde_json::to_value(win).unwrap_or_default())
34}
35
36#[path = "window_create_steps.rs"]
37mod steps;
38
39// Phase E.5.8 — CreateWindow migrated through the reducer.
40// Two paths: (1) empty workspace_id → CreateWorkspace +
41// CreateTab + CreateWindow as a multi-step dispatch (mirrors
42// wcore::create_window_full's "fresh workspace" path); (2)
43// existing workspace_id → just CreateWindow. The subscriber's
44// apply_srv_window_opened handles `Client.windowids` updates
45// and Window-row creation. Layout setup for the new tab uses
46// the apply_tab_created provisioning (E.4 layout migration is
47// separate; default rootnode = None matches wcore behaviour).
48pub(crate) async fn handle_create_window(state: &AppState, call: &WebCallType) -> WebReturnType {
49    let args = &call.args;
50    let requested_ws_id: String = service::get_arg(args, 1).unwrap_or_default();
51    let restore = steps::restore_request(state, args).await;
52    // "Open in New Window" from a widget's context menu (arg 4/5, optional,
53    // same additive pattern as restoreIfAvailable) — when present,
54    // seed the fresh tab with ONLY this one block instead of the default
55    // 3-pane agent/swarm/sysinfo layout. Ignored on the tear-off / existing-
56    // workspace path (`resolve_workspace`'s existing-workspace case), same as the default seed is.
57    let seed_view: Option<String> = service::get_optional_arg(args, 4).unwrap_or(None);
58    let seed_meta: Option<serde_json::Value> = service::get_optional_arg(args, 5).unwrap_or(None);
59    let mut choice = match steps::resolve_workspace(state, requested_ws_id, restore.restore_if_available, seed_view, seed_meta).await {
60        Ok(choice) => choice,
61        Err(reply) => return reply,
62    };
63
64    // Step 3: register the window in the reducer.
65    let (window_id, win_events) = match steps::register_window(state, &choice.ws_id, &choice.fresh_workspace_events).await {
66        Ok(registered) => registered,
67        Err(reply) => return reply,
68    };
69    let host_label: String = service::get_arg(args, 2).unwrap_or_default();
70    let crumb_events = steps::write_label_crumb(state, &window_id, &host_label).await;
71    let name_events = steps::restored_name_events(state, &window_id, &choice.ws_id).await;
72    let inherit_events = steps::inherited_events(state, args, &window_id, &host_label).await;
73    // Publish all events from this multi-step (workspace + tab + window).
74    let mut all_events = std::mem::take(&mut choice.fresh_workspace_events);
75    all_events.extend(win_events);
76    all_events.extend(crumb_events);
77    all_events.extend(name_events);
78    all_events.extend(inherit_events);
79    publish_events(state, &all_events);
80    // Return the Window struct (matches the prior RPC contract).
81    steps::created_reply(state, &window_id, &choice)
82}
83
84/// The message of the first error among `events`, if any.
85fn first_error(events: &[ipc::Event]) -> Option<String> {
86    events.iter().find_map(|e| match e {
87        ipc::Event::Error { message, .. } => Some(message.clone()),
88        _ => None,
89    })
90}
91
92/// Writes `events` through to the store, stopping at the first failure.
93fn persist(events: &[ipc::Event], store: &crate::backend::storage::store::Store) -> Result<(), String> {
94    for ev in events {
95        crate::persist_subscriber::apply_event_to_mstore(ev, store).map_err(|e| format!("CreateWindow: SQLite write failed: {}", e))?;
96    }
97    Ok(())
98}
99
100/// Step 1: the new workspace's id and the events that made it.
101async fn create_workspace(state: &AppState) -> Result<(String, Vec<ipc::Event>), String> {
102    let events = dispatch_to_reducer(state, ipc::Command::CreateWorkspace { name: String::new() }).await;
103    if let Some(err_msg) = first_error(&events) {
104        return Err(err_msg);
105    }
106    persist(&events, &state.mstore)?;
107    let ws_id = events
108        .iter()
109        .find_map(|e| match e {
110            ipc::Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
111            _ => None,
112        })
113        .unwrap_or_default();
114    Ok((ws_id, events))
115}
116
117/// Step 2: the workspace's tab, and the events that made it. When the tab can't be made, the empty
118/// workspace is deleted again.
119async fn create_tab(state: &AppState, ws_id: &str) -> Result<Vec<ipc::Event>, String> {
120    let events = dispatch_to_reducer(state, ipc::Command::CreateTab { workspace_id: ws_id.to_string(), name: String::new() }).await;
121    if let Some(err_msg) = first_error(&events) {
122        // Compensate: delete the empty workspace.
123        let comp = dispatch_to_reducer(
124            state,
125            ipc::Command::DeleteWorkspace {
126                workspace_id: ws_id.to_string(),
127                // Internal compensation path — not
128                // saga-driven (Step 5 PR 2 added the
129                // `force` flag for saga provenance).
130                force: false,
131            },
132        )
133        .await;
134        for ev in &comp {
135            let _ = crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore);
136        }
137        publish_events(state, &comp);
138        return Err(err_msg);
139    }
140    persist(&events, &state.mstore)?;
141    Ok(events)
142}
143
144/// Dispatches the seed block(s) through the reducer: the `seed_view` alone (with `seed_meta` when
145/// given), or the default agent, swarm and sysinfo. For the default 3-pane case, order is the one
146/// `default_three_pane_tree` expects positionally (agent, swarm, sysinfo) — NOT top-to-bottom
147/// display order, since sysinfo renders above swarm. Returns the ids made and their events; a block
148/// that can't be made ends the seeding (the tab opens with what there is).
149async fn seed_blocks(
150    state: &AppState,
151    tab_id: &str,
152    seed_view: Option<&str>,
153    seed_meta: Option<&serde_json::Value>,
154) -> (Vec<String>, Vec<ipc::Event>) {
155    let views: Vec<&str> = match seed_view {
156        Some(v) => vec![v],
157        None => vec!["agent", "swarm", "sysinfo"],
158    };
159    let mut seeded_ids: Vec<String> = Vec::new();
160    let mut seed_events: Vec<ipc::Event> = Vec::new();
161    for view in views {
162        let meta = match (seed_view, seed_meta) {
163            (Some(_), Some(meta)) => meta.clone(),
164            _ => serde_json::json!({ "view": view }),
165        };
166        let evs = dispatch_to_reducer(state, ipc::Command::CreateBlock { tab_id: tab_id.to_string(), meta }).await;
167        if let Some(err_msg) = first_error(&evs) {
168            tracing::warn!(tab_id = %tab_id, view = %view, error = %err_msg, "CreateWindow: seed block create failed — opening blank tab");
169            break;
170        }
171        for ev in &evs {
172            if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore) {
173                tracing::warn!(tab_id = %tab_id, error = %e, "CreateWindow: seed block SQLite write failed");
174            }
175        }
176        seeded_ids.extend(evs.iter().find_map(|e| match e {
177            ipc::Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
178            _ => None,
179        }));
180        seed_events.extend(evs);
181    }
182    (seeded_ids, seed_events)
183}
184
185/// Writes the layout for the seeded panes: a single leaf for a widget's "Open in New Window" (see
186/// `single_leaf_tree`), the shared three-pane tree for the default. A cold start with nothing of
187/// its own to restore (`offer_other_build`) also notes what it seeded, for a layout another build
188/// saved to be offered. A seeding that came out short leaves the tab blank.
189async fn seed_layout(state: &AppState, ws_id: &str, tab_id: &str, seed_view: Option<&str>, seeded_ids: &[String], offer_other_build: bool) {
190    let tree_and_focus = match (seed_view, seeded_ids) {
191        (Some(_), [only]) => Some(crate::backend::wcore::single_leaf_tree(only)),
192        (None, [agent, swarm, sysinfo]) => {
193            if offer_other_build {
194                super::session_other_builds::remember_seeded_default(&state.mstore, ws_id, tab_id, seeded_ids);
195            }
196            // SPEC_864 Phase 3 — post-bootstrap seed routes through the reducer (single writer of
197            // db_layout); the tree shape is shared with the pre-bootstrap store-direct first-launch
198            // seed via `default_three_pane_tree`.
199            Some(crate::backend::wcore::default_three_pane_tree(agent, swarm, sysinfo))
200        }
201        _ => None,
202    };
203    if let Some((tree, focused)) = tree_and_focus {
204        if let Err(e) = super::reducer_helpers::seed_layout_via_reducer(state, tab_id, tree, focused, String::new()).await {
205            tracing::warn!(tab_id = %tab_id, error = %e, "CreateWindow: default layout write failed — opening blank tab");
206        }
207    }
208}
209
210/// A new window's contents: a workspace with one tab seeded with the default
211/// panes (agent | sysinfo / swarm), or with the single `seed_view` pane a
212/// widget's "Open in New Window" asks for. No window shows it yet. Also what
213/// a new user workspace's first window opens (`user_workspace_switch`).
214/// `offer_other_build`: a cold start with nothing to restore, which may offer
215/// a layout another build saved. Returns the workspace and the applied events,
216/// unpublished.
217///
218/// Seeding is non-fatal: a failure leaves an empty tab (the prior behaviour) rather than failing
219/// window creation. Only this fresh-workspace path seeds; tear-off (an existing workspace)
220/// reattaches its populated workspace as-is. See docs/retro/retro-blank-new-window-2026-06-21.md.
221///
222/// 2nd-window-tear-off desync fix (#1681): the seed blocks MUST be created through the reducer
223/// (CreateBlock command), NOT via the store-only `seed_default_layout`/`create_block` path. This
224/// runs AFTER bootstrap, so anything written straight to SQLite is invisible to the in-memory
225/// reducer `srv_state` until the next restart: a later `TearOffBlock` from that window would be
226/// rejected "block not found". Dispatching CreateBlock per pane lands the blocks in BOTH srv_state
227/// and (via the subscriber) SQLite, then the shared layout is written referencing them.
228pub(crate) async fn create_default_contents(
229    state: &AppState,
230    seed_view: Option<String>,
231    seed_meta: Option<serde_json::Value>,
232    offer_other_build: bool,
233) -> Result<(String, Vec<ipc::Event>), String> {
234    let (new_ws_id, mut combined) = create_workspace(state).await?;
235    let tab_events = create_tab(state, &new_ws_id).await?;
236    let new_tab_id = tab_events.iter().find_map(|e| match e {
237        ipc::Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
238        _ => None,
239    });
240    combined.extend(tab_events);
241    if let Some(tab_id) = new_tab_id {
242        let (seeded_ids, seed_events) = seed_blocks(state, &tab_id, seed_view.as_deref(), seed_meta.as_ref()).await;
243        seed_layout(state, &new_ws_id, &tab_id, seed_view.as_deref(), &seeded_ids, offer_other_build).await;
244        combined.extend(seed_events);
245    }
246    Ok((new_ws_id, combined))
247}
248
249#[cfg(test)]
250#[path = "window_create_tests.rs"]
251mod create_tests;
252
253#[cfg(test)]
254#[path = "window_create_contents_tests.rs"]
255mod contents_tests;
256
257#[cfg(test)]
258mod create_window_seed_tests {
259    use super::super::window::handle_window_service;
260    use crate::backend::obj::{Block, LayoutState, Tab};
261    use crate::backend::service::WebCallType;
262    use crate::server::tests::test_state;
263
264    fn create_window_call(workspace_id: &str) -> WebCallType {
265        WebCallType {
266            service: "window".to_string(),
267            method: "CreateWindow".to_string(),
268            uicontext: None,
269            // arg0 is ignored by the handler; arg1 is the (optional) workspace
270            // to reattach. Empty → fresh-workspace seed path.
271            args: vec![
272                serde_json::Value::Null,
273                serde_json::Value::String(workspace_id.to_string()),
274            ],
275        }
276    }
277
278    /// Regression for the 2nd-window-tear-off desync (#1681).
279    ///
280    /// "Open another window" used to seed its default blocks straight
281    /// into SQLite (`seed_default_layout` → `create_block`), bypassing the
282    /// reducer. The handler runs after bootstrap, so those blocks never
283    /// reached the in-memory `srv_state`. The frontend rendered them (it reads
284    /// SQLite) but a subsequent `TearOffBlock` from that window was rejected
285    /// "block not found" — the workspace/tab existed (they went through the
286    /// reducer) but the block did not. This asserts the seed blocks now land in
287    /// `srv_state` AND that a tear-off from the new window succeeds end-to-end.
288    #[tokio::test]
289    async fn new_window_seed_blocks_are_in_reducer_state_and_tear_off_succeeds() {
290        let state = test_state();
291        let blocks_before = state.srv_state.lock().await.blocks.len();
292
293        let ret = handle_window_service(&state, &create_window_call("")).await;
294        assert!(ret.success, "CreateWindow failed: {:?}", ret.error);
295
296        let win = ret.data.expect("CreateWindow returns the Window");
297        let workspace_id = win
298            .get("workspaceid")
299            .and_then(|v| v.as_str())
300            .expect("window has a workspaceid")
301            .to_string();
302
303        // The fix: the seed blocks are present in the in-memory reducer
304        // state, attached to the new window's tab.
305        let (tab_id, block_id) = {
306            let s = state.srv_state.lock().await;
307            assert_eq!(
308                s.blocks.len(),
309                blocks_before + 3,
310                "the 3 seed blocks must be tracked in srv_state, not only SQLite"
311            );
312            let ws = s
313                .workspaces
314                .get(&workspace_id)
315                .expect("new workspace is in the reducer");
316            let tab_id = ws.tab_ids.first().expect("new workspace has a tab").clone();
317            let tab = s.tabs.get(&tab_id).expect("new tab is in the reducer");
318            assert_eq!(
319                tab.block_ids.len(),
320                3,
321                "the new window's tab must hold its 3 seed blocks in the reducer"
322            );
323            (tab_id, tab.block_ids[0].clone())
324        };
325
326        // End-to-end: tearing a block off the freshly-created window no longer
327        // hits the "block not found" pre-condition.
328        let result =
329            crate::sagas::tear_off_block::run(&state, block_id, tab_id, workspace_id).await;
330        assert!(
331            result.is_ok(),
332            "tear-off from a freshly-created window must succeed, got: {:?}",
333            result.err()
334        );
335    }
336
337    /// A widget's "Open in New Window" (arg 4 `seed_view` / arg 5
338    /// `seed_meta`) must seed the new tab with ONLY that one pane — not the
339    /// default 3-pane layout plus the widget as a 4th split. Regression: the
340    /// pre-existing frontend-only `initial_view` mechanism opened the
341    /// default 3-pane layout via CreateWindow and then called `pane.open`
342    /// on top of it, which only ever ADDED a pane rather than replacing the
343    /// seed.
344    #[tokio::test]
345    async fn new_window_with_seed_view_seeds_a_single_pane_not_the_default_three() {
346        let state = test_state();
347
348        let call = WebCallType {
349            service: "window".to_string(),
350            method: "CreateWindow".to_string(),
351            uicontext: None,
352            args: vec![
353                serde_json::Value::Null,                        // winSize
354                serde_json::Value::String(String::new()),       // workspaceId — fresh
355                serde_json::Value::Null,                        // hostLabel
356                serde_json::Value::Bool(false),                 // restoreIfAvailable
357                serde_json::Value::String("browser".to_string()), // seedView
358                serde_json::json!({ "view": "browser", "url": "https://example.com" }), // seedMeta
359            ],
360        };
361
362        let ret = handle_window_service(&state, &call).await;
363        assert!(ret.success, "CreateWindow failed: {:?}", ret.error);
364
365        let win = ret.data.expect("CreateWindow returns the Window");
366        let workspace_id = win
367            .get("workspaceid")
368            .and_then(|v| v.as_str())
369            .expect("window has a workspaceid")
370            .to_string();
371
372        let tab_id = {
373            let s = state.srv_state.lock().await;
374            let ws = s.workspaces.get(&workspace_id).expect("new workspace is in the reducer");
375            assert_eq!(ws.tab_ids.len(), 1, "one tab");
376            let tab_id = ws.tab_ids.first().unwrap().clone();
377            let tab = s.tabs.get(&tab_id).expect("new tab is in the reducer");
378            assert_eq!(
379                tab.block_ids.len(),
380                1,
381                "seeded with exactly ONE block, not the default 3-pane layout"
382            );
383            tab_id
384        };
385
386        let store = &state.mstore;
387        let tab = store.must_get::<Tab>(&tab_id).unwrap();
388        assert_eq!(tab.blockids.len(), 1);
389        let block = store.must_get::<Block>(&tab.blockids[0]).unwrap();
390        assert_eq!(block.meta.get("view").and_then(|v| v.as_str()), Some("browser"));
391        assert_eq!(
392            block.meta.get("url").and_then(|v| v.as_str()),
393            Some("https://example.com"),
394            "the full seedMeta must be used, not just a bare {{view}} object"
395        );
396
397        // Single-leaf tree — no split, root node itself wraps the block.
398        let layout = store.must_get::<LayoutState>(&tab.layoutstate).unwrap();
399        let root = layout.rootnode.as_ref().expect("layout must be populated");
400        assert!(root.children.is_empty(), "single pane — no split children");
401        assert_eq!(root.data.as_ref().unwrap().block_id, tab.blockids[0]);
402    }
403}