trusty_code/fs_browse/protocol.rs
1//! `fs.*` JSON-RPC method handlers — the daemon's directory inspection surface.
2//!
3//! Why: screen 7a's folder picker needs to browse the local disk, and the UI is
4//! a thin client that never touches the filesystem itself (see the parent
5//! module's docs for the full rationale, including why no path guard belongs
6//! here). Reaching it over `/rpc` alongside `session.*`/`task.*` — rather than
7//! as a new REST resource — keeps the API exactly what it is today: one
8//! JSON-RPC endpoint, three HTTP routes.
9//! What: [`register`] wires `fs.list_dir` onto a [`Router`]. The handler parses
10//! typed params, forwards to [`super::list_dir`], and maps
11//! [`super::ListDirError`] onto the vision spec's §13.2 domain taxonomy via
12//! [`to_rpc_error`] — reusing the codes already in the table rather than
13//! inventing `fs`-specific ones.
14//! Test: `protocol::tests::*`.
15
16use serde::Deserialize;
17use serde_json::{Value, json};
18
19use crate::jsonrpc::{ConnectionContext, Router, RpcError};
20
21use super::ListDirError;
22
23/// `params` shape for `fs.list_dir`.
24///
25/// Why: both fields are optional so the picker's very first call — the
26/// projectless cold start, where the client has no path to offer — is simply
27/// `fs.list_dir({})`.
28/// What: `path` defaults to `~` (the natural place to start browsing for
29/// projects); `include_hidden` defaults to `false`.
30/// Test: `tests::omitted_path_defaults_to_home`.
31#[derive(Deserialize)]
32struct ListDirParams {
33 #[serde(default)]
34 path: Option<String>,
35 #[serde(default)]
36 include_hidden: Option<bool>,
37}
38
39/// Register every `fs.*` method onto `router`.
40///
41/// Why: mirrors `session::protocol::register` / `task::protocol::register` —
42/// the one place listing this namespace's full surface, so `serve::build_router`
43/// stays a one-line call per group.
44/// What: registers `"fs.list_dir"` and `"fs.list_projects"` (issue #3365's
45/// project-picker roster). Unlike the `session.*`/`task.*` groups this takes
46/// no shared state: both are pure functions of the filesystem at call time,
47/// with no registry to close over.
48/// Test: `tests::register_wires_fs_list_dir`,
49/// `tests::register_wires_fs_list_projects`.
50pub fn register(router: &mut Router) {
51 router.register("fs.list_dir", list_dir);
52 router.register("fs.list_projects", list_projects);
53}
54
55/// Map a typed [`ListDirError`] onto the vision spec's §13.2 error taxonomy.
56///
57/// Why: the picker must distinguish causes without substring-matching a
58/// message; every variant gets a distinct code carrying a stable
59/// `data.error_type`. These are the spec's EXISTING codes — a missing path is
60/// the same `not_found` (-32002) an unknown agent is, and an OS refusal is the
61/// same `permission_denied` (-32001) an RBAC refusal is — so no `fs`-specific
62/// code enters the table.
63/// What: `NotFound` → -32002 `not_found`; `PermissionDenied` → -32001
64/// `permission_denied`; `NotADirectory`/`NoHome` → -32003 `invalid_argument`
65/// (the caller named a path that is semantically wrong for this method);
66/// `Io` → -32603 `internal` (an OS fault is not the caller's error).
67/// Test: `tests::nonexistent_path_maps_to_not_found`,
68/// `tests::file_path_maps_to_invalid_argument`,
69/// `tests::errors_are_distinguishable_by_code`.
70fn to_rpc_error(err: ListDirError) -> RpcError {
71 let message = err.to_string();
72 match err {
73 ListDirError::NotFound(_) => RpcError::not_found(message),
74 ListDirError::PermissionDenied(_) => RpcError::permission_denied(message),
75 ListDirError::NotADirectory(_) | ListDirError::NoHome(_) => {
76 RpcError::invalid_argument(message)
77 }
78 ListDirError::Io { .. } => RpcError::internal(message),
79 }
80}
81
82/// `fs.list_dir(path?, include_hidden?) -> DirListing` (UI Phase-1, screen 7a).
83///
84/// Why: the daemon-side folder picker — the only way a thin UI client can browse
85/// the local disk to choose a project root. One call answers both of 7a's
86/// questions: what to draw (breadcrumb + rows + `git` badges) and what each row
87/// would bind to (a git repo, or an equally-supported non-git directory).
88/// What: `path` defaults to `~`; `~` is expanded and the path canonicalized
89/// server-side, so a client navigates up by passing the previous response's
90/// `parent`. Returns [`super::DirListing`] serialized whole — `{path,
91/// display_path, parent, entries[]}`. Error codes per [`to_rpc_error`]. Note a
92/// non-git directory is a normal success with `is_git_repo: false`, NOT an
93/// error (#2728).
94/// Test: `tests::lists_a_directory`, `tests::omitted_path_defaults_to_home`,
95/// `tests::response_shape_supports_7a_rendering`.
96async fn list_dir(params: Value, _ctx: ConnectionContext) -> Result<Value, RpcError> {
97 // `params` is absent for a no-argument call; treat that as `{}` so
98 // `fs.list_dir()` and `fs.list_dir({})` behave identically.
99 let params = if params.is_null() { json!({}) } else { params };
100 let p: ListDirParams = serde_json::from_value(params)
101 .map_err(|e| RpcError::invalid_params(format!("fs.list_dir: {e}")))?;
102
103 let path = p.path.as_deref().unwrap_or("~");
104 let listing = super::list_dir(path, p.include_hidden.unwrap_or(false)).map_err(to_rpc_error)?;
105
106 serde_json::to_value(listing)
107 .map_err(|e| RpcError::internal(format!("fs.list_dir: serializing listing: {e}")))
108}
109
110/// `fs.list_projects() -> ProjectRoster` — the known-project roster for the
111/// GUI's workstream-first project-picker modal (issue #3365; re-sourced from
112/// trusty-mpm's shared project registry by issue #3435).
113///
114/// Why: the modal's supported roster data source. As of #3435 this is no
115/// longer a pure filesystem scan — see `crate::fs_browse::mpm_registry`
116/// module docs for the registry-primary/fs-secondary merge policy and the
117/// mpm-daemon-unreachable degradation. `fs.list_dir` (this method's sibling)
118/// is untouched — it remains the manual browse-and-descend surface (7a), not
119/// re-sourced by this ticket.
120/// What: no params — `params` is ignored entirely (a caller passing `{}` or
121/// omitting params behaves identically, matching `fs.list_dir`'s tolerance
122/// for a no-argument call). Never returns a caller-facing error: an
123/// unreachable mpm daemon degrades to the filesystem-only roster
124/// (`mpm_registry::merged_roster`'s docs), and an unreadable/missing scan
125/// root degrades further to an empty roster (`roster::list_projects`'s
126/// best-effort docs) — so the only failure mode here is JSON serialization,
127/// which cannot fail for this struct shape in practice — kept as a `Result`
128/// only for symmetry with every other registered method and to surface a
129/// genuine bug rather than `unwrap`.
130/// Test: `tests::list_projects_returns_entries_array`,
131/// `tests::register_wires_fs_list_projects`.
132async fn list_projects(_params: Value, _ctx: ConnectionContext) -> Result<Value, RpcError> {
133 let roster = super::mpm_registry::merged_roster().await;
134 serde_json::to_value(roster)
135 .map_err(|e| RpcError::internal(format!("fs.list_projects: serializing roster: {e}")))
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141 use tokio::sync::mpsc;
142
143 fn test_ctx() -> ConnectionContext {
144 let (tx, _rx) = mpsc::unbounded_channel();
145 ConnectionContext::new(tx)
146 }
147
148 /// `fs.list_dir` on a real directory returns its entries.
149 #[tokio::test]
150 async fn lists_a_directory() {
151 let tmp = tempfile::tempdir().expect("tempdir");
152 std::fs::create_dir(tmp.path().join("alpha")).expect("mkdir");
153
154 let result = list_dir(
155 json!({"path": tmp.path().display().to_string()}),
156 test_ctx(),
157 )
158 .await
159 .expect("list_dir must succeed");
160
161 assert_eq!(result["entries"][0]["name"], "alpha");
162 assert_eq!(result["entries"][0]["is_dir"], true);
163 }
164
165 /// An omitted `path` must default to the user's home rather than erroring —
166 /// the projectless cold-start call is `fs.list_dir({})`.
167 #[tokio::test]
168 async fn omitted_path_defaults_to_home() {
169 let Some(home) = dirs::home_dir() else {
170 return; // no home on this box; nothing to assert
171 };
172 let result = list_dir(json!({}), test_ctx())
173 .await
174 .expect("default list_dir must succeed");
175 let expected = std::fs::canonicalize(&home).unwrap_or(home);
176 assert_eq!(result["path"], expected.display().to_string());
177 assert_eq!(result["display_path"], "~");
178 }
179
180 /// Absent `params` (a no-argument call) must behave like `{}`.
181 #[tokio::test]
182 async fn null_params_are_treated_as_empty_object() {
183 if dirs::home_dir().is_none() {
184 return;
185 }
186 let result = list_dir(Value::Null, test_ctx())
187 .await
188 .expect("null params must succeed");
189 assert_eq!(result["display_path"], "~");
190 }
191
192 /// The response must carry everything screen 7a renders: a breadcrumb
193 /// caption, an up-target, and per-row name/path/is_dir/git-badge state.
194 #[tokio::test]
195 async fn response_shape_supports_7a_rendering() {
196 let tmp = tempfile::tempdir().expect("tempdir");
197 let repo = tmp.path().join("acme-api");
198 std::fs::create_dir(&repo).expect("mkdir");
199 std::fs::create_dir(repo.join(".git")).expect("mkdir .git");
200 std::fs::create_dir(tmp.path().join("scratch")).expect("mkdir");
201
202 let result = list_dir(
203 json!({"path": tmp.path().display().to_string()}),
204 test_ctx(),
205 )
206 .await
207 .expect("list_dir must succeed");
208
209 // Breadcrumb + up-navigation.
210 assert!(result["display_path"].is_string());
211 assert!(result["parent"].is_string());
212
213 // `acme-api git` and `scratch —` — both rows present, badge only on
214 // the repo, and each row carries the path the client binds/navigates to.
215 let entries = result["entries"].as_array().expect("entries array");
216 let acme = entries
217 .iter()
218 .find(|e| e["name"] == "acme-api")
219 .expect("acme-api row");
220 let scratch = entries
221 .iter()
222 .find(|e| e["name"] == "scratch")
223 .expect("scratch row");
224 assert_eq!(acme["is_git_repo"], true);
225 assert_eq!(scratch["is_git_repo"], false);
226 assert!(acme["path"].is_string());
227 assert_eq!(acme["is_dir"], true);
228 }
229
230 /// A nonexistent path must map to `-32002 not_found`.
231 #[tokio::test]
232 async fn nonexistent_path_maps_to_not_found() {
233 let tmp = tempfile::tempdir().expect("tempdir");
234 let missing = tmp.path().join("no-such-dir");
235
236 let err = list_dir(json!({"path": missing.display().to_string()}), test_ctx())
237 .await
238 .expect_err("must fail");
239 assert_eq!(err.code, -32002);
240 assert_eq!(err.data, Some(json!({"error_type": "not_found"})));
241 }
242
243 /// A path that exists but is a FILE must map to `-32003 invalid_argument`,
244 /// distinct from the not-found code.
245 #[tokio::test]
246 async fn file_path_maps_to_invalid_argument() {
247 let tmp = tempfile::tempdir().expect("tempdir");
248 let file = tmp.path().join("a.txt");
249 std::fs::write(&file, "x").expect("write");
250
251 let err = list_dir(json!({"path": file.display().to_string()}), test_ctx())
252 .await
253 .expect_err("must fail");
254 assert_eq!(err.code, -32003);
255 assert_eq!(err.data, Some(json!({"error_type": "invalid_argument"})));
256 }
257
258 /// The three caller-actionable failures must be tellable apart by code —
259 /// the whole point of the typed error (a client must not substring-match).
260 #[test]
261 fn errors_are_distinguishable_by_code() {
262 let not_found = to_rpc_error(ListDirError::NotFound("/x".into()));
263 let not_dir = to_rpc_error(ListDirError::NotADirectory("/x".into()));
264 let denied = to_rpc_error(ListDirError::PermissionDenied("/x".into()));
265 let io = to_rpc_error(ListDirError::Io {
266 path: "/x".into(),
267 source: std::io::Error::other("boom"),
268 });
269
270 assert_eq!(not_found.code, -32002);
271 assert_eq!(not_dir.code, -32003);
272 assert_eq!(denied.code, -32001);
273 assert_eq!(io.code, -32603);
274
275 let codes = [not_found.code, not_dir.code, denied.code, io.code];
276 let mut unique = codes.to_vec();
277 unique.sort_unstable();
278 unique.dedup();
279 assert_eq!(unique.len(), codes.len(), "every cause needs its own code");
280 }
281
282 /// Malformed params (wrong type) must be rejected as invalid params rather
283 /// than silently defaulting.
284 #[tokio::test]
285 async fn wrong_typed_params_are_rejected() {
286 let err = list_dir(json!({"path": 42}), test_ctx())
287 .await
288 .expect_err("must fail");
289 assert_eq!(err.code, -32602);
290 }
291
292 /// `register` must wire `fs.list_dir` so the router recognises it.
293 #[tokio::test]
294 async fn register_wires_fs_list_dir() {
295 use trusty_mcp::Request;
296
297 let mut router = Router::new();
298 register(&mut router);
299
300 let tmp = tempfile::tempdir().expect("tempdir");
301 let req = Request {
302 jsonrpc: Some("2.0".to_string()),
303 id: Some(json!(1)),
304 method: "fs.list_dir".to_string(),
305 params: Some(json!({"path": tmp.path().display().to_string()})),
306 };
307 let resp = router.dispatch(req, &test_ctx()).await;
308 assert!(
309 resp.error.is_none(),
310 "fs.list_dir must be registered, got {:?}",
311 resp.error
312 );
313 }
314
315 /// `fs.list_projects` must never error and must return an `entries`
316 /// array — the response shape the picker modal dereferences. This runs
317 /// against the REAL developer/CI-runner home directory AND whatever real
318 /// mpm daemon (if any) happens to be reachable at the default loopback
319 /// URL (the handler has no injectable seam, unlike
320 /// `mpm_registry::merged_roster_with`, which carries the real
321 /// merge/degradation coverage), so this only pins the wire shape, not
322 /// any particular content — it must pass identically whether or not a
323 /// real mpm daemon is running locally.
324 #[tokio::test]
325 async fn list_projects_returns_entries_array() {
326 let result = list_projects(Value::Null, test_ctx())
327 .await
328 .expect("fs.list_projects must not error");
329 assert!(result["entries"].is_array());
330 }
331
332 /// `register` must wire `fs.list_projects` so the router recognises it.
333 #[tokio::test]
334 async fn register_wires_fs_list_projects() {
335 use trusty_mcp::Request;
336
337 let mut router = Router::new();
338 register(&mut router);
339
340 let req = Request {
341 jsonrpc: Some("2.0".to_string()),
342 id: Some(json!(1)),
343 method: "fs.list_projects".to_string(),
344 params: None,
345 };
346 let resp = router.dispatch(req, &test_ctx()).await;
347 assert!(
348 resp.error.is_none(),
349 "fs.list_projects must be registered, got {:?}",
350 resp.error
351 );
352 }
353}