Skip to main content

settings_model/
source.rs

1//! The settings a process reads: the source its host installed.
2//!
3//! The session installs its settings as resources of the workspace; a sandboxed app installs its
4//! channel to the session; a service the session started, and a browser page, install a
5//! [`HostDocument`] of what their host gives them; a window of the toolkit alone installs none.
6//! A process with none installed reads every setting's default.
7
8use std::sync::atomic::{AtomicU64, Ordering};
9use std::sync::{Arc, Mutex, RwLock};
10
11use serde_json::{Map, Value};
12use tilo_lock::{MutexRecover as _, RwLockRecover as _};
13
14#[derive(Debug)]
15pub enum ConditionalUpdate {
16    Superseded,
17    Stored,
18}
19
20#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
21pub struct ChangeOrigin {
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub action: Option<String>,
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub actor: Option<String>,
26}
27
28impl ChangeOrigin {
29    pub const LOCAL_USER: &'static str = "local-user";
30
31    #[must_use]
32    pub fn action(action: impl Into<String>) -> Self {
33        Self {
34            action: Some(action.into()),
35            actor: None,
36        }
37    }
38
39    #[must_use]
40    pub fn by(mut self, actor: impl Into<String>) -> Self {
41        self.actor = Some(actor.into());
42        self
43    }
44
45    #[must_use]
46    pub fn local(action: impl Into<String>) -> Self {
47        Self::action(action).by(Self::LOCAL_USER)
48    }
49}
50
51/// What a read-modify-write makes of the current section: the leaves to
52/// merge into it. Called once, with the section as stored at that moment.
53pub type SectionChange<'a> = dyn FnMut(&Map<String, Value>) -> Map<String, Value> + 'a;
54
55pub trait SettingsSource: Send + Sync {
56    fn load(&self) -> Map<String, Value>;
57
58    fn update_section(&self, name: &str, values: Map<String, Value>) -> std::io::Result<()>;
59
60    fn update_section_by(
61        &self,
62        name: &str,
63        values: Map<String, Value>,
64        origin: &ChangeOrigin,
65    ) -> std::io::Result<()> {
66        let _ = origin;
67        self.update_section(name, values)
68    }
69
70    /// Read section `name` and merge what `change` makes of it, recording
71    /// `origin`, as one step no other write to this source lands inside.
72    /// This is the read-modify-write behind a typed key's update: a toggle
73    /// pressed twice in quick succession flips twice.
74    ///
75    /// The default reads and then writes, which is atomic only where the
76    /// source's writer serialises them itself (an app's settings channel,
77    /// whose host applies writes in order); a source that owns its document
78    /// overrides it to hold its lock across both.
79    ///
80    /// # Errors
81    /// As [`Self::update_section`].
82    fn update_section_with(
83        &self,
84        name: &str,
85        origin: &ChangeOrigin,
86        change: &mut SectionChange<'_>,
87    ) -> std::io::Result<()> {
88        let current = match self.load().remove(name) {
89            Some(Value::Object(section)) => section,
90            _ => Map::new(),
91        };
92        self.update_section_by(name, change(&current), origin)
93    }
94
95    /// Merge each of `sections` as one change made by `origin`: one step history takes back
96    /// together, a choice spanning sections (the model agents answer with) included.
97    ///
98    /// # Errors
99    /// As [`Self::update_section`].
100    fn update_sections(
101        &self,
102        sections: Vec<(String, Map<String, Value>)>,
103        origin: &ChangeOrigin,
104    ) -> std::io::Result<()> {
105        for (name, values) in sections {
106            self.update_section_by(&name, values, origin)?;
107        }
108        Ok(())
109    }
110
111    /// [`Self::update_sections`], only if each of `expected` (a section, and what it held when
112    /// the caller read it) still holds what it did. `Superseded` means a newer change replaced
113    /// what the caller read.
114    ///
115    /// # Errors
116    /// As [`Self::update_section`].
117    fn compare_update_sections(
118        &self,
119        _expected: &[(&str, Map<String, Value>)],
120        _sections: Vec<(String, Map<String, Value>)>,
121        _origin: &ChangeOrigin,
122    ) -> std::io::Result<ConditionalUpdate> {
123        Err(std::io::Error::new(
124            std::io::ErrorKind::Unsupported,
125            "conditional settings persistence is unavailable",
126        ))
127    }
128
129    /// Why writing `values` to section `name` is refused — a field the section declares read only
130    /// would change — asked before the settings channel writes an app's values there. The field
131    /// is changed by the action a section declares and by nothing else, so no app's write reaches
132    /// it. `None` from a source that keeps no such declarations.
133    fn readonly_refusal(&self, _name: &str, _values: &Map<String, Value>) -> Option<String> {
134        None
135    }
136
137    /// Take back (`undo`) or bring back the last step any of `invokers` (actors, as a change
138    /// names them) took on section `section`, of the app `app` where the section keeps each
139    /// app's preferences apart. Whether there was one.
140    ///
141    /// # Errors
142    /// The settings' history is not kept here, or the step was refused.
143    fn step(
144        &self,
145        _section: &str,
146        _app: Option<&str>,
147        _undo: bool,
148        _invokers: &[String],
149    ) -> std::io::Result<bool> {
150        Err(std::io::Error::new(
151            std::io::ErrorKind::Unsupported,
152            "the settings' history is kept by the session",
153        ))
154    }
155
156    /// The changes of section `section`, oldest first, each as the stamp it carries in the
157    /// settings' history (or will, once written): which setter set what, and who invoked it.
158    ///
159    /// # Errors
160    /// The settings' history is not kept here.
161    fn stamps(&self, _section: &str) -> std::io::Result<Vec<tilo_actions::stamp::Stamp>> {
162        Err(std::io::Error::new(
163            std::io::ErrorKind::Unsupported,
164            "the settings' history is kept by the session",
165        ))
166    }
167
168    fn flush_pending(&self) {}
169
170    fn take_deferred_failures(&self) -> Vec<DeferredFailure> {
171        Vec::new()
172    }
173
174    fn revision(&self) -> u64;
175
176    /// Rings every time [`Self::revision`] changes, so a reader waiting for
177    /// a change wakes at once instead of looking again and again.
178    fn changes(&self) -> &ChangeSignal;
179}
180
181/// [`SettingsSource::compare_update_sections`] of one section: merge `values` into `name` only
182/// if it still holds `expected`.
183///
184/// # Errors
185/// As [`SettingsSource::update_section`].
186pub fn compare_update_section(
187    source: &dyn SettingsSource,
188    name: &str,
189    expected: &Map<String, Value>,
190    values: Map<String, Value>,
191) -> std::io::Result<ConditionalUpdate> {
192    source.compare_update_sections(
193        &[(name, expected.clone())],
194        vec![(name.to_owned(), values)],
195        &ChangeOrigin::default(),
196    )
197}
198
199macro_rules! shared_source {
200    ($(fn $name:ident(&self $(, $arg:ident: $ty:ty)* $(,)?) $(-> $ret:ty)?;)*) => {
201        impl<T: SettingsSource + ?Sized> SettingsSource for Arc<T> {
202            $(
203                fn $name(&self $(, $arg: $ty)*) $(-> $ret)? {
204                    (**self).$name($($arg),*)
205                }
206            )*
207        }
208    };
209}
210
211shared_source! {
212    fn load(&self) -> Map<String, Value>;
213    fn update_section(&self, name: &str, values: Map<String, Value>) -> std::io::Result<()>;
214    fn update_section_by(
215        &self,
216        name: &str,
217        values: Map<String, Value>,
218        origin: &ChangeOrigin,
219    ) -> std::io::Result<()>;
220    fn update_section_with(
221        &self,
222        name: &str,
223        origin: &ChangeOrigin,
224        change: &mut SectionChange<'_>,
225    ) -> std::io::Result<()>;
226    fn update_sections(
227        &self,
228        sections: Vec<(String, Map<String, Value>)>,
229        origin: &ChangeOrigin,
230    ) -> std::io::Result<()>;
231    fn compare_update_sections(
232        &self,
233        expected: &[(&str, Map<String, Value>)],
234        sections: Vec<(String, Map<String, Value>)>,
235        origin: &ChangeOrigin,
236    ) -> std::io::Result<ConditionalUpdate>;
237    fn readonly_refusal(&self, name: &str, values: &Map<String, Value>) -> Option<String>;
238    fn step(
239        &self,
240        section: &str,
241        app: Option<&str>,
242        undo: bool,
243        invokers: &[String],
244    ) -> std::io::Result<bool>;
245    fn stamps(&self, section: &str) -> std::io::Result<Vec<tilo_actions::stamp::Stamp>>;
246    fn flush_pending(&self);
247    fn take_deferred_failures(&self) -> Vec<DeferredFailure>;
248    fn revision(&self) -> u64;
249    fn changes(&self) -> &ChangeSignal;
250}
251
252#[derive(Default)]
253pub struct ChangeSignal {
254    listeners: Mutex<Vec<std::sync::Weak<Listener>>>,
255}
256
257/// What a reader runs when the document changed: hand the news on, nothing
258/// slow; it runs on the thread that made or noticed the change.
259pub type Listener = dyn Fn() + Send + Sync;
260
261impl ChangeSignal {
262    pub fn listen(&self, listener: &Arc<Listener>) {
263        let mut listeners = self.listeners.lock_recover();
264        listeners.retain(|known| known.strong_count() > 0);
265        listeners.push(Arc::downgrade(listener));
266    }
267
268    pub fn ring(&self) {
269        let listeners: Vec<Arc<Listener>> = self
270            .listeners
271            .lock_recover()
272            .iter()
273            .filter_map(std::sync::Weak::upgrade)
274            .collect();
275        for listener in listeners {
276            listener();
277        }
278    }
279}
280
281static SOURCE: RwLock<Option<Arc<dyn SettingsSource>>> = RwLock::new(None);
282
283/// What gives the settings a process reads when its host installed none.
284pub type Fallback = fn() -> Option<Arc<dyn SettingsSource>>;
285
286/// Where this process reads its settings when its host installed none ([`register_fallback`]).
287static FALLBACK: RwLock<Option<Fallback>> = RwLock::new(None);
288
289/// Where this process reads its settings when its host installed none: what the profile's
290/// session left for processes outside it, for a process started outside the session. The
291/// process's starter registers it (its `main`, or the app runner as it starts an app), never a
292/// library: a process that registered none reads every setting's default.
293pub fn register_fallback(fallback: Fallback) {
294    *FALLBACK.write_recover() = Some(fallback);
295}
296
297/// The settings of this process: the source its host installed, else the fallback its starter
298/// registered ([`register_fallback`]); `None` where there is neither, and every setting reads as
299/// its default.
300#[must_use]
301pub fn source() -> Option<Arc<dyn SettingsSource>> {
302    installed_source().or_else(|| (*FALLBACK.read_recover())?())
303}
304
305#[derive(Clone, Debug, PartialEq, Eq)]
306pub struct DeferredFailure {
307    pub sections: Vec<String>,
308    pub error: String,
309}
310
311/// Make `source` the settings document of this process, or restore the
312/// local profile with `None`. A host does this once, as it starts; a test
313/// that needs a document of its own takes a [`scoped_source`], which no
314/// other test sees.
315pub fn install_source(source: Option<Arc<dyn SettingsSource>>) {
316    *SOURCE.write_recover() = source;
317    INSTALLED.fetch_add(1, Ordering::AcqRel);
318}
319
320/// How many settings documents this process has installed in place of others.
321static INSTALLED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
322
323/// The version of `source` as this process reads it: the document's own revision, told apart
324/// from every document installed in another's place before it, so a reader that caches what it
325/// read by version reads a replaced document again even where the two number alike. A reader
326/// told only the document's own revision takes a document put in place of another for the one
327/// it replaced, and keeps reading what the old one said.
328#[must_use]
329pub fn installed_version(source: &dyn SettingsSource) -> u64 {
330    let mut folded = 0xcbf2_9ce4_8422_2325u64 ^ INSTALLED.load(Ordering::Acquire);
331    for byte in source.revision().to_le_bytes() {
332        folded = (folded ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3);
333    }
334    folded
335}
336
337pub fn installed_source() -> Option<Arc<dyn SettingsSource>> {
338    if let Some(scoped) = SCOPED.with(|scoped| scoped.borrow().last().cloned()) {
339        return scoped;
340    }
341    SOURCE.read_recover().clone()
342}
343
344thread_local! {
345    static SCOPED: std::cell::RefCell<Vec<Option<Arc<dyn SettingsSource>>>> =
346        const { std::cell::RefCell::new(Vec::new()) };
347}
348
349#[must_use = "the scope ends when it is dropped"]
350pub fn scoped_source(source: Option<Arc<dyn SettingsSource>>) -> SourceScope {
351    SCOPED.with(|scoped| scoped.borrow_mut().push(source));
352    // A document put in front of the one this thread read is a new version of it, as
353    // [`install_source`]'s is.
354    INSTALLED.fetch_add(1, Ordering::AcqRel);
355    SourceScope {
356        _not_send: std::marker::PhantomData,
357    }
358}
359
360pub struct SourceScope {
361    _not_send: std::marker::PhantomData<*const ()>,
362}
363
364impl Drop for SourceScope {
365    fn drop(&mut self) {
366        SCOPED.with(|scoped| {
367            scoped.borrow_mut().pop();
368        });
369        INSTALLED.fetch_add(1, Ordering::AcqRel);
370    }
371}
372
373/// Merge `values` into section `name` of `doc`, keeping every other section
374/// and every key `values` does not mention. A section of the wrong type is
375/// replaced: there is nothing to preserve in a value that cannot be read.
376pub fn merge_section(doc: &mut Map<String, Value>, name: &str, values: Map<String, Value>) {
377    let entry = doc
378        .entry(name.to_string())
379        .or_insert_with(|| Value::Object(Map::new()));
380    if !entry.is_object() {
381        *entry = Value::Object(Map::new());
382    }
383    if let Some(obj) = entry.as_object_mut() {
384        for (k, v) in values {
385            obj.insert(k, v);
386        }
387    }
388}
389
390type Persist = dyn Fn(&Map<String, Value>) -> std::io::Result<()> + Send + Sync;
391
392pub struct HostDocument {
393    doc: Mutex<Map<String, Value>>,
394    revision: AtomicU64,
395    persist: Box<Persist>,
396    changes: ChangeSignal,
397}
398
399impl HostDocument {
400    pub fn new(
401        initial: Map<String, Value>,
402        persist: impl Fn(&Map<String, Value>) -> std::io::Result<()> + Send + Sync + 'static,
403    ) -> Self {
404        Self {
405            doc: Mutex::new(initial),
406            revision: AtomicU64::new(1),
407            persist: Box::new(persist),
408            changes: ChangeSignal::default(),
409        }
410    }
411}
412
413impl HostDocument {
414    /// Merge what `change` makes of the document, under its lock, persisting it first; `None`
415    /// from `change` leaves it as it is.
416    fn change(
417        &self,
418        change: impl FnOnce(&Map<String, Value>) -> Option<Vec<(String, Map<String, Value>)>>,
419    ) -> std::io::Result<ConditionalUpdate> {
420        let mut doc = self.doc.lock_recover();
421        let Some(sections) = change(&doc) else {
422            return Ok(ConditionalUpdate::Superseded);
423        };
424        let mut next = doc.clone();
425        for (name, values) in sections {
426            merge_section(&mut next, &name, values);
427        }
428        (self.persist)(&next)?;
429        *doc = next;
430        self.revision.fetch_add(1, Ordering::AcqRel);
431        drop(doc);
432        self.changes.ring();
433        Ok(ConditionalUpdate::Stored)
434    }
435}
436
437impl SettingsSource for HostDocument {
438    fn load(&self) -> Map<String, Value> {
439        self.doc.lock_recover().clone()
440    }
441
442    fn update_section(&self, name: &str, values: Map<String, Value>) -> std::io::Result<()> {
443        let mut values = Some(values);
444        self.update_section_with(name, &ChangeOrigin::default(), &mut |_| {
445            values.take().unwrap_or_default()
446        })
447    }
448
449    fn update_section_with(
450        &self,
451        name: &str,
452        _origin: &ChangeOrigin,
453        change: &mut SectionChange<'_>,
454    ) -> std::io::Result<()> {
455        self.change(|doc| {
456            let current = match doc.get(name) {
457                Some(Value::Object(section)) => section.clone(),
458                _ => Map::new(),
459            };
460            Some(vec![(name.to_owned(), change(&current))])
461        })
462        .map(drop)
463    }
464
465    fn update_sections(
466        &self,
467        sections: Vec<(String, Map<String, Value>)>,
468        _origin: &ChangeOrigin,
469    ) -> std::io::Result<()> {
470        self.change(|_| Some(sections)).map(drop)
471    }
472
473    fn compare_update_sections(
474        &self,
475        expected: &[(&str, Map<String, Value>)],
476        sections: Vec<(String, Map<String, Value>)>,
477        _origin: &ChangeOrigin,
478    ) -> std::io::Result<ConditionalUpdate> {
479        self.change(|doc| {
480            expected
481                .iter()
482                .all(|(name, expected)| match doc.get(*name) {
483                    Some(Value::Object(section)) => section == expected,
484                    _ => expected.is_empty(),
485                })
486                .then_some(sections)
487        })
488    }
489
490    fn revision(&self) -> u64 {
491        self.revision.load(Ordering::Acquire)
492    }
493
494    fn changes(&self) -> &ChangeSignal {
495        &self.changes
496    }
497}
498
499/// One version of the document a [`SettingsSource`] holds, for readers that follow it.
500#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
501pub struct SettingsStamp(pub u64);
502
503/// A settings document's body read as an object: anything else is the empty document, so a
504/// broken file reads as every setting's default.
505#[must_use]
506pub fn parse(text: &str) -> Map<String, Value> {
507    match serde_json::from_str::<Value>(text) {
508        Ok(Value::Object(m)) => m,
509        _ => Map::new(),
510    }
511}
512
513/// Section `name` of `doc` as an object. A missing section, or one that is not an object,
514/// yields an empty map.
515#[must_use]
516pub fn section_of(mut doc: Map<String, Value>, name: &str) -> Map<String, Value> {
517    match doc.remove(name) {
518        Some(Value::Object(m)) => m,
519        _ => Map::new(),
520    }
521}
522
523/// Section `name` of what `source` holds, as [`section_of`].
524#[must_use]
525pub fn load_section_in(source: &dyn SettingsSource, name: &str) -> Map<String, Value> {
526    section_of(source.load(), name)
527}
528
529/// The settings of a profile kept apart from the person's (a headless app's, a test's, the
530/// models a host keeps for a workspace it serves), by its root: one per root for the life of the
531/// process, kept in the root's `settings.json`, which a write replaces whole.
532#[must_use]
533pub fn profile(root: &std::path::Path) -> Arc<HostDocument> {
534    static PROFILES: Mutex<Vec<(std::path::PathBuf, Arc<HostDocument>)>> = Mutex::new(Vec::new());
535    let mut profiles = PROFILES.lock_recover();
536    if let Some((_, held)) = profiles.iter().find(|(held, _)| held == root) {
537        return Arc::clone(held);
538    }
539    let file = root.join(PROFILE_FILE);
540    let kept = std::fs::read(&file)
541        .ok()
542        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
543        .unwrap_or_default();
544    let document = Arc::new(HostDocument::new(kept, move |document| {
545        let bytes = serde_json::to_vec(document).map_err(std::io::Error::other)?;
546        if let Some(parent) = file.parent() {
547            std::fs::create_dir_all(parent)?;
548        }
549        let partial = file.with_extension("json.partial");
550        std::fs::write(&partial, bytes)?;
551        std::fs::rename(&partial, &file)
552    }));
553    profiles.push((root.to_owned(), Arc::clone(&document)));
554    document
555}
556
557/// Keep the settings of the profile at `root` in what `source` makes, in place of its own
558/// document ([`profile`]), unless something keeps them already: what a host that keeps a
559/// person's settings as resources of a workspace gives the profile it opens a window on, so they
560/// are kept, stepped and read back as that host keeps the person's, and a later window on the
561/// profile finds what an earlier one set.
562pub fn keep_profile(root: &std::path::Path, source: impl FnOnce() -> Arc<dyn SettingsSource>) {
563    let mut kept = KEPT_PROFILES.lock_recover();
564    if !kept.iter().any(|(held, _)| held == root) {
565        kept.push((root.to_owned(), source()));
566    }
567}
568
569/// The settings of the profile at `root`: what a host gave it to keep them ([`keep_profile`]),
570/// else its own document ([`profile`]).
571#[must_use]
572pub fn profile_source(root: &std::path::Path) -> Arc<dyn SettingsSource> {
573    let kept = KEPT_PROFILES
574        .lock_recover()
575        .iter()
576        .find(|(held, _)| held == root)
577        .map(|(_, source)| Arc::clone(source));
578    kept.unwrap_or_else(|| profile(root))
579}
580
581static KEPT_PROFILES: Mutex<Vec<(std::path::PathBuf, Arc<dyn SettingsSource>)>> =
582    Mutex::new(Vec::new());
583
584/// The file a [`profile`] is kept in, below its root.
585const PROFILE_FILE: &str = "settings.json";
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590    use serde_json::json;
591
592    fn object(value: Value) -> Map<String, Value> {
593        let Value::Object(map) = value else {
594            panic!("not an object")
595        };
596        map
597    }
598
599    tilo_test_env::scenario! {
600        fn a_host_document_stores_what_its_persist_accepts;
601
602        phase host_document_merges_persists_then_publishes;
603        {
604            let persisted = Arc::new(Mutex::new(Vec::new()));
605            let sink = Arc::clone(&persisted);
606            let doc = HostDocument::new(
607                object(json!({"region": {"locale": "de-DE"}, "power": 3})),
608                move |doc| {
609                    sink.lock().unwrap().push(Value::Object(doc.clone()));
610                    Ok(())
611                },
612            );
613            let before = doc.revision();
614            doc.update_section("power", object(json!({"idle": 5})))
615                .unwrap();
616            doc.update_section("region", object(json!({"units": "metric"})))
617                .unwrap();
618            let expected =
619                json!({"region": {"locale": "de-DE", "units": "metric"}, "power": {"idle": 5}});
620            assert_eq!(Value::Object(doc.load()), expected);
621            assert_eq!(persisted.lock().unwrap().last(), Some(&expected));
622            assert_eq!(doc.revision(), before + 2);
623        }
624
625        phase a_conditional_section_update_stores_only_over_what_it_read;
626        {
627            let doc = HostDocument::new(object(json!({"a": {"x": 1}})), |_| Ok(()));
628            let read = object(json!({"x": 1}));
629            assert!(matches!(
630                compare_update_section(&doc, "a", &read, object(json!({"x": 2}))).unwrap(),
631                ConditionalUpdate::Stored
632            ));
633            assert!(matches!(
634                compare_update_section(&doc, "a", &read, object(json!({"x": 3}))).unwrap(),
635                ConditionalUpdate::Superseded
636            ));
637            assert!(matches!(
638                compare_update_section(&doc, "new", &Map::new(), object(json!({"y": 1})))
639                    .unwrap(),
640                ConditionalUpdate::Stored
641            ));
642            assert_eq!(
643                Value::Object(doc.load()),
644                json!({"a": {"x": 2}, "new": {"y": 1}})
645            );
646        }
647
648        phase a_refused_persist_leaves_the_document_unchanged;
649        {
650            let doc = HostDocument::new(object(json!({"a": {"x": 1}})), |_| {
651                Err(std::io::Error::other("quota"))
652            });
653            let before = doc.revision();
654            assert!(doc.update_section("a", object(json!({"x": 2}))).is_err());
655            assert_eq!(Value::Object(doc.load()), json!({"a": {"x": 1}}));
656            assert_eq!(doc.revision(), before);
657        }
658    }
659
660    #[test]
661    fn a_scoped_document_is_its_threads_alone_and_ends_with_its_scope() {
662        let document = |mode: &str| -> Arc<dyn SettingsSource> {
663            Arc::new(HostDocument::new(
664                object(json!({"appearance": {"mode": mode}})),
665                |_| Ok(()),
666            ))
667        };
668        let mode = || -> Option<String> {
669            let doc = installed_source()?.load();
670            Some(doc.get("appearance")?.get("mode")?.as_str()?.to_owned())
671        };
672        let outer = scoped_source(Some(document("light")));
673        assert_eq!(mode().as_deref(), Some("light"));
674        let elsewhere = std::thread::spawn(move || mode().as_deref() != Some("light"))
675            .join()
676            .unwrap_or(false);
677        assert!(elsewhere);
678        {
679            let _inner = scoped_source(Some(document("dark")));
680            assert_eq!(mode().as_deref(), Some("dark"));
681        }
682        assert_eq!(mode().as_deref(), Some("light"));
683        drop(outer);
684        assert!(SCOPED.with(|scoped| scoped.borrow().is_empty()));
685    }
686}