sniplab 0.3.2

A filesystem-native snippet library and agent-friendly CLI, installed as `snip`
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
use std::collections::{HashMap, HashSet};
use std::sync::mpsc::Sender;
use std::time::{Duration, Instant};

use ratatui::widgets::ListState;
use uuid::Uuid;

use crate::config::{AppConfig, TuiThemeSetting};
use crate::domain::{FolderFilter, Snippet};
use crate::error::Result;
use crate::filesystem::Library;
use crate::search::{MemoryIndex, SearchIndex, SearchQuery};
use crate::service::trash_entries;

use super::super::event::{AppEvent, GitTaskResult};
use super::super::highlight::Highlighter;
use super::super::icons::IconMode;
use super::super::layout::LayoutRects;
use super::super::persist::SessionState;
use super::super::preview::PreviewCache;
use super::super::selection::PreviewSelection;
use super::super::sidebar;
use super::super::state::{
    Filter, Pane, SearchState, SidebarState, StatusLevel, StatusMessage, VisibleRow,
};
use super::super::theme::TuiTheme;
use super::super::trash::TrashState;
use super::types::{App, GitState, ThemePreviewState};

impl App {
    /// Builds an app with no carried-over session state.
    ///
    /// Loading the on-disk state belongs to the real entry point, not to a
    /// constructor: reading it here would make every caller — tests included —
    /// silently inherit whatever the developer's own `state.toml` holds.
    pub fn new(library: Library, config: &AppConfig) -> Result<Self> {
        Self::new_with_session_state(library, config, SessionState::default())
    }

    pub(crate) fn new_with_session_state(
        library: Library,
        config: &AppConfig,
        session_state: SessionState,
    ) -> Result<Self> {
        let SessionState {
            recent_commands,
            extra,
            ..
        } = session_state;
        let catalog = library.scan()?;
        let index = MemoryIndex::new(catalog.clone());
        let tui = config.tui.clone().unwrap_or_default();
        let theme_overrides = tui
            .extra
            .get("colors")
            .and_then(toml::Value::as_table)
            .cloned()
            .unwrap_or_default();
        let (theme_source, theme_warnings) = crate::theme::resolve(&tui);
        let theme_name = theme_source.name.clone();
        let theme = TuiTheme::from(&theme_source).with_overrides(&theme_overrides);
        let sort = tui.sort;
        let density = tui.density;
        let show_line_numbers = tui.line_numbers;
        let icon_mode = IconMode::Ascii;
        let mut app = Self {
            config_path: crate::config::config_path()?,
            git: GitState::probe(&library, &config.git.clone().unwrap_or_default()),
            library,
            catalog,
            index,
            focus: Pane::Sidebar,
            sidebar: SidebarState::default(),
            filter: Filter::default(),
            search: SearchState::default(),
            visible: Vec::new(),
            list_state: ListState::default(),
            selected_id: None,
            fragment_index: 0,
            preview_scroll: 0,
            show_line_numbers,
            sort,
            density,
            layout: LayoutRects::default(),
            preview: PreviewCache::default(),
            preview_selection: PreviewSelection::default(),
            highlighter: Highlighter::new(&theme_source)?,
            theme,
            theme_source,
            theme_name,
            theme_preview: None,
            theme_setting: tui.theme,
            theme_config: tui.clone(),
            theme_overrides,
            icon_mode,
            theme_checked_at: Instant::now(),
            status: None,
            modal: None,
            palette: Default::default(),
            session_state_extra: extra,
            trash: TrashState::default(),
            should_quit: false,
            pending_quit: false,
            editor_cmd: config.editor.clone(),
            vscode_cmd: config.vscode_cmd.clone(),
            show_help: false,
            help_scroll: 0,
            default_language: config
                .default_language
                .clone()
                .unwrap_or_else(|| "text".to_owned()),
            default_folder: config.default_folder.clone(),
            default_tags: config.default_tags.clone(),
            last_click: None,
        };
        app.palette.set_recent(
            recent_commands
                .iter()
                .filter_map(|slug| crate::tui::command::by_slug(slug))
                .collect(),
        );
        let trash_count = trash_entries(&app.library).map_or(0, |entries| entries.len());
        sidebar::rebuild(&mut app.sidebar, &app.catalog, trash_count);
        app.refresh_visible();
        app.refresh_git();
        if !theme_warnings.is_empty() {
            app.set_status(theme_warnings.join("; "), StatusLevel::Error);
        }
        Ok(app)
    }

    pub(crate) fn session_state(&self) -> SessionState {
        SessionState {
            schema_version: crate::tui::persist::STATE_SCHEMA_VERSION,
            recent_commands: self
                .palette
                .recent()
                .iter()
                .map(|id| crate::tui::command::get(*id).slug.to_owned())
                .collect(),
            extra: self.session_state_extra.clone(),
        }
    }

    pub fn selected_snippet(&self) -> Option<&Snippet> {
        let id = self.selected_id?;
        self.catalog
            .snippets
            .iter()
            .find(|snippet| snippet.id == id)
    }

    pub fn set_status(&mut self, text: impl Into<String>, level: StatusLevel) {
        self.status = Some(StatusMessage::new(text, level));
    }

    pub(super) fn preview_theme(&mut self, name: &str) -> Result<()> {
        if self.theme_preview.is_none() {
            self.theme_preview = Some(ThemePreviewState {
                original_name: self.theme_name.clone(),
                original_source: self.theme_source.clone(),
                original_tui: self.theme,
            });
        }
        let source = crate::theme::load(name)?;
        if let Some(failure) = crate::theme::validate::check(&source)
            .into_iter()
            .find(|check| check.level == crate::theme::validate::Level::Fail)
        {
            return Err(crate::error::SnipError::validation(format!(
                "theme {name}: {}: {}",
                failure.id, failure.detail
            )));
        }
        // `[tui.colors]` is the last layer for every other path that builds a
        // theme, so it has to be reapplied here too. Without it, switching
        // themes from the palette would silently drop the user's overrides for
        // the rest of the session.
        let theme = TuiTheme::from(&source).with_overrides(&self.theme_overrides);
        self.highlighter.set_theme(&source)?;
        self.theme_source = source;
        self.theme = theme;
        self.theme_name = name.to_owned();
        self.preview.invalidate();
        Ok(())
    }

    pub(super) fn restore_theme_preview(&mut self) -> Result<()> {
        let Some(original) = self.theme_preview.take() else {
            return Ok(());
        };
        self.highlighter.set_theme(&original.original_source)?;
        self.theme_name = original.original_name;
        self.theme_source = original.original_source;
        self.theme = original.original_tui;
        self.preview.invalidate();
        Ok(())
    }

    pub fn tick_status(&mut self) {
        if self.modal.is_none() && self.status.as_ref().is_some_and(StatusMessage::expired) {
            self.status = None;
        }
    }

    pub fn tick_theme(&mut self) -> Result<()> {
        if self.theme_setting != TuiThemeSetting::Auto || self.theme_preview.is_some() {
            return Ok(());
        }
        if self.theme_checked_at.elapsed() < Duration::from_secs(5) {
            return Ok(());
        }
        self.theme_checked_at = Instant::now();
        self.theme_config.theme = self.theme_setting;
        let (source, warnings) = crate::theme::resolve(&self.theme_config);
        let theme = TuiTheme::from(&source).with_overrides(&self.theme_overrides);
        if source.name != self.theme_name || theme.appearance != self.theme.appearance {
            self.highlighter.set_theme(&source)?;
            self.theme_name = source.name.clone();
            self.theme_source = source;
            self.theme = theme;
            self.preview.invalidate();
        }
        if !warnings.is_empty() {
            self.set_status(warnings.join("; "), StatusLevel::Error);
        }
        Ok(())
    }

    pub fn tick_git(&mut self) {
        let Some(repo) = self.git.repo.as_ref() else {
            return;
        };
        if self.git.checked_at.elapsed() < self.git.interval
            || repo.git_dir.join("index.lock").exists()
        {
            return;
        }
        self.refresh_git();
    }

    pub fn tick_auto_backup(&mut self) {
        if self.should_quit
            || self.pending_quit
            || self.modal.is_some()
            || self.git.operation_queued
        {
            return;
        }

        if self
            .git
            .auto_attempted_at
            .is_none_or(|attempt| attempt.elapsed() >= Duration::from_secs(5))
            && let (Some(repo), Some(status)) = (self.git.repo.clone(), self.git.status.clone())
            && crate::git::should_auto_backup(
                &status,
                time::OffsetDateTime::now_utc().unix_timestamp(),
                self.git.auto_commit_interval,
                self.git.auto_backup_paused,
            )
        {
            let message = crate::git::backup_message(&status);
            self.git.auto_attempted_at = Some(Instant::now());
            // A push does not hold the index lock. Let commits continue while a
            // background push is in flight; a newer HEAD is pushed next time.
            match crate::git::commit(&repo, &message) {
                Ok(()) => {
                    self.git.last_commit_error = None;
                    // The push gate below must see the commit that just landed.
                    self.refresh_git();
                }
                Err(error) if crate::git::is_library_lock_conflict(&error) => {}
                Err(error) => {
                    let message = error.to_string();
                    if auto_error_transition(&mut self.git.last_commit_error, message.clone()) {
                        self.set_status(
                            format!("automatic commit failed: {message}"),
                            StatusLevel::Error,
                        );
                    }
                }
            }
        }

        if self.git.auto_commit_interval == 0
            || !self.git.auto_push
            || self.git.push_attempted_at.is_some_and(|attempt| {
                attempt.elapsed()
                    < Duration::from_secs(u64::from(self.git.auto_commit_interval) * 60)
            })
        {
            return;
        }
        self.spawn_auto_push();
    }

    pub fn set_git_sender(&mut self, sender: Sender<AppEvent>) {
        self.git.sender = Some(sender);
    }

    fn spawn_auto_push(&mut self) {
        let (Some(repo), Some(sender)) = (self.git.repo.clone(), self.git.sender.clone()) else {
            return;
        };
        let Some(status) = self.git.status.as_ref() else {
            return;
        };
        if self.git.push_in_flight
            || !crate::git::should_auto_push(
                status,
                self.git.auto_push,
                self.git.auto_backup_paused,
            )
        {
            return;
        }
        self.git.push_in_flight = true;
        self.git.push_attempted_at = Some(Instant::now());
        std::thread::spawn(move || {
            let outcome = crate::git::push(&repo)
                .map(|()| crate::git::ActionOutcome {
                    action: "push",
                    committed: false,
                    pushed: true,
                    message: "backup pushed".to_owned(),
                })
                .map_err(|error| error.to_string());
            let _ = sender.send(AppEvent::GitFinished(GitTaskResult {
                action: "push",
                outcome,
                manual: false,
            }));
        });
    }

    pub fn spawn_fetch(&mut self) {
        let (Some(repo), Some(sender)) = (self.git.repo.clone(), self.git.sender.clone()) else {
            self.set_status("Git fetch is unavailable", StatusLevel::Error);
            return;
        };
        if self.git.push_in_flight || self.git.fetch_in_flight {
            self.set_status(
                "a background Git network task is running",
                StatusLevel::Error,
            );
            return;
        }
        self.git.fetch_in_flight = true;
        std::thread::spawn(move || {
            let outcome = crate::git::fetch(&repo)
                .map(|()| crate::git::ActionOutcome {
                    action: "fetch",
                    committed: false,
                    pushed: false,
                    message: "remote status refreshed".to_owned(),
                })
                .map_err(|error| error.to_string());
            let _ = sender.send(AppEvent::GitFinished(GitTaskResult {
                action: "fetch",
                outcome,
                manual: false,
            }));
        });
    }

    /// Spawns a manual git operation (backup, commit, push) as a background
    /// task. The caller must have already set `operation_queued = true` and
    /// validated preconditions. Results arrive via `AppEvent::GitFinished`.
    pub(super) fn spawn_git_operation(&mut self, action: crate::git::GitAction) {
        let (action_name, pending) = match &action {
            crate::git::GitAction::Backup => ("backup", "backing up…"),
            crate::git::GitAction::Commit { .. } => ("commit", "committing…"),
            crate::git::GitAction::Push => ("push", "pushing…"),
            crate::git::GitAction::Init => {
                debug_assert!(false, "Init must use the interactive RunGit effect");
                self.set_status("git init requires the interactive flow", StatusLevel::Error);
                self.finish_git_operation();
                return;
            }
        };
        let (Some(repo), Some(sender)) = (self.git.repo.clone(), self.git.sender.clone()) else {
            self.set_status("Git is unavailable", StatusLevel::Error);
            self.finish_git_operation();
            return;
        };
        self.set_status(pending, StatusLevel::Info);
        std::thread::spawn(move || {
            let outcome =
                crate::git::execute_non_interactive(&repo, &action).map_err(|e| e.to_string());
            let _ = sender.send(AppEvent::GitFinished(GitTaskResult {
                action: action_name,
                outcome,
                manual: true,
            }));
        });
    }

    pub fn handle_git_task(&mut self, result: GitTaskResult) {
        if result.action == "push" && !result.manual {
            self.git.push_in_flight = false;
        } else if result.action == "fetch" {
            self.git.fetch_in_flight = false;
        }
        self.refresh_git();
        if result.manual {
            // Manual user-triggered operation: always show result.
            match &result.outcome {
                Ok(outcome) => {
                    // A successful manual push retires the stale panel banner
                    // left behind by an earlier automatic push failure.
                    if outcome.pushed {
                        self.git.last_push_error = None;
                    }
                    self.set_status(&outcome.message, StatusLevel::Info);
                }
                Err(message) => self.set_status(message, StatusLevel::Error),
            }
            self.finish_git_operation();
        } else {
            // Automatic background task: quiet on success, throttled on error.
            match result.outcome {
                Ok(_) => {
                    if result.action == "fetch" {
                        self.git.last_fetch_error = None;
                        self.git.fetched_at = Some(Instant::now());
                        self.set_status("remote status refreshed", StatusLevel::Info);
                    } else {
                        self.git.last_push_error = None;
                    }
                }
                Err(message) => {
                    let slot = if result.action == "fetch" {
                        &mut self.git.last_fetch_error
                    } else {
                        &mut self.git.last_push_error
                    };
                    if auto_error_transition(slot, message.clone()) {
                        self.set_status(
                            format!("background {} failed: {message}", result.action),
                            StatusLevel::Error,
                        );
                    }
                }
            }
        }
    }

    pub fn refresh_git(&mut self) {
        let Some(repo) = self.git.repo.as_ref() else {
            return;
        };
        if repo.git_dir.join("index.lock").exists() {
            return;
        }
        let started = Instant::now();
        match crate::git::status(repo) {
            Ok(status) => {
                self.git.status = Some(status);
                self.git.error = None;
            }
            Err(error) => {
                // Checkouts can expose a transient state. Keep the last good badge.
                self.git.error = Some(error.to_string());
            }
        }
        self.git.checked_at = Instant::now();
        self.git.interval = if started.elapsed() > Duration::from_millis(250) {
            Duration::from_secs(30)
        } else {
            Duration::from_secs(5)
        };
    }

    pub fn reprobe_git(&mut self) {
        self.git.reprobe(&self.library);
        self.refresh_git();
    }

    pub fn finish_git_operation(&mut self) {
        self.git.operation_queued = false;
        if self.pending_quit {
            self.should_quit = true;
        }
    }

    pub fn rescan(&mut self) -> Result<()> {
        let catalog = self.library.scan()?;
        self.catalog = catalog.clone();
        self.index = MemoryIndex::new(catalog);
        self.rebuild_sidebar();
        self.refresh_visible();
        if self.trash.open {
            self.trash.reload(&self.library)?;
        }
        self.refresh_git();
        Ok(())
    }

    pub(super) fn rescan_now(&mut self) {
        match self.rescan() {
            Ok(()) => self.set_status("library refreshed", StatusLevel::Info),
            Err(error) => self.set_status(error.to_string(), StatusLevel::Error),
        }
    }

    pub fn refresh_visible(&mut self) {
        let old_index = self.list_state.selected().unwrap_or(0);
        let allowed = self
            .catalog
            .snippets
            .iter()
            .filter(|snippet| self.matches_filter(snippet))
            .map(|snippet| snippet.id)
            .collect::<HashSet<_>>();

        let mut visible = if self.search.query.is_empty() {
            let mut snippets = self
                .catalog
                .snippets
                .iter()
                .filter(|snippet| allowed.contains(&snippet.id))
                .collect::<Vec<_>>();
            let sort = self.sort;
            snippets.sort_by(|left, right| sort.compare(left, right));
            snippets
                .into_iter()
                .map(|snippet| VisibleRow {
                    snippet_id: snippet.id,
                    excerpt: None,
                    score: 0,
                })
                .collect()
        } else {
            let mut best = HashMap::<Uuid, VisibleRow>::new();
            // The sidebar folder filter is applied separately through `allowed`,
            // so the query only carries the tag. Substring matching cannot fail,
            // hence the query is always constructible here.
            let query = SearchQuery::new(&self.search.query, false)
                .expect("substring queries never fail to build")
                .tag(self.filter.tag.as_deref());
            for result in self.index.search(&query) {
                if !allowed.contains(&result.snippet_id) {
                    continue;
                }
                best.entry(result.snippet_id).or_insert(VisibleRow {
                    snippet_id: result.snippet_id,
                    excerpt: Some(result.excerpt),
                    score: result.score,
                });
            }
            let mut rows = best.into_values().collect::<Vec<_>>();
            rows.sort_by(|left, right| {
                right.score.cmp(&left.score).then_with(|| {
                    self.title_for(left.snippet_id)
                        .to_lowercase()
                        .cmp(&self.title_for(right.snippet_id).to_lowercase())
                })
            });
            rows
        };

        let selection = self
            .selected_id
            .and_then(|id| visible.iter().position(|row| row.snippet_id == id))
            .or_else(|| (!visible.is_empty()).then(|| old_index.min(visible.len() - 1)));
        self.list_state.select(selection);
        self.selected_id = selection.map(|index| visible[index].snippet_id);
        self.visible.clear();
        self.visible.append(&mut visible);
        self.clamp_fragment();
        self.preview.invalidate();
        self.preview_scroll = 0;
    }

    pub(super) fn rebuild_sidebar(&mut self) {
        let trash_count = trash_entries(&self.library).map_or(0, |entries| entries.len());
        sidebar::rebuild(&mut self.sidebar, &self.catalog, trash_count);
    }

    pub(super) fn clamp_fragment(&mut self) {
        let count = self
            .selected_snippet()
            .map_or(0, |snippet| snippet.loaded_fragments.len());
        self.fragment_index = self.fragment_index.min(count.saturating_sub(1));
    }

    pub(super) fn title_for(&self, id: Uuid) -> &str {
        self.catalog
            .snippets
            .iter()
            .find(|snippet| snippet.id == id)
            .map_or("", |snippet| snippet.title.as_str())
    }

    pub(super) fn matches_filter(&self, snippet: &Snippet) -> bool {
        if self.filter.uncategorized {
            return snippet.folder.is_empty();
        }
        let folder_matches = self
            .filter
            .folder
            .as_deref()
            .is_none_or(|folder| FolderFilter::recursive(folder).matches(&snippet.folder));
        let tag_matches = self.filter.tag.as_ref().is_none_or(|tag| {
            snippet
                .tags
                .iter()
                .any(|candidate| candidate.eq_ignore_ascii_case(tag))
        });
        folder_matches && tag_matches
    }
}

fn auto_error_transition(last: &mut Option<String>, next: String) -> bool {
    if last.as_deref() == Some(next.as_str()) {
        false
    } else {
        *last = Some(next);
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::AppConfig;
    use crate::tui::command::CommandId;
    use crate::tui::persist::SessionState;

    #[test]
    fn repeated_auto_backup_errors_are_silent_until_the_message_changes() {
        let mut last = None;
        assert!(auto_error_transition(&mut last, "first".to_owned()));
        assert!(!auto_error_transition(&mut last, "first".to_owned()));
        assert!(auto_error_transition(&mut last, "second".to_owned()));
        assert_eq!(last.as_deref(), Some("second"));
    }

    #[test]
    fn persisted_recent_commands_round_trip_and_ignore_unknown_slugs() {
        let temporary = tempfile::tempdir().unwrap();
        let library = Library::init(&temporary.path().join("Recent.sniplib"), None).unwrap();
        let mut app = App::new(library.clone(), &AppConfig::default()).unwrap();
        // Both commands are session-only. A command that persists (density,
        // line numbers) would rewrite the developer's real config.toml.
        app.run_command(CommandId::ViewCycleSort);
        app.run_command(CommandId::ViewToggleHelp);
        let path = temporary.path().join("state.toml");
        let mut extra = toml::Table::new();
        extra.insert(
            "future_setting".to_owned(),
            toml::Value::String("kept".to_owned()),
        );
        SessionState {
            recent_commands: app
                .palette
                .recent()
                .iter()
                .map(|id| crate::tui::command::get(*id).slug.to_owned())
                .chain(std::iter::once("snippet.does-not-exist".to_owned()))
                .collect(),
            extra,
            ..SessionState::default()
        }
        .save_to(&path)
        .unwrap();
        let state = SessionState::load_from(&path);
        let mut reopened =
            App::new_with_session_state(library, &AppConfig::default(), state).unwrap();
        reopened.palette.open();
        reopened.refresh_palette();
        assert_eq!(reopened.palette.matches[0].id, CommandId::ViewToggleHelp);
        assert_eq!(reopened.palette.matches[1].id, CommandId::ViewCycleSort);
        assert_eq!(reopened.palette.recent().len(), 2);
        reopened.session_state().save_to(&path).unwrap();
        assert_eq!(
            SessionState::load_from(&path)
                .extra
                .get("future_setting")
                .and_then(toml::Value::as_str),
            Some("kept")
        );
    }
}