Skip to main content

agentmux_srv_core/backend/wcore/
window.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Window CRUD, focus, workspace switching, and repair operations.
5
6use uuid::Uuid;
7
8use crate::backend::storage::store::Store;
9use crate::backend::storage::StoreError;
10use crate::backend::obj::*;
11
12use super::get_client;
13use super::tab::create_tab;
14use super::workspace::create_workspace;
15
16/// Create a new window pointing to a workspace.
17/// If workspace_id is empty, auto-creates a new workspace + default tab (matches Go behavior).
18pub fn create_window(
19    store: &Store,
20    workspace_id: &str,
21) -> Result<Window, StoreError> {
22    let ws_id = if workspace_id.is_empty() {
23        let ws = create_workspace(store, "")?;
24        let _tab = create_tab(store, &ws.oid)?;
25        ws.oid
26    } else {
27        let _ws = store.must_get::<Workspace>(workspace_id)?;
28        workspace_id.to_string()
29    };
30    let mut window = Window {
31        oid: Uuid::new_v4().to_string(),
32        workspaceid: ws_id,
33        isnew: true,
34        pos: Point { x: 0, y: 0 },
35        winsize: WinSize {
36            width: 0,
37            height: 0,
38        },
39        meta: MetaMapType::new(),
40        ..Default::default()
41    };
42    store.insert(&mut window)?;
43    Ok(window)
44}
45
46/// Create a new window with all required objects in a single transaction.
47/// If workspace_id is empty, creates workspace + tab + window + updates client
48/// all in one BEGIN/COMMIT — reducing 8+ lock acquisitions and fsyncs to 1.
49///
50/// Returns the created Window. Production creates windows through the
51/// reducer (`server/service/window_create.rs`); tests use this to seed rows.
52#[cfg(any(test, feature = "test-support"))]
53pub fn create_window_full(
54    store: &Store,
55    workspace_id: &str,
56) -> Result<Window, StoreError> {
57    store.with_tx(|tx| {
58        let ws_id = if workspace_id.is_empty() {
59            // Create workspace
60            let mut ws = Workspace {
61                oid: Uuid::new_v4().to_string(),
62                name: String::new(),
63                tabids: vec![],
64                pinnedtabids: vec![],
65                activetabid: String::new(),
66                meta: MetaMapType::new(),
67                ..Default::default()
68            };
69            tx.insert(&mut ws)?;
70
71            // Create layout state for tab
72            let mut layout = LayoutState {
73                oid: Uuid::new_v4().to_string(),
74                rootnode: None,
75                magnifiednodeid: String::new(),
76                focusednodeid: String::new(),
77                pendingbackendactions: None,
78                meta: None,
79                ..Default::default()
80            };
81            tx.insert(&mut layout)?;
82
83            // Create tab
84            let mut tab = Tab {
85                oid: Uuid::new_v4().to_string(),
86                // "Tab N" — same scheme as `wcore/tab.rs`'s
87                // `create_tab_with_opts` and the `handle_create_tab` service
88                // handler behind the user's "+" button. Earlier
89                // this used "T{N}" (a stylistic mismatch), then plain
90                // "tabN" (SPEC_TAB_GAPS_AND_NAMING_2026_04_25 + the
91                // first-principles spec SPEC_TAB_BAR_FIRST_PRINCIPLES_2026_04_25),
92                // revised to "Tab N" 2026-09-02.
93                name: format!("Tab {}", ws.tabids.len() + ws.pinnedtabids.len() + 1),
94                layoutstate: layout.oid.clone(),
95                blockids: vec![],
96                meta: MetaMapType::new(),
97                ..Default::default()
98            };
99            tx.insert(&mut tab)?;
100
101            // Link tab to workspace
102            ws.tabids.push(tab.oid.clone());
103            ws.activetabid = tab.oid.clone();
104            tx.update(&mut ws)?;
105
106            ws.oid
107        } else {
108            let _ws = tx.must_get::<Workspace>(workspace_id)?;
109            workspace_id.to_string()
110        };
111
112        // Create window
113        let mut window = Window {
114            oid: Uuid::new_v4().to_string(),
115            workspaceid: ws_id,
116            isnew: true,
117            pos: Point { x: 0, y: 0 },
118            winsize: WinSize {
119                width: 0,
120                height: 0,
121            },
122            meta: MetaMapType::new(),
123            ..Default::default()
124        };
125        tx.insert(&mut window)?;
126
127        // Update client with new window ID
128        let clients = tx.get_all::<Client>()?;
129        if let Some(client) = clients.into_iter().next() {
130            let mut client = client;
131            client.windowids.push(window.oid.clone());
132            tx.update(&mut client)?;
133        }
134
135        Ok(window)
136    })
137}
138
139/// Focus a window (move to front of client's window list).
140pub fn focus_window(store: &Store, window_id: &str) -> Result<(), StoreError> {
141    let mut client = get_client(store)?;
142    if let Some(pos) = client.windowids.iter().position(|id| id == window_id) {
143        let id = client.windowids.remove(pos);
144        client.windowids.insert(0, id);
145        store.update(&mut client)?;
146    }
147    Ok(())
148}
149
150/// Check and fix a window — ensure it has a valid workspace with tabs.
151pub(super) fn check_and_fix_window(store: &Store, window_id: &str) -> Result<(), StoreError> {
152    let window = match store.get::<Window>(window_id)? {
153        Some(w) => w,
154        None => return Ok(()), // window doesn't exist, nothing to fix
155    };
156
157    // Check workspace exists
158    let ws = match store.get::<Workspace>(&window.workspaceid)? {
159        Some(ws) => ws,
160        None => {
161            // Workspace missing — create a new one
162            let ws = create_workspace(store, "")?;
163            let mut window = window;
164            window.workspaceid = ws.oid.clone();
165            store.update(&mut window)?;
166            ws
167        }
168    };
169
170    // Ensure workspace has at least one tab (matches Go: checks both tabids and pinnedtabids)
171    if ws.tabids.is_empty() && ws.pinnedtabids.is_empty() {
172        create_tab(store, &ws.oid)?;
173    }
174
175    Ok(())
176}