1#![allow(dead_code)]
2use std::collections::HashMap;
15
16use serde::{Deserialize, Serialize};
17
18use super::obj;
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct WebCallType {
26 pub service: String,
27 pub method: String,
28 #[serde(default, skip_serializing_if = "Option::is_none")]
29 pub uicontext: Option<UIContext>,
30 #[serde(default)]
31 pub args: Vec<serde_json::Value>,
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct UIContext {
38 #[serde(default, rename = "activetabid")]
39 pub active_tab_id: String,
40 #[serde(flatten)]
41 pub extra: HashMap<String, serde_json::Value>,
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct WebReturnType {
48 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
49 pub success: bool,
50 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub error: Option<String>,
52 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub data: Option<serde_json::Value>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub updates: Option<Vec<obj::MuxObjUpdate>>,
56}
57
58impl WebReturnType {
59 pub fn success(data: serde_json::Value) -> Self {
61 Self {
62 success: true,
63 error: None,
64 data: Some(data),
65 updates: None,
66 }
67 }
68
69 pub fn success_empty() -> Self {
71 Self {
72 success: true,
73 error: None,
74 data: None,
75 updates: None,
76 }
77 }
78
79 pub fn success_with_updates(updates: Vec<obj::MuxObjUpdate>) -> Self {
81 Self {
82 success: true,
83 error: None,
84 data: None,
85 updates: if updates.is_empty() {
86 None
87 } else {
88 Some(updates)
89 },
90 }
91 }
92
93 pub fn success_data_updates(
95 data: serde_json::Value,
96 updates: Vec<obj::MuxObjUpdate>,
97 ) -> Self {
98 Self {
99 success: true,
100 error: None,
101 data: Some(data),
102 updates: if updates.is_empty() {
103 None
104 } else {
105 Some(updates)
106 },
107 }
108 }
109
110 pub fn error(msg: impl Into<String>) -> Self {
112 Self {
113 success: false,
114 error: Some(msg.into()),
115 data: None,
116 updates: None,
117 }
118 }
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct MethodMeta {
130 #[serde(default, skip_serializing_if = "Option::is_none")]
131 pub desc: Option<String>,
132 #[serde(default, skip_serializing_if = "Vec::is_empty")]
133 pub arg_names: Vec<String>,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub return_desc: Option<String>,
136}
137
138pub fn get_method_meta(service: &str, method: &str) -> Option<MethodMeta> {
140 match (service, method) {
141 ("block", "SendCommand") => Some(MethodMeta {
143 desc: Some("send command to block".into()),
144 arg_names: vec!["blockid".into(), "cmd".into()],
145 return_desc: None,
146 }),
147 ("block", "GetControllerStatus") => Some(MethodMeta {
148 desc: Some("get block controller status".into()),
149 arg_names: vec!["blockid".into()],
150 return_desc: None,
151 }),
152 ("block", "SaveTerminalState") => Some(MethodMeta {
153 desc: Some("save the terminal state to a blockfile".into()),
154 arg_names: vec![
155 "ctx".into(),
156 "blockId".into(),
157 "state".into(),
158 "stateType".into(),
159 "ptyOffset".into(),
160 "termSize".into(),
161 ],
162 return_desc: None,
163 }),
164
165 ("object", "GetObject") => Some(MethodMeta {
167 desc: Some("get wave object by oref".into()),
168 arg_names: vec!["oref".into()],
169 return_desc: None,
170 }),
171 ("object", "GetObjects") => Some(MethodMeta {
172 desc: Some("get multiple wave objects".into()),
173 arg_names: vec!["orefs".into()],
174 return_desc: Some("objects".into()),
175 }),
176 ("object", "UpdateTabName") => Some(MethodMeta {
177 desc: Some("update tab name".into()),
178 arg_names: vec!["uiContext".into(), "tabId".into(), "name".into()],
179 return_desc: None,
180 }),
181 ("object", "CreateBlock") => Some(MethodMeta {
182 desc: Some("create a new block".into()),
183 arg_names: vec![
193 "uiContext".into(),
194 "blockDef".into(),
195 "rtOpts".into(),
196 "tabId".into(),
197 ],
198 return_desc: Some("blockId".into()),
199 }),
200 ("object", "DeleteBlock") => Some(MethodMeta {
201 desc: Some("delete a block".into()),
202 arg_names: vec!["uiContext".into(), "blockId".into()],
203 return_desc: None,
204 }),
205 ("object", "QuitAgent") => Some(MethodMeta {
206 desc: Some("end an agent gracefully and close its own tab (/quit)".into()),
207 arg_names: vec!["uiContext".into(), "blockId".into()],
208 return_desc: Some("{status, agent, released_claims, stopped_shells, crons_targeting, survivors}".into()),
209 }),
210 ("object", "ShutdownAgent") => Some(MethodMeta {
211 desc: Some("shut an agent down from My agents or its pane's menu; the conversation is kept".into()),
212 arg_names: vec!["uiContext".into(), "blockId".into(), "stopBackground".into()],
213 return_desc: Some("{status, agent, released_claims, stopped_shells, crons_targeting, survivors}".into()),
214 }),
215 ("object", "ShutdownPreview") => Some(MethodMeta {
216 desc: Some("what shutting an agent down would end: a turn, claims, crons".into()),
217 arg_names: vec!["uiContext".into(), "blockId".into()],
218 return_desc: Some("{working, claims, crons_targeting}".into()),
219 }),
220 ("object", "ClosePane") => Some(MethodMeta {
221 desc: Some("close a pane: stop and delete every block in its stack".into()),
222 arg_names: vec!["uiContext".into(), "blockIds".into()],
223 return_desc: None,
224 }),
225 ("object", "UpdateObjectMeta") => Some(MethodMeta {
226 desc: Some("update object meta".into()),
227 arg_names: vec!["uiContext".into(), "oref".into(), "meta".into()],
228 return_desc: None,
229 }),
230 ("object", "ApplyLayoutIntent") => Some(MethodMeta {
231 desc: Some("apply a layout intent to a tab's layout (layout.applyIntent)".into()),
232 arg_names: vec!["tabId".into(), "intent".into(), "actionId".into()],
233 return_desc: Some("{applied, error, version}".into()),
234 }),
235 ("object", "UpdateObject") => Some(MethodMeta {
236 desc: Some("update a wave object".into()),
237 arg_names: vec!["uiContext".into(), "muxObj".into(), "returnUpdates".into()],
238 return_desc: None,
239 }),
240
241 ("client", "GetClientData") => Some(MethodMeta {
243 desc: Some("get client data".into()),
244 arg_names: vec![],
245 return_desc: None,
246 }),
247 ("client", "GetTab") => Some(MethodMeta {
248 desc: Some("get tab by ID".into()),
249 arg_names: vec!["tabId".into()],
250 return_desc: None,
251 }),
252 ("client", "GetAllConnStatus") => Some(MethodMeta {
253 desc: Some("get all connection statuses".into()),
254 arg_names: vec![],
255 return_desc: None,
256 }),
257 ("client", "FocusWindow") => Some(MethodMeta {
258 desc: Some("focus a window".into()),
259 arg_names: vec!["windowId".into()],
260 return_desc: None,
261 }),
262 ("client", "AgreeTos") => Some(MethodMeta {
263 desc: Some("agree to terms of service".into()),
264 arg_names: vec![],
265 return_desc: None,
266 }),
267 ("client", "TelemetryUpdate") => Some(MethodMeta {
268 desc: Some("update telemetry setting".into()),
269 arg_names: vec!["telemetryEnabled".into()],
270 return_desc: None,
271 }),
272
273 ("window", "GetWindow") => Some(MethodMeta {
275 desc: Some("get window by ID".into()),
276 arg_names: vec!["windowId".into()],
277 return_desc: None,
278 }),
279 ("window", "CreateWindow") => Some(MethodMeta {
280 desc: Some("create a new window".into()),
281 arg_names: vec!["ctx".into(), "winSize".into(), "workspaceId".into()],
282 return_desc: None,
283 }),
284 ("window", "SetWindowPosAndSize") => Some(MethodMeta {
285 desc: Some("set window position and size".into()),
286 arg_names: vec!["ctx".into(), "windowId".into(), "pos".into(), "size".into()],
287 return_desc: None,
288 }),
289 ("window", "SetWindowOpacity") => Some(MethodMeta {
290 desc: Some("set (or clear, via null) a window's persisted opacity".into()),
291 arg_names: vec!["ctx".into(), "windowId".into(), "opacity".into()],
292 return_desc: None,
293 }),
294 ("window", "MarkWindowOpen") => Some(MethodMeta {
295 desc: Some("a mark to take before opening a window that should inherit appearance".into()),
296 arg_names: vec![],
297 return_desc: Some("mark".into()),
298 }),
299 ("window", "InheritWindowAppearance") => Some(MethodMeta {
300 desc: Some("copy a window's theme and opacity onto the window opened after the mark with this host label".into()),
301 arg_names: vec!["sourceWindowId".into(), "hostLabel".into(), "mark".into()],
302 return_desc: None,
303 }),
304 ("window", "SetWindowTopology") => Some(MethodMeta {
305 desc: Some("set a window's persisted kind + parent_window_id".into()),
306 arg_names: vec!["ctx".into(), "windowId".into(), "kind".into(), "parentWindowId".into()],
307 return_desc: None,
308 }),
309 ("window", "MoveBlockToNewWindow") => Some(MethodMeta {
310 desc: Some("move block to new window".into()),
311 arg_names: vec!["ctx".into(), "currentTabId".into(), "blockId".into()],
312 return_desc: None,
313 }),
314 ("window", "SwitchWorkspace") => Some(MethodMeta {
315 desc: Some("switch workspace".into()),
316 arg_names: vec!["ctx".into(), "windowId".into(), "workspaceId".into()],
317 return_desc: None,
318 }),
319 ("window", "CloseWindow") => Some(MethodMeta {
320 desc: Some("close a window".into()),
321 arg_names: vec!["ctx".into(), "windowId".into(), "fromElectron".into()],
322 return_desc: None,
323 }),
324 ("window", "SaveSessionSnapshot") => Some(MethodMeta {
325 desc: Some("flush the session snapshot without tearing down (OS shutdown)".into()),
326 arg_names: vec![],
327 return_desc: None,
328 }),
329
330 ("workspace", "CreateWorkspace") => Some(MethodMeta {
332 desc: Some("create a new workspace".into()),
333 arg_names: vec![
334 "ctx".into(),
335 "name".into(),
336 ],
337 return_desc: Some("workspaceId".into()),
338 }),
339 ("workspace", "UpdateWorkspace") => Some(MethodMeta {
340 desc: Some("update workspace properties".into()),
341 arg_names: vec![
342 "ctx".into(),
343 "workspaceId".into(),
344 "name".into(),
345 ],
346 return_desc: None,
347 }),
348 ("workspace", "GetWorkspace") => Some(MethodMeta {
349 desc: Some("get workspace by ID".into()),
350 arg_names: vec!["workspaceId".into()],
351 return_desc: Some("workspace".into()),
352 }),
353 ("workspace", "DeleteWorkspace") => Some(MethodMeta {
354 desc: Some("delete a workspace".into()),
355 arg_names: vec!["workspaceId".into()],
356 return_desc: None,
357 }),
358 ("workspace", "ListWorkspaces") => Some(MethodMeta {
359 desc: Some("list all workspaces".into()),
360 arg_names: vec![],
361 return_desc: None,
362 }),
363 ("workspace", "CreateTab") => Some(MethodMeta {
364 desc: Some("create a new tab".into()),
365 arg_names: vec![
366 "workspaceId".into(),
367 "tabName".into(),
368 "activateTab".into(),
369 "pinned".into(),
370 ],
371 return_desc: Some("tabId".into()),
372 }),
373 ("workspace", "UpdateTabIds") => Some(MethodMeta {
374 desc: Some("update tab ordering".into()),
375 arg_names: vec![
376 "uiContext".into(),
377 "workspaceId".into(),
378 "tabIds".into(),
379 "pinnedTabIds".into(),
380 ],
381 return_desc: None,
382 }),
383 ("workspace", "SetActiveTab") => Some(MethodMeta {
384 desc: Some("set active tab".into()),
385 arg_names: vec!["workspaceId".into(), "tabId".into()],
386 return_desc: None,
387 }),
388 ("workspace", "CloseTab") => Some(MethodMeta {
389 desc: Some("close a tab".into()),
390 arg_names: vec![
391 "ctx".into(),
392 "workspaceId".into(),
393 "tabId".into(),
394 "fromElectron".into(),
395 ],
396 return_desc: Some("CloseTabRtn".into()),
397 }),
398
399 ("userinput", "SendUserInputResponse") => Some(MethodMeta {
401 desc: Some("send user input response".into()),
402 arg_names: vec!["response".into()],
403 return_desc: None,
404 }),
405
406 _ => None,
407 }
408}
409
410#[derive(Debug, Clone, Serialize, Deserialize)]
415pub struct CloseTabRtnType {
416 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
417 pub closewindow: bool,
418 #[serde(default, skip_serializing_if = "String::is_empty")]
419 pub newactivetabid: String,
420}
421
422pub const SERVICES: &[&str] = &[
424 "block",
425 "object",
426 "client",
427 "window",
428 "workspace",
429 "userinput",
430];
431
432pub fn is_valid_service(name: &str) -> bool {
434 SERVICES.contains(&name)
435}
436
437pub fn get_arg<T: serde::de::DeserializeOwned>(
439 args: &[serde_json::Value],
440 idx: usize,
441) -> Result<T, String> {
442 let val = args
443 .get(idx)
444 .ok_or_else(|| format!("missing argument at index {}", idx))?;
445 serde_json::from_value(val.clone()).map_err(|e| format!("invalid argument at index {}: {}", idx, e))
446}
447
448pub fn get_optional_arg<T: serde::de::DeserializeOwned>(
451 args: &[serde_json::Value],
452 idx: usize,
453) -> Result<Option<T>, String> {
454 match args.get(idx) {
455 None | Some(serde_json::Value::Null) => Ok(None),
456 Some(val) => serde_json::from_value(val.clone())
457 .map(Some)
458 .map_err(|e| format!("invalid argument at index {}: {}", idx, e)),
459 }
460}
461
462#[cfg(test)]
463mod tests {
464 use super::*;
465
466 #[test]
467 fn test_web_call_type_deserialize() {
468 let json = r#"{
469 "service": "object",
470 "method": "GetObject",
471 "args": ["block:abc123"]
472 }"#;
473 let call: WebCallType = serde_json::from_str(json).unwrap();
474 assert_eq!(call.service, "object");
475 assert_eq!(call.method, "GetObject");
476 assert_eq!(call.args.len(), 1);
477 assert!(call.uicontext.is_none());
478 }
479
480 #[test]
481 fn test_web_call_type_with_uicontext() {
482 let json = r#"{
483 "service": "object",
484 "method": "CreateBlock",
485 "uicontext": {"activetabid": "tab-123"},
486 "args": [{"view": "term"}, {}]
487 }"#;
488 let call: WebCallType = serde_json::from_str(json).unwrap();
489 assert_eq!(call.service, "object");
490 assert_eq!(call.method, "CreateBlock");
491 assert_eq!(call.uicontext.as_ref().unwrap().active_tab_id, "tab-123");
492 assert_eq!(call.args.len(), 2);
493 }
494
495 #[test]
496 fn test_web_return_type_success() {
497 let rtn = WebReturnType::success(serde_json::json!("hello"));
498 assert!(rtn.success);
499 assert!(rtn.error.is_none());
500 assert_eq!(rtn.data, Some(serde_json::json!("hello")));
501 }
502
503 #[test]
504 fn test_web_return_type_error() {
505 let rtn = WebReturnType::error("something went wrong");
506 assert!(!rtn.success);
507 assert_eq!(rtn.error.as_deref(), Some("something went wrong"));
508 assert!(rtn.data.is_none());
509 }
510
511 #[test]
512 fn test_web_return_type_success_empty() {
513 let rtn = WebReturnType::success_empty();
514 assert!(rtn.success);
515 assert!(rtn.data.is_none());
516 assert!(rtn.updates.is_none());
517 }
518
519 #[test]
520 fn test_web_return_type_with_updates() {
521 let updates = vec![obj::MuxObjUpdate {
522 updatetype: "update".into(),
523 otype: "tab".into(),
524 oid: "123".into(),
525 obj: None,
526 }];
527 let rtn = WebReturnType::success_with_updates(updates);
528 assert!(rtn.success);
529 assert_eq!(rtn.updates.as_ref().unwrap().len(), 1);
530 }
531
532 #[test]
533 fn test_web_return_type_empty_updates_omitted() {
534 let rtn = WebReturnType::success_with_updates(vec![]);
535 let json = serde_json::to_string(&rtn).unwrap();
536 assert!(!json.contains("updates"));
537 }
538
539 #[test]
540 fn test_web_return_type_serde_roundtrip() {
541 let rtn = WebReturnType::success_data_updates(
542 serde_json::json!({"id": "block-1"}),
543 vec![obj::MuxObjUpdate {
544 updatetype: "update".into(),
545 otype: "block".into(),
546 oid: "abc".into(),
547 obj: Some(serde_json::json!({"otype": "block"})),
548 }],
549 );
550 let json = serde_json::to_string(&rtn).unwrap();
551 let parsed: WebReturnType = serde_json::from_str(&json).unwrap();
552 assert!(parsed.success);
553 assert!(parsed.data.is_some());
554 assert_eq!(parsed.updates.as_ref().unwrap().len(), 1);
555 }
556
557 #[test]
558 fn test_close_tab_rtn_type() {
559 let rtn = CloseTabRtnType {
560 closewindow: true,
561 newactivetabid: String::new(),
562 };
563 let json = serde_json::to_string(&rtn).unwrap();
564 assert!(json.contains("closewindow"));
565 assert!(!json.contains("newactivetabid")); }
567
568 #[test]
569 fn test_method_meta_exists() {
570 assert!(get_method_meta("object", "GetObject").is_some());
571 assert!(get_method_meta("workspace", "CreateTab").is_some());
572 assert!(get_method_meta("block", "SaveTerminalState").is_some());
573 assert!(get_method_meta("nonexistent", "Foo").is_none());
574 }
575
576 #[test]
577 fn test_is_valid_service() {
578 assert!(is_valid_service("block"));
579 assert!(is_valid_service("object"));
580 assert!(is_valid_service("workspace"));
581 assert!(!is_valid_service("invalid"));
582 assert!(!is_valid_service(""));
583 }
584
585 #[test]
586 fn test_get_arg() {
587 let args = vec![
588 serde_json::json!("hello"),
589 serde_json::json!(42),
590 serde_json::json!(true),
591 ];
592 assert_eq!(get_arg::<String>(&args, 0).unwrap(), "hello");
593 assert_eq!(get_arg::<i64>(&args, 1).unwrap(), 42);
594 assert_eq!(get_arg::<bool>(&args, 2).unwrap(), true);
595 assert!(get_arg::<String>(&args, 5).is_err());
596 }
597
598 #[test]
599 fn test_get_optional_arg() {
600 let args = vec![
601 serde_json::json!("hello"),
602 serde_json::Value::Null,
603 ];
604 assert_eq!(
605 get_optional_arg::<String>(&args, 0).unwrap(),
606 Some("hello".to_string())
607 );
608 assert_eq!(get_optional_arg::<String>(&args, 1).unwrap(), None);
609 assert_eq!(get_optional_arg::<String>(&args, 5).unwrap(), None);
610 }
611
612 #[test]
613 fn test_ui_context_deserialize() {
614 let json = r#"{"activetabid": "tab-1", "extra_field": true}"#;
615 let ctx: UIContext = serde_json::from_str(json).unwrap();
616 assert_eq!(ctx.active_tab_id, "tab-1");
617 assert_eq!(ctx.extra.get("extra_field"), Some(&serde_json::json!(true)));
618 }
619
620 #[test]
621 fn test_web_call_no_args() {
622 let json = r#"{"service": "client", "method": "GetClientData"}"#;
623 let call: WebCallType = serde_json::from_str(json).unwrap();
624 assert_eq!(call.service, "client");
625 assert!(call.args.is_empty());
626 }
627}