Skip to main content

sapphire_framework_server/
fs_methods.rs

1//! The `fs.*` and `journal.*` methods: the current workspace's files for an explorer, with
2//! moves, renames, new folders and trashing as undoable batches
3//! (`docs/superpowers/specs/2026-11-13-workspace-explorer-design.md`).
4//!
5//! The engine is corundum-framework-fs's [`FsService`]; this module only keeps one for the
6//! current workspace, says who calls, and tells sync about a change.
7
8use std::path::PathBuf;
9use std::sync::{Arc, Mutex};
10
11use corundum_framework_fs::api::{
12    ApplyParams, FS_APPLY, FS_LIST, FS_READ, FS_STAT, FS_VERSION, JOURNAL_HISTORY, JOURNAL_REDO,
13    JOURNAL_STATUS, JOURNAL_UNDO, JOURNAL_UNDO_BATCH,
14};
15use corundum_framework_fs::journal::Actor;
16use corundum_framework_fs::{FsService, Workspace, WorkspaceApp};
17use sapphire_ipc::{RequestCtx, Router, RpcError};
18use serde_json::Value;
19
20use crate::current::Current;
21use crate::error::Error;
22use crate::handlers::{rpc_error, scanned};
23
24/// The folder at the workspace's root that `fs.trash` keeps the trash in.
25///
26/// Not `.<app>`: the sync filter syncs `.<app>/` and no other dot-name, so the trash stays
27/// on this device. To the other devices a trashed entry is deleted, and an undo makes it
28/// again.
29pub const OWN_FOLDER: &str = ".sapphire-local";
30
31/// The principal of every IPC client: they are all the person signed in on this device.
32pub const LOCAL_PRINCIPAL: &str = "local";
33
34/// The `ClientInfo::kind` of the MCP server's connection (`sapphire_framework_mcp::CLIENT_KIND`),
35/// whose changes an agent makes.
36const MCP_CLIENT_KIND: &str = "mcp";
37
38/// Every method this module answers.
39pub const METHODS: [&str; 10] = [
40    FS_VERSION,
41    FS_LIST,
42    FS_STAT,
43    FS_READ,
44    FS_APPLY,
45    JOURNAL_UNDO,
46    JOURNAL_REDO,
47    JOURNAL_UNDO_BATCH,
48    JOURNAL_HISTORY,
49    JOURNAL_STATUS,
50];
51
52/// sapphire's side of the engine: no managed files, every dot-name hidden (corundum's
53/// defaults), and the trash in [`OWN_FOLDER`].
54#[derive(Debug, Clone, Copy, Default)]
55pub struct SapphireApp;
56
57impl WorkspaceApp for SapphireApp {
58    fn own_folder(&self) -> &str {
59        OWN_FOLDER
60    }
61}
62
63/// Who a connection is, to the journal.
64pub fn actor_for(client_kind: &str) -> Actor {
65    Actor {
66        principal: LOCAL_PRINCIPAL.to_owned(),
67        agent: client_kind == MCP_CLIENT_KIND,
68    }
69}
70
71/// The service of one workspace root, made again when the current root changes: a switch
72/// starts an empty history, as a restart does.
73struct Services {
74    current: Arc<Current>,
75    served: Mutex<Option<(PathBuf, FsService<SapphireApp>)>>,
76}
77
78impl Services {
79    /// The current root and its service.
80    fn get(&self) -> Result<(PathBuf, FsService<SapphireApp>), RpcError> {
81        let root = self
82            .current
83            .root()
84            .ok_or_else(|| rpc_error(&Error::NoWorkspace))?;
85        let mut served = self.served.lock().unwrap_or_else(|e| e.into_inner());
86        if let Some((at, service)) = served.as_ref()
87            && *at == root
88        {
89            return Ok((root, service.clone()));
90        }
91        let ws = Workspace::open(&root).map_err(fs_error)?;
92        let service = FsService::new(ws, SapphireApp);
93        *served = Some((root.clone(), service.clone()));
94        Ok((root, service))
95    }
96}
97
98/// An engine error as the JSON-RPC error a client of `fs-api` expects: its code from
99/// `fs_api::codes`, its message.
100fn fs_error(err: corundum_framework_fs::FsError) -> RpcError {
101    RpcError {
102        code: err.code(),
103        message: err.to_string(),
104        data: None,
105    }
106}
107
108/// Whether `method` with `params` may have changed the workspace.
109fn changes(method: &str, params: &Value) -> bool {
110    match method {
111        FS_APPLY => serde_json::from_value::<ApplyParams>(params.clone())
112            .map(|p| !p.dry_run)
113            .unwrap_or(false),
114        JOURNAL_UNDO | JOURNAL_REDO | JOURNAL_UNDO_BATCH => true,
115        _ => false,
116    }
117}
118
119/// Add the `fs.*` and `journal.*` methods, on `current`'s workspace, to `router`.
120pub(crate) fn fs_methods(current: Arc<Current>, router: Router) -> Router {
121    let services = Arc::new(Services {
122        current,
123        served: Mutex::new(None),
124    });
125    METHODS.iter().fold(router, |router, &method| {
126        let services = Arc::clone(&services);
127        router.method(method, move |ctx: RequestCtx| {
128            let services = Arc::clone(&services);
129            async move {
130                let actor = actor_for(&ctx.peer.client().kind);
131                let (root, service) = services.get()?;
132                let changed = changes(method, &ctx.params);
133                let result = service
134                    .dispatch(method, ctx.params, &actor)
135                    .await
136                    .map_err(fs_error);
137                // A refused undo changed nothing, but a batch whose every operation was
138                // skipped is still a success: scan after any answer that is not an error.
139                if changed && result.is_ok() {
140                    scanned(services.current.sync(), &root, method).await;
141                }
142                result
143            }
144        })
145    })
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[test]
153    fn the_mcp_client_is_an_agent_and_the_rest_are_the_person() {
154        assert_eq!(
155            actor_for("mcp"),
156            Actor {
157                principal: "local".into(),
158                agent: true
159            }
160        );
161        for kind in ["desktop", "cli", "sapphire-sync"] {
162            assert!(!actor_for(kind).agent, "{kind}");
163            assert_eq!(actor_for(kind).principal, "local");
164        }
165    }
166
167    #[test]
168    fn only_a_real_apply_and_the_undo_methods_change_anything() {
169        let apply = |dry_run| serde_json::json!({"ops": [], "origin": "o", "dry_run": dry_run});
170        assert!(changes(FS_APPLY, &apply(false)));
171        assert!(!changes(FS_APPLY, &apply(true)));
172        assert!(changes(JOURNAL_UNDO, &serde_json::json!({})));
173        assert!(changes(JOURNAL_UNDO_BATCH, &serde_json::json!({})));
174        for read in [
175            FS_LIST,
176            FS_STAT,
177            FS_READ,
178            FS_VERSION,
179            JOURNAL_HISTORY,
180            JOURNAL_STATUS,
181        ] {
182            assert!(!changes(read, &serde_json::json!({})), "{read}");
183        }
184    }
185
186    #[test]
187    fn the_trash_folder_is_not_synced() {
188        let dir = tempfile::tempdir().unwrap();
189        let filter = sapphire_sync::SyncFilter::load(dir.path(), "sapphire-sync").unwrap();
190        assert!(!filter.allows(&format!("{OWN_FOLDER}/trash/x/a.txt"), false));
191        assert!(filter.allows(".sapphire-sync/embedded/a.vec", false));
192    }
193}