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
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
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss
)]
use anyhow::{Context as _, Result};

use dugix_core::app::{
    Popup, SEARCH_PROVIDERS, SETTINGS_GROUPS, SettingsField, SettingsRow, VERBOSITY_LEVELS,
};

use crate::app_view::AppView;

impl AppView {
    pub fn open_settings(&mut self) {
        self.settings_selected = 0;
        self.settings_inputs = [
            self.core
                .settings
                .temperature
                .map(|v| v.to_string())
                .unwrap_or_default(),
            self.core
                .settings
                .top_p
                .map(|v| v.to_string())
                .unwrap_or_default(),
            self.core
                .settings
                .max_tokens
                .map(|v| v.to_string())
                .unwrap_or_default(),
            self.core.settings.compact_threshold.to_string(),
            self.core.search.searxng_url.clone(),
            self.core.search.langsearch_key.clone(),
            std::fs::read_to_string(
                self.core
                    .space
                    .blocked_domains_path(&self.core.active_space.name),
            )
            .unwrap_or_default(),
        ];
        self.push_status(
            "↑/↓ field · type to edit · Space toggles · Ctrl+E system prompt · Esc saves"
                .to_string(),
        );
        self.popup = Popup::Settings;
    }

    pub fn settings_rows(&self) -> Vec<SettingsRow> {
        let mut rows = Vec::new();
        for (i, g) in SETTINGS_GROUPS.iter().enumerate() {
            rows.push(SettingsRow::Group(i));
            if !self.settings_collapsed.contains(&i) {
                rows.extend(g.fields.iter().map(|f| SettingsRow::Field(*f)));
            }
        }
        rows
    }

    pub fn settings_row(&self) -> SettingsRow {
        let rows = self.settings_rows();
        rows.get(self.settings_selected.min(rows.len().saturating_sub(1)))
            .copied()
            .unwrap_or(SettingsRow::Group(0))
    }

    pub fn settings_field(&self) -> Option<SettingsField> {
        match self.settings_row() {
            SettingsRow::Field(f) => Some(f),
            SettingsRow::Group(_) => None,
        }
    }

    pub fn move_settings_selection(&mut self, delta: i32) {
        let n = self.settings_rows().len() as i32;
        if n == 0 {
            return;
        }
        self.settings_selected = (self.settings_selected as i32 + delta).rem_euclid(n) as usize;
    }

    pub fn toggle_settings_field(&mut self) {
        match self.settings_row() {
            SettingsRow::Group(i) => {
                if !self.settings_collapsed.remove(&i) {
                    self.settings_collapsed.insert(i);
                }
            }
            SettingsRow::Field(field) => match field {
                SettingsField::RemoteImages => {
                    let value = if self.core.settings.remote_images {
                        "off"
                    } else {
                        "on"
                    };
                    let _ = self.core.set_setting("remote_images", value);
                }
                SettingsField::ShowStats => {
                    self.core.settings.show_stats = !self.core.settings.show_stats;
                }
                SettingsField::ShowReasoning => {
                    self.core.settings.show_reasoning = !self.core.settings.show_reasoning;
                    self.pin_viewport_top = true;
                }
                SettingsField::HideHints => {
                    self.core.settings.hide_hints = !self.core.settings.hide_hints;
                }
                SettingsField::ReplyStyle => {
                    let styles = dugix_core::app::REPLY_STYLES;
                    let i = styles
                        .iter()
                        .position(|&s| s == self.core.settings.reply_style)
                        .unwrap_or(0);
                    let _ = self
                        .core
                        .set_setting("reply_style", styles[(i + 1) % styles.len()]);
                }
                SettingsField::ImageViewer => {
                    let modes = dugix_core::app::IMAGE_VIEWERS;
                    let i = modes
                        .iter()
                        .position(|&m| m == self.core.settings.image_viewer)
                        .unwrap_or(0);
                    let _ = self
                        .core
                        .set_setting("image_viewer", modes[(i + 1) % modes.len()]);
                }
                SettingsField::CacheLifetime => {
                    let value = if self.core.settings.cache_lifetime == "extended" {
                        "default"
                    } else {
                        "extended"
                    };
                    let _ = self.core.set_setting("cache_lifetime", value);
                }
                SettingsField::CacheLongOpenai => {
                    let value = if self.core.settings.cache_long_openai {
                        "off"
                    } else {
                        "on"
                    };
                    let _ = self.core.set_setting("cache_long_openai", value);
                }
                SettingsField::Verbosity => {
                    let i = VERBOSITY_LEVELS
                        .iter()
                        .position(|&l| l == self.core.verbosity)
                        .unwrap_or(1);
                    self.core.verbosity =
                        VERBOSITY_LEVELS[(i + 1) % VERBOSITY_LEVELS.len()].to_string();
                }
                SettingsField::SearchProvider => {
                    let i = SEARCH_PROVIDERS
                        .iter()
                        .position(|&p| p == self.core.search.provider)
                        .unwrap_or(0);
                    self.core.search.provider =
                        SEARCH_PROVIDERS[(i + 1) % SEARCH_PROVIDERS.len()].to_string();
                }
                SettingsField::ColumnWidth => {
                    let _ = self.cycle_column_width(1);
                }
                _ => {}
            },
        }
    }

    pub fn cycle_column_width(&mut self, dir: i32) -> Result<()> {
        const STOPS: [&str; 6] = ["auto", "full", "100", "140", "180", "220"];
        let next = STOPS
            .iter()
            .position(|stop| *stop == self.core.settings.column_width)
            .map_or(0, |i| {
                (i as i32 + dir.signum()).rem_euclid(STOPS.len() as i32) as usize
            });
        self.core.set_setting("column_width", STOPS[next])
    }

    pub fn toggle_reasoning_view(&mut self) -> Result<()> {
        self.core.settings.show_reasoning = !self.core.settings.show_reasoning;
        self.pin_viewport_top = true;
        self.core.db.set_setting(
            "show_reasoning",
            if self.core.settings.show_reasoning {
                "1"
            } else {
                "0"
            },
        )?;
        let msg = if self.core.settings.show_reasoning {
            "reasoning expanded".to_string()
        } else {
            "reasoning collapsed".to_string()
        };
        self.push_status(msg);
        Ok(())
    }

    pub fn settings_input_char(&mut self, c: char) {
        let Some(i) = self.text_index() else { return };
        let numeric = !matches!(
            self.settings_field(),
            Some(
                SettingsField::SearxngUrl
                    | SettingsField::LangsearchKey
                    | SettingsField::BlockedDomains
            )
        );
        if numeric && !(c.is_ascii_digit() || c == '.') {
            return;
        }
        if !numeric && c.is_control() {
            return;
        }
        self.settings_inputs[i].push(c);
    }

    pub fn settings_input_backspace(&mut self) {
        if let Some(i) = self.text_index() {
            self.settings_inputs[i].pop();
        }
    }

    pub fn save_settings(&mut self) -> Result<()> {
        self.core.settings.temperature = self.settings_inputs[0].trim().parse().ok();
        self.core.settings.top_p = self.settings_inputs[1].trim().parse().ok();
        self.core.settings.max_tokens = self.settings_inputs[2].trim().parse().ok();
        self.core.settings.compact_threshold =
            self.settings_inputs[3].trim().parse().unwrap_or(0).min(100);

        let flag = |on: bool| if on { "1" } else { "0" }.to_string();
        self.core.search.searxng_url = self.settings_inputs[4]
            .trim()
            .trim_end_matches('/')
            .to_string();
        self.core.search.langsearch_key = self.settings_inputs[5].trim().to_string();

        // Rewriting unchanged rows bumps sync versions and can overwrite another device's edits.
        let values = [
            ("show_stats", flag(self.core.settings.show_stats)),
            ("show_reasoning", flag(self.core.settings.show_reasoning)),
            ("hide_hints", flag(self.core.settings.hide_hints)),
            ("temperature", self.settings_inputs[0].trim().to_string()),
            ("top_p", self.settings_inputs[1].trim().to_string()),
            ("max_tokens", self.settings_inputs[2].trim().to_string()),
            (
                "compact_threshold",
                self.core.settings.compact_threshold.to_string(),
            ),
            ("searxng_url", self.core.search.searxng_url.clone()),
            ("verbosity", self.core.verbosity.clone()),
            ("langsearch_key", self.core.search.langsearch_key.clone()),
            ("search_provider", self.core.search.provider.clone()),
        ];
        let stored: std::collections::HashMap<String, String> =
            self.core.db.load_settings()?.into_iter().collect();
        let mut changed = false;
        for (key, value) in values {
            if stored.get(key).map(String::as_str) != Some(value.as_str()) {
                self.core.db.set_setting(key, &value)?;
                changed = true;
            }
        }
        let blocked_path = self
            .core
            .space
            .blocked_domains_path(&self.core.active_space.name);
        let blocked = self.settings_inputs[6].trim();
        if std::fs::read_to_string(&blocked_path)
            .unwrap_or_default()
            .trim()
            != blocked
        {
            // Search reads this file, so a failed write must not report "settings saved".
            std::fs::write(&blocked_path, blocked)
                .with_context(|| format!("saving blocked domains to {}", blocked_path.display()))?;
            changed = true;
        }
        self.popup = Popup::None;
        if changed {
            self.core.refresh_toolbox();
            self.core.start_embedding();
            self.push_status("settings saved".to_string());
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use dugix_core::app::App;
    use dugix_core::db::Db;
    use dugix_core::space::Space;

    fn test_space() -> Space {
        Space {
            root: std::env::temp_dir().join(format!("dugix-flow-test-{}", uuid::Uuid::new_v4())),
        }
    }

    fn test_app() -> AppView {
        AppView::new(App::new(
            Db::open_in_memory().unwrap(),
            Some("sk-or-test-key"),
            test_space(),
        ))
    }

    #[test]
    fn searxng_url_setting_persists_and_enables_search_tool() {
        let db = Db::open_in_memory().unwrap();
        let mut a = AppView::new(App::new(db, Some("k"), test_space()));
        // search always works (DuckDuckGo fallback needs no config); only
        // the backend it uses depends on this setting.
        assert!(a.core.toolbox.defs().iter().any(|t| t.name == "search"));

        a.popup = Popup::Settings;
        a.settings_selected = a
            .settings_rows()
            .iter()
            .position(|row| matches!(row, SettingsRow::Field(SettingsField::SearxngUrl)))
            .unwrap();
        for c in "http://localhost:8080/".chars() {
            a.settings_input_char(c);
        }
        a.save_settings().unwrap();

        assert_eq!(a.core.search.searxng_url, "http://localhost:8080"); // trailing slash trimmed
        // The toolbox sits behind the `ToolExecutor` seam — the URL wiring
        // itself is covered by tools::tests::new_wires_searxng_url_and_langsearch_key.
        assert!(!a.skills.iter().any(|s| s.name == "web-search")); // retired bundled skill

        let reloaded = a.core.db.load_settings().unwrap();
        assert!(
            reloaded
                .iter()
                .any(|(k, v)| k == "searxng_url" && v == "http://localhost:8080")
        );

        // Reloading a fresh App from the same db picks it back up.
        let mut b = AppView::new(App::new(a.core.db, Some("k"), test_space()));
        // Re-apply persisted settings the way `App::new` would (load_settings is
        // private domain plumbing; the public path is a fresh App over the db).
        b.core.refresh_toolbox();
        assert_eq!(b.core.search.searxng_url, "http://localhost:8080");
    }

    #[test]
    fn verbosity_setting_persists_and_changes_the_prompt() {
        let mut a = test_app();
        a.popup = Popup::Settings;
        a.settings_selected = 4; // Verbosity
        a.toggle_settings_field(); // -> caveman
        a.save_settings().unwrap();
        assert!(a.core.system_prompt().contains("caveman-terse"));

        let reloaded = a.core.db.load_settings().unwrap();
        assert!(
            reloaded
                .iter()
                .any(|(k, v)| k == "verbosity" && v == "caveman")
        );
    }

    #[test]
    fn reply_style_cycles_in_settings_and_persists() {
        let mut a = test_app();
        a.popup = Popup::Settings;
        a.settings_selected = a
            .settings_rows()
            .iter()
            .position(|row| matches!(row, SettingsRow::Field(SettingsField::ReplyStyle)))
            .unwrap();
        assert_eq!(a.core.settings.reply_style, "interactive");
        a.toggle_settings_field();
        assert_eq!(a.core.settings.reply_style, "auto");
        a.toggle_settings_field();
        assert_eq!(a.core.settings.reply_style, "rich");
        a.toggle_settings_field();
        assert_eq!(a.core.settings.reply_style, "plain");
        a.toggle_settings_field();
        assert_eq!(a.core.settings.reply_style, "interactive");
        a.toggle_settings_field();
        a.toggle_settings_field();
        assert!(
            a.core
                .db
                .load_settings()
                .unwrap()
                .iter()
                .any(|(k, v)| k == "reply_style" && v == "rich")
        );
    }

    #[test]
    fn verbosity_cycles_through_all_three_levels() {
        let mut a = test_app();
        a.popup = Popup::Settings;
        a.settings_selected = 4; // Verbosity
        assert_eq!(a.verbosity, "concise");
        a.toggle_settings_field();
        assert_eq!(a.verbosity, "caveman");
        a.toggle_settings_field();
        assert_eq!(a.verbosity, "normal");
        a.toggle_settings_field();
        assert_eq!(a.verbosity, "concise");
    }

    #[test]
    fn collapsing_a_group_hides_its_fields_and_toggling_header_again_restores_them() {
        let db = Db::open_in_memory().unwrap();
        let mut a = AppView::new(App::new(db, Some("k"), test_space()));
        a.popup = Popup::Settings;
        let rows_expanded = a.settings_rows().len();
        a.settings_selected = 0; // first group header ("Interface")
        assert!(matches!(a.settings_row(), SettingsRow::Group(0)));
        a.toggle_settings_field(); // collapse it
        let rows_collapsed = a.settings_rows().len();
        assert!(rows_collapsed < rows_expanded);
        a.toggle_settings_field(); // expand it again
        assert_eq!(a.settings_rows().len(), rows_expanded);
    }

    #[test]
    fn settings_edit_and_save_persists() {
        let db = Db::open_in_memory().unwrap();
        let mut a = AppView::new(App::new(db, Some("k"), test_space()));
        a.popup = Popup::Settings;
        a.settings_selected = 1; // ShowStats (row 0 is the "Interface" group header)
        a.toggle_settings_field();
        assert!(a.core.settings.show_stats);
        a.settings_selected = 6; // Temperature (row 5 is the "Generation" group header)
        for c in "0.7".chars() {
            a.settings_input_char(c);
        }
        a.save_settings().unwrap();
        assert_eq!(a.core.settings.temperature, Some(0.7));

        // reload from db picks up the saved values
        let b = App::new(Db::open_in_memory().unwrap(), Some("k"), test_space());
        let _ = b; // separate in-memory db; just assert current instance loads its own
        let reloaded = a.core.db.load_settings().unwrap();
        assert!(
            reloaded
                .iter()
                .any(|(k, v)| k == "temperature" && v == "0.7")
        );
        assert!(reloaded.iter().any(|(k, v)| k == "show_stats" && v == "1"));
    }

    /// Saving /config never writes the removed per-feature model keys, and a
    /// stored one (an older build's, or another device's) is left untouched.
    #[test]
    fn saving_settings_writes_no_removed_model_keys() {
        let mut a = test_app();
        a.core.db.set_setting("ocr_model", "old/ocr").unwrap();
        a.open_settings();
        a.settings_inputs[0] = "0.3".into();
        a.save_settings().unwrap();
        let stored = a.core.db.load_settings().unwrap();
        assert!(stored.iter().any(|(k, v)| k == "temperature" && v == "0.3"));
        for removed in [
            "memory_model",
            "transcriber_model",
            "ocr_engine",
            "embedding_model",
            "image_gen_model",
            "video_gen_model",
        ] {
            assert!(stored.iter().all(|(k, _)| k != removed), "{removed}");
        }
        assert!(
            stored
                .iter()
                .any(|(k, v)| k == "ocr_model" && v == "old/ocr"),
            "a stored legacy row is left alone"
        );
    }

    /// Closing /config without edits rewrites nothing (each write bumps the
    /// row's sync version and would win LWW over other devices), so it says
    /// nothing either; a real edit still reports the save.
    #[test]
    fn closing_settings_unchanged_is_a_silent_no_op() {
        let mut a = test_app();
        a.open_settings();
        a.save_settings().unwrap();
        let _ = a.last_status();
        a.open_settings();
        let _ = a.last_status(); // the popup's own hint line
        a.save_settings().unwrap();
        assert_eq!(a.last_status(), "", "no 'settings saved' for a no-op close");

        a.open_settings();
        let _ = a.last_status();
        a.settings_inputs[0] = "0.3".into();
        a.save_settings().unwrap();
        assert_eq!(a.last_status(), "settings saved");
    }
}