synaps-tui 0.6.1

Terminal UI layer — ratatui, crossterm, syntect, tachyonfx
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
//! Settings modal — full-screen overlay opened via /settings.
//! Persists changes to ~/.synaps-cli/config and mutates Runtime where possible.

pub(crate) mod defs;
pub(crate) mod draw;
pub(crate) mod input;
pub(crate) mod plugin_editor;
pub(crate) mod schema;

pub(crate) use draw::render;
pub(crate) use input::{handle_event, InputOutcome};

use crate::tui::focus::FocusRing;

const BUILTIN_THEMES: &[&str] = &[
    "default",
    "night-city",
    "neon-rain",
    "amber",
    "phosphor",
    "solarized-dark",
    "blood",
    "ocean",
    "rose-pine",
    "nord",
    "dracula",
    "monokai",
    "gruvbox",
    "catppuccin",
    "tokyo-night",
    "sunset",
    "ice",
    "forest",
    "lavender",
];

pub(crate) fn theme_options() -> Vec<String> {
    let mut opts: Vec<String> = BUILTIN_THEMES.iter().map(|s| s.to_string()).collect();
    if let Some(home) = std::env::var_os("HOME") {
        let themes_dir = std::path::PathBuf::from(home).join(".synaps-cli/themes");
        if let Ok(entries) = std::fs::read_dir(&themes_dir) {
            for e in entries.flatten() {
                if let Some(name) = e.path().file_stem().and_then(|s| s.to_str()) {
                    let s = name.to_string();
                    if !opts.contains(&s) {
                        opts.push(s);
                    }
                }
            }
        }
    }
    opts
}

use schema::SettingDef;

#[derive(Clone)]
pub(crate) struct PluginRow {
    pub name: String,
    pub skill_count: usize,
}

#[derive(Clone)]
/// Snapshot of live runtime + persisted config values, used to display current
/// values in the modal and seed text editors.
pub(crate) struct RuntimeSnapshot {
    pub model: String,
    pub thinking: String,
    pub context_window: String,
    pub compaction_model: String,
    pub max_tool_output: usize,
    pub bash_timeout: u64,
    pub bash_max_timeout: u64,
    pub subagent_timeout: u64,
    pub api_retries: u32,
    pub theme_name: String,
    pub plugins: Vec<PluginRow>,
    pub disabled_plugins: Vec<String>,
    pub provider_keys: std::collections::BTreeMap<String, String>,
    /// Cached ping results for models. Key format: "provider/model" (or bare
    /// model id for Anthropic). Empty until `/ping` has been run.
    pub model_health:
        std::collections::HashMap<String, (synaps_cli::runtime::openai::ping::PingStatus, u64)>,
    /// Plugin-declared settings categories snapshotted from the registry
    /// at modal-open time. Each entry contributes a category row in the
    /// left pane and a list of fields in the right pane. Path B Phase 4.
    pub plugin_categories: Vec<synaps_cli::skills::registry::PluginSettingsCategory>,
    /// Phase 8 8A.4: lifecycle claims used by `schema::visible_categories`
    /// to hide the legacy global `Sidecar` page when a plugin has staked a
    /// claim with a `settings_category`.
    pub lifecycle_claims: Vec<synaps_cli::skills::registry::LifecycleClaim>,
}

impl RuntimeSnapshot {
    #[allow(dead_code)]
    pub fn from_runtime(
        runtime: &synaps_cli::Runtime,
        registry: &synaps_cli::skills::registry::CommandRegistry,
    ) -> Self {
        Self::from_runtime_with_health(runtime, registry, Default::default())
    }

    pub fn from_runtime_with_health(
        runtime: &synaps_cli::Runtime,
        registry: &synaps_cli::skills::registry::CommandRegistry,
        model_health: std::collections::HashMap<
            String,
            (synaps_cli::runtime::openai::ping::PingStatus, u64),
        >,
    ) -> Self {
        let config = synaps_cli::config::load_config();
        // Build the plugin list from *all* discovered plugins on disk (not
        // just the registry, which excludes disabled plugins).  This ensures
        // disabled plugins remain visible in the settings list so the user
        // can re-enable them.
        let registry_map: std::collections::HashMap<String, usize> = registry
            .plugins()
            .into_iter()
            .map(|p| (p.name, p.skill_count))
            .collect();
        let (all_plugins, _all_skills) =
            synaps_cli::skills::loader::load_all(&synaps_cli::skills::loader::default_roots());
        let mut plugins: Vec<PluginRow> = all_plugins
            .into_iter()
            .map(|p| {
                let skill_count = registry_map.get(&p.name).copied().unwrap_or(0);
                PluginRow {
                    name: p.name,
                    skill_count,
                }
            })
            .collect();
        plugins.sort_by(|a, b| a.name.cmp(&b.name));
        Self {
            model: runtime.model().to_string(),
            thinking: runtime.thinking_level().to_string(),
            compaction_model: runtime.compaction_model().to_string(),
            context_window: {
                match config.context_window {
                    Some(200_000) => "200k".to_string(),
                    Some(1_000_000) => "1m".to_string(),
                    Some(v) => v.to_string(),
                    None => "auto".to_string(),
                }
            },
            max_tool_output: runtime.max_tool_output(),
            bash_timeout: runtime.bash_timeout(),
            bash_max_timeout: runtime.bash_max_timeout(),
            subagent_timeout: runtime.subagent_timeout(),
            api_retries: runtime.api_retries(),
            theme_name: config.theme.unwrap_or_else(|| "(default)".to_string()),
            plugins,
            disabled_plugins: config.disabled_plugins.clone(),
            provider_keys: config.provider_keys.clone(),
            model_health,
            plugin_categories: registry.plugin_settings_categories(),
            lifecycle_claims: registry.lifecycle_claims(),
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Focus {
    Left,
    Right,
}

#[derive(Clone)]
pub(super) enum ActiveEditor {
    Text {
        buffer: String,
        setting_key: &'static str,
        numeric: bool,
        error: Option<String>,
    },
    Picker {
        setting_key: &'static str,
        options: Vec<String>,
        cursor: usize,
    },
    CustomModel {
        buffer: String,
        setting_key: &'static str,
    },
    ApiKey {
        provider_id: String,
        buffer: String,
    },
    /// Text editor for a plugin-declared `text` field. Path B Phase 4.
    /// Commits via `InputOutcome::PluginApply` to the plugin config namespace.
    PluginText {
        plugin_id: String,
        key: String,
        buffer: String,
        numeric: bool,
        error: Option<String>,
    },
    /// Plugin-owned custom editor render returned by `settings.editor.open`.
    PluginCustom {
        plugin_id: String,
        category: String,
        field: String,
        render: crate::tui::settings::plugin_editor::PluginEditorSession,
    },
}

#[derive(Clone)]
pub(super) struct SettingsState {
    pub category_idx: usize,
    pub setting_idx: usize,
    /// Left/Right focus as read by draw code (`settings/draw.rs` reads it
    /// directly). P7.7: now a synced projection of `focus_ring` — the
    /// authoritative traversal store below.
    pub focus: Focus,
    /// Authoritative Left/Right traversal store: a two-slot [`FocusRing`] from
    /// the FocusManager (slot 0 = Left, slot 1 = Right). Tab / focus moves go
    /// through this ring (P7.7), replacing the old direct `focus` assignments;
    /// `focus` above is re-derived from it after every move. Focus survives
    /// occlusion (e.g. marketplace/PluginEditor pushed on top) because it lives
    /// in the retained `SettingsState` (§4).
    focus_ring: FocusRing,
    pub edit_mode: Option<ActiveEditor>,
    /// Transient error/note shown under a row.
    pub row_error: Option<(String, String)>,
    /// When a theme picker is open, the theme name before previewing began.
    pub original_theme_name: Option<String>,
}

impl SettingsState {
    pub fn new() -> Self {
        Self {
            category_idx: 0,
            setting_idx: 0,
            focus: Focus::Left,
            focus_ring: FocusRing::of_len(2),
            edit_mode: None,
            row_error: None,
            original_theme_name: None,
        }
    }

    /// Current Left/Right focus, read from the two-slot [`FocusRing`] backing
    /// store (slot 0 = Left, slot 1 = Right). Equals the synced `focus` field.
    #[cfg(test)]
    pub fn focus(&self) -> Focus {
        Self::focus_from_ring(&self.focus_ring)
    }

    fn focus_from_ring(ring: &FocusRing) -> Focus {
        match ring.current().map(|slot| slot.id()) {
            Some(1) => Focus::Right,
            _ => Focus::Left,
        }
    }

    /// Re-derive the public `focus` projection from the authoritative ring.
    fn sync_focus_field(&mut self) {
        self.focus = Self::focus_from_ring(&self.focus_ring);
    }

    /// Tab: toggle Left <-> Right. On the two-slot ring this is `next()`
    /// (wraps), preserving today's exact toggle semantics.
    pub fn toggle_focus(&mut self) {
        self.focus_ring.next();
        self.sync_focus_field();
    }

    /// Set focus to a specific side. On the two-slot ring, one `next()` flips
    /// to the other slot, so we step only when currently on the wrong side.
    #[cfg(test)]
    pub fn set_focus(&mut self, target: Focus) {
        if self.focus() != target {
            self.focus_ring.next();
        }
        self.sync_focus_field();
    }

    /// Settings in the currently selected category.
    pub fn current_settings(&self, snap: &RuntimeSnapshot) -> Vec<&'static SettingDef> {
        // `category_idx` indexes the *visible* category list (built-ins with any
        // hidden `Sidecar` removed) followed by plugin categories — NOT the
        // static `CATEGORIES` array. Map through the visible list: a plugin
        // position, or a stale index past the list (plugin hot-reloaded while
        // the modal is open), yields no built-in settings instead of
        // mis-mapping onto a static-array neighbour (e.g. returning Sidecar's
        // keybind for a plugin category) or panicking on an out-of-bounds index.
        let visible = schema::visible_categories(&snap.lifecycle_claims);
        let Some(&cat) = visible.get(self.category_idx) else {
            return Vec::new();
        };
        if cat == schema::Category::Plugins || cat == schema::Category::Providers {
            return Vec::new();
        }
        schema::ALL_SETTINGS
            .iter()
            .filter(|s| s.category == cat)
            .collect()
    }

    pub fn current_setting(&self, snap: &RuntimeSnapshot) -> Option<&'static SettingDef> {
        self.current_settings(snap).get(self.setting_idx).copied()
    }

    /// True iff `category_idx` points past the built-in categories at a
    /// plugin-declared category from `snap.plugin_categories`.
    pub fn is_plugin_category(&self, snap: &RuntimeSnapshot) -> bool {
        let n_builtin = schema::visible_categories(&snap.lifecycle_claims).len();
        self.category_idx >= n_builtin
            && self.category_idx - n_builtin < snap.plugin_categories.len()
    }

    /// Plugin-declared category at the current `category_idx`, or None
    /// if the cursor is on a built-in category.
    pub fn current_plugin_category<'a>(
        &self,
        snap: &'a RuntimeSnapshot,
    ) -> Option<&'a synaps_cli::skills::registry::PluginSettingsCategory> {
        if !self.is_plugin_category(snap) {
            return None;
        }
        snap.plugin_categories
            .get(self.category_idx - schema::visible_categories(&snap.lifecycle_claims).len())
    }

    /// Plugin field at `setting_idx` within the current plugin category.
    pub fn current_plugin_field<'a>(
        &self,
        snap: &'a RuntimeSnapshot,
    ) -> Option<&'a synaps_cli::skills::registry::PluginSettingsField> {
        self.current_plugin_category(snap)
            .and_then(|c| c.fields.get(self.setting_idx))
    }
}

#[cfg(test)]
mod wireup_tests {
    use super::*;
    use synaps_cli::skills::registry::LifecycleClaim;

    fn snap_with_claims(claims: Vec<LifecycleClaim>) -> RuntimeSnapshot {
        RuntimeSnapshot {
            model: "m".into(),
            thinking: "medium".into(),
            context_window: "auto".into(),
            compaction_model: "m".into(),
            max_tool_output: 0,
            bash_timeout: 0,
            bash_max_timeout: 0,
            subagent_timeout: 0,
            api_retries: 0,
            theme_name: "t".into(),
            plugins: Vec::new(),
            disabled_plugins: Vec::new(),
            provider_keys: std::collections::BTreeMap::new(),
            model_health: std::collections::HashMap::new(),
            plugin_categories: Vec::new(),
            lifecycle_claims: claims,
        }
    }

    fn claim(settings_category: Option<&str>) -> LifecycleClaim {
        LifecycleClaim {
            plugin: "p".into(),
            command: "capture".into(),
            settings_category: settings_category.map(|s| s.into()),
            display_name: "Sample".into(),
            importance: 0,
        }
    }

    #[test]
    fn visible_categories_excludes_sidecar_when_claim_present() {
        let snap = snap_with_claims(vec![claim(Some("capture"))]);
        let v = schema::visible_categories(&snap.lifecycle_claims);
        assert!(!v.contains(&schema::Category::Sidecar));
    }

    #[test]
    fn visible_categories_includes_sidecar_when_no_claim_settings_category() {
        let snap_empty = snap_with_claims(Vec::new());
        assert!(schema::visible_categories(&snap_empty.lifecycle_claims)
            .contains(&schema::Category::Sidecar));

        let snap_no_cat = snap_with_claims(vec![claim(None)]);
        assert!(schema::visible_categories(&snap_no_cat.lifecycle_claims)
            .contains(&schema::Category::Sidecar));
    }

    #[test]
    fn current_settings_maps_plugin_category_to_empty_not_static_neighbour() {
        // Regression (PR#60 review). `category_idx` indexes the VISIBLE category
        // list (built-ins minus a hidden Sidecar) followed by plugin categories —
        // NOT the static `CATEGORIES` array. Two failure modes pinned here:
        //  (1) silverhand: an index past the list must not panic.
        //  (2) shady: with Sidecar hidden, the first plugin category sits at
        //      idx == visible_len (6). The OLD `CATEGORIES[6]` returned Sidecar's
        //      keybind def for that plugin category (silent mis-map that let a
        //      keypress rewire the sidecar toggle). It must resolve to empty.
        let mut state = SettingsState::new();

        // --- No plugin claim: all 7 built-ins visible, Sidecar present. ---
        let snap_plain = snap_with_claims(Vec::new());
        // One past the array must not panic and must be empty (silverhand).
        state.category_idx = schema::CATEGORIES.len();
        assert!(state.current_settings(&snap_plain).is_empty());
        assert!(state.current_setting(&snap_plain).is_none());
        state.category_idx = schema::CATEGORIES.len() + 5;
        assert!(state.current_settings(&snap_plain).is_empty());
        assert!(state.current_setting(&snap_plain).is_none());

        // --- Plugin claim present: Sidecar hidden, visible list len 6. ---
        let snap_claimed = snap_with_claims(vec![claim(Some("capture"))]);
        let visible = schema::visible_categories(&snap_claimed.lifecycle_claims);
        assert_eq!(
            visible.len(),
            schema::CATEGORIES.len() - 1,
            "Sidecar should be hidden when a plugin claims a settings_category"
        );

        // idx == visible_len is the first PLUGIN position — must be empty, NOT
        // Sidecar's settings (shady's silent-mis-map blocker).
        state.category_idx = visible.len();
        assert!(
            state.current_settings(&snap_claimed).is_empty(),
            "first plugin category must return NO built-in settings (not Sidecar's)"
        );
        assert!(state.current_setting(&snap_claimed).is_none());

        // Every built-in position still maps to exactly its own settings —
        // proves the visible-list mapping didn't regress in-range lookups.
        for (idx, &cat) in visible.iter().enumerate() {
            state.category_idx = idx;
            let expected = if cat == schema::Category::Plugins
                || cat == schema::Category::Providers
            {
                0
            } else {
                schema::ALL_SETTINGS
                    .iter()
                    .filter(|s| s.category == cat)
                    .count()
            };
            assert_eq!(
                state.current_settings(&snap_claimed).len(),
                expected,
                "built-in category at idx {idx} mapped to the wrong settings"
            );
        }
    }
}