sapphire-framework-server 0.29.0

App server skeleton for sapphire-framework: owns a workspace's cache and serves it over IPC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//! The `workspace.*` methods, one per [`WorkspaceBackend`] method.

use std::sync::Arc;

use sapphire_backend::protocol as proto;
use sapphire_backend::{WorkspaceBackend, protocol::Ack};
use sapphire_ipc::{RequestCtx, Router, RpcError, codes};
use serde::de::DeserializeOwned;
use serde_json::Value;

use crate::current::Current;
use crate::error::Error;
use crate::sync::SyncRuntime;

/// Turn a server error into a JSON-RPC error.
///
/// Only a caller's mistake is `INVALID_PARAMS`: a path outside the workspace, a directory
/// that is not a workspace, an unreadable sync id, a parameter object that does not fit. A
/// failing database or an unreachable bridge is the server's problem, and the caller cannot
/// fix it by asking differently.
pub(crate) fn rpc_error(err: &Error) -> RpcError {
    use sapphire_workspace::Error as WsError;

    let caller_error = matches!(
        err,
        Error::UnknownWorkspace(..)
            | Error::NoWorkspace
            | Error::UnknownWorkspaceName(..)
            | Error::WrongApp { .. }
            | Error::SyncId(..)
            | Error::Workspace(
                WsError::PathEscapesWorkspace { .. }
                    | WsError::MarkerDirMissing { .. }
                    | WsError::MarkerNotFound { .. }
            )
    ) || matches!(
        err,
        Error::Backend(sapphire_backend::Error::Workspace(
            WsError::PathEscapesWorkspace { .. }
                | WsError::MarkerDirMissing { .. }
                | WsError::MarkerNotFound { .. }
        ))
    );

    if caller_error {
        RpcError::invalid_params(err.to_string())
    } else {
        RpcError {
            code: codes::INTERNAL_ERROR,
            message: err.to_string(),
            data: None,
        }
    }
}

fn params<T: DeserializeOwned>(ctx: &RequestCtx) -> std::result::Result<T, RpcError> {
    serde_json::from_value(ctx.params.clone())
        .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))
}

fn ok<T: serde::Serialize>(value: T) -> std::result::Result<Value, RpcError> {
    serde_json::to_value(value).map_err(|e| RpcError::internal(e.to_string()))
}

/// Scan `root` after a write, if this server syncs. A failed scan is logged, not
/// returned: the caller's write succeeded, and reporting a sync problem as a write
/// failure would make an unrelated outage look like the caller's.
pub(crate) async fn scanned(sync: Option<&Arc<SyncRuntime>>, root: &std::path::Path, what: &str) {
    if let Some(runtime) = sync {
        if let Err(err) = runtime.scan(root).await {
            tracing::warn!(root = %root.display(), "scan after {what} failed: {err}");
        }
        runtime.request_embed(root);
    }
}

/// The file methods of `workspace.*`, on the current workspace (#215).
///
/// The three methods that change a file take the exact path: after the write succeeds, the
/// replica is told to [`scan`], so the change is committed without waiting for the watcher's
/// debounce. The watcher is the safety net for edits the server did not make; this is the
/// main route, and it is not optional for the same reason the watcher is not — a skipped
/// scan loses an edit until the next one.
///
/// [`scan`]: SyncRuntime::scan
pub fn workspace_router(current: Arc<Current>) -> Router {
    let read = Arc::clone(&current);
    let write = Arc::clone(&current);
    let append = Arc::clone(&current);
    let delete = Arc::clone(&current);
    let list = Arc::clone(&current);
    let search = Arc::clone(&current);
    let reindex = current;

    Router::new()
        .method(proto::READ_FILE, move |ctx| {
            let current = Arc::clone(&read);
            async move {
                let p: proto::PathParams = params(&ctx)?;
                let backend = current.host().backend().await.map_err(|e| rpc_error(&e))?;
                let content = backend
                    .read_file(&p.path)
                    .await
                    .map_err(|e| rpc_error(&Error::Backend(e)))?;
                ok(proto::ReadResult { content })
            }
        })
        .method(proto::WRITE_FILE, move |ctx| {
            let current = Arc::clone(&write);
            async move {
                let p: proto::ContentParams = params(&ctx)?;
                let (root, backend) = current.host().current().await.map_err(|e| rpc_error(&e))?;
                backend
                    .write_file(&p.path, &p.content)
                    .await
                    .map_err(|e| rpc_error(&Error::Backend(e)))?;
                scanned(current.sync(), &root, "a write").await;
                ok(Ack {})
            }
        })
        .method(proto::APPEND_FILE, move |ctx| {
            let current = Arc::clone(&append);
            async move {
                let p: proto::ContentParams = params(&ctx)?;
                let (root, backend) = current.host().current().await.map_err(|e| rpc_error(&e))?;
                backend
                    .append_file(&p.path, &p.content)
                    .await
                    .map_err(|e| rpc_error(&Error::Backend(e)))?;
                scanned(current.sync(), &root, "an append").await;
                ok(Ack {})
            }
        })
        .method(proto::DELETE_FILE, move |ctx| {
            let current = Arc::clone(&delete);
            async move {
                let p: proto::PathParams = params(&ctx)?;
                let (root, backend) = current.host().current().await.map_err(|e| rpc_error(&e))?;
                backend
                    .delete_file(&p.path)
                    .await
                    .map_err(|e| rpc_error(&Error::Backend(e)))?;
                scanned(current.sync(), &root, "a delete").await;
                ok(Ack {})
            }
        })
        .method(proto::LIST_DIR, move |ctx| {
            let current = Arc::clone(&list);
            async move {
                let p: proto::PathParams = params(&ctx)?;
                let backend = current.host().backend().await.map_err(|e| rpc_error(&e))?;
                let entries = backend
                    .list_dir(&p.path)
                    .await
                    .map_err(|e| rpc_error(&Error::Backend(e)))?
                    .into_iter()
                    .map(|(path, is_dir)| proto::DirEntry { path, is_dir })
                    .collect();
                ok(proto::ListDirResult { entries })
            }
        })
        .method(proto::SEARCH, move |ctx| {
            let current = Arc::clone(&search);
            async move {
                let p: proto::SearchParams = params(&ctx)?;
                let backend = current.host().backend().await.map_err(|e| rpc_error(&e))?;
                let hits = backend
                    .search(&p.query, p.limit, p.mode)
                    .await
                    .map_err(|e| rpc_error(&Error::Backend(e)))?;
                ok(proto::SearchResult { hits })
            }
        })
        .method(proto::REINDEX, move |_| {
            let current = Arc::clone(&reindex);
            async move {
                let backend = current.host().backend().await.map_err(|e| rpc_error(&e))?;
                let started = std::time::Instant::now();
                let summary = backend.sync().await;
                crate::instrument::reindexed(started, summary.is_ok());
                let summary = summary.map_err(|e| rpc_error(&Error::Backend(e)))?;
                ok(proto::ReindexResult {
                    upserted: summary.upserted,
                    removed: summary.removed,
                })
            }
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use sapphire_backend::protocol as proto;
    use sapphire_ipc::{Client, ClientInfo, Connection, ManagedBy, ServerInfo, serve};
    use sapphire_workspace::{AppContext, AppKind};
    use std::ffi::OsString;
    use std::path::PathBuf;

    use crate::test_support;

    static CTX: AppContext = AppContext::new("sapphire-handlertest");

    /// The env vars `init_ctx` writes, in the order the guard restores them.
    const DIR_VARS: [&str; 3] = [
        "SAPPHIRE_HANDLERTEST_CACHE_DIR",
        "SAPPHIRE_HANDLERTEST_DATA_DIR",
        "SAPPHIRE_HANDLERTEST_CONFIG_DIR",
    ];

    /// Point the context's directories at `tmp` and restore the previous values (present
    /// or absent) when dropped — including while unwinding from a panic. Without the
    /// unconditional restore, a panicking assertion would leave the variables pointing at
    /// a temp directory the test then deletes, and the context of a later test would
    /// resolve into the void.
    struct EnvGuard {
        previous: [Option<OsString>; 3],
        _lock: std::sync::MutexGuard<'static, ()>,
    }

    impl EnvGuard {
        /// Write the three directory vars while holding the environment lock.
        fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
            let previous = DIR_VARS.map(std::env::var_os);
            let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
            // SAFETY (via `test_support::set`): `lock` serialises every read and write of
            // the process environment in this test binary — the `host` module's tests
            // share the same lock — and it is held until `drop` has restored the old
            // values.
            for (name, dir) in DIR_VARS.iter().zip(dirs) {
                test_support::set(name, &dir);
            }
            EnvGuard {
                previous,
                _lock: lock,
            }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            // SAFETY: `self._lock` still serialises the environment; it is dropped only
            // after this method returns.
            for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
                match previous.take() {
                    Some(value) => unsafe { std::env::set_var(name, value) },
                    None => test_support::remove(name),
                }
            }
        }
    }

    /// Point the context's directories at a scratch location. The static context is
    /// first-writer-wins, so whichever test initialises it first fixes the directories
    /// for the whole binary; every test therefore holds the env lock for its entire body
    /// (see [`Fixture`]).
    fn init_ctx(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
        let guard = EnvGuard::set(lock, tmp);
        CTX.init(AppKind::Server);
        guard
    }

    /// Everything one test needs, held for the test's whole body.
    ///
    /// `_tmp` is declared before `_env` so the scratch tree is deleted while the
    /// environment lock is still held: a sibling test that wakes on the lock must never
    /// observe the tree mid-deletion, nor env vars pointing at a deleted directory.
    struct Fixture {
        _tmp: tempfile::TempDir,
        _env: EnvGuard,
        ws: PathBuf,
        client: Client,
        current: Arc<Current>,
    }

    /// A server over an in-process connection, plus a workspace root to use.
    ///
    /// The caller must keep the fixture (and with it the environment lock) alive for the
    /// whole test: the static [`CTX`] is first-writer-wins, so while one test runs, every
    /// other test that would re-point the context's directories must wait.
    async fn fixture() -> Fixture {
        fixture_selecting(true).await
    }

    async fn fixture_selecting(select: bool) -> Fixture {
        let lock = test_support::lock();
        let tmp = tempfile::tempdir().unwrap();
        let _env = init_ctx(lock, tmp.path());
        let root = tmp.path().join("ws");
        std::fs::create_dir_all(root.join(".sapphire-handlertest")).unwrap();
        let ws = root.canonicalize().unwrap();

        let current = Arc::new(Current::new(
            &CTX,
            Arc::new(crate::host::WorkspaceHost::new(&CTX)),
            None,
            crate::selection::SelectionFile::at(tmp.path().join("workspace.toml")),
        ));
        if select {
            current.select(&ws).await.unwrap();
        }
        // `fs.*` and `journal.*` beside `workspace.*`, as the server mounts them.
        let router = Arc::new(crate::fs_methods::fs_methods(
            Arc::clone(&current),
            workspace_router(Arc::clone(&current)),
        ));
        let (client_conn, server_conn) = Connection::pair();
        tokio::spawn(async move {
            let info = ServerInfo {
                version: "0.0.0".into(),
                api: sapphire_backend::protocol::API_VERSION,
                app_api: None,
                pid: std::process::id(),
                managed_by: ManagedBy::Spawned,
            };
            let _ = serve(server_conn, router, "sapphire-handlertest", info).await;
        });
        let client_info = ClientInfo {
            kind: "test".into(),
            version: "0.0.0".into(),
            api: sapphire_backend::protocol::API_VERSION,
            app_api: None,
            pid: std::process::id(),
        };
        let (client, _) = Client::handshake(client_conn, "sapphire-handlertest", client_info)
            .await
            .unwrap();
        Fixture {
            _tmp: tmp,
            _env,
            ws,
            client,
            current,
        }
    }

    #[tokio::test]
    async fn a_file_written_through_the_server_can_be_read_back() {
        let f = fixture().await;
        let _: proto::Ack = f
            .client
            .call(
                proto::WRITE_FILE,
                proto::ContentParams {
                    path: PathBuf::from("a.md"),
                    content: "# hello".into(),
                },
            )
            .await
            .unwrap();

        let read: proto::ReadResult = f
            .client
            .call(
                proto::READ_FILE,
                proto::PathParams {
                    path: PathBuf::from("a.md"),
                },
            )
            .await
            .unwrap();
        assert_eq!(read.content, "# hello");
    }

    #[tokio::test]
    async fn appending_adds_to_the_file() {
        let f = fixture().await;
        let write = proto::ContentParams {
            path: PathBuf::from("a.md"),
            content: "one\n".into(),
        };
        let _: proto::Ack = f.client.call(proto::WRITE_FILE, write).await.unwrap();
        let append = proto::ContentParams {
            path: PathBuf::from("a.md"),
            content: "two\n".into(),
        };
        let _: proto::Ack = f.client.call(proto::APPEND_FILE, append).await.unwrap();

        let read: proto::ReadResult = f
            .client
            .call(
                proto::READ_FILE,
                proto::PathParams {
                    path: PathBuf::from("a.md"),
                },
            )
            .await
            .unwrap();
        assert_eq!(read.content, "one\ntwo\n");
    }

    #[tokio::test]
    async fn a_deleted_file_is_gone() {
        let f = fixture().await;
        let _: proto::Ack = f
            .client
            .call(
                proto::WRITE_FILE,
                proto::ContentParams {
                    path: PathBuf::from("a.md"),
                    content: "x".into(),
                },
            )
            .await
            .unwrap();
        let _: proto::Ack = f
            .client
            .call(
                proto::DELETE_FILE,
                proto::PathParams {
                    path: PathBuf::from("a.md"),
                },
            )
            .await
            .unwrap();

        let err = f
            .client
            .call::<_, proto::ReadResult>(
                proto::READ_FILE,
                proto::PathParams {
                    path: PathBuf::from("a.md"),
                },
            )
            .await
            .unwrap_err();
        assert!(matches!(err, sapphire_ipc::Error::Rpc(_)), "got {err:?}");
    }

    #[tokio::test]
    async fn a_directory_listing_separates_files_from_directories() {
        let f = fixture().await;
        std::fs::create_dir_all(f.ws.join("notes")).unwrap();
        let _: proto::Ack = f
            .client
            .call(
                proto::WRITE_FILE,
                proto::ContentParams {
                    path: PathBuf::from("a.md"),
                    content: "x".into(),
                },
            )
            .await
            .unwrap();

        let listing: proto::ListDirResult = f
            .client
            .call(
                proto::LIST_DIR,
                proto::PathParams {
                    path: PathBuf::from("."),
                },
            )
            .await
            .unwrap();
        assert!(
            listing
                .entries
                .iter()
                .any(|e| e.is_dir && e.path.ends_with("notes")),
            "{:?}",
            listing.entries
        );
        assert!(
            listing
                .entries
                .iter()
                .any(|e| !e.is_dir && e.path.ends_with("a.md")),
            "{:?}",
            listing.entries
        );
    }

    #[tokio::test]
    async fn a_written_file_is_searchable() {
        let f = fixture().await;
        let _: proto::Ack = f
            .client
            .call(
                proto::WRITE_FILE,
                proto::ContentParams {
                    path: PathBuf::from("a.md"),
                    content: "the quick brown fox".into(),
                },
            )
            .await
            .unwrap();

        let hits: proto::SearchResult = f
            .client
            .call(
                proto::SEARCH,
                proto::SearchParams {
                    query: "brown".into(),
                    limit: 10,
                    mode: sapphire_backend::SearchMode::Fts,
                },
            )
            .await
            .unwrap();
        assert!(
            hits.hits.iter().any(|h| h.path.ends_with("a.md")),
            "{:?}",
            hits.hits
        );
    }

    #[tokio::test]
    async fn reindexing_reports_what_it_found() {
        let f = fixture().await;
        std::fs::write(f.ws.join("outside.md"), "written behind the server's back").unwrap();

        let report: proto::ReindexResult = f
            .client
            .call(proto::REINDEX, serde_json::json!({}))
            .await
            .unwrap();
        assert!(report.upserted >= 1, "{report:?}");
    }

    #[tokio::test]
    async fn a_path_escaping_the_workspace_is_an_invalid_parameter() {
        let f = fixture().await;
        let err = f
            .client
            .call::<_, proto::ReadResult>(
                proto::READ_FILE,
                proto::PathParams {
                    path: PathBuf::from("../../etc/passwd"),
                },
            )
            .await
            .unwrap_err();
        match err {
            sapphire_ipc::Error::Rpc(e) => {
                assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS, "{}", e.message);
            }
            other => panic!("got {other:?}"),
        }
    }

    #[tokio::test]
    async fn without_a_workspace_every_call_is_an_invalid_parameter() {
        let f = fixture_selecting(false).await;
        let err = f
            .client
            .call::<_, proto::ReadResult>(
                proto::READ_FILE,
                proto::PathParams {
                    path: PathBuf::from("a.md"),
                },
            )
            .await
            .unwrap_err();
        match err {
            sapphire_ipc::Error::Rpc(e) => {
                assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS, "{}", e.message);
            }
            other => panic!("got {other:?}"),
        }
    }

    #[tokio::test]
    async fn a_malformed_parameter_object_is_an_invalid_parameter() {
        let f = fixture().await;
        let err = f
            .client
            .call::<_, proto::ReadResult>(proto::READ_FILE, serde_json::json!({ "ws": 42 }))
            .await
            .unwrap_err();
        match err {
            sapphire_ipc::Error::Rpc(e) => {
                assert_eq!(e.code, sapphire_ipc::codes::INVALID_PARAMS);
            }
            other => panic!("got {other:?}"),
        }
    }

    /// The names `fs.list` answers at `path`.
    async fn listed(client: &Client, path: &str) -> Vec<String> {
        let listing: Value = client
            .call("fs.list", serde_json::json!({ "path": path }))
            .await
            .unwrap();
        listing["entries"]
            .as_array()
            .unwrap()
            .iter()
            .map(|e| e["name"].as_str().unwrap().to_owned())
            .collect()
    }

    /// Applies `ops` as one batch of `origin`, answering its done and skipped counts.
    async fn apply(client: &Client, origin: &str, ops: Value) -> (u64, u64) {
        let records: Value = client
            .call(
                "fs.apply",
                serde_json::json!({ "ops": ops, "origin": origin, "label": "test" }),
            )
            .await
            .unwrap();
        let summary = &records["summary"];
        (
            summary["done"].as_u64().unwrap(),
            summary["skipped"].as_u64().unwrap(),
        )
    }

    #[tokio::test]
    async fn the_explorer_lists_the_workspace_without_its_dot_names() {
        let f = fixture().await;
        std::fs::write(f.ws.join("a.md"), "a").unwrap();
        std::fs::create_dir(f.ws.join("notes")).unwrap();
        let version: Value = f
            .client
            .call("fs.version", serde_json::json!({}))
            .await
            .unwrap();
        assert_eq!(version["api"], corundum_framework_fs::api::API_VERSION);
        assert_eq!(listed(&f.client, "").await, ["a.md", "notes"]);
    }

    #[tokio::test]
    async fn a_move_is_undone_by_its_origin() {
        let f = fixture().await;
        std::fs::write(f.ws.join("a.md"), "a").unwrap();
        std::fs::create_dir(f.ws.join("notes")).unwrap();
        let moved = apply(
            &f.client,
            "gui:1",
            serde_json::json!([{ "kind": "fs.move", "from": "a.md", "to": "notes/a.md" }]),
        )
        .await;
        assert_eq!(moved, (1, 0));
        assert!(f.ws.join("notes/a.md").exists());

        let _: Value = f
            .client
            .call("journal.undo", serde_json::json!({ "origin": "gui:1" }))
            .await
            .unwrap();
        assert!(f.ws.join("a.md").exists());
        assert!(!f.ws.join("notes/a.md").exists());
    }

    #[tokio::test]
    async fn the_trash_is_kept_in_the_unsynced_folder() {
        let f = fixture().await;
        std::fs::write(f.ws.join("a.md"), "a").unwrap();
        let trashed = apply(
            &f.client,
            "gui:1",
            serde_json::json!([{ "kind": "fs.trash", "path": "a.md" }]),
        )
        .await;
        assert_eq!(trashed, (1, 0));
        assert!(!f.ws.join("a.md").exists());
        let trash = f.ws.join(crate::fs_methods::OWN_FOLDER).join("trash");
        let ids: Vec<_> = std::fs::read_dir(&trash).unwrap().collect();
        assert_eq!(ids.len(), 1);
        assert!(ids[0].as_ref().unwrap().path().join("a.md").exists());
        // Hidden from the explorer, as every dot-name is.
        assert!(listed(&f.client, "").await.is_empty());
    }

    #[tokio::test]
    async fn another_workspace_is_served_with_an_empty_history() {
        let f = fixture().await;
        std::fs::write(f.ws.join("a.md"), "a").unwrap();
        apply(
            &f.client,
            "gui:1",
            serde_json::json!([{ "kind": "fs.move", "from": "a.md", "to": "b.md" }]),
        )
        .await;

        let other = f.ws.parent().unwrap().join("other");
        std::fs::create_dir_all(other.join(".sapphire-handlertest")).unwrap();
        std::fs::write(other.join("c.md"), "c").unwrap();
        f.current.select(&other).await.unwrap();

        assert_eq!(listed(&f.client, "").await, ["c.md"]);
        let err = f
            .client
            .call::<_, Value>("journal.undo", serde_json::json!({ "origin": "gui:1" }))
            .await
            .unwrap_err();
        let sapphire_ipc::Error::Rpc(err) = err else {
            panic!("not an RPC error: {err}");
        };
        assert_eq!(err.code, corundum_framework_fs::api::codes::NOTHING_TO_UNDO);
        assert!(f.ws.join("b.md").exists());
    }

    #[tokio::test]
    async fn without_a_workspace_the_explorer_is_refused() {
        let f = fixture_selecting(false).await;
        let err = f
            .client
            .call::<_, Value>("fs.list", serde_json::json!({ "path": "" }))
            .await
            .unwrap_err();
        assert!(matches!(err, sapphire_ipc::Error::Rpc(_)), "{err}");
    }
}