1use std::sync::Arc;
5
6use crate::backend::rpc::engine::WshRpcEngine;
7use crate::backend::rpc_types::{COMMAND_WRITE_AGENT_CONFIG, CommandWriteAgentConfigData};
8use crate::backend::agent_config::BUNDLE_SECTION_HEADING;
9use crate::backend::base::expand_home_dir_safe;
10use crate::backend::rpc_types::{
11 CommandReadEditorFileData, CommandWriteEditorFileData, CreateEditorDirReq, CreateEditorFileReq,
12 CreateScratchFileReq, DeleteEditorFileReq, EditorDrive, EditorRootsReq, GetEditorHomeResult, GetEditorRootsResult,
13 ListEditorDirReq, MoveScratchFileReq, OpenInShellReq, UnwatchMediaDirReq, WatchEditorFileReq,
14 WatchMediaDirReq,
15};
16use crate::backend::storage::store::Store;
17
18use super::AppState;
19
20mod agent_config;
21mod file_io;
22mod scratch;
23#[cfg(test)]
24mod direct_tests;
25
26static SCRATCH_SESSION_TOKEN: std::sync::OnceLock<String> = std::sync::OnceLock::new();
30
31fn scratch_session_token() -> &'static str {
32 SCRATCH_SESSION_TOKEN.get_or_init(|| uuid::Uuid::new_v4().to_string())
33}
34
35fn editor_may_change(canonical: &std::path::Path, canonical_home: &std::path::Path) -> bool {
40 canonical.starts_with(canonical_home) || in_a_distro_home(canonical)
41}
42
43fn is_a_home(canonical: &std::path::Path, canonical_home: &std::path::Path) -> bool {
45 canonical == canonical_home
46 || crate::backend::remote::wsl_fs::share_of(canonical)
47 .is_some_and(|s| crate::backend::remote::wsl_fs::is_home(&s.linux))
48}
49
50fn in_a_distro_home(path: &std::path::Path) -> bool {
51 crate::backend::remote::wsl_fs::share_of(path)
52 .is_some_and(|s| crate::backend::remote::wsl_fs::in_home(&s.linux))
53}
54
55#[cfg(target_os = "windows")]
65pub(super) fn list_drives() -> Vec<EditorDrive> {
66 let mut drives = Vec::new();
67 for letter in b'A'..=b'Z' {
68 let path = format!("{}:\\", letter as char);
69 if std::path::Path::new(&path).exists() {
70 drives.push(EditorDrive {
71 name: format!("{}:", letter as char),
72 path,
73 });
74 }
75 }
76 drives
77}
78
79#[cfg(target_os = "macos")]
87pub(super) fn list_drives() -> Vec<EditorDrive> {
88 Vec::new()
89}
90
91#[cfg(all(not(target_os = "windows"), not(target_os = "macos")))]
93pub(super) fn list_drives() -> Vec<EditorDrive> {
94 let mut drives = vec![EditorDrive { name: "/".to_string(), path: "/".to_string() }];
95 for mount_dir in ["/mnt", "/media", "/Volumes"] {
96 if let Ok(entries) = std::fs::read_dir(mount_dir) {
97 for entry in entries.flatten() {
98 let path = entry.path();
99 if path.is_dir() {
100 drives.push(EditorDrive {
101 name: entry.file_name().to_string_lossy().to_string(),
102 path: path.to_string_lossy().to_string(),
103 });
104 }
105 }
106 }
107 }
108 drives
109}
110
111pub(crate) fn inject_global_bundles(claude_md: &str, id_store: &Arc<Store>, agent_mode: &str, agent_block: &str) -> String {
118 let bundles = crate::backend::operator_config_seed::global_bundles_for_agent(
119 id_store.bundle_list_global().unwrap_or_default(),
120 agent_mode,
121 );
122 let bundle_block = crate::backend::storage::join_startup_blocks(
123 &crate::backend::storage::format_global_bundle_block(&bundles),
124 agent_block,
125 );
126 if bundle_block.is_empty() {
127 return claude_md.to_string();
128 }
129
130 let heading_line = format!("\n{BUNDLE_SECTION_HEADING}\n");
132 if let Some(pos) = claude_md.find(&heading_line) {
133 let insert_at = pos + heading_line.len();
134 let (before, after) = claude_md.split_at(insert_at);
135 format!("{}{}\n\n---\n\n{}", before, bundle_block, after)
136 } else {
137 let anchor = "\n# Available Skills\n";
139 if let Some(pos) = claude_md.find(anchor) {
140 let (before, after) = claude_md.split_at(pos);
141 format!("{before}{heading_line}{bundle_block}{after}")
142 } else {
143 format!("{claude_md}{heading_line}{bundle_block}\n")
144 }
145 }
146}
147
148use crate::backend::fs_ops::remote as remote_fs;
149
150pub fn register_editor_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
151 register_watchers(engine, state);
152 register_file_io(engine, state);
153 register_tree_mutations(engine);
154 register_scratch(engine);
155 register_agent_config(engine, state);
156}
157
158fn home_or(message: &str) -> Result<std::path::PathBuf, String> {
160 dirs::home_dir().ok_or_else(|| message.to_string())
161}
162
163fn register_watchers(engine: &Arc<WshRpcEngine>, state: &AppState) {
169 let watcher = state.editor_file_watcher.clone();
171 engine.register_typed("watcheditorfile", move |cmd: WatchEditorFileReq, _ctx| {
172 let watcher = watcher.clone();
173 async move {
174 watcher.watch_path(expand_home_dir_safe(&cmd.path).as_path(), &cmd.block_id);
175 Ok(())
176 }
177 });
178 let watcher = state.editor_file_watcher.clone();
181 engine.register_typed("unwatcheditorfile", move |cmd: WatchEditorFileReq, _ctx| {
182 let watcher = watcher.clone();
183 async move {
184 watcher.unwatch_path(expand_home_dir_safe(&cmd.path).as_path(), &cmd.block_id);
185 Ok(())
186 }
187 });
188 let watcher = state.media_file_watcher.clone();
191 engine.register_typed("watchmediadir", move |cmd: WatchMediaDirReq, _ctx| {
192 let watcher = watcher.clone();
193 async move {
194 watcher.watch_directory(expand_home_dir_safe(&cmd.path).as_path(), &cmd.block_id, &cmd.extensions);
195 Ok(())
196 }
197 });
198 let watcher = state.media_file_watcher.clone();
199 engine.register_typed("unwatchmediadir", move |cmd: UnwatchMediaDirReq, _ctx| {
200 let watcher = watcher.clone();
201 async move {
202 watcher.unwatch_directory(expand_home_dir_safe(&cmd.path).as_path(), &cmd.block_id);
203 Ok(())
204 }
205 });
206}
207
208fn register_file_io(engine: &Arc<WshRpcEngine>, state: &AppState) {
210 let auth_key = state.auth_key.clone();
211 engine.register_typed("readeditorfile", move |cmd: CommandReadEditorFileData, _ctx| {
212 let auth_key = auth_key.clone();
213 async move {
214 match remote_fs::ssh_connection(cmd.connection.as_deref()) {
215 Some(conn) => file_io::read_remote_file(conn, &cmd, &auth_key).await,
216 None => file_io::read_local_file(&cmd.path),
217 }
218 }
219 });
220 let auth_key = state.auth_key.clone();
221 engine.register_typed("writeeditorfile", move |cmd: CommandWriteEditorFileData, _ctx| {
222 let auth_key = auth_key.clone();
223 async move {
224 file_io::check_write_size(&cmd)?;
225 match remote_fs::ssh_connection(cmd.connection.as_deref()) {
226 Some(conn) => file_io::write_remote_file(conn, &cmd, &auth_key).await,
227 None => file_io::write_local_file(&home_or("writeeditorfile: cannot determine home directory")?, &cmd),
228 }
229 }
230 });
231 engine.register_typed("listeditordir", |cmd: ListEditorDirReq, _ctx| async move { file_io::list_dir(&cmd) });
232 engine.register_typed("geteditorhome", |_req: Option<EditorRootsReq>, _ctx| async move {
235 let home = home_or("geteditorhome: cannot determine home directory")?;
236 Ok(GetEditorHomeResult { home: home.to_string_lossy().into_owned() })
237 });
238 engine.register_typed("geteditorroots", |_req: Option<EditorRootsReq>, _ctx| async move {
242 let home = home_or("geteditorroots: cannot determine home directory")?;
243 let mut drives = list_drives();
245 drives.extend(crate::backend::remote::wsl::list_cached().await.into_iter().map(|d| EditorDrive {
246 path: crate::backend::remote::wsl_fs::share_path(&d, "/"),
247 name: format!("{d} (WSL)"),
248 }));
249 Ok(GetEditorRootsResult { home: home.to_string_lossy().into_owned(), drives })
250 });
251}
252
253fn register_tree_mutations(engine: &Arc<WshRpcEngine>) {
255 engine.register_typed("openinshell", |cmd: OpenInShellReq, _ctx| async move {
256 file_io::reveal_in_shell(&home_or("openinshell: cannot determine home directory")?, &cmd)
257 });
258 engine.register_typed("createeditorfile", |cmd: CreateEditorFileReq, _ctx| async move {
259 file_io::create_file(&home_or("createeditorfile: cannot determine home")?, &cmd)
260 });
261 engine.register_typed("createeditordir", |cmd: CreateEditorDirReq, _ctx| async move {
262 file_io::create_dir(&home_or("createeditordir: cannot determine home")?, &cmd)
263 });
264 engine.register_typed("deleteeditorfile", |cmd: DeleteEditorFileReq, _ctx| async move {
265 file_io::delete_file(&home_or("deleteeditorfile: cannot determine home")?, &cmd)
266 });
267}
268
269fn register_scratch(engine: &Arc<WshRpcEngine>) {
270 engine.register_typed("createscratchfile", |cmd: CreateScratchFileReq, _ctx| async move {
271 scratch::create_scratch_file(&home_or("createscratchfile: cannot determine home directory")?, cmd)
272 });
273 engine.register_typed("movescratchfile", |cmd: MoveScratchFileReq, _ctx| async move {
274 scratch::move_scratch_file(&home_or("movescratchfile: cannot determine home")?, &cmd)
275 });
276}
277
278fn register_agent_config(engine: &Arc<WshRpcEngine>, state: &AppState) {
279 let stores = Arc::new(agent_config::ConfigStores {
280 id_store: state.id_store.clone(),
281 mstore: state.mstore.clone(),
282 identity_store: state.identity_store.clone(),
283 });
284 engine.register_typed(COMMAND_WRITE_AGENT_CONFIG, move |cmd: CommandWriteAgentConfigData, ctx| {
285 let stores = stores.clone();
286 let hands_out_keys = ctx.operator_only("only the AgentMux window writes an agent's signing keys").is_ok();
288 async move { agent_config::write_agent_config(&stores, &ctx, hands_out_keys, cmd) }
289 });
290}
291
292#[cfg(test)]
293mod tests {
294 use crate::backend::rpc_types::AgentConfigFile;
295 use crate::backend::rpc_types::{
296 CommandReadEditorFileResult, CreateScratchFileReq, DeleteEditorFileReq, DirEntry,
297 };
298
299 #[test]
303 fn the_startup_file_gets_global_memory_then_the_picked_bundles() {
304 use crate::backend::storage::store::{Bundle, Store};
305 let id_store = std::sync::Arc::new(Store::open_in_memory().unwrap());
306 let file = "# Agent\n\n# Memory\nown notes\n";
307 let picks = "# [Bundle] Writer\n\nwrite plainly";
308
309 let only_picks = super::inject_global_bundles(file, &id_store, "host", picks);
310 assert_eq!(only_picks, "# Agent\n\n# Memory\n# [Bundle] Writer\n\nwrite plainly\n\n---\n\nown notes\n");
311
312 id_store
313 .bundle_upsert(&Bundle {
314 id: "g1".into(),
315 name: "Rules".into(),
316 description: String::new(),
317 is_blank: false,
318 is_global: true,
319 provider: String::new(),
320 model: String::new(),
321 instructions: "global rule".into(),
322 instructions_by_provider: "{}".into(),
323 context_files: "[]".into(),
324 mcp_servers: "[]".into(),
325 skills: "[]".into(),
326 sort_order: 0,
327 created_at: 0,
328 updated_at: 0,
329 is_system: false,
330 })
331 .unwrap();
332 let both = super::inject_global_bundles(file, &id_store, "host", picks);
333 let global = both.find("# [Workspace] Rules").unwrap();
334 let writer = both.find("# [Bundle] Writer").unwrap();
335 let own = both.find("own notes").unwrap();
336 assert!(global < writer && writer < own, "{both}");
337 assert_eq!(super::inject_global_bundles(file, &id_store, "host", ""), both.replace("\n\n---\n\n# [Bundle] Writer\n\nwrite plainly", ""));
338 }
339
340 #[cfg(windows)]
345 #[test]
346 fn the_editor_may_change_files_under_a_distro_home_and_nowhere_else_in_it() {
347 use std::path::Path;
348 let home = Path::new(r"C:\Users\me");
349 let may = |p: &str| super::editor_may_change(Path::new(p), home);
350 assert!(may(r"\\?\UNC\wsl.localhost\Ubuntu\home\u\proj\main.rs"));
351 assert!(may(r"\\wsl.localhost\Ubuntu\root\notes.md"));
352 assert!(may(r"\\wsl.localhost\Ubuntu\home\u"), "a parent for a new file");
353 assert!(!may(r"\\wsl.localhost\Ubuntu\etc\passwd"));
354 assert!(!may(r"\\wsl.localhost\Ubuntu\srv\app\x"));
355 assert!(
356 !may(r"\\wsl.localhost\Ubuntu\mnt\c\Windows\x"),
357 "a Windows drive through the distro is not a way around the home rule"
358 );
359 assert!(super::is_a_home(Path::new(r"\\wsl.localhost\Ubuntu\home\u"), home));
360 assert!(super::is_a_home(Path::new(r"\\wsl.localhost\Ubuntu\root"), home));
361 assert!(!super::is_a_home(Path::new(r"\\wsl.localhost\Ubuntu\home\u\x"), home));
362 }
363
364 #[tokio::test]
375 async fn register_typed_records_the_four_watchers() {
376 let state = crate::server::tests::test_state();
377 let (engine, _rx) = crate::backend::rpc::engine::WshRpcEngine::new();
378 super::register_editor_handlers(&engine, &state);
379 let schema = engine.schema_json();
380 let rows = schema.as_array().unwrap();
381 let find = |cmd: &str| {
382 rows.iter()
383 .find(|r| r["command"] == cmd)
384 .unwrap_or_else(|| panic!("{cmd} missing from the schema"))
385 };
386
387 for (cmd, req) in [
388 ("watcheditorfile", "WatchEditorFileReq"),
389 ("unwatcheditorfile", "WatchEditorFileReq"),
390 ("watchmediadir", "WatchMediaDirReq"),
391 ("unwatchmediadir", "UnwatchMediaDirReq"),
392 ] {
393 let row = find(cmd);
394 assert_eq!(row["requestName"], req, "{cmd} request");
395 assert_eq!(row["responseName"], "()", "{cmd} answers nothing");
396 }
397
398 let wac = find(crate::backend::rpc_types::COMMAND_WRITE_AGENT_CONFIG);
403 assert_eq!(wac["requestName"], "CommandWriteAgentConfigData");
404 assert_eq!(wac["responseName"], "CommandWriteAgentConfigResult");
405 }
406
407 #[tokio::test]
411 async fn register_typed_records_the_editor_read_commands() {
412 let state = crate::server::tests::test_state();
413 let (engine, _rx) = crate::backend::rpc::engine::WshRpcEngine::new();
414 super::register_editor_handlers(&engine, &state);
415 let schema = engine.schema_json();
416 let rows = schema.as_array().unwrap();
417 let find = |cmd: &str| {
418 rows.iter()
419 .find(|r| r["command"] == cmd)
420 .unwrap_or_else(|| panic!("{cmd} missing from the schema"))
421 };
422
423 for (cmd, resp) in [
424 ("readeditorfile", "CommandReadEditorFileResult"),
425 ("writeeditorfile", "()"),
426 ("listeditordir", "ListEditorDirResult"),
427 ("geteditorhome", "GetEditorHomeResult"),
428 ("geteditorroots", "GetEditorRootsResult"),
429 ] {
430 assert_eq!(find(cmd)["responseName"], resp, "{cmd} response");
431 }
432 assert_eq!(find("readeditorfile")["requestName"], "CommandReadEditorFileData");
433 assert_eq!(find("writeeditorfile")["requestName"], "CommandWriteEditorFileData");
434 assert_eq!(find("listeditordir")["requestName"], "ListEditorDirReq");
435 }
436
437 #[tokio::test]
442 async fn the_no_argument_read_commands_accept_both_encodings() {
443 let state = crate::server::tests::test_state();
444 let (engine, mut rx) = crate::backend::rpc::engine::WshRpcEngine::new();
445 super::register_editor_handlers(&engine, &state);
446
447 for cmd in ["geteditorhome", "geteditorroots"] {
448 for (i, payload) in [serde_json::json!({}), serde_json::Value::Null]
449 .into_iter()
450 .enumerate()
451 {
452 engine.handle_message(crate::backend::rpc_types::RpcMessage {
453 command: cmd.to_string(),
454 reqid: format!("{cmd}-{i}"),
455 data: Some(payload.clone()),
456 ..Default::default()
457 });
458 let resp = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
459 .await
460 .unwrap()
461 .unwrap();
462 assert!(
463 resp.error.is_empty(),
464 "{cmd} should accept {payload}, got error: {}",
465 resp.error,
466 );
467 }
468 }
469 }
470
471 #[test]
477 fn readeditorfile_always_reports_the_encoding_fields() {
478 let decoded = crate::backend::text_encoding::decode_file(b"hello");
479 let v = serde_json::to_value(CommandReadEditorFileResult {
480 content: decoded.content,
481 encoding: decoded.encoding,
482 bom: decoded.bom.to_string(),
483 line_ending: decoded.line_ending.to_string(),
484 had_decode_errors: decoded.had_decode_errors,
485 read_only: false,
486 })
487 .unwrap();
488 for key in ["content", "encoding", "bom", "line_ending", "had_decode_errors", "read_only"] {
489 assert!(v.get(key).is_some(), "{key} must always be present, got {v}");
490 }
491 assert_eq!(v["encoding"], "UTF-8");
492 assert_eq!(v["bom"], "none");
493 assert_eq!(v["line_ending"], "lf");
494 }
495
496 #[test]
501 fn a_directory_entry_omits_size_rather_than_sending_zero() {
502 let dir = DirEntry {
503 name: "src".to_string(),
504 is_dir: true,
505 is_symlink: false,
506 size: None,
507 mtime: None,
508 };
509 let v = serde_json::to_value(&dir).unwrap();
510 assert!(v.get("size").is_none(), "expected size omitted, got {v}");
511 assert!(v.get("mtime").is_none(), "expected mtime omitted, got {v}");
512
513 let file = DirEntry {
514 name: "main.rs".to_string(),
515 is_dir: false,
516 is_symlink: false,
517 size: Some(0),
518 mtime: Some(1_700_000_000_000),
519 };
520 let v = serde_json::to_value(&file).unwrap();
521 assert_eq!(v["size"], 0, "a real empty file still reports its size");
522 assert_eq!(v["mtime"], 1_700_000_000_000u64);
523 }
524
525 #[tokio::test]
535 async fn register_typed_records_the_editor_mutation_commands() {
536 let state = crate::server::tests::test_state();
537 let (engine, _rx) = crate::backend::rpc::engine::WshRpcEngine::new();
538 super::register_editor_handlers(&engine, &state);
539 let schema = engine.schema_json();
540 let rows = schema.as_array().unwrap();
541 let find = |cmd: &str| {
542 rows.iter()
543 .find(|r| r["command"] == cmd)
544 .unwrap_or_else(|| panic!("{cmd} missing from the schema — did it fall back to register_handler?"))
545 };
546
547 for (cmd, req, resp) in [
548 ("openinshell", "OpenInShellReq", "()"),
549 ("createeditorfile", "CreateEditorFileReq", "CreateEditorFileResult"),
550 ("createeditordir", "CreateEditorDirReq", "CreateEditorDirResult"),
551 ("deleteeditorfile", "DeleteEditorFileReq", "()"),
552 ("createscratchfile", "CreateScratchFileReq", "CreateScratchFileResult"),
553 ("movescratchfile", "MoveScratchFileReq", "MoveScratchFileResult"),
554 ] {
555 let row = find(cmd);
556 assert_eq!(row["requestName"], req, "{cmd} request");
557 assert_eq!(row["responseName"], resp, "{cmd} response");
558 }
559 }
560
561 #[test]
571 fn deleteeditorfile_will_not_deserialize_without_recursive() {
572 let err = serde_json::from_value::<DeleteEditorFileReq>(
573 serde_json::json!({ "path": "/home/u/x" }),
574 )
575 .expect_err("recursive must not be defaultable");
576 assert!(
577 err.to_string().contains("recursive"),
578 "expected the error to name the field, got {err}",
579 );
580
581 for recursive in [true, false] {
583 let req: DeleteEditorFileReq = serde_json::from_value(
584 serde_json::json!({ "path": "/home/u/x", "recursive": recursive }),
585 )
586 .unwrap();
587 assert_eq!(req.recursive, recursive);
588 }
589 }
590
591 #[test]
596 fn createscratchfile_accepts_an_empty_request() {
597 let req: CreateScratchFileReq = serde_json::from_value(serde_json::json!({}))
598 .expect("both fields are optional");
599 assert!(req.display_name.is_none());
600 assert!(req.exclude_scratch_ids.is_none());
601
602 let full: CreateScratchFileReq = serde_json::from_value(serde_json::json!({
603 "display_name": "Notes",
604 "exclude_scratch_ids": ["a", "b"],
605 }))
606 .unwrap();
607 assert_eq!(full.display_name.as_deref(), Some("Notes"));
608 assert_eq!(full.exclude_scratch_ids.unwrap().len(), 2);
609 }
610
611 #[test]
621 fn writeagentconfig_files_produce_the_expected_managed_skill_paths() {
622 let files = vec![
623 AgentConfigFile { path: "CLAUDE.md".to_string(), content: "soul".to_string() },
624 AgentConfigFile {
625 path: ".claude/commands/deploy.md".to_string(),
626 content: "deploy".to_string(),
627 },
628 AgentConfigFile {
629 path: ".claude/skills/review/SKILL.md".to_string(),
630 content: "review".to_string(),
631 },
632 AgentConfigFile { path: ".mcp.json".to_string(), content: "{}".to_string() },
633 ];
634 let managed = crate::backend::agent_config::managed_skill_file_paths(
635 files.iter().map(|f| f.path.as_str()),
636 );
637 assert_eq!(managed.len(), 2, "expected exactly the two skill-derived paths: {managed:?}");
638 assert!(managed.contains(".claude/commands/deploy.md"));
639 assert!(managed.contains(".claude/skills/review/SKILL.md"));
640 assert!(!managed.contains("CLAUDE.md"));
641 assert!(!managed.contains(".mcp.json"));
642 }
643
644 #[test]
650 fn stale_skill_file_is_removed_across_two_materializations() {
651 let work_dir = tempfile::tempdir().unwrap();
652 let base_path = work_dir.path();
653
654 let launch1 = vec![AgentConfigFile {
656 path: ".claude/skills/deploy/SKILL.md".to_string(),
657 content: "body".to_string(),
658 }];
659 let managed1 = crate::backend::agent_config::managed_skill_file_paths(
660 launch1.iter().map(|f| f.path.as_str()),
661 );
662 crate::backend::agent_config::cleanup_stale_managed_skill_files(base_path, &managed1);
663 for f in &launch1 {
664 let p = base_path.join(&f.path);
665 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
666 std::fs::write(&p, &f.content).unwrap();
667 }
668 crate::backend::agent_config::write_managed_skill_file_manifest(base_path, &managed1);
669 let skill_md = base_path.join(".claude/skills/deploy/SKILL.md");
670 assert!(skill_md.exists());
671
672 let launch2 = vec![AgentConfigFile {
674 path: ".claude/commands/deploy.md".to_string(),
675 content: "body".to_string(),
676 }];
677 let managed2 = crate::backend::agent_config::managed_skill_file_paths(
678 launch2.iter().map(|f| f.path.as_str()),
679 );
680 crate::backend::agent_config::cleanup_stale_managed_skill_files(base_path, &managed2);
681 for f in &launch2 {
682 let p = base_path.join(&f.path);
683 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
684 std::fs::write(&p, &f.content).unwrap();
685 }
686 crate::backend::agent_config::write_managed_skill_file_manifest(base_path, &managed2);
687
688 assert!(
689 !skill_md.exists(),
690 "stale .claude/skills/deploy/SKILL.md must be removed by the writeagentconfig path too"
691 );
692 assert!(base_path.join(".claude/commands/deploy.md").exists());
693 }
694
695 #[test]
706 fn writeagentconfig_extracts_slug_and_injects_signing_keys_into_the_real_mcp_json_shape() {
707 let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
708 let (_wan_dir, wan) = crate::backend::storage::wan_identity::attach_temp_wan_identity(&store);
709 let files = vec![AgentConfigFile {
710 path: ".mcp.json".to_string(),
711 content: serde_json::to_string(&serde_json::json!({
712 "mcpServers": {
713 "agentmux": {
714 "type": "stdio",
715 "command": "agentmux-mcp",
716 "args": [],
717 "env": { "AGENTMUX_AGENT_ID": "aria" }
718 }
719 }
720 }))
721 .unwrap(),
722 }];
723
724 let pos = files.iter().position(|f| f.path == ".mcp.json").unwrap();
725 let agent_slug = serde_json::from_str::<serde_json::Value>(&files[pos].content)
726 .ok()
727 .and_then(|v| {
728 v.pointer("/mcpServers/agentmux/env/AGENTMUX_AGENT_ID")
729 .and_then(|s| s.as_str())
730 .map(str::to_string)
731 })
732 .expect("must extract the agent slug from the real .mcp.json shape");
733 assert_eq!(agent_slug, "aria");
734
735 let rewritten = crate::backend::agent_config::inject_jekt_signing_keys_into_mcp_json(
736 &files[pos].content,
737 &store,
738 &agent_slug,
739 )
740 .expect("keys must ensure successfully against a fresh in-memory store");
741 let parsed: serde_json::Value = serde_json::from_str(&rewritten).unwrap();
742 let env = &parsed["mcpServers"]["agentmux"]["env"];
743 assert_eq!(env["AGENTMUX_AGENT_ID"], "aria");
744 assert!(env.get("AGENTMUX_JEKT_KEY").is_none() && env.get("AGENTMUX_LAN_KEY").is_none());
746 assert!(store.agent_jekt_key_load("aria").unwrap().is_some() && store.agent_lan_key_load("aria").unwrap().is_some());
747 assert!(env.get("AGENTMUX_WAN_KEY").is_none());
750 assert!(env.get("AGENTMUX_HOST_LABEL").is_none());
751 assert!(wan.agent_key_load("aria").unwrap().is_some());
752
753 }
754}
755
756#[cfg(test)]
757#[path = "editor_handlers_keys_tests.rs"]
758mod write_agent_config_keys_tests;