dugix 1.0.0

A local-first terminal chat app for deep research and multi-agent work
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
//! The `/library` popup: a snapshot of the list and of each mode, and every key.
//! Dialogs are scripted and the studio window is `cat`, so nothing opens.

use std::path::PathBuf;
use std::time::{Duration, SystemTime};

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use dugix_core::app::{App, Popup};
use dugix_core::canvas::dialogs::Scripted;
use dugix_core::db::Db;
use dugix_core::deck::Deck;
use dugix_core::doc::Doc;
use dugix_core::space::Space;
use ratatui::Terminal;
use ratatui::backend::TestBackend;

use crate::app_view::AppView;

struct Fixture {
    app: AppView,
    root: PathBuf,
}

impl Fixture {
    fn new() -> Self {
        let db = Db::open_in_memory().unwrap();
        let root =
            std::env::temp_dir().join(format!("dugix-library-popup-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(root.join("spaces")).unwrap();
        let root = root.canonicalize().unwrap();
        let app = AppView::new(App::new(db, Some("k"), Space { root: root.clone() }));
        Self { app, root }
    }

    fn files(&self) -> PathBuf {
        self.app.space.files_dir(&self.app.active_space.name)
    }

    fn put(&self, relative: &str, bytes: &[u8], age_seconds: u64) -> PathBuf {
        let path = self.files().join(relative);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, bytes).unwrap();
        let file = std::fs::File::options().write(true).open(&path).unwrap();
        file.set_modified(SystemTime::now() - Duration::from_secs(age_seconds))
            .unwrap();
        path
    }

    fn deck(&self, relative: &str, title: &str, age_seconds: u64) -> PathBuf {
        self.put(
            relative,
            &serde_json::to_vec_pretty(&Deck::titled(title)).unwrap(),
            age_seconds,
        )
    }

    fn doc(&self, relative: &str, title: &str, age_seconds: u64) -> PathBuf {
        let mut doc = Doc::from_design(title, &dugix_core::design::Design::default());
        doc.blocks =
            dugix_core::doc::markdown::parse_document("# T\n\nBody.\n\nMore.\n", true).blocks;
        let doc = Doc::check(&serde_json::to_string(&doc).unwrap()).unwrap();
        self.put(
            relative,
            &serde_json::to_vec_pretty(&doc).unwrap(),
            age_seconds,
        )
    }

    /// Three files, oldest to newest: a deck, a doc and a deck.
    fn library(&mut self) {
        self.deck("decks/roadmap.deck.json", "Roadmap 2027", 5 * 86_400 + 600);
        self.doc("docs/memo.doc.json", "Q3 memo", 26 * 3600);
        self.deck("decks/launch.deck.json", "Launch review", 3 * 3600 + 300);
    }

    fn open(&mut self) {
        self.app.run_command("library").unwrap();
    }

    fn key(&mut self, code: KeyCode) {
        crate::ui::popups::library::handle_key(&mut self.app, KeyEvent::from(code));
    }

    fn press(&mut self, c: char) {
        self.key(KeyCode::Char(c));
    }

    fn ctrl(&mut self, c: char) {
        crate::ui::popups::library::handle_key(
            &mut self.app,
            KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL),
        );
    }

    fn screen(&self, width: u16, height: u16) -> String {
        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal
            .draw(|frame| crate::ui::popups::library::render(frame, &self.app))
            .unwrap();
        let buffer = terminal.backend().buffer();
        let mut out = String::new();
        for y in 0..buffer.area.height {
            for x in 0..buffer.area.width {
                out.push_str(buffer[(x, y)].symbol());
            }
            out.push('\n');
        }
        out
    }

    /// The newest status line: what the popup said through the event seam.
    fn status(&mut self) -> String {
        while let Some(event) = self.app.pop_pending_event() {
            self.app.apply_event(&event);
        }
        self.app.status.clone()
    }
}

impl Drop for Fixture {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.root);
    }
}

/// The framed body of a popup: each line between the borders, trimmed, with
/// empty ones dropped.
fn body(screen: &str) -> Vec<String> {
    screen
        .lines()
        .filter_map(|line| {
            let (_, text) = line.split_once('โ”‚')?;
            let (text, _) = text.rsplit_once('โ”‚')?;
            let text = text.trim();
            (!text.is_empty()).then(|| text.to_string())
        })
        .collect()
}

#[test]
fn library_is_a_command_with_a_catalog_entry() {
    let mut f = Fixture::new();
    assert!(
        dugix_core::app::COMMANDS
            .iter()
            .any(|c| c.name == "library" && !c.desc.is_empty())
    );
    assert_eq!(
        f.app.core.parse_command("library").unwrap(),
        dugix_core::app::AppCommand::OpenLibrary
    );
    assert_eq!(
        f.app.core.parse_command("decks").unwrap(),
        dugix_core::app::AppCommand::OpenLibrary
    );
    f.app.run_command("library").unwrap();
    assert_eq!(f.app.popup, Popup::Library);
    f.app
        .core
        .execute(dugix_core::app::AppCommand::OpenLibrary)
        .unwrap();
}

#[test]
fn the_popup_lists_kind_title_count_and_time_newest_first() {
    let mut f = Fixture::new();
    f.library();
    f.open();
    let screen = f.screen(100, 22);
    println!("{screen}");
    assert!(screen.contains(" Library "), "{screen}");
    assert_eq!(
        body(&screen),
        [
            "โŒ• Type to filter".to_string(),
            "โ”€".repeat(74),
            "โ–ธ deck   Launch review".to_string(),
            "1 slide ยท 3 hours ago".to_string(),
            "doc    Q3 memo".to_string(),
            "3 blocks ยท yesterday ยท dugix".to_string(),
            "deck   Roadmap 2027".to_string(),
            "1 slide ยท 5 days ago".to_string(),
        ]
    );
    assert!(
        screen
            .lines()
            .find(|line| line.contains('โ•ญ'))
            .unwrap()
            .contains("3 documents")
            && screen.contains("โ†‘โ†“ ยท Enter open ยท ^E export ยท ^D delete ยท Esc close"),
        "{screen}"
    );
}

#[test]
fn an_empty_library_says_so() {
    let mut f = Fixture::new();
    f.open();
    let screen = f.screen(100, 12);
    assert!(
        screen.contains("No decks or docs yet. Ask the model to draft one."),
        "{screen}"
    );
    assert!(screen.contains("Esc close"), "{screen}");
    f.ctrl('e');
    f.ctrl('d');
    f.key(KeyCode::Enter);
    assert_eq!(f.app.library.mode, crate::ui::popups::library::Mode::Browse);
}

#[test]
fn the_cursor_moves_and_clamps() {
    let mut f = Fixture::new();
    f.library();
    f.open();
    f.key(KeyCode::Up);
    assert_eq!(f.app.library.selected, 0);
    f.key(KeyCode::Down);
    f.key(KeyCode::Down);
    assert_eq!(f.app.library.selected, 2);
    f.key(KeyCode::Down);
    assert_eq!(f.app.library.selected, 2, "the end clamps");
    f.key(KeyCode::Up);
    assert_eq!(f.app.library.selected, 1);
    f.key(KeyCode::Home);
    assert_eq!(f.app.library.selected, 0);
    f.key(KeyCode::End);
    assert_eq!(f.app.library.selected, 2);
    f.key(KeyCode::PageUp);
    assert_eq!(f.app.library.selected, 0);
    f.key(KeyCode::PageDown);
    assert_eq!(f.app.library.selected, 2);
    let screen = f.screen(100, 22);
    assert!(screen.contains("โ–ธ deck   Roadmap 2027"), "{screen}");
}

#[test]
fn escape_closes_and_the_list_is_read_again_on_reopen() {
    let mut f = Fixture::new();
    f.library();
    f.open();
    f.key(KeyCode::Esc);
    assert_eq!(f.app.popup, Popup::None);
    f.deck("decks/new.deck.json", "Brand new", 1);
    f.open();
    assert_eq!(f.app.library.entries.len(), 4);
    assert_eq!(f.app.library.entries[0].title, "Brand new");
}

#[test]
fn enter_opens_the_file_in_studio() {
    let mut f = Fixture::new();
    f.library();
    f.app.attach_fake_studio();
    f.open();
    f.key(KeyCode::Down);
    f.key(KeyCode::Enter);
    assert_eq!(f.app.popup, Popup::None);
    assert!(
        f.app
            .studio_last_file()
            .is_some_and(|path| path.ends_with("docs/memo.doc.json"))
    );
    assert_eq!(f.status(), "studio focused");
}

#[test]
fn e_asks_for_a_format_then_exports_through_the_save_dialog() {
    let mut f = Fixture::new();
    f.library();
    let out = f.root.join("Desktop");
    std::fs::create_dir_all(&out).unwrap();
    let dialogs = Scripted::new([Some(out.join("review.pptx")), Some(out.join("memo"))]);
    f.app.dialogs = Box::new(dialogs.clone());
    f.open();
    f.ctrl('e');
    let screen = f.screen(100, 22);
    assert!(screen.contains("Export โ€œLaunch reviewโ€"), "{screen}");
    assert!(
        screen.contains("p pptx ยท f pdf ยท g png ยท h html ยท j json ยท Esc back"),
        "{screen}"
    );
    f.press('z');
    assert_eq!(
        f.app.library.mode,
        crate::ui::popups::library::Mode::ExportAs
    );
    f.key(KeyCode::Esc);
    assert_eq!(f.app.library.mode, crate::ui::popups::library::Mode::Browse);
    assert_eq!(f.app.popup, Popup::Library, "Escape went back, not out");

    f.ctrl('e');
    f.press('p');
    assert_eq!(&std::fs::read(out.join("review.pptx")).unwrap()[..2], b"PK");
    assert!(f.status().starts_with("exported to "), "{}", f.status());
    let asked = dialogs.requests();
    assert!(asked[0].save);
    assert_eq!(asked[0].name, "Launch review.pptx");
    assert_eq!(asked[0].filters, ["PowerPoint"]);
    assert!(asked[0].start.is_none());

    f.key(KeyCode::Down);
    f.ctrl('e');
    let screen = f.screen(100, 22);
    assert!(
        screen.contains("w docx ยท f pdf ยท m md ยท h html ยท Esc back"),
        "{screen}"
    );
    f.press('w');
    assert_eq!(&std::fs::read(out.join("memo.docx")).unwrap()[..2], b"PK");
    assert_eq!(dialogs.requests()[1].name, "Q3 memo.docx");
    assert_eq!(dialogs.requests()[1].start.as_deref(), Some(out.as_path()));
    assert_eq!(f.app.popup, Popup::Library);
    assert_eq!(f.app.library.selected, 1);
}

#[test]
fn a_cancelled_dialog_exports_nothing() {
    let mut f = Fixture::new();
    f.library();
    f.app.dialogs = Box::new(Scripted::new([None]));
    f.open();
    f.ctrl('e');
    f.press('p');
    assert_eq!(f.status(), "export cancelled");
    assert!(!f.files().join("exports").exists());
}

#[test]
fn without_a_desktop_session_the_export_goes_to_the_exports_folder() {
    let mut f = Fixture::new();
    f.library();
    let dialogs = Scripted::unavailable();
    f.app.dialogs = Box::new(dialogs.clone());
    f.open();
    f.ctrl('e');
    f.press('f');
    assert!(dialogs.requests().is_empty(), "no dialog was asked for");
    let exported = f.files().join("exports/launch-review.pdf");
    assert_eq!(&std::fs::read(exported).unwrap()[..4], b"%PDF");
    let status = f.status();
    assert!(
        status.starts_with("no desktop session for a Save dialog โ€” exported to "),
        "{status}"
    );
}

#[test]
fn d_confirms_before_moving_the_file_to_the_trash() {
    let mut f = Fixture::new();
    f.library();
    f.open();
    f.key(KeyCode::Down);
    f.ctrl('d');
    let screen = f.screen(100, 22);
    assert!(screen.contains("Delete document?"), "{screen}");
    assert!(
        screen.contains("โ€œdocs/memo.doc.jsonโ€ will be moved to the trash folder."),
        "{screen}"
    );
    assert!(screen.contains("^D delete ยท Esc cancel"), "{screen}");
    f.press('x');
    assert_eq!(
        f.app.library.mode,
        crate::ui::popups::library::Mode::ConfirmDelete
    );
    f.key(KeyCode::Esc);
    assert_eq!(f.app.library.mode, crate::ui::popups::library::Mode::Browse);
    assert!(f.files().join("docs/memo.doc.json").is_file());
    f.ctrl('d');
    f.press('n');
    assert!(f.files().join("docs/memo.doc.json").is_file());
    assert_eq!(
        f.app.library.mode,
        crate::ui::popups::library::Mode::ConfirmDelete
    );
    f.press('y');
    assert!(f.files().join("docs/memo.doc.json").is_file());
    f.ctrl('d');
    assert!(!f.files().join("docs/memo.doc.json").exists());
    assert!(
        f.status()
            .starts_with("moved \"Q3 memo\" to the trash folder"),
        "{}",
        f.status()
    );
    assert_eq!(f.app.library.entries.len(), 2);
    assert_eq!(f.app.library.selected, 1);
    assert!(std::fs::read_dir(f.files().join(".trash")).unwrap().count() == 1);
    f.ctrl('d');
    crate::ui::popups::library::handle_key(
        &mut f.app,
        KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL),
    );
    assert_eq!(f.app.library.entries.len(), 1);
}

#[test]
fn studio_without_a_recent_file_opens_the_library_instead() {
    let mut f = Fixture::new();
    f.library();
    f.app.run_command("studio").unwrap();
    let status = f.status();
    assert_eq!(f.app.popup, Popup::Library, "{status}");
    assert_eq!(f.app.library.entries.len(), 3);
    f.app.popup = Popup::None;
    f.app.attach_fake_studio();
    f.app.run_command("studio decks/launch.deck.json").unwrap();
    assert_eq!(f.app.popup, Popup::None);
    assert!(
        f.app
            .studio_last_file()
            .unwrap()
            .ends_with("decks/launch.deck.json")
    );
    f.app.run_command("studio").unwrap();
    assert_eq!(f.app.popup, Popup::None);
    assert_eq!(f.status(), "studio focused");
}

#[test]
fn incognito_has_no_library() {
    let mut f = Fixture::new();
    f.library();
    f.app.core.incognito = true;
    f.app.run_command("library").unwrap();
    assert_eq!(f.app.popup, Popup::None);
    assert_eq!(f.status(), "library isn't available in incognito mode");
}

#[test]
fn the_list_records_where_each_row_is_drawn_for_mouse_clicks() {
    // Rendering records three lines per entry; clicks map through that.
    let mut f = Fixture::new();
    f.library();
    f.open();
    let screen = f.screen(100, 22);
    assert!(!screen.is_empty());
    let hit = f
        .app
        .list_hit
        .get()
        .expect("the list records where it drew");
    assert_eq!(hit.item_lines, 3);
    assert_eq!(hit.total, 3);
    assert_eq!(hit.selected, Some(0));
}