1use std::sync::Arc;
23
24use crate::backend::fs_ops;
25use crate::backend::rpc::engine::WshRpcEngine;
26use crate::backend::rpc_types::{
27 FsAgentFolder, FsCreateReq, FsDeleteReq, FsEmptyResult, FsGitStatus, FsLinkFileReq, FsListReq, FsListResult, FsOpCancelReq, FsOpResolveReq,
28 FsOpResult, FsOpResults, FsOpStartReq, FsOpStartResult, FsPathReq, FsPlace, FsPlaceKind, FsPlacesReq, FsPlacesResult,
29 FsCreateResult, FsRenameReq, FsRenameResult, FsRestoreReq, FsTrashReq, FsUnwatchReq, FsWatchReq,
30 FsWatchResult,
31};
32
33use super::AppState;
34
35async fn blocking<T, F>(f: F) -> Result<T, String>
37where
38 T: Send + 'static,
39 F: FnOnce() -> T + Send + 'static,
40{
41 tokio::task::spawn_blocking(f).await.map_err(|e| format!("filesystem task failed: {e}"))
42}
43
44fn op_results(paths: Vec<String>, outcomes: Vec<Result<(), String>>) -> FsOpResults {
46 FsOpResults {
47 results: paths
48 .into_iter()
49 .zip(outcomes)
50 .map(|(path, outcome)| FsOpResult { path, ok: outcome.is_ok(), error: outcome.err() })
51 .collect(),
52 }
53}
54
55use crate::backend::fs_ops::remote as fs_remote;
56
57fn remote_of<'a>(conn: &'a str, block_id: Option<&'a str>, auth_key: &'a str) -> fs_remote::Remote<'a> {
58 fs_remote::Remote {
59 connection: conn,
60 block_id,
61 auth_key,
62 }
63}
64
65pub(crate) fn asks_first_message(agent: &str) -> String {
68 if agent.is_empty() {
69 return "[asks-first:] This file is in a folder a container agent can change. Opening it runs your computer's app on what the agent wrote, so it asks first.".to_string();
70 }
71 format!("[asks-first:{agent}] This file is in the folder of {agent}, a container agent that can change it. Opening it runs your computer's app on what {agent} wrote, so it asks first.")
72}
73
74pub(super) async fn open_or_reveal_bound(state: &AppState, cmd: FsPathReq, reveal: bool) -> Result<FsEmptyResult, String> {
77 if super::files_root::is_confined(state, cmd.block_id.as_deref()) {
78 return Err(super::files_root::NO_PROGRAMS.to_string());
79 }
80 if !reveal && cmd.confirmed != Some(true) {
81 let asked = cmd.path.clone();
82 let place = blocking(move || fs_ops::container_folders::place(&asked)).await?;
83 if let Some(agent) = fs_ops::container_folders::open_asks_first(&place) {
84 return Err(asks_first_message(&agent));
85 }
86 }
87 let path = cmd.path;
88 blocking(move || fs_ops::open_or_reveal(&path, reveal)).await??;
89 Ok(FsEmptyResult {})
90}
91
92pub(crate) async fn fs_list(state: &AppState, mut cmd: FsListReq) -> Result<FsListResult, String> {
97 if let Some(root) = cmd.block_id.as_deref().and_then(|b| super::files_root::root_of(state, b)) {
99 let asked = cmd.path.clone();
100 match blocking(move || super::files_root::confine(&root, &asked)).await? {
101 Ok(real) => cmd.path = real.to_string_lossy().into_owned(),
102 Err(message) => return Ok(super::files_root::outside_listing(&cmd.path, message)),
103 }
104 }
105 if let Some(conn) = fs_remote::ssh_connection(cmd.connection.as_deref()) {
106 let r = remote_of(conn, cmd.block_id.as_deref(), &state.auth_key);
107 return fs_remote::list(r, &cmd.path).await;
108 }
109 fs_ops::ensure_cursor_sweeper();
110 blocking(move || fs_ops::list_page(&cmd)).await
111}
112
113pub(crate) async fn fs_agent_folder(cmd: FsPathReq) -> Result<FsAgentFolder, String> {
116 let Ok(path) = fs_ops::resolve_request_path(&cmd.path) else { return Ok(FsAgentFolder::default()) };
117 blocking(move || FsAgentFolder { agent_folder: fs_ops::container_folders::written_by_a_container_agent(&path) }).await
118}
119
120pub(crate) async fn fs_places() -> Result<FsPlacesResult, String> {
123 let distros = crate::backend::remote::wsl::list_cached().await;
124 blocking(move || {
125 let (home, mut places) = fs_ops::home_and_known_places();
126 places.extend(super::editor_handlers::list_drives().into_iter().map(|d| FsPlace {
127 id: format!("drive:{}", d.path),
128 label: d.name,
129 path: d.path,
130 kind: FsPlaceKind::Drive,
131 }));
132 places.extend(distros.into_iter().map(|d| FsPlace {
133 id: format!("wsl:{d}"),
134 path: crate::backend::remote::wsl_fs::share_path(&d, "/"),
135 label: d,
136 kind: FsPlaceKind::Wsl,
137 }));
138 FsPlacesResult { home, sep: std::path::MAIN_SEPARATOR.to_string(), places }
139 })
140 .await
141}
142
143pub(crate) async fn fs_watch(state: &AppState, cmd: FsWatchReq) -> Result<FsWatchResult, String> {
146 let path = cmd.path.clone();
147 let root = super::files_root::root_of(state, &cmd.block_id);
148 let dir = blocking(move || -> Result<std::path::PathBuf, String> {
149 if let Some(root) = &root {
150 return super::files_root::confine(root, &path);
151 }
152 let canonical = fs_ops::resolve_request_path(&path)?
153 .canonicalize()
154 .map_err(|e| fs_ops::classify_folder_error(&e).1)?;
155 if !canonical.is_dir() {
156 return Err("This isn't a folder.".to_string());
157 }
158 Ok(canonical)
159 })
160 .await??;
161 Ok(FsWatchResult { watch_id: state.files_watcher.watch(&dir, &cmd.block_id) })
162}
163
164pub(crate) fn fs_unwatch(state: &AppState, cmd: FsUnwatchReq) -> Result<FsEmptyResult, String> {
166 state.files_watcher.unwatch(&cmd.watch_id);
167 Ok(FsEmptyResult {})
168}
169
170pub(crate) async fn fs_git_status(state: &AppState, cmd: FsPathReq) -> Result<FsGitStatus, String> {
173 fs_ops::container_folders::install(&state.mstore);
175 crate::backend::container::mounts::read_exec::install(&state.container_manager);
176 if !super::files_root::is_confined(state, cmd.block_id.as_deref()) {
177 return Ok(fs_ops::git::git_status(&cmd.path).await);
178 }
179 let Ok(path) = super::files_root::bound_path(state, cmd.block_id.as_deref(), &cmd.path).await else {
183 return Ok(Default::default());
184 };
185 let asked = path.clone();
186 let place = tokio::task::spawn_blocking(move || fs_ops::container_folders::place(&asked)).await;
187 if !matches!(place, Ok(fs_ops::container_folders::Place::Inside(_))) {
188 return Ok(Default::default());
189 }
190 Ok(fs_ops::git::git_status(&path).await)
191}
192
193pub(crate) async fn fs_rename(state: &AppState, cmd: FsRenameReq) -> Result<FsRenameResult, String> {
197 super::files_root::refuse_change(state, cmd.block_id.as_deref())?;
198 if let Some(conn) = fs_remote::ssh_connection(cmd.connection.as_deref()) {
199 let r = remote_of(conn, cmd.block_id.as_deref(), &state.auth_key);
200 let new_path = fs_remote::rename(r, &cmd.path, &cmd.new_name).await?;
201 publish_renamed(&state.broker, cmd.path.clone(), new_path.clone(), Some(conn.to_string()));
202 return Ok(FsRenameResult { new_path });
203 }
204 let broker = state.broker.clone();
205 blocking(move || {
206 let old_path = fs_ops::entry_display_path(&cmd.path).unwrap_or_else(|| cmd.path.clone());
207 let renamed = fs_ops::rename(&cmd)?;
208 publish_renamed(&broker, old_path, renamed.new_path.clone(), None);
209 Ok(renamed)
210 })
211 .await?
212}
213
214fn publish_renamed(broker: &crate::backend::mps::Broker, old_path: String, new_path: String, connection: Option<String>) {
217 if old_path == new_path {
218 return;
219 }
220 broker.publish_event::<crate::backend::mps_events::FileRenamed>(
221 &crate::backend::mps_events::FileRenamedEvent { old_path, new_path, connection },
222 vec![],
223 0,
224 );
225}
226
227pub(crate) async fn fs_create(state: &AppState, cmd: FsCreateReq) -> Result<FsCreateResult, String> {
229 super::files_root::refuse_change(state, cmd.block_id.as_deref())?;
230 if let Some(conn) = fs_remote::ssh_connection(cmd.connection.as_deref()) {
231 let r = remote_of(conn, cmd.block_id.as_deref(), &state.auth_key);
232 let path = fs_remote::create(r, &cmd.parent, &cmd.name, cmd.kind).await?;
233 return Ok(FsCreateResult { path });
234 }
235 blocking(move || fs_ops::create(&cmd)).await?
236}
237
238pub(crate) async fn fs_trash(state: &AppState, cmd: FsTrashReq) -> Result<FsOpResults, String> {
240 super::files_root::refuse_change(state, cmd.block_id.as_deref())?;
241 if let Some(conn) = fs_remote::ssh_connection(cmd.connection.as_deref()) {
242 return Err(fs_remote::no_trash(conn));
243 }
244 let paths = cmd.paths;
245 let for_worker = paths.clone();
246 let outcomes = fs_ops::trash_worker::run(move || for_worker.iter().map(|p| fs_ops::trash(p)).collect()).await?;
247 Ok(op_results(paths, outcomes))
248}
249
250pub(crate) async fn fs_restore(state: &AppState, cmd: FsRestoreReq) -> Result<FsOpResults, String> {
252 super::files_root::refuse_change(state, cmd.block_id.as_deref())?;
253 if let Some(conn) = fs_remote::ssh_connection(cmd.connection.as_deref()) {
254 return Err(fs_remote::no_trash(conn));
255 }
256 let paths = cmd.paths;
257 let for_worker = paths.clone();
258 let outcomes = fs_ops::trash_worker::run(move || fs_ops::restore(&for_worker)).await?;
259 Ok(op_results(paths, outcomes))
260}
261
262pub(crate) async fn fs_delete(state: &AppState, cmd: FsDeleteReq) -> Result<FsOpResults, String> {
264 super::files_root::refuse_change(state, cmd.block_id.as_deref())?;
265 if let Some(conn) = fs_remote::ssh_connection(cmd.connection.as_deref()) {
266 let r = remote_of(conn, cmd.block_id.as_deref(), &state.auth_key);
267 return Ok(FsOpResults {
268 results: fs_remote::delete(r, &cmd.paths).await,
269 });
270 }
271 let paths = cmd.paths;
272 let for_worker = paths.clone();
273 let outcomes =
274 blocking(move || for_worker.iter().map(|p| fs_ops::delete_permanently(p)).collect()).await?;
275 Ok(op_results(paths, outcomes))
276}
277
278pub(crate) async fn fs_op_start(state: &AppState, cmd: FsOpStartReq) -> Result<FsOpStartResult, String> {
283 if cmd.block_id.is_empty() {
284 return Err("No pane was named to report the operation's progress to.".to_string());
285 }
286 super::files_root::refuse_change(state, Some(&cmd.block_id))?;
287 let emit = fs_ops::jobs::broker_emitter(state.broker.clone(), cmd.block_id.clone());
288 let from = fs_remote::ssh_connection(cmd.source_connection.as_deref());
291 let to = fs_remote::ssh_connection(cmd.connection.as_deref());
292 if from.is_some() || to.is_some() {
293 let ask = crate::backend::remote::sessions::AskIn {
294 block_id: &cmd.block_id,
295 auth_key: &state.auth_key,
296 };
297 let connect = |conn: Option<&str>| {
300 let conn = conn.map(str::to_string);
301 async move {
302 match conn {
303 None => Ok(fs_ops::host_jobs::End::Local),
304 Some(c) => crate::backend::remote::files::connect(&c, Some(ask))
305 .await
306 .map(fs_ops::host_jobs::End::host)
307 .map_err(|e| e.message),
308 }
309 }
310 };
311 let (src, dest) = tokio::join!(connect(from), connect(to));
312 let (src, dest) = (src?, dest?);
313 return fs_ops::host_jobs::start(cmd.kind, src, cmd.sources, dest, cmd.dest_dir, emit).await;
314 }
315 blocking(move || fs_ops::jobs::JOBS.start(&cmd, emit)).await?
316}
317
318pub(crate) fn fs_op_resolve(cmd: FsOpResolveReq) -> Result<FsEmptyResult, String> {
321 fs_ops::jobs::JOBS.resolve(&cmd.op_id, cmd.choice, cmd.apply_to_all)?;
322 Ok(FsEmptyResult {})
323}
324
325pub(crate) fn fs_op_cancel(cmd: FsOpCancelReq) -> Result<FsEmptyResult, String> {
327 fs_ops::jobs::JOBS.cancel(&cmd.op_id);
328 Ok(FsEmptyResult {})
329}
330
331fn register_fs_browsing(engine: &Arc<WshRpcEngine>, state: &AppState) {
332 let s = state.clone();
333 engine.register_typed("fs.list", move |cmd: FsListReq, _ctx| {
334 let s = s.clone();
335 async move { fs_list(&s, cmd).await }
336 });
337
338 engine.register_typed(
339 "fs.places",
340 |_req: Option<FsPlacesReq>, _ctx| async move { fs_places().await },
342 );
343
344 let s = state.clone();
345 engine.register_typed("fs.watch", move |cmd: FsWatchReq, _ctx| {
346 let s = s.clone();
347 async move { fs_watch(&s, cmd).await }
348 });
349 let s = state.clone();
350 engine.register_typed("fs.unwatch", move |cmd: FsUnwatchReq, _ctx| {
351 let s = s.clone();
352 async move { fs_unwatch(&s, cmd) }
353 });
354
355 let s = state.clone();
356 engine.register_typed("fs.git_status", move |cmd: FsPathReq, _ctx| {
357 let s = s.clone();
358 async move { fs_git_status(&s, cmd).await }
359 });
360 engine.register_typed("fs.agent_folder", |cmd: FsPathReq, _ctx| async move { fs_agent_folder(cmd).await });
361 let s = state.clone();
362 engine.register_typed("fs.link_file_check", move |cmd: FsLinkFileReq, _ctx| {
363 let s = s.clone();
364 async move { super::link_file_check::fs_link_file_check(&s, cmd).await }
365 });
366}
367
368fn register_fs_mutations(engine: &Arc<WshRpcEngine>, state: &AppState) {
369 let s = state.clone();
370 engine.register_typed("fs.rename", move |cmd: FsRenameReq, _ctx| {
371 let s = s.clone();
372 async move { fs_rename(&s, cmd).await }
373 });
374 let s = state.clone();
375 engine.register_typed("fs.create", move |cmd: FsCreateReq, _ctx| {
376 let s = s.clone();
377 async move { fs_create(&s, cmd).await }
378 });
379 let s = state.clone();
380 engine.register_typed("fs.trash", move |cmd: FsTrashReq, _ctx| {
381 let s = s.clone();
382 async move { fs_trash(&s, cmd).await }
383 });
384 let s = state.clone();
385 engine.register_typed("fs.restore", move |cmd: FsRestoreReq, _ctx| {
386 let s = s.clone();
387 async move { fs_restore(&s, cmd).await }
388 });
389 let s = state.clone();
390 engine.register_typed("fs.delete", move |cmd: FsDeleteReq, _ctx| {
391 let s = s.clone();
392 async move { fs_delete(&s, cmd).await }
393 });
394
395 let s = state.clone();
398 engine.register_typed("fs.open", move |cmd: FsPathReq, _ctx| {
399 let s = s.clone();
400 async move { open_or_reveal_bound(&s, cmd, false).await }
401 });
402 let s = state.clone();
403 engine.register_typed("fs.reveal", move |cmd: FsPathReq, _ctx| {
404 let s = s.clone();
405 async move { open_or_reveal_bound(&s, cmd, true).await }
406 });
407}
408
409fn register_fs_jobs(engine: &Arc<WshRpcEngine>, state: &AppState) {
410 let s = state.clone();
411 engine.register_typed("fs.op.start", move |cmd: FsOpStartReq, _ctx| {
412 let s = s.clone();
413 async move { fs_op_start(&s, cmd).await }
414 });
415 engine.register_typed("fs.op.resolve", |cmd: FsOpResolveReq, _ctx| async move { fs_op_resolve(cmd) });
416 engine.register_typed("fs.op.cancel", |cmd: FsOpCancelReq, _ctx| async move { fs_op_cancel(cmd) });
417}
418
419pub fn register_fs_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
420 crate::backend::editor_probe::register(engine);
423 crate::backend::editor_search::register(engine);
425 crate::backend::editor_search_text::register(engine);
426 crate::backend::editor_lines::register(engine);
428 register_fs_browsing(engine, state);
429 register_fs_mutations(engine, state);
430 register_fs_jobs(engine, state);
431}
432
433#[cfg(test)]
434mod tests {
435 use crate::backend::rpc_types::RpcMessage;
436
437 #[tokio::test]
440 async fn every_fs_command_records_its_types() {
441 let state = crate::server::tests::test_state();
442 let (engine, _rx) = crate::backend::rpc::engine::WshRpcEngine::new();
443 super::register_fs_handlers(&engine, &state);
444 let schema = engine.schema_json();
445 let rows = schema.as_array().unwrap();
446 let find = |cmd: &str| {
447 rows.iter()
448 .find(|r| r["command"] == cmd)
449 .unwrap_or_else(|| panic!("{cmd} missing from the schema"))
450 };
451 for (cmd, req, resp) in [
452 ("fs.list", "FsListReq", "FsListResult"),
453 ("fs.watch", "FsWatchReq", "FsWatchResult"),
454 ("fs.unwatch", "FsUnwatchReq", "FsEmptyResult"),
455 ("fs.rename", "FsRenameReq", "FsRenameResult"),
456 ("fs.create", "FsCreateReq", "FsCreateResult"),
457 ("fs.trash", "FsTrashReq", "FsOpResults"),
458 ("fs.restore", "FsRestoreReq", "FsOpResults"),
459 ("fs.delete", "FsDeleteReq", "FsOpResults"),
460 ("fs.open", "FsPathReq", "FsEmptyResult"),
461 ("fs.reveal", "FsPathReq", "FsEmptyResult"),
462 ("fs.op.start", "FsOpStartReq", "FsOpStartResult"),
463 ("fs.op.resolve", "FsOpResolveReq", "FsEmptyResult"),
464 ("fs.op.cancel", "FsOpCancelReq", "FsEmptyResult"),
465 ("fs.git_status", "FsPathReq", "FsGitStatus"),
466 ("fs.agent_folder", "FsPathReq", "FsAgentFolder"),
467 ("fs.link_file_check", "FsLinkFileReq", "FsLinkFileCheck"),
468 ] {
469 let row = find(cmd);
470 assert_eq!(row["requestName"], req, "{cmd} request");
471 assert_eq!(row["responseName"], resp, "{cmd} response");
472 }
473 assert_eq!(find("fs.places")["responseName"], "FsPlacesResult");
474 }
475
476 #[test]
477 fn the_answer_that_asks_first_names_the_agent_and_carries_its_marker() {
478 let said = super::asks_first_message("aria");
479 assert!(said.starts_with("[asks-first:aria] "), "{said}");
480 assert!(said.contains("the folder of aria") && said.contains("what aria wrote"), "{said}");
481 assert!(super::asks_first_message("").starts_with("[asks-first:] "));
482 }
483
484 #[tokio::test]
487 async fn places_accepts_both_encodings_of_no_argument() {
488 let state = crate::server::tests::test_state();
489 let (engine, mut rx) = crate::backend::rpc::engine::WshRpcEngine::new();
490 super::register_fs_handlers(&engine, &state);
491 for (i, payload) in [serde_json::json!({}), serde_json::Value::Null].into_iter().enumerate() {
492 engine.handle_message(RpcMessage {
493 command: "fs.places".to_string(),
494 reqid: format!("places-{i}"),
495 data: Some(payload.clone()),
496 ..Default::default()
497 });
498 let resp = tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv()).await.unwrap().unwrap();
499 assert!(resp.error.is_empty(), "fs.places should accept {payload}, got: {}", resp.error);
500 let data = resp.data.unwrap();
501 assert_eq!(data["sep"], std::path::MAIN_SEPARATOR.to_string());
502 assert!(data["places"].as_array().unwrap().iter().any(|p| p["kind"] == "home"));
503 }
504 }
505
506 #[tokio::test]
509 async fn a_batch_answers_per_path() {
510 let state = crate::server::tests::test_state();
511 let (engine, mut rx) = crate::backend::rpc::engine::WshRpcEngine::new();
512 super::register_fs_handlers(&engine, &state);
513 let dir = tempfile::tempdir().unwrap();
514 let file = dir.path().join("doomed.txt");
515 std::fs::write(&file, "x").unwrap();
516 let missing = dir.path().join("missing.txt");
517
518 engine.handle_message(RpcMessage {
519 command: "fs.delete".to_string(),
520 reqid: "del".to_string(),
521 data: Some(serde_json::json!({ "paths": [file.to_string_lossy(), missing.to_string_lossy()] })),
522 ..Default::default()
523 });
524 let resp = tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv()).await.unwrap().unwrap();
525 assert!(resp.error.is_empty(), "{}", resp.error);
526 let results = resp.data.unwrap()["results"].as_array().unwrap().clone();
527 assert_eq!(results.len(), 2);
528 assert_eq!(results[0]["ok"], true);
529 assert_eq!(results[1]["ok"], false);
530 assert!(results[1]["error"].is_string());
531 assert!(!file.exists());
532 }
533
534 fn req<T: serde::de::DeserializeOwned>(v: serde_json::Value) -> T {
535 serde_json::from_value(v).unwrap()
536 }
537
538 #[tokio::test]
540 async fn create_rename_and_list_agree() {
541 let state = crate::server::tests::test_state();
542 let dir = tempfile::tempdir().unwrap();
543 let parent = dir.path().to_string_lossy().into_owned();
544
545 let made = super::fs_create(&state, req(serde_json::json!({ "parent": parent, "name": "a.txt", "kind": "file" }))).await.unwrap();
546 assert!(std::path::Path::new(&made.path).exists());
547
548 let renamed = super::fs_rename(&state, req(serde_json::json!({ "path": made.path, "new_name": "b.txt" }))).await.unwrap();
549 assert!(renamed.new_path.ends_with("b.txt"));
550 assert!(!dir.path().join("a.txt").exists() && dir.path().join("b.txt").exists());
551
552 let page = super::fs_list(&state, req(serde_json::json!({ "path": parent }))).await.unwrap();
553 let names: Vec<String> = serde_json::to_value(&page).unwrap()["entries"]
554 .as_array()
555 .unwrap()
556 .iter()
557 .map(|e| e["name"].as_str().unwrap().to_string())
558 .collect();
559 assert_eq!(names, vec!["b.txt".to_string()]);
560 }
561
562 #[tokio::test]
564 async fn fs_delete_reports_each_path_in_request_order() {
565 let state = crate::server::tests::test_state();
566 let dir = tempfile::tempdir().unwrap();
567 let gone = dir.path().join("gone.txt");
568 std::fs::write(&gone, "x").unwrap();
569 let missing = dir.path().join("missing.txt");
570 let out = super::fs_delete(&state, req(serde_json::json!({ "paths": [gone.to_string_lossy(), missing.to_string_lossy()] }))).await.unwrap();
571 assert_eq!(out.results.len(), 2);
572 assert!(out.results[0].ok && !out.results[1].ok);
573 assert_eq!(out.results[0].path, gone.to_string_lossy());
574 }
575
576 #[tokio::test]
579 async fn fs_watch_answers_with_an_id_and_refuses_a_file() {
580 let state = crate::server::tests::test_state();
581 let dir = tempfile::tempdir().unwrap();
582 let watched = super::fs_watch(&state, req(serde_json::json!({ "path": dir.path().to_string_lossy(), "block_id": "watch-block" }))).await.unwrap();
583 assert!(!watched.watch_id.is_empty());
584 super::fs_unwatch(&state, req(serde_json::json!({ "watch_id": watched.watch_id }))).unwrap();
585
586 let file = dir.path().join("f.txt");
587 std::fs::write(&file, "x").unwrap();
588 let err = super::fs_watch(&state, req(serde_json::json!({ "path": file.to_string_lossy(), "block_id": "watch-block" }))).await.unwrap_err();
589 assert_eq!(err, "This isn't a folder.");
590 }
591
592 #[tokio::test]
594 async fn fs_op_start_wants_a_pane_to_report_to() {
595 let state = crate::server::tests::test_state();
596 let err = super::fs_op_start(&state, req(serde_json::json!({ "kind": "copy", "sources": [], "dest_dir": "x", "block_id": "" }))).await.unwrap_err();
597 assert_eq!(err, "No pane was named to report the operation's progress to.");
598 }
599
600 #[tokio::test]
602 async fn fs_git_status_outside_a_repository_is_empty_not_an_error() {
603 let state = crate::server::tests::test_state();
604 let dir = tempfile::tempdir().unwrap();
605 let status = super::fs_git_status(&state, req(serde_json::json!({ "path": dir.path().to_string_lossy() }))).await.unwrap();
606 assert!(!status.in_repo, "a temp folder is not a repository");
607 assert!(status.entries.is_empty());
608 }
609
610 #[tokio::test]
612 async fn a_rename_is_published_once_and_a_refusal_is_not() {
613 let state = crate::server::tests::test_state();
614 let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
615 let sink = seen.clone();
616 state.broker.add_observer(std::sync::Arc::new(move |e: &crate::backend::mps::MuxEvent| {
617 if e.event == "fs:renamed" {
618 sink.lock().unwrap().push((e.scopes.clone(), e.data.clone().unwrap_or_default()));
619 }
620 }));
621 let dir = tempfile::tempdir().unwrap();
622 std::fs::write(dir.path().join("a.txt"), "a").unwrap();
623 std::fs::write(dir.path().join("taken.txt"), "t").unwrap();
624 let req = |name: &str| crate::backend::rpc_types::FsRenameReq {
625 path: dir.path().join("a.txt").to_string_lossy().into_owned(),
626 new_name: name.to_string(),
627 connection: None,
628 block_id: None,
629 };
630
631 assert!(super::fs_rename(&state, req("taken.txt")).await.unwrap_err().contains("already exists"));
632 super::fs_rename(&state, req("a.txt")).await.unwrap();
633 assert!(seen.lock().unwrap().is_empty(), "nothing was renamed yet");
634
635 let out = super::fs_rename(&state, req("b.txt")).await.unwrap();
636 let events = seen.lock().unwrap();
637 assert_eq!(events.len(), 1);
638 let (scopes, data) = &events[0];
639 assert!(scopes.is_empty(), "to every window, not one pane");
640 assert_eq!(data["new_path"], out.new_path);
641 assert!(data["old_path"].as_str().unwrap().ends_with("a.txt"));
642 assert!(!data["old_path"].as_str().unwrap().starts_with(r"\\?\"), "as the panes show paths");
643 assert!(data["connection"].is_null());
644 }
645}