Skip to main content

agentmux_srv/server/service/
window_inherit.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `window` service handlers — `MarkWindowOpen` and `InheritWindowAppearance`:
5//! a new window opens with the theme and opacity of the window that created
6//! it (docs/specs/SPEC_PER_WINDOW_THEME_AND_OPACITY_2026_10_12.md §6).
7//!
8//! The creator takes a mark (`MarkWindowOpen`), opens the window, learns its
9//! host label from that call's return, and then calls
10//! `InheritWindowAppearance` with its own window id, the label and the mark.
11//! The new window's renderer creates its Window row (`CreateWindow`) at about
12//! the same moment, so the two calls race. Each side first publishes what it
13//! has, then checks for the other: `InheritWindowAppearance` records a
14//! pending entry and then looks for the row; `CreateWindow` records its row
15//! and then takes any pending entry. Whichever side takes the entry applies
16//! it, so it is applied exactly once whatever the order.
17//!
18//! Host labels are reused: a pool window can be demoted and promoted again
19//! straight away, and the old row can outlive that (its close runs on
20//! another thread). The mark is what tells the new row from the old one.
21//! Marks and row records share one counter, so a row created after the mark
22//! was taken is the one this open made; any older row for the label belongs
23//! to an earlier use of it and never takes the entry.
24
25use std::collections::HashMap;
26use std::sync::atomic::{AtomicU64, Ordering};
27use std::sync::{LazyLock, Mutex};
28use std::time::{Duration, Instant};
29
30use crate::backend::obj::*;
31use crate::backend::service::{self, WebCallType, WebReturnType};
32
33use super::super::AppState;
34use super::reducer_helpers::{dispatch_to_reducer, publish_events};
35
36/// The per-window appearance keys a new window copies from its creator.
37pub(crate) const INHERITED_KEYS: &[&str] = &["window:theme", "window:opacity"];
38
39/// What a row takes from the row it replaces (the same window in a new row: a reload, or a window
40/// recreated after a crash): its appearance, and the name the user gave the window. The old row is
41/// closed while the new one holds its workspace, so nothing else keeps the name.
42pub(crate) const REPLACED_KEYS: &[&str] = &["window:theme", "window:opacity", "window:displayname"];
43
44/// How long a pending entry waits for its window. A new window creates its
45/// row within a second or two of being opened.
46const PENDING_TTL: Duration = Duration::from_secs(30);
47
48/// Orders marks and row records: every mark and every recorded row gets the
49/// next value.
50static SEQ: AtomicU64 = AtomicU64::new(1);
51
52struct Pending {
53    source_window_id: String,
54    /// Only a row recorded after this mark is the window being opened.
55    after: u64,
56    at: Instant,
57}
58
59/// host label → the inheritance waiting for that label's new row.
60static PENDING: LazyLock<Mutex<HashMap<String, Pending>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
61
62/// host label → (the window id `CreateWindow` last made for it, its sequence, when).
63static CREATED: LazyLock<Mutex<HashMap<String, (String, u64, Instant)>>> =
64    LazyLock::new(|| Mutex::new(HashMap::new()));
65
66fn next_seq() -> u64 {
67    SEQ.fetch_add(1, Ordering::SeqCst)
68}
69
70/// Called by `CreateWindow` once the row exists, before it takes a pending
71/// entry. Returns the row's sequence, for `take_pending`.
72pub(crate) fn record_created(label: &str, window_id: &str) -> u64 {
73    let seq = next_seq();
74    let mut created = CREATED.lock().unwrap_or_else(|e| e.into_inner());
75    created.retain(|_, (_, _, at)| at.elapsed() < PENDING_TTL);
76    created.insert(label.to_string(), (window_id.to_string(), seq, Instant::now()));
77    seq
78}
79
80/// Take the pending source for `label` if a row with sequence `row_seq` is
81/// the one it waits for: recorded after its mark, and the entry still fresh.
82pub(crate) fn take_pending(label: &str, row_seq: u64) -> Option<String> {
83    let mut pending = PENDING.lock().unwrap_or_else(|e| e.into_inner());
84    let entry = pending.get(label)?;
85    if row_seq <= entry.after {
86        return None;
87    }
88    let entry = pending.remove(label)?;
89    (entry.at.elapsed() < PENDING_TTL).then_some(entry.source_window_id)
90}
91
92fn record_pending(label: &str, source_window_id: &str, after: u64) {
93    let mut pending = PENDING.lock().unwrap_or_else(|e| e.into_inner());
94    pending.retain(|_, p| p.at.elapsed() < PENDING_TTL);
95    pending.insert(
96        label.to_string(),
97        Pending {
98            source_window_id: source_window_id.to_string(),
99            after,
100            at: Instant::now(),
101        },
102    );
103}
104
105/// The source window's appearance keys that are set, as a meta patch.
106/// `None` when the source is gone or has none of them set.
107pub(crate) fn appearance_patch(source: &Window) -> Option<serde_json::Value> {
108    patch_of(source, INHERITED_KEYS)
109}
110
111/// Those of `keys` the source has set, as a meta patch. `None` when it has none of them set.
112fn patch_of(source: &Window, keys: &[&str]) -> Option<serde_json::Value> {
113    let patch: serde_json::Map<String, serde_json::Value> = keys
114        .iter()
115        .filter_map(|k| {
116            source
117                .meta
118                .get(*k)
119                .filter(|v| !v.is_null())
120                .map(|v| (k.to_string(), v.clone()))
121        })
122        .collect();
123    (!patch.is_empty()).then(|| serde_json::Value::Object(patch))
124}
125
126/// Copy `source_window_id`'s appearance onto `target_window_id`. Returns the
127/// events to publish; empty when there is nothing to copy.
128pub(crate) async fn apply_inheritance(
129    state: &AppState,
130    source_window_id: &str,
131    target_window_id: &str,
132) -> Vec<agentmux_common::ipc::Event> {
133    copy_keys(state, source_window_id, target_window_id, INHERITED_KEYS).await
134}
135
136/// Copy onto `target_window_id` what a row takes from the row it replaces ([`REPLACED_KEYS`]).
137/// Returns the events to publish; empty when there is nothing to copy.
138pub(crate) async fn apply_replacement(
139    state: &AppState,
140    replaced_window_id: &str,
141    target_window_id: &str,
142) -> Vec<agentmux_common::ipc::Event> {
143    copy_keys(state, replaced_window_id, target_window_id, REPLACED_KEYS).await
144}
145
146async fn copy_keys(
147    state: &AppState,
148    source_window_id: &str,
149    target_window_id: &str,
150    keys: &[&str],
151) -> Vec<agentmux_common::ipc::Event> {
152    let store = &state.mstore;
153    let Some(patch) = store
154        .get::<Window>(source_window_id)
155        .ok()
156        .flatten()
157        .and_then(|w| patch_of(&w, keys))
158    else {
159        return Vec::new();
160    };
161    let evs = dispatch_to_reducer(
162        state,
163        agentmux_common::ipc::Command::UpdateWindowMeta {
164            window_id: target_window_id.to_string(),
165            meta_patch: patch,
166        },
167    )
168    .await;
169    for ev in &evs {
170        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, store) {
171            tracing::warn!(
172                window_id = %target_window_id,
173                error = %e,
174                "InheritWindowAppearance: meta write failed — window keeps the defaults"
175            );
176        }
177    }
178    evs
179}
180
181/// No args. Returns a mark to pass to `InheritWindowAppearance`; take it
182/// before opening the window.
183pub(crate) async fn handle_mark_window_open(_state: &AppState, _call: &WebCallType) -> WebReturnType {
184    WebReturnType::success(serde_json::json!(next_seq()))
185}
186
187/// Args: `sourceWindowId`, `hostLabel` (the new window's host label), `mark`
188/// (from `MarkWindowOpen`, taken before the window was opened).
189pub(crate) async fn handle_inherit_window_appearance(state: &AppState, call: &WebCallType) -> WebReturnType {
190    let args = &call.args;
191    let source_window_id: String = match service::get_arg(args, 0) {
192        Ok(v) => v,
193        Err(e) => return WebReturnType::error(e),
194    };
195    let label: String = match service::get_arg(args, 1) {
196        Ok(v) => v,
197        Err(e) => return WebReturnType::error(e),
198    };
199    let mark: u64 = match service::get_arg(args, 2) {
200        Ok(v) => v,
201        Err(e) => return WebReturnType::error(e),
202    };
203    if source_window_id.is_empty() || label.is_empty() {
204        return WebReturnType::error("InheritWindowAppearance: empty sourceWindowId or hostLabel".to_string());
205    }
206    record_pending(&label, &source_window_id, mark);
207    // The row may already exist (its renderer won the race). If so, and
208    // CreateWindow hasn't already taken the entry, apply it here.
209    let created = CREATED.lock().unwrap_or_else(|e| e.into_inner()).get(&label).cloned();
210    if let Some((target, row_seq, _)) = created {
211        if target != source_window_id {
212            if let Some(source) = take_pending(&label, row_seq) {
213                let evs = apply_inheritance(state, &source, &target).await;
214                publish_events(state, &evs);
215            }
216        }
217    }
218    WebReturnType::success_empty()
219}
220
221#[cfg(test)]
222mod tests {
223    use super::super::window::handle_window_service;
224    use crate::backend::obj::Window;
225    use crate::backend::service::WebCallType;
226    use crate::server::tests::test_state;
227
228    fn call(method: &str, args: Vec<serde_json::Value>) -> WebCallType {
229        WebCallType {
230            service: "window".to_string(),
231            method: method.to_string(),
232            uicontext: None,
233            args,
234        }
235    }
236
237    async fn create(state: &crate::server::AppState, label: &str) -> String {
238        let ret = handle_window_service(
239            state,
240            &call("CreateWindow", vec![serde_json::Value::Null, "".into(), label.into()]),
241        )
242        .await;
243        assert!(ret.success, "CreateWindow failed: {:?}", ret.error);
244        ret.data
245            .as_ref()
246            .and_then(|d| d.get("oid"))
247            .and_then(|v| v.as_str())
248            .expect("CreateWindow returns the Window with oid")
249            .to_string()
250    }
251
252    async fn set_meta(state: &crate::server::AppState, window_id: &str, patch: serde_json::Value) {
253        let evs = super::dispatch_to_reducer(
254            state,
255            agentmux_common::ipc::Command::UpdateWindowMeta {
256                window_id: window_id.to_string(),
257                meta_patch: patch,
258            },
259        )
260        .await;
261        for ev in &evs {
262            crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore).unwrap();
263        }
264    }
265
266    fn meta(state: &crate::server::AppState, window_id: &str, key: &str) -> Option<serde_json::Value> {
267        state.mstore.must_get::<Window>(window_id).unwrap().meta.get(key).cloned()
268    }
269
270    async fn mark(state: &crate::server::AppState) -> u64 {
271        let ret = handle_window_service(state, &call("MarkWindowOpen", vec![])).await;
272        assert!(ret.success, "MarkWindowOpen failed: {:?}", ret.error);
273        ret.data.and_then(|d| d.as_u64()).expect("MarkWindowOpen returns a number")
274    }
275
276    async fn inherit(state: &crate::server::AppState, source: &str, label: &str, mark: u64) {
277        let ret = handle_window_service(
278            state,
279            &call("InheritWindowAppearance", vec![source.into(), label.into(), mark.into()]),
280        )
281        .await;
282        assert!(ret.success, "InheritWindowAppearance failed: {:?}", ret.error);
283    }
284
285    /// The creator's call lands first: CreateWindow applies it as it makes the row.
286    #[tokio::test]
287    async fn inherits_when_the_creator_calls_before_the_window_exists() {
288        let state = test_state();
289        let source = create(&state, "inherit-src-a").await;
290        set_meta(&state, &source, serde_json::json!({ "window:theme": "dracula", "window:opacity": 0.7 })).await;
291
292        let m = mark(&state).await;
293        inherit(&state, &source, "inherit-new-a", m).await;
294        let new = create(&state, "inherit-new-a").await;
295
296        assert_eq!(meta(&state, &new, "window:theme"), Some("dracula".into()));
297        assert_eq!(meta(&state, &new, "window:opacity"), Some(serde_json::json!(0.7)));
298    }
299
300    /// The new window's row exists first: the creator's call applies it.
301    #[tokio::test]
302    async fn inherits_when_the_window_exists_before_the_creator_calls() {
303        let state = test_state();
304        let source = create(&state, "inherit-src-b").await;
305        set_meta(&state, &source, serde_json::json!({ "window:theme": "nord" })).await;
306
307        let m = mark(&state).await;
308        let new = create(&state, "inherit-new-b").await;
309        assert_eq!(meta(&state, &new, "window:theme"), None);
310        inherit(&state, &source, "inherit-new-b", m).await;
311
312        assert_eq!(meta(&state, &new, "window:theme"), Some("nord".into()));
313        // Keys the source doesn't set aren't written as nulls.
314        assert_eq!(meta(&state, &new, "window:opacity"), None);
315    }
316
317    /// A window opened with no inheritance pending keeps the defaults, and an
318    /// entry is used once: a later window with the same label gets nothing.
319    #[tokio::test]
320    async fn an_entry_is_used_once() {
321        let state = test_state();
322        let source = create(&state, "inherit-src-c").await;
323        set_meta(&state, &source, serde_json::json!({ "window:theme": "dracula" })).await;
324
325        let plain = create(&state, "inherit-new-c").await;
326        assert_eq!(meta(&state, &plain, "window:theme"), None);
327
328        let m = mark(&state).await;
329        inherit(&state, &source, "inherit-new-d", m).await;
330        let first = create(&state, "inherit-new-d").await;
331        let second = create(&state, "inherit-new-d").await;
332        assert_eq!(meta(&state, &first, "window:theme"), Some("dracula".into()));
333        assert_eq!(meta(&state, &second, "window:theme"), None);
334    }
335
336    /// A label reused at once (a pool window demoted and promoted again): the
337    /// earlier use's row, created moments before the mark, never takes the
338    /// entry; the row made after the mark does.
339    #[tokio::test]
340    async fn a_row_from_an_earlier_use_of_the_label_does_not_take_it() {
341        let state = test_state();
342        let source = create(&state, "inherit-src-f").await;
343        set_meta(&state, &source, serde_json::json!({ "window:theme": "nord" })).await;
344        let earlier = create(&state, "inherit-new-f").await;
345
346        let m = mark(&state).await;
347        inherit(&state, &source, "inherit-new-f", m).await;
348        assert_eq!(meta(&state, &earlier, "window:theme"), None);
349        let new = create(&state, "inherit-new-f").await;
350        assert_eq!(meta(&state, &new, "window:theme"), Some("nord".into()));
351    }
352
353    /// A reloaded window other than the main one gets a new row; passing the
354    /// row it had before (CreateWindow arg 6) brings its own theme and
355    /// opacity across.
356    #[tokio::test]
357    async fn a_reload_keeps_the_windows_own_appearance() {
358        let state = test_state();
359        let before = create(&state, "inherit-reload-a").await;
360        set_meta(&state, &before, serde_json::json!({ "window:theme": "nord", "window:opacity": 0.5 })).await;
361
362        let ret = handle_window_service(
363            &state,
364            &call(
365                "CreateWindow",
366                vec![
367                    serde_json::Value::Null,
368                    "".into(),
369                    "inherit-reload-a".into(),
370                    serde_json::Value::Null,
371                    serde_json::Value::Null,
372                    serde_json::Value::Null,
373                    before.clone().into(),
374                ],
375            ),
376        )
377        .await;
378        assert!(ret.success, "CreateWindow failed: {:?}", ret.error);
379        let after = ret.data.as_ref().and_then(|d| d.get("oid")).and_then(|v| v.as_str()).unwrap().to_string();
380        assert_ne!(after, before);
381        assert_eq!(meta(&state, &after, "window:theme"), Some("nord".into()));
382        assert_eq!(meta(&state, &after, "window:opacity"), Some(serde_json::json!(0.5)));
383    }
384
385    /// A source with no appearance of its own copies nothing.
386    #[tokio::test]
387    async fn a_default_source_copies_nothing() {
388        let state = test_state();
389        let source = create(&state, "inherit-src-e").await;
390        let m = mark(&state).await;
391        inherit(&state, &source, "inherit-new-e", m).await;
392        let new = create(&state, "inherit-new-e").await;
393        assert_eq!(meta(&state, &new, "window:theme"), None);
394        assert_eq!(meta(&state, &new, "window:opacity"), None);
395    }
396
397    #[tokio::test]
398    async fn rejects_empty_or_missing_args() {
399        let state = test_state();
400        let ret = handle_window_service(&state, &call("InheritWindowAppearance", vec!["".into(), "x".into(), 1.into()])).await;
401        assert!(!ret.success);
402        let ret = handle_window_service(&state, &call("InheritWindowAppearance", vec!["w".into(), "x".into()])).await;
403        assert!(!ret.success, "a request without a mark is refused");
404    }
405}