1use 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
36pub(crate) const INHERITED_KEYS: &[&str] = &["window:theme", "window:opacity"];
38
39pub(crate) const REPLACED_KEYS: &[&str] = &["window:theme", "window:opacity", "window:displayname"];
43
44const PENDING_TTL: Duration = Duration::from_secs(30);
47
48static SEQ: AtomicU64 = AtomicU64::new(1);
51
52struct Pending {
53 source_window_id: String,
54 after: u64,
56 at: Instant,
57}
58
59static PENDING: LazyLock<Mutex<HashMap<String, Pending>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
61
62static 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
70pub(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
80pub(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
105pub(crate) fn appearance_patch(source: &Window) -> Option<serde_json::Value> {
108 patch_of(source, INHERITED_KEYS)
109}
110
111fn 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
126pub(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
136pub(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
181pub(crate) async fn handle_mark_window_open(_state: &AppState, _call: &WebCallType) -> WebReturnType {
184 WebReturnType::success(serde_json::json!(next_seq()))
185}
186
187pub(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 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 #[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 #[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 assert_eq!(meta(&state, &new, "window:opacity"), None);
315 }
316
317 #[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 #[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 #[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 #[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}