Skip to main content

agentmux_srv/server/
editor_handlers.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4use 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
26// Per-process token written into scratch claim files. Stale claim files from a
27// previous process run have a different token and are ignored during reuse scans,
28// allowing crash-recovery (the scratch becomes reclaimable on restart).
29static 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
35/// The editor changes files only under the user's home folder (an allowlist).
36/// A WSL distro's file through `\\wsl.localhost` counts when it is under a
37/// distro user's home folder (`remote::wsl_fs::in_home`): the same rule, in
38/// the distro. Its `/mnt/<letter>` is a Windows drive and never counts here.
39fn 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
43/// A home folder itself, the user's or a distro user's: never renamed or deleted.
44fn 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/// Enumerate drives/mounts to surface as editor file-tree roots alongside
56/// $HOME (via the `geteditorroots` RPC). On **macOS** this returns nothing, so
57/// the file-tree's roots are limited to $HOME — `/`, `/Volumes`, and external
58/// mounts aren't offered as starting points (root scoping for the tree, not a
59/// sandbox; see the note at the macOS arm). On Linux/Windows it exposes the
60/// filesystem root + mounts.
61/// Spec: docs/specs/SPEC_EDITOR_FILE_TREE_2026-05-26.md (multi-root follow-up).
62/// Also the drives section of `fs.places` (fs_handlers.rs), so the editor
63/// tree and the Files pane offer the same roots.
64#[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// macOS: scope the editor file-tree ROOTS to the user's home. HOME is the sole
80// root from GetEditorRoots, so the tree doesn't offer `/`, `/Volumes`, or
81// external mounts as starting points (no nudging the user toward volumes they
82// didn't choose). NOTE: this is root scoping, not a sandbox — listeditordir /
83// readeditorfile still serve any absolute path the frontend sends, and a
84// symlink under HOME can resolve outside it; macOS TCC remains the actual gate
85// for protected locations.
86#[cfg(target_os = "macos")]
87pub(super) fn list_drives() -> Vec<EditorDrive> {
88    Vec::new()
89}
90
91// Linux (and any other non-Windows, non-macOS unix): filesystem root + mounts.
92#[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
111/// Prepend Global Memory, then `agent_block` (the agent's picked bundles,
112/// `format_agent_bundle_block`), into the `BUNDLE_SECTION_HEADING` section of
113/// a CLAUDE.md string, mirroring the injection done by
114/// `write_agent_config_files` in the `agent.open` RPC path.  If the file has
115/// no such section, a new one is inserted before `# Available Skills` (or at
116/// the end of the file).
117pub(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    // Inject after the `BUNDLE_SECTION_HEADING` line if it exists.
131    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        // No bundle section — insert one before `# Available Skills` or append.
138        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
158/// The user's home folder, or the command's own message when there is none.
159fn home_or(message: &str) -> Result<std::path::PathBuf, String> {
160    dirs::home_dir().ok_or_else(|| message.to_string())
161}
162
163/// Live-reload watching of editor files (spec: docs/specs/SPEC_EDITOR_LIVE_FILE_RELOAD_2026_07_18.md) and
164/// live-update watching of Media panes pointed at a directory (docs/specs/SPEC_MEDIA_PANE_2026_07_26.md). Both
165/// watchers always exist since the move onto the shared FsWatchPool
166/// (SPEC_SHARED_FS_WATCHER_FRAMEWORK_2026_08_07.md): a construction-time failure degrades into
167/// `FsWatchPool::health()`'s degraded_paths, so there's nothing to check here.
168fn register_watchers(engine: &Arc<WshRpcEngine>, state: &AppState) {
169    // watcheditorfile starts watching a (path, block_id) pair once a tab's content has loaded.
170    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    // unwatcheditorfile stops it, on tab close / pane dispose. The same Req type as `watcheditorfile`, on
179    // purpose (see `WatchEditorFileReq`): an unwatch that cannot name exactly what the watch named leaks a watcher.
180    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    // watchmediadir starts it for a directory target (a fixed single file has nothing new to watch for; it is
189    // re-fetched on demand); unwatchmediadir stops it when the target moves away, or on dispose.
190    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
208/// Reading, writing and listing for the editor pane, and the roots its file tree starts from.
209fn 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    // geteditorhome is the OS home directory, the editor file-tree's default root. The request is an `Option<_>`
233    // (see `EditorRootsReq`): it is what makes both encodings of "no argument" deserialize.
234    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    // geteditorroots is home plus (Linux/Windows) the filesystem root and mounts, rendered as sibling top-level
239    // roots. On macOS `list_drives` returns none, so the file tree is scoped to $HOME only.
240    // Spec: docs/specs/SPEC_EDITOR_FILE_TREE_2026-05-26.md (multi-root follow-up)
241    engine.register_typed("geteditorroots", |_req: Option<EditorRootsReq>, _ctx| async move {
242        let home = home_or("geteditorroots: cannot determine home directory")?;
243        // WSL distros after the drives, at their roots through the share.
244        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
253/// The file tree's context-menu mutations, each confined to the user's home folder.
254fn 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        // Only the window, proven by its host, gets an agent's keys; an agent writes only its own (agent_config_guard).
287        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    /// The picker launch path puts the agent's picked bundles after Global
300    /// Memory under `# Memory`, as `agent.open` does, and still adds them
301    /// when there is no Global Memory.
302    #[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    /// The editor's "only under your home folder" rule, in a WSL distro: under
341    /// a distro user's home, never its system folders or the Windows drives
342    /// mounted in it, and never a home folder itself. Windows only: elsewhere
343    /// such a path is an ordinary one (`wsl_fs::share_of`).
344    #[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    /// The four watchers record their types too, and `writeagentconfig` migrates
365    /// in the same slice as its own agent.ts stub -- so this file is finished:
366    /// it has no untyped registrations left at all.
367    ///
368    /// `watcheditorfile` and `unwatcheditorfile` share one request type on
369    /// purpose. They are not merely same-shaped: an unwatch that cannot name
370    /// exactly what the watch named leaks a watcher, so sharing makes a future
371    /// divergence a compile error instead. `watchmediadir` and
372    /// `unwatchmediadir` do NOT share, because the extension filter is
373    /// genuinely not part of the registration key.
374    #[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        // `writeagentconfig` migrated too, in the same slice as its agent.ts
399        // stub -- so editor_handlers.rs now has no untyped registrations at
400        // all, and this asserts the file is finished rather than that one
401        // command is still pending.
402        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    /// The five read commands record their request and response types too. With
408    /// the four watchers and `writeagentconfig` covered by the test above,
409    /// nothing in this file is left untyped.
410    #[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    /// `geteditorhome` and `geteditorroots` take no argument, and the two
438    /// encodings of that both reach the server -- the stub sends `{}`, a client
439    /// that omits `data` sends `null`. `Option<EditorRootsReq>` takes both;
440    /// a bare struct rejects the second and `()` rejects the first.
441    #[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    /// `readeditorfile`'s four encoding fields were typed `?:` by hand "for
472    /// back-compat; absent ⇒ treat as UTF-8", but the server has never omitted
473    /// them: `decode_file` returns all four unconditionally. Pin that, because
474    /// the generated type now says they are required and this is the only
475    /// thing that would notice if the handler started omitting one.
476    #[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    /// `DirEntry.size` / `.mtime` really are absent rather than zero: a
497    /// directory has no meaningful size, and `0` would be indistinguishable
498    /// from a real empty file. The generated TS says `size?: number`, and this
499    /// is the half of that claim the TS cannot check.
500    #[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    /// The seven file-tree mutation commands record their request and response
526    /// types.
527    ///
528    /// Each of them used to deserialize into a `struct Cmd` declared inside its
529    /// own closure, with the response built by an inline `json!({..})`. Neither
530    /// can be named, so neither could be generated from — which is exactly why
531    /// the frontend restated all fourteen shapes by hand. A command that falls
532    /// back to `register_handler` disappears from the registry rather than
533    /// being recorded wrong, and that absence is what this catches.
534    #[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    /// `recursive` is required on purpose, and this is the assertion that keeps
562    /// it that way.
563    ///
564    /// Adding `#[serde(default)]` would compile, pass every gate, and quietly
565    /// turn "a caller that forgot the field" into "delete a directory tree it
566    /// never asked to delete" — the generated TS would go from `recursive:
567    /// boolean` to still-required (ts-rs cannot express the default anyway), so
568    /// nothing downstream would flag it either. The destructive choice has to
569    /// stay explicit on the wire.
570    #[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        // Both explicit values still work, so this is about absence only.
582        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    /// `createscratchfile`'s two fields are genuinely optional — the stub
592    /// defaults its argument to `{}` — and they are `Option<T>` in Rust, so
593    /// ts-rs can say `display_name?: string` without the derive-a-narrower-type
594    /// dance the `serde(default)`-on-`String` fields elsewhere need.
595    #[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    /// reagent P1, PR #2322: `writeagentconfig` (this file) is the actual
612    /// "click Launch" path, distinct from `agent.open`'s
613    /// `write_agent_config_files` (agent_open.rs) which already had
614    /// stale-skill-file cleanup. This exercises the exact integration point
615    /// the handler uses -- `crate::backend::rpc_types::block::AgentConfigFile`
616    /// has a `path` field (not `filename`, unlike `agent_config::AgentConfigFile`)
617    /// -- to catch a field-name mismatch silently no-op'ing the cleanup, which
618    /// a test only calling `managed_skill_file_paths` with hand-built strings
619    /// would not catch.
620    #[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    /// End-to-end proof (real filesystem, no RPC engine needed) that the
645    /// three shared calls this handler makes -- compute managed paths,
646    /// clean up stale ones from a prior manifest, write the new manifest --
647    /// actually remove a stale skill artifact between two materializations,
648    /// using this handler's own `AgentConfigFile{path, content}` shape.
649    #[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        // "Launch 1": agent-skill format.
655        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        // "Launch 2": switched to prompt format -- same skill, different path.
673        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    /// docs/specs/REPORT_JEKT_SIGNING_KEY_INJECTION_GAP_2026_08_16.md: before
696    /// this fix, `WriteAgentConfig` (the actual "click Launch" path) never
697    /// injected jekt/LAN signing keys at all -- only `agent.open` did, a
698    /// path most normal launches don't go through. This exercises the exact
699    /// slug-extraction-then-injection sequence the real handler runs,
700    /// against the real `rpc_types::AgentConfigFile{path, content}` shape
701    /// a caller of this RPC sends (only
702    /// `AGENTMUX_AGENT_ID` set -- no jekt fields), the same
703    /// field-name-mismatch class of bug the test above this one guards
704    /// against for `managed_skill_file_paths`.
705    #[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        // The file holds references, not values: the keys are ensured in the store and not written.
745        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        // No WAN key on this path either (SPEC_WAN_JEKT_SIGNED_BY_SRV_2026_10_14.md):
748        // srv signs WAN jekts, and the key it uses is minted in wan.db here.
749        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;