Skip to main content

sapphire_framework_server/
current.rs

1//! The one workspace a server serves, and what changing it does (#215).
2//!
3//! [`WorkspaceHost`] holds the open workspace; this decides which one it is. Selecting
4//! another closes the current one — its index, its replica, its live sessions — and opens
5//! the new one; sync follows the workspace that has it (decision 3 of the spec). Every
6//! `workspace.*` and `sync.*` method acts through here.
7
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10
11use grain_id::GrainId;
12use sapphire_backend::WorkspaceBackend;
13use sapphire_backend::protocol as proto;
14use sapphire_ipc::{Router, RpcError};
15use sapphire_workspace::{AppContext, Workspace};
16use tokio::sync::Mutex as AsyncMutex;
17
18use crate::error::{Error, Result};
19use crate::handlers::rpc_error;
20use crate::host::WorkspaceHost;
21use crate::selection::{Selection, SelectionFile, slug};
22use crate::settings::Settings;
23use crate::sync::{SYNC_ID_FILE, SyncRuntime};
24
25/// How long a move or a delete waits for the workspace's replica store to close.
26const RELEASE_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
27
28/// The server's current workspace.
29pub struct Current {
30    ctx: &'static AppContext,
31    host: Arc<WorkspaceHost>,
32    sync: Option<Arc<SyncRuntime>>,
33    file: SelectionFile,
34    /// The settings whose workspace scope is the selected workspace's file, read again
35    /// whenever the selection changes.
36    settings: Option<Settings>,
37    /// One selection, and one sync switch, at a time.
38    switching: AsyncMutex<()>,
39}
40
41impl std::fmt::Debug for Current {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        f.debug_struct("Current")
44            .field("root", &self.host.root())
45            .finish()
46    }
47}
48
49impl Current {
50    /// The current workspace of `host`, synced by `sync` if there is one, remembered in
51    /// `file`.
52    pub fn new(
53        ctx: &'static AppContext,
54        host: Arc<WorkspaceHost>,
55        sync: Option<Arc<SyncRuntime>>,
56        file: SelectionFile,
57    ) -> Current {
58        Current {
59            ctx,
60            host,
61            sync,
62            file,
63            settings: None,
64            switching: AsyncMutex::new(()),
65        }
66    }
67
68    /// Read `settings` again whenever the selected workspace changes, so its workspace
69    /// keys follow the selection.
70    pub(crate) fn with_settings(mut self, settings: Settings) -> Current {
71        self.settings = Some(settings);
72        self
73    }
74
75    /// The host holding the open workspace.
76    pub fn host(&self) -> &Arc<WorkspaceHost> {
77        &self.host
78    }
79
80    /// The sync runtime, when this server syncs.
81    pub fn sync(&self) -> Option<&Arc<SyncRuntime>> {
82        self.sync.as_ref()
83    }
84
85    /// The current workspace's root.
86    pub fn root(&self) -> Option<PathBuf> {
87        self.host.root()
88    }
89
90    /// Make the workspace at `dir` current. Sync is on for it when it has a sync id.
91    pub async fn select(&self, dir: &Path) -> Result<proto::CurrentWorkspace> {
92        let root = resolve(dir)?;
93        let sync = has_sync_id(self.ctx, &root);
94        self.switch(&root, sync, false).await?;
95        self.describe().await.ok_or(Error::NoWorkspace)
96    }
97
98    /// Create this app's workspace at `dir` — its marker, idempotently — and make it
99    /// current.
100    pub async fn init(&self, dir: &Path) -> Result<proto::WorkspaceInitResult> {
101        let result = init_workspace(self.ctx, dir)?;
102        let sync = has_sync_id(self.ctx, &result.root);
103        self.switch(&result.root, sync, false).await?;
104        Ok(result)
105    }
106
107    /// Place the workgroup workspace `selector` at `dir`, make it current and sync it.
108    ///
109    /// `dir` needs no marker: placing makes one. One that an older `workspace.init` made
110    /// first may hold a `config.toml` with nothing but the `[workspace]` registry, which
111    /// would meet the workspace's own `config.toml` as a conflict on the first sync and win
112    /// (#253), so a directory mapped for the first time loses it.
113    pub async fn map(&self, selector: &str, dir: &Path) -> Result<GrainId> {
114        let runtime = self.runtime()?;
115        let first = !has_sync_id(self.ctx, &resolve(dir)?);
116        let root = runtime.place(selector, dir).await?;
117        if first {
118            let config = Workspace::from_root(self.ctx, &root)?.config_path();
119            if let Err(err) = drop_bare_registry(&config) {
120                tracing::warn!(config = %config.display(), "could not clear the registry-only config: {err}");
121            }
122        }
123        self.switch(&root, false, false).await?;
124        self.enable_sync().await
125    }
126
127    /// Move the current workspace's folder to `dir`, which must not exist yet, and keep
128    /// serving it from there, syncing as before.
129    ///
130    /// The replica's state moves with it, so sync carries on as the same replica rather
131    /// than meeting its own files as strangers. The search index does not — it records
132    /// absolute paths — and is rebuilt in the background.
133    pub async fn relocate(&self, dir: &Path) -> Result<proto::CurrentWorkspace> {
134        {
135            let _one = self.switching.lock().await;
136            let from = self.root().ok_or(Error::NoWorkspace)?;
137            let to = destination(dir)?;
138            if to.starts_with(&from) {
139                return Err(Error::Config(format!(
140                    "cannot move {} into itself",
141                    from.display()
142                )));
143            }
144            // Read before the move: the cache is keyed by the root's path.
145            let from_cache = Workspace::from_root(self.ctx, &from)?.cache_dir();
146            let synced = self.let_go(&from).await?;
147            self.host.close();
148            if let Err(err) = std::fs::rename(&from, &to) {
149                // Back where it was, as it was.
150                self.reopen(&from, synced).await;
151                return Err(match err.kind() {
152                    std::io::ErrorKind::CrossesDevices => Error::Config(format!(
153                        "cannot move {} to another drive ({}); move it there yourself, then open it",
154                        from.display(),
155                        to.display()
156                    )),
157                    _ => Error::Io(std::io::Error::new(
158                        err.kind(),
159                        format!(
160                            "could not move {} to {}: {err}",
161                            from.display(),
162                            to.display()
163                        ),
164                    )),
165                });
166            }
167
168            let workspace = Workspace::from_root(self.ctx, &to)?;
169            carry_cache(&from_cache, &workspace.cache_dir(), &to);
170            self.reopen(&to, synced).await;
171        }
172        // Outside the switch lock: a reindex walks every file, and a switch must not wait
173        // on it. One that lands first finds this workspace no longer current, and stops.
174        if let Ok(backend) = self.host.backend().await {
175            tokio::spawn(async move {
176                let started = std::time::Instant::now();
177                let result = backend.sync().await;
178                crate::instrument::reindexed(started, result.is_ok());
179                if let Err(err) = result {
180                    tracing::warn!("re-indexing the moved workspace: {err}");
181                }
182            });
183        }
184        self.describe().await.ok_or(Error::NoWorkspace)
185    }
186
187    /// Stop serving the current workspace; with `delete`, delete its folder and its cache
188    /// too. Sync stops for this host only: the workgroup and the other devices keep it.
189    pub async fn remove(&self, delete: bool) -> Result<()> {
190        let _one = self.switching.lock().await;
191        let root = self.root().ok_or(Error::NoWorkspace)?;
192        // Read before anything goes: the cache is keyed by the root's path.
193        let cache = Workspace::from_root(self.ctx, &root)
194            .ok()
195            .map(|w| w.cache_dir());
196        // Stopped first, so the watcher never reports the files going as deletions to
197        // replicate; and, before a delete, closed, so its store can go too.
198        if delete {
199            self.let_go(&root).await?;
200        } else if let Some(runtime) = &self.sync
201            && let Err(err) = runtime.disable(&root).await
202        {
203            tracing::warn!(root = %root.display(), "stopping sync before the removal: {err}");
204        }
205        self.host.close();
206        self.file.clear()?;
207        self.refresh_settings();
208        if delete {
209            match std::fs::remove_dir_all(&root) {
210                Ok(()) => {}
211                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
212                Err(e) => {
213                    return Err(Error::Io(std::io::Error::new(
214                        e.kind(),
215                        format!("could not delete {}: {e}", root.display()),
216                    )));
217                }
218            }
219            if let Some(cache) = cache
220                && let Err(err) = std::fs::remove_dir_all(&cache)
221                && err.kind() != std::io::ErrorKind::NotFound
222            {
223                tracing::warn!(cache = %cache.display(), "could not delete the cache: {err}");
224            }
225        }
226        Ok(())
227    }
228
229    /// Stop syncing `root` and close its replica store, before its folder moves or goes,
230    /// returning whether it was synced. A store still in use is the error, and leaves the
231    /// workspace syncing as before.
232    async fn let_go(&self, root: &Path) -> Result<bool> {
233        let Some(runtime) = &self.sync else {
234            return Ok(false);
235        };
236        if !runtime.roots().await.iter().any(|r| r == root) {
237            return Ok(false);
238        }
239        if let Err(err) = runtime.release(root, RELEASE_LIMIT).await {
240            if let Err(again) = runtime.enable(root).await {
241                tracing::warn!(root = %root.display(), "could not restart sync: {again}");
242            }
243            return Err(err);
244        }
245        Ok(true)
246    }
247
248    /// Open `root` again after [`relocate`](Self::relocate) closed it, and sync it again
249    /// when it was. Failures leave it selected, unopened, the way a restore does.
250    async fn reopen(&self, root: &Path, sync: bool) {
251        if let Err(err) = self.host.select(root, true).await {
252            tracing::warn!(root = %root.display(), "could not reopen the workspace: {err}");
253        }
254        if sync
255            && let Some(runtime) = &self.sync
256            && let Err(err) = runtime.enable(root).await
257        {
258            tracing::warn!(root = %root.display(), "could not restart sync: {err}");
259        }
260        self.remember(root, sync);
261    }
262
263    /// Start syncing the current workspace, and remember that.
264    pub async fn enable_sync(&self) -> Result<GrainId> {
265        let runtime = self.runtime()?;
266        let _one = self.switching.lock().await;
267        let root = self.root().ok_or(Error::NoWorkspace)?;
268        let id = match runtime.enable(&root).await {
269            Ok(id) => id,
270            // The runtime enables it once the bridge is back, so remember it as synced: the
271            // next start tries again too (#244).
272            Err(err @ Error::BridgeDisconnected) => {
273                self.remember(&root, true);
274                return Err(err);
275            }
276            Err(err) => return Err(err),
277        };
278        self.remember(&root, true);
279        Ok(id)
280    }
281
282    /// Stop syncing the current workspace, and remember that.
283    pub async fn disable_sync(&self) -> Result<()> {
284        let runtime = self.runtime()?;
285        let _one = self.switching.lock().await;
286        let root = self.root().ok_or(Error::NoWorkspace)?;
287        runtime.disable(&root).await?;
288        self.remember(&root, false);
289        Ok(())
290    }
291
292    /// The current workspace's sync state; not synced when there is none.
293    pub async fn status(&self) -> proto::SyncStatusResult {
294        match &self.sync {
295            // An empty root names nothing, which the runtime reports as not synced, with
296            // the bridge's view all the same.
297            Some(runtime) => runtime
298                .status(&self.root().unwrap_or_default())
299                .await
300                .into(),
301            None => proto::SyncStatusResult::not_synced(),
302        }
303    }
304
305    /// The current workspace as `workspace.current` reports it.
306    pub async fn describe(&self) -> Option<proto::CurrentWorkspace> {
307        let root = self.root()?;
308        let marker = root.join(format!(".{}", self.ctx.app_name));
309        // Read, never minted: describing must not create a sync id nobody asked for.
310        let workspace_id = std::fs::read_to_string(marker.join(SYNC_ID_FILE))
311            .ok()
312            .and_then(|s| s.trim().parse().ok());
313        let sync = match &self.sync {
314            Some(runtime) => runtime.status(&root).await.into(),
315            None => proto::SyncStatusResult::not_synced(),
316        };
317        Some(proto::CurrentWorkspace {
318            reachable: marker.is_dir(),
319            root,
320            workspace_id,
321            sync,
322        })
323    }
324
325    /// Come back to the workspace `workspace.toml` names. A root that is gone stays
326    /// selected, unopened, so `workspace.current` can say so.
327    ///
328    /// The open happens now, so the first client finds the workspace; sync, which talks to
329    /// the bridge and may dial peers, starts on the returned task.
330    pub(crate) async fn restore(self: &Arc<Self>) -> Option<tokio::task::JoinHandle<()>> {
331        let selection = match self.file.load(self.ctx.app_name) {
332            Ok(Some(selection)) => selection,
333            Ok(None) => return None,
334            Err(err) => {
335                tracing::warn!("could not read the selected workspace: {err}");
336                return None;
337            }
338        };
339        {
340            let _one = self.switching.lock().await;
341            if let Err(err) = self.host.select(&selection.root, true).await {
342                tracing::warn!(root = %selection.root.display(), "could not restore the workspace: {err}");
343                return None;
344            }
345            self.refresh_settings();
346        }
347        if !selection.sync {
348            return None;
349        }
350        let runtime = self.sync.clone()?;
351        let current = Arc::clone(self);
352        Some(tokio::spawn(async move {
353            // A switch that landed first wins: sync starts only for a workspace still
354            // current.
355            let _one = current.switching.lock().await;
356            if current.root().as_deref() != Some(&selection.root) {
357                return;
358            }
359            if let Err(err) = runtime.enable(&selection.root).await {
360                tracing::warn!(root = %selection.root.display(), "could not restore sync: {err}");
361            }
362        }))
363    }
364
365    /// Make `root` current; sync it when `sync`. The previous workspace stops syncing.
366    ///
367    /// The open comes first: a workspace that does not open leaves the previous one current,
368    /// syncing as before. `restoring` keeps a root that is gone selected, unopened.
369    async fn switch(&self, root: &Path, sync: bool, restoring: bool) -> Result<()> {
370        let _one = self.switching.lock().await;
371        let previous = self.root();
372        self.host.select(root, restoring).await?;
373        if let Some(runtime) = &self.sync {
374            if let Some(previous) = previous.filter(|p| p != root)
375                && let Err(err) = runtime.disable(&previous).await
376            {
377                tracing::warn!(root = %previous.display(), "stopping sync of the previous workspace: {err}");
378            }
379            if sync && let Err(err) = runtime.enable(root).await {
380                // Selected all the same: the workspace works without sync, and the status
381                // carries the failure.
382                tracing::warn!(root = %root.display(), "could not start sync: {err}");
383            }
384        }
385        self.remember(root, sync);
386        Ok(())
387    }
388
389    fn remember(&self, root: &Path, sync: bool) {
390        let selection = Selection {
391            root: root.to_owned(),
392            sync,
393        };
394        if let Err(err) = self.file.save(&selection) {
395            tracing::warn!(root = %root.display(), "could not record the selected workspace: {err}");
396        }
397        self.refresh_settings();
398    }
399
400    /// Read the settings again, the workspace scope now the selected workspace's file.
401    fn refresh_settings(&self) {
402        if let Some(settings) = &self.settings
403            && settings.refresh().is_err()
404        {
405            // The error may quote the file; the selection itself succeeded.
406            tracing::warn!("could not read the settings of the selected workspace");
407        }
408    }
409
410    fn runtime(&self) -> Result<&Arc<SyncRuntime>> {
411        self.sync
412            .as_ref()
413            .ok_or_else(|| Error::Config("this server does not sync".to_owned()))
414    }
415}
416
417/// Whether `root` has synced before: it carries a sync id.
418fn has_sync_id(ctx: &AppContext, root: &Path) -> bool {
419    root.join(format!(".{}", ctx.app_name))
420        .join(SYNC_ID_FILE)
421        .is_file()
422}
423
424/// `dir` as a canonical root. A relative `dir` is resolved against the server's cwd.
425fn resolve(dir: &Path) -> Result<PathBuf> {
426    std::env::current_dir()
427        .map_err(Error::Io)?
428        .join(dir)
429        .canonicalize()
430        .map_err(Error::Io)
431}
432
433/// Where a move to `dir` puts the root: `dir` made absolute, through its parent's
434/// canonical path, since `dir` itself must not exist yet.
435fn destination(dir: &Path) -> Result<PathBuf> {
436    let dir = std::env::current_dir().map_err(Error::Io)?.join(dir);
437    if dir.exists() {
438        return Err(Error::Config(format!(
439            "{} already exists; choose a new folder name",
440            dir.display()
441        )));
442    }
443    let (Some(parent), Some(name)) = (dir.parent(), dir.file_name()) else {
444        return Err(Error::Config(format!(
445            "{} cannot be a workspace root",
446            dir.display()
447        )));
448    };
449    Ok(parent.canonicalize().map_err(Error::Io)?.join(name))
450}
451
452/// Carry a moved workspace's cache from `from` to `to`, its new key: the replica's state,
453/// rebased onto `root`. The rest — the search index, which records absolute paths — is
454/// dropped, to be rebuilt.
455///
456/// Best-effort: a replica that does not come along is a replica that starts over, and
457/// syncing reports why.
458fn carry_cache(from: &Path, to: &Path, root: &Path) {
459    let sync_from = from.join("sync");
460    if sync_from.is_dir() {
461        let sync_to = to.join("sync");
462        let moved =
463            std::fs::create_dir_all(to).and_then(|()| std::fs::rename(&sync_from, &sync_to));
464        match moved {
465            Ok(()) => {
466                let store = sync_to.join("sync.redb");
467                if store.is_file()
468                    && let Err(err) =
469                        sapphire_sync::ReplicaStore::relocate(&store, &root.to_string_lossy())
470                {
471                    tracing::warn!(store = %store.display(), "could not rebase the replica: {err}");
472                }
473            }
474            Err(err) => {
475                tracing::warn!(cache = %from.display(), "could not carry the replica over: {err}");
476            }
477        }
478    }
479    if let Err(err) = std::fs::remove_dir_all(from)
480        && err.kind() != std::io::ErrorKind::NotFound
481    {
482        tracing::warn!(cache = %from.display(), "could not delete the old cache: {err}");
483    }
484}
485
486/// Add `workspace.init`, `workspace.select`, `workspace.current`, `workspace.move` and
487/// `workspace.remove` to `router`.
488pub(crate) fn current_methods(current: Arc<Current>, router: Router) -> Router {
489    let init = Arc::clone(&current);
490    let select = Arc::clone(&current);
491    let relocate = Arc::clone(&current);
492    let remove = Arc::clone(&current);
493    router
494        .method(proto::WORKSPACE_MOVE, move |req| {
495            let current = Arc::clone(&relocate);
496            async move {
497                let p: proto::WorkspaceMoveParams = serde_json::from_value(req.params)
498                    .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
499                let result = current.relocate(&p.dir).await.map_err(|e| rpc_error(&e))?;
500                serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
501            }
502        })
503        .method(proto::WORKSPACE_REMOVE, move |req| {
504            let current = Arc::clone(&remove);
505            async move {
506                let p: proto::WorkspaceRemoveParams = serde_json::from_value(req.params)
507                    .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
508                current.remove(p.delete).await.map_err(|e| rpc_error(&e))?;
509                serde_json::to_value(proto::Ack {}).map_err(|e| RpcError::internal(e.to_string()))
510            }
511        })
512        .method(proto::WORKSPACE_INIT, move |req| {
513            let current = Arc::clone(&init);
514            async move {
515                let p: proto::WorkspaceInitParams = serde_json::from_value(req.params)
516                    .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
517                let result = current.init(&p.dir).await.map_err(|e| rpc_error(&e))?;
518                serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
519            }
520        })
521        .method(proto::WORKSPACE_SELECT, move |req| {
522            let current = Arc::clone(&select);
523            async move {
524                let p: proto::WorkspaceSelectParams = serde_json::from_value(req.params)
525                    .map_err(|e| RpcError::invalid_params(format!("bad parameters: {e}")))?;
526                let result = current.select(&p.dir).await.map_err(|e| rpc_error(&e))?;
527                serde_json::to_value(result).map_err(|e| RpcError::internal(e.to_string()))
528            }
529        })
530        .method(proto::WORKSPACE_CURRENT, move |_| {
531            let current = Arc::clone(&current);
532            async move {
533                let workspace = current.describe().await;
534                serde_json::to_value(proto::WorkspaceCurrentResult { workspace })
535                    .map_err(|e| RpcError::internal(e.to_string()))
536            }
537        })
538}
539
540/// Create the workspace home at `dir`: the marker directory, idempotently. The sync id is
541/// `sync.enable` / `sync.map`'s to mint, not this one's.
542///
543/// A relative `dir` is resolved against the server's cwd. `created` is `false` when the
544/// marker was already there.
545///
546/// No `[workspace]` registry is written into the marker's `config.toml` any more (#217):
547/// it keyed the apps' `--workspace` selectors, which went with the server serving one
548/// workspace, and a `config.toml` holding only it lost the application's settings on the
549/// first sync (#253).
550fn init_workspace(ctx: &'static AppContext, dir: &Path) -> Result<proto::WorkspaceInitResult> {
551    let root = resolve(dir)?;
552    let marker = root.join(format!(".{}", ctx.app_name));
553    let created = !marker.is_dir();
554    if created {
555        std::fs::create_dir(&marker).map_err(Error::Io)?;
556    }
557
558    Ok(proto::WorkspaceInitResult {
559        workspace_id: slug(&root),
560        root,
561        created,
562    })
563}
564
565/// Delete the marker's `config.toml` when it holds the `[workspace]` registry an older
566/// `workspace.init` wrote, and nothing else.
567fn drop_bare_registry(path: &Path) -> Result<()> {
568    let config = read_config(path)?;
569    if config.len() == 1 && config.contains_key("workspace") {
570        std::fs::remove_file(path).map_err(Error::Io)?;
571    }
572    Ok(())
573}
574
575/// The marker's `config.toml` as a table; an empty one when there is no file.
576fn read_config(path: &Path) -> Result<toml::Table> {
577    match std::fs::read_to_string(path) {
578        Ok(text) => text.parse().map_err(|e: toml::de::Error| {
579            Error::Config(format!(
580                "{}: {}",
581                path.display(),
582                sapphire_framework_settings::describe_toml_error(&text, e.span(), e.message())
583            ))
584        }),
585        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(toml::Table::new()),
586        Err(e) => Err(Error::Io(e)),
587    }
588}
589
590#[cfg(test)]
591mod tests {
592    use super::*;
593
594    const REGISTRY_ONLY: &str = "[workspace.ledger]\npath = \"/home/me/ledger\"\n";
595
596    #[test]
597    fn only_a_registry_only_config_is_dropped() {
598        let dir = tempfile::tempdir().unwrap();
599        let path = dir.path().join("config.toml");
600
601        std::fs::write(&path, REGISTRY_ONLY).unwrap();
602        drop_bare_registry(&path).unwrap();
603        assert!(!path.exists());
604        // Nothing there is nothing to drop.
605        drop_bare_registry(&path).unwrap();
606
607        std::fs::write(&path, format!("schema_version = 2\n\n{REGISTRY_ONLY}")).unwrap();
608        drop_bare_registry(&path).unwrap();
609        assert!(path.exists());
610    }
611
612    /// An application with one `Live` key in the workspace: `<app>.note`.
613    struct NoteApp(&'static str);
614
615    impl crate::settings::AppSettings for NoteApp {
616        fn defs(&self) -> Vec<sapphire_framework_settings::SettingDef> {
617            vec![sapphire_framework_settings::SettingDef {
618                key: format!("{}.note", self.0),
619                kind: sapphire_framework_settings::Kind::String { non_empty: false },
620                scopes: vec![sapphire_framework_settings::Scope::Workspace],
621                overridable: false,
622                apply: sapphire_framework_settings::Apply::Live,
623                default: None,
624                section: "Test".into(),
625                doc: "test".into(),
626                process: sapphire_framework_settings::Process::App,
627            }]
628        }
629    }
630
631    #[tokio::test(flavor = "multi_thread")]
632    async fn workspace_settings_follow_the_selection() {
633        const APP: &str = "sapphire-curtest";
634        let dir = tempfile::tempdir().unwrap();
635        let ctx: &'static AppContext = Box::leak(Box::new(AppContext::new(APP)));
636        ctx.set_config_dir(dir.path().join("config"));
637        ctx.set_cache_dir(dir.path().join("cache"));
638        ctx.set_data_dir(dir.path().join("data"));
639        let file = SelectionFile::at(dir.path().join("config").join("workspace.toml"));
640        let (a, b) = (dir.path().join("a"), dir.path().join("b"));
641        for (root, value) in [(&a, "from a"), (&b, "from b")] {
642            std::fs::create_dir_all(root).unwrap();
643            init_workspace(ctx, root).unwrap();
644            std::fs::write(
645                root.join(format!(".{APP}")).join("config.toml"),
646                format!("[{APP}]\nnote = \"{value}\"\n"),
647            )
648            .unwrap();
649        }
650        let settings = crate::settings::Settings::load_with(
651            ctx,
652            std::sync::Arc::new(NoteApp(APP)),
653            file.clone(),
654        )
655        .unwrap();
656        let key = format!("{APP}.note");
657        let current = Current::new(ctx, Arc::new(WorkspaceHost::new(ctx)), None, file)
658            .with_settings(settings.clone());
659        let mut changed = settings.changed();
660
661        current.select(&a).await.unwrap();
662        assert!(changed.has_changed().unwrap());
663        changed.mark_unchanged();
664        assert_eq!(settings.get_as::<String>(&key).as_deref(), Some("from a"));
665
666        current.select(&b).await.unwrap();
667        assert!(changed.has_changed().unwrap());
668        changed.mark_unchanged();
669        assert_eq!(settings.get_as::<String>(&key).as_deref(), Some("from b"));
670
671        // No workspace, no workspace value.
672        current.remove(false).await.unwrap();
673        assert!(changed.has_changed().unwrap());
674        assert_eq!(settings.get(&key), None);
675    }
676
677    #[test]
678    fn an_unparsable_marker_config_is_never_quoted() {
679        let dir = tempfile::tempdir().unwrap();
680        let path = dir.path().join("config.toml");
681        std::fs::write(&path, "[app]\ntoken = \"hunter2\" x\n").unwrap();
682        let err = read_config(&path).unwrap_err().to_string();
683        assert!(err.contains(&path.display().to_string()), "{err}");
684        assert!(err.contains("line 2"), "{err}");
685        assert!(!err.contains("hunter2"), "{err}");
686    }
687
688    #[test]
689    fn init_writes_no_config() {
690        let dir = tempfile::tempdir().unwrap();
691        let ctx: &'static AppContext = Box::leak(Box::new(AppContext::new("sapphire-initapp")));
692        let result = init_workspace(ctx, dir.path()).unwrap();
693        assert!(result.created);
694        let workspace = Workspace::from_root(ctx, dir.path()).unwrap();
695        assert!(workspace.marker_dir().is_dir());
696        assert!(!workspace.config_path().exists());
697    }
698}