kimun-notes 0.24.5

A terminal-based notes application
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
use std::sync::Arc;

use async_trait::async_trait;
use kimun_core::NoteVault;
use kimun_core::error::VaultError;
use kimun_core::nfs::VaultPath;
use throbber_widgets_tui::ThrobberState;

use crate::app_screen::{AppScreen, ScreenKind};
use crate::components::event_state::EventState;
use crate::components::events::{AppEvent, AppTx, InputEvent};
use crate::components::indexing::{IndexingProgressState, render_indexing_overlay, spawn_running};
use crate::settings::SharedSettings;
use crate::settings::themes::Theme;

pub struct StartScreen {
    settings: SharedSettings,
    theme: Theme,
    vault: Option<Arc<NoteVault>>,
    overlay: Option<IndexingProgressState>,
    throbber_state: ThrobberState,
}

impl StartScreen {
    pub fn new(settings: SharedSettings, vault: Option<Arc<NoteVault>>) -> Self {
        let theme = settings.read().unwrap().get_theme();
        Self {
            settings,
            theme,
            vault,
            overlay: None,
            throbber_state: ThrobberState::default(),
        }
    }

    /// Where the restored session lands: the newest history entry still on
    /// disk, or the vault root when none is. Notes moved or deleted outside
    /// kimün are skipped, not offered for re-creation — the user asked for
    /// their last note, not for a new one — and dropped from the history so
    /// they stop turning up in recents.
    ///
    /// When the note it would have landed on is the one gone, it parks a
    /// flash saying so: the editor opening somewhere else unannounced reads
    /// as kimün losing the note.
    ///
    /// Only trusted after a successful index (`vault_reachable`): when the
    /// vault itself can't be read every note looks gone, and pruning then
    /// would wipe the history for good. It lands on the newest entry
    /// unchecked instead, as it did before any of this existed.
    async fn restore_target(&self, vault_reachable: bool, tx: &AppTx) -> VaultPath {
        let history = self.settings.read().unwrap().current_last_paths();
        // No vault (no workspace — the open is routed to onboarding) or one
        // that failed to index: nothing trustworthy to check the history
        // against.
        let Some(vault) = self.vault.as_ref().filter(|_| vault_reachable) else {
            return history.first().cloned().unwrap_or_else(VaultPath::root);
        };
        let mut live = Vec::with_capacity(history.len());
        let mut gone = Vec::new();
        for path in &history {
            // Gone means the filesystem said not found. Any other failure
            // (permissions, I/O) keeps the entry: it may well still be there.
            if vault
                .entry_kind(path)
                .await
                .is_err_and(|e| e.is_not_found())
            {
                gone.push(path.clone());
            } else {
                live.push(path.clone());
            }
        }
        if !gone.is_empty() {
            self.settings.read().unwrap().edit_path_history(|paths| {
                paths.retain(|p| !gone.iter().any(|g| g.is_like(p)));
                true
            });
        }
        if let Some(last) = history.first()
            && live.first() != Some(last)
        {
            tx.send(AppEvent::ParkFlash(format!(
                "{last} is gone (moved or deleted outside kimün)"
            )))
            .ok();
        }
        live.first().cloned().unwrap_or_else(VaultPath::root)
    }
}

#[async_trait]
impl AppScreen for StartScreen {
    async fn on_enter(&mut self, tx: &AppTx) {
        if let Some(vault) = self.vault.clone() {
            let tx2 = tx.clone();
            let handle = tokio::spawn(async move {
                match vault.validate_and_init().await {
                    Ok(report) => {
                        tx2.send(AppEvent::IndexingDone(Ok(report.duration))).ok();
                    }
                    Err(e @ VaultError::CaseConflict { .. }) => {
                        // Route structural vault conflicts to VaultConflict so the main
                        // loop can clear the vault path and redirect to settings.
                        // To support a future VaultError conflict type: add one arm here.
                        tx2.send(AppEvent::VaultConflict(e.to_string())).ok();
                    }
                    Err(e) => {
                        tx2.send(AppEvent::IndexingDone(Err(e.to_string()))).ok();
                    }
                }
            });
            self.overlay = Some(spawn_running(handle, tx));
        } else {
            let path = self.restore_target(false, tx).await;
            tx.send(AppEvent::open(path)).ok();
        }
    }

    fn get_kind(&self) -> ScreenKind {
        ScreenKind::Start
    }

    fn handle_input(&mut self, _event: &InputEvent, _tx: &AppTx) -> EventState {
        if matches!(self.overlay, Some(IndexingProgressState::Running { .. })) {
            return EventState::Consumed;
        }
        EventState::NotConsumed
    }

    async fn handle_app_message(&mut self, msg: AppEvent, tx: &AppTx) {
        if let AppEvent::IndexingDone(result) = &msg {
            self.overlay = None;
            let path = self.restore_target(result.is_ok(), tx).await;
            tx.send(AppEvent::open(path)).ok();
        }
    }

    fn render(&mut self, f: &mut ratatui::Frame) {
        if let Some(ref state) = self.overlay {
            render_indexing_overlay(
                f,
                state,
                &mut self.throbber_state,
                &self.theme,
                "Initializing vault…",
            );
            return;
        }
        let block = ratatui::widgets::Block::default()
            .title("Start app")
            .borders(ratatui::widgets::Borders::ALL);
        f.render_widget(block, f.area());
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;
    use crate::settings::AppSettings;
    use crate::test_support::{key_event, temp_vault};
    use kimun_core::VaultConfig;
    use ratatui::crossterm::event::KeyCode;
    use std::sync::{Arc, RwLock};
    use tokio::sync::mpsc::unbounded_channel;

    fn shared_defaults() -> SharedSettings {
        Arc::new(RwLock::new(AppSettings::default()))
    }

    async fn make_vault() -> Arc<NoteVault> {
        temp_vault("start").await
    }

    #[tokio::test]
    async fn on_enter_vault_none_sends_open_path() {
        let (tx, mut rx) = unbounded_channel::<AppEvent>();
        let mut screen = StartScreen::new(shared_defaults(), None);
        screen.on_enter(&tx).await;
        let msg = rx.try_recv().expect("expected a message");
        assert!(
            matches!(msg, AppEvent::OpenPath { .. }),
            "expected OpenPath, got {:?}",
            msg
        );
        assert!(
            screen.overlay.is_none(),
            "overlay should be None when vault is None"
        );
    }

    #[tokio::test]
    async fn on_enter_vault_some_sets_overlay_and_defers_open_path() {
        let (tx, mut rx) = unbounded_channel::<AppEvent>();
        let vault = make_vault().await;
        let mut screen = StartScreen::new(shared_defaults(), Some(vault));
        screen.on_enter(&tx).await;
        assert!(
            matches!(screen.overlay, Some(IndexingProgressState::Running { .. })),
            "overlay should be Running after on_enter with vault"
        );
        // Drain all messages and ensure none are OpenPath
        let messages: Vec<AppEvent> = std::iter::from_fn(|| rx.try_recv().ok()).collect::<Vec<_>>();
        let has_open_path = messages
            .iter()
            .any(|m| matches!(m, AppEvent::OpenPath { .. }));
        assert!(
            !has_open_path,
            "OpenPath should not be sent immediately when vault is Some"
        );
    }

    #[tokio::test]
    async fn handle_app_message_indexing_done_ok_clears_overlay_and_sends_open_path() {
        let (tx, mut rx) = unbounded_channel::<AppEvent>();
        let mut screen = StartScreen::new(shared_defaults(), None);
        screen.overlay = Some(IndexingProgressState::Running {
            work: tokio::spawn(async {}),
            ticker: tokio::spawn(async {}),
        });
        screen
            .handle_app_message(AppEvent::IndexingDone(Ok(Duration::from_secs(1))), &tx)
            .await;
        assert!(screen.overlay.is_none(), "overlay should be cleared");
        let msg = rx.try_recv().expect("expected OpenPath message");
        assert!(
            matches!(msg, AppEvent::OpenPath { .. }),
            "expected OpenPath after indexing done"
        );
    }

    #[tokio::test]
    async fn handle_app_message_indexing_done_err_clears_overlay_and_sends_open_path() {
        let (tx, mut rx) = unbounded_channel::<AppEvent>();
        let mut screen = StartScreen::new(shared_defaults(), None);
        screen.overlay = Some(IndexingProgressState::Running {
            work: tokio::spawn(async {}),
            ticker: tokio::spawn(async {}),
        });
        screen
            .handle_app_message(AppEvent::IndexingDone(Err("fail".to_string())), &tx)
            .await;
        assert!(
            screen.overlay.is_none(),
            "overlay should be cleared on error"
        );
        let msg = rx.try_recv().expect("expected OpenPath message");
        assert!(
            matches!(msg, AppEvent::OpenPath { .. }),
            "expected OpenPath even after failed indexing"
        );
    }

    /// A vault holding `existing` notes, and settings whose history for it is
    /// `history` (newest first). Returns the history dir guard with the rest.
    async fn restore_fixture(
        history: &[&str],
        existing: &[&str],
    ) -> (StartScreen, SharedSettings, tempfile::TempDir) {
        let vault = make_vault().await;
        for note in existing {
            vault
                .create_note(&VaultPath::new(*note), "text")
                .await
                .unwrap();
        }
        let history_dir = tempfile::TempDir::new().unwrap();
        let settings = AppSettings::for_test_workspace(
            "ws",
            vault.workspace_path(),
            crate::test_support::sys(history_dir.path()),
        );
        settings.seed_test_history(history);
        let settings: SharedSettings = Arc::new(RwLock::new(settings));
        let screen = StartScreen::new(settings.clone(), Some(vault));
        (screen, settings, history_dir)
    }

    /// Runs the post-indexing restore and returns every event it sent.
    async fn restore(screen: &mut StartScreen) -> Vec<AppEvent> {
        restore_after(screen, Ok(Duration::from_secs(0))).await
    }

    async fn restore_after(
        screen: &mut StartScreen,
        indexing: Result<Duration, String>,
    ) -> Vec<AppEvent> {
        let (tx, mut rx) = unbounded_channel::<AppEvent>();
        screen
            .handle_app_message(AppEvent::IndexingDone(indexing), &tx)
            .await;
        std::iter::from_fn(|| rx.try_recv().ok()).collect()
    }

    /// A failed index usually means the vault itself is out of reach (an
    /// unmounted drive, a sync folder not there yet). Every note looks
    /// missing then, and pruning would wipe the history for good.
    /// Only a note the filesystem reports as not found is gone. One it can't
    /// look at right now (permissions, I/O) may well still be there.
    #[cfg(unix)]
    #[tokio::test]
    async fn restore_keeps_a_note_it_cannot_check() {
        use std::os::unix::fs::PermissionsExt;

        let (mut screen, settings, _dir) = restore_fixture(
            &["locked/note.md", "still.md"],
            &["locked/note.md", "still.md"],
        )
        .await;
        let locked = screen
            .vault
            .as_ref()
            .unwrap()
            .workspace_path()
            .join("locked")
            .into_path_buf();
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
        restore(&mut screen).await;
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();

        assert_eq!(
            settings.read().unwrap().current_last_paths(),
            vec![VaultPath::new("locked/note.md"), VaultPath::new("still.md")]
        );
    }

    #[tokio::test]
    async fn restore_after_failed_indexing_leaves_the_history_alone() {
        let (mut screen, settings, _dir) =
            restore_fixture(&["gone.md", "still.md"], &["still.md"]).await;
        let events = restore_after(&mut screen, Err("unreachable".to_string())).await;
        assert_eq!(
            settings.read().unwrap().current_last_paths(),
            vec![VaultPath::new("gone.md"), VaultPath::new("still.md")]
        );
        assert!(parked_flashes(&events).is_empty());
    }

    fn opened(events: &[AppEvent]) -> Vec<VaultPath> {
        events
            .iter()
            .filter_map(|e| match e {
                AppEvent::OpenPath { path, .. } => Some(path.clone()),
                _ => None,
            })
            .collect()
    }

    #[tokio::test]
    async fn restore_skips_a_last_note_gone_from_disk() {
        let (mut screen, _settings, _dir) =
            restore_fixture(&["gone.md", "still.md"], &["still.md"]).await;
        let events = restore(&mut screen).await;
        assert_eq!(opened(&events), vec![VaultPath::new("still.md")]);
    }

    fn parked_flashes(events: &[AppEvent]) -> Vec<String> {
        events
            .iter()
            .filter_map(|e| match e {
                AppEvent::ParkFlash(msg) => Some(msg.clone()),
                _ => None,
            })
            .collect()
    }

    #[tokio::test]
    async fn restore_tells_the_user_their_last_note_is_gone() {
        let (mut screen, _settings, _dir) =
            restore_fixture(&["gone.md", "still.md"], &["still.md"]).await;
        let events = restore(&mut screen).await;
        let flashes = parked_flashes(&events);
        assert_eq!(
            flashes.len(),
            1,
            "expected one parked flash, got {flashes:?}"
        );
        assert!(
            flashes[0].contains("gone.md"),
            "flash must name the note: {flashes:?}"
        );
    }

    /// Only the note the user expected to land on is worth a word; older
    /// entries vanishing from recents is not news.
    #[tokio::test]
    async fn restore_is_silent_when_only_older_entries_are_gone() {
        let (mut screen, _settings, _dir) =
            restore_fixture(&["still.md", "gone.md"], &["still.md"]).await;
        let events = restore(&mut screen).await;
        assert!(parked_flashes(&events).is_empty());
    }

    #[tokio::test]
    async fn restore_lands_on_the_root_when_no_history_entry_survives() {
        let (mut screen, _settings, _dir) = restore_fixture(&["a.md", "b.md"], &[]).await;
        let events = restore(&mut screen).await;
        assert_eq!(opened(&events), vec![VaultPath::root()]);
    }

    #[tokio::test]
    async fn restore_drops_notes_gone_from_disk_from_the_history() {
        let (mut screen, settings, _dir) =
            restore_fixture(&["gone.md", "still.md", "also_gone.md"], &["still.md"]).await;
        restore(&mut screen).await;
        assert_eq!(
            settings.read().unwrap().current_last_paths(),
            vec![VaultPath::new("still.md")]
        );
    }

    #[tokio::test]
    async fn handle_input_blocked_while_overlay_running() {
        let (tx, mut rx) = unbounded_channel::<AppEvent>();
        let mut screen = StartScreen::new(shared_defaults(), None);
        screen.overlay = Some(IndexingProgressState::Running {
            work: tokio::spawn(async {}),
            ticker: tokio::spawn(async {}),
        });
        let state = screen.handle_input(&key_event(KeyCode::Enter), &tx);
        assert!(
            matches!(state, EventState::Consumed),
            "input should be consumed while overlay is running"
        );
        // Drain the ticker Redraw messages but confirm no other app-level messages
        let messages: Vec<AppEvent> = std::iter::from_fn(|| rx.try_recv().ok()).collect::<Vec<_>>();
        let has_non_redraw = messages.iter().any(|m| !matches!(m, AppEvent::Redraw));
        assert!(
            !has_non_redraw,
            "handle_input should not send non-Redraw messages"
        );
    }

    #[tokio::test]
    async fn handle_input_not_consumed_while_overlay_none() {
        let (tx, _rx) = unbounded_channel::<AppEvent>();
        let mut screen = StartScreen::new(shared_defaults(), None);
        screen.overlay = None;
        let state = screen.handle_input(&key_event(KeyCode::Enter), &tx);
        assert!(
            matches!(state, EventState::NotConsumed),
            "input should not be consumed when overlay is None"
        );
    }

    // Linux only: macOS and Windows filesystems are case-insensitive by default,
    // so creating note.md + Note.md would silently overwrite on those platforms.
    #[cfg(target_os = "linux")]
    #[tokio::test]
    async fn on_enter_case_conflict_sends_vault_conflict_not_indexing_done() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::write(tmp.path().join("note.md"), "a").unwrap();
        std::fs::write(tmp.path().join("Note.md"), "b").unwrap();

        let vault = Arc::new(
            NoteVault::new(VaultConfig::new(crate::test_support::sys(tmp.path())))
                .await
                .unwrap(),
        );
        let (tx, mut rx) = unbounded_channel::<AppEvent>();
        let mut screen = StartScreen::new(shared_defaults(), Some(vault));
        screen.on_enter(&tx).await;

        // Drain events until VaultConflict arrives; skip Redraw ticks from the spinner.
        let conflict_msg = loop {
            let msg = tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv())
                .await
                .expect("timed out waiting for VaultConflict")
                .expect("channel closed");

            match msg {
                AppEvent::VaultConflict(details) => break details,
                AppEvent::Redraw => continue,
                AppEvent::IndexingDone(_) => panic!("expected VaultConflict, got IndexingDone"),
                _ => continue,
            }
        };

        assert!(
            conflict_msg.contains("note.md") && conflict_msg.contains("Note.md"),
            "conflict message should name both files, got: {}",
            conflict_msg
        );
    }
}