Skip to main content

opensession_runtime_config/
lib.rs

1//! Shared daemon/TUI configuration types.
2//!
3//! Both `opensession-daemon` and `opensession-tui` read/write `opensession.toml`
4//! using these types. Daemon-specific logic (watch-path resolution, project
5//! config merging) lives in the daemon crate; TUI-specific logic (settings
6//! layout, field editing) lives in the TUI crate.
7
8use serde::{Deserialize, Serialize};
9
10/// Canonical config file name used by daemon/cli/tui.
11pub const CONFIG_FILE_NAME: &str = "opensession.toml";
12
13/// Top-level daemon configuration (persisted as `opensession.toml`).
14#[derive(Debug, Clone, Serialize, Deserialize, Default)]
15pub struct DaemonConfig {
16    #[serde(default)]
17    pub daemon: DaemonSettings,
18    #[serde(default)]
19    pub server: ServerSettings,
20    #[serde(default)]
21    pub identity: IdentitySettings,
22    #[serde(default)]
23    pub privacy: PrivacySettings,
24    #[serde(default)]
25    pub watchers: WatcherSettings,
26    #[serde(default)]
27    pub git_storage: GitStorageSettings,
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct DaemonSettings {
32    #[serde(default = "default_false")]
33    pub auto_publish: bool,
34    #[serde(default = "default_debounce")]
35    pub debounce_secs: u64,
36    #[serde(default = "default_publish_on")]
37    pub publish_on: PublishMode,
38    #[serde(default = "default_max_retries")]
39    pub max_retries: u32,
40    #[serde(default = "default_health_check_interval")]
41    pub health_check_interval_secs: u64,
42    #[serde(default = "default_realtime_debounce_ms")]
43    pub realtime_debounce_ms: u64,
44    /// Enable realtime file preview refresh in TUI session detail.
45    #[serde(default = "default_detail_realtime_preview_enabled")]
46    pub detail_realtime_preview_enabled: bool,
47    /// Expand selected timeline event detail rows by default in TUI session detail.
48    #[serde(default = "default_detail_auto_expand_selected_event")]
49    pub detail_auto_expand_selected_event: bool,
50    /// Enable timeline/event summary generation in TUI detail view.
51    #[serde(default = "default_false")]
52    pub summary_enabled: bool,
53    /// Summary engine/provider selection.
54    /// Examples: `anthropic`, `openai`, `openai-compatible`, `gemini`, `cli:auto`, `cli:codex`.
55    #[serde(default)]
56    pub summary_provider: Option<String>,
57    /// Optional model override for summary generation.
58    #[serde(default)]
59    pub summary_model: Option<String>,
60    /// Summary verbosity mode (`normal` or `minimal`).
61    #[serde(default = "default_summary_content_mode")]
62    pub summary_content_mode: String,
63    /// Persist summary cache entries on disk/local DB.
64    #[serde(default = "default_true")]
65    pub summary_disk_cache_enabled: bool,
66    /// OpenAI-compatible endpoint full URL override.
67    #[serde(default)]
68    pub summary_openai_compat_endpoint: Option<String>,
69    /// OpenAI-compatible base URL override.
70    #[serde(default)]
71    pub summary_openai_compat_base: Option<String>,
72    /// OpenAI-compatible path override.
73    #[serde(default)]
74    pub summary_openai_compat_path: Option<String>,
75    /// OpenAI-compatible payload style (`chat` or `responses`).
76    #[serde(default)]
77    pub summary_openai_compat_style: Option<String>,
78    /// OpenAI-compatible API key.
79    #[serde(default)]
80    pub summary_openai_compat_key: Option<String>,
81    /// OpenAI-compatible API key header (default `Authorization` when omitted).
82    #[serde(default)]
83    pub summary_openai_compat_key_header: Option<String>,
84    /// Number of events to include in each summary window.
85    /// `0` means adaptive mode.
86    #[serde(default = "default_summary_event_window")]
87    pub summary_event_window: u32,
88    /// Debounce before dispatching summary jobs.
89    #[serde(default = "default_summary_debounce_ms")]
90    pub summary_debounce_ms: u64,
91    /// Max concurrent summary jobs.
92    #[serde(default = "default_summary_max_inflight")]
93    pub summary_max_inflight: u32,
94    /// Internal one-way migration marker for summary window v2 semantics.
95    #[serde(default = "default_false")]
96    pub summary_window_migrated_v2: bool,
97}
98
99impl Default for DaemonSettings {
100    fn default() -> Self {
101        Self {
102            auto_publish: false,
103            debounce_secs: 5,
104            publish_on: PublishMode::Manual,
105            max_retries: 3,
106            health_check_interval_secs: 300,
107            realtime_debounce_ms: 500,
108            detail_realtime_preview_enabled: false,
109            detail_auto_expand_selected_event: true,
110            summary_enabled: false,
111            summary_provider: None,
112            summary_model: None,
113            summary_content_mode: default_summary_content_mode(),
114            summary_disk_cache_enabled: true,
115            summary_openai_compat_endpoint: None,
116            summary_openai_compat_base: None,
117            summary_openai_compat_path: None,
118            summary_openai_compat_style: None,
119            summary_openai_compat_key: None,
120            summary_openai_compat_key_header: None,
121            summary_event_window: default_summary_event_window(),
122            summary_debounce_ms: default_summary_debounce_ms(),
123            summary_max_inflight: default_summary_max_inflight(),
124            summary_window_migrated_v2: false,
125        }
126    }
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
130#[serde(rename_all = "snake_case")]
131pub enum PublishMode {
132    SessionEnd,
133    Realtime,
134    Manual,
135}
136
137impl PublishMode {
138    pub fn cycle(&self) -> Self {
139        match self {
140            Self::SessionEnd => Self::Realtime,
141            Self::Realtime => Self::Manual,
142            Self::Manual => Self::SessionEnd,
143        }
144    }
145
146    pub fn display(&self) -> &'static str {
147        match self {
148            Self::SessionEnd => "Session End",
149            Self::Realtime => "Realtime",
150            Self::Manual => "Manual",
151        }
152    }
153}
154
155#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
156#[serde(rename_all = "snake_case")]
157pub enum CalendarDisplayMode {
158    Smart,
159    Relative,
160    Absolute,
161}
162
163#[derive(Debug, Clone, Serialize, Deserialize)]
164pub struct ServerSettings {
165    #[serde(default = "default_server_url")]
166    pub url: String,
167    #[serde(default)]
168    pub api_key: String,
169}
170
171impl Default for ServerSettings {
172    fn default() -> Self {
173        Self {
174            url: default_server_url(),
175            api_key: String::new(),
176        }
177    }
178}
179
180#[derive(Debug, Clone, Serialize, Deserialize)]
181pub struct IdentitySettings {
182    #[serde(default = "default_nickname")]
183    pub nickname: String,
184    /// Team ID to upload sessions to
185    #[serde(default)]
186    pub team_id: String,
187}
188
189impl Default for IdentitySettings {
190    fn default() -> Self {
191        Self {
192            nickname: default_nickname(),
193            team_id: String::new(),
194        }
195    }
196}
197
198#[derive(Debug, Clone, Serialize, Deserialize)]
199pub struct PrivacySettings {
200    #[serde(default = "default_true")]
201    pub strip_paths: bool,
202    #[serde(default = "default_true")]
203    pub strip_env_vars: bool,
204    #[serde(default = "default_exclude_patterns")]
205    pub exclude_patterns: Vec<String>,
206    #[serde(default)]
207    pub exclude_tools: Vec<String>,
208}
209
210impl Default for PrivacySettings {
211    fn default() -> Self {
212        Self {
213            strip_paths: true,
214            strip_env_vars: true,
215            exclude_patterns: default_exclude_patterns(),
216            exclude_tools: Vec::new(),
217        }
218    }
219}
220
221#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct WatcherSettings {
223    /// Deprecated agent toggles kept for backward-compatible config parsing.
224    #[serde(default = "default_true", skip_serializing)]
225    pub claude_code: bool,
226    /// Deprecated agent toggles kept for backward-compatible config parsing.
227    #[serde(default = "default_true", skip_serializing)]
228    pub opencode: bool,
229    /// Deprecated agent toggles kept for backward-compatible config parsing.
230    #[serde(default = "default_true", skip_serializing)]
231    pub cursor: bool,
232    #[serde(default = "default_watch_paths")]
233    pub custom_paths: Vec<String>,
234}
235
236impl Default for WatcherSettings {
237    fn default() -> Self {
238        Self {
239            claude_code: true,
240            opencode: true,
241            cursor: true,
242            custom_paths: default_watch_paths(),
243        }
244    }
245}
246
247#[derive(Debug, Clone, Serialize, Deserialize)]
248pub struct GitStorageSettings {
249    #[serde(default)]
250    pub method: GitStorageMethod,
251    #[serde(default)]
252    pub token: String,
253}
254
255impl Default for GitStorageSettings {
256    fn default() -> Self {
257        Self {
258            method: GitStorageMethod::Native,
259            token: String::new(),
260        }
261    }
262}
263
264#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
265#[serde(rename_all = "snake_case")]
266pub enum GitStorageMethod {
267    /// Store sessions as git objects on an orphan branch (branch-based git-native).
268    #[default]
269    #[serde(alias = "platform_api", alias = "platform-api", alias = "api")]
270    Native,
271    /// Store session bodies in SQLite-backed storage.
272    #[serde(alias = "none", alias = "sqlite_local", alias = "sqlite-local")]
273    Sqlite,
274    /// Unknown/invalid values are normalized by compatibility fallbacks.
275    #[serde(other)]
276    Unknown,
277}
278
279// ── Serde default functions ─────────────────────────────────────────────
280
281fn default_true() -> bool {
282    true
283}
284fn default_false() -> bool {
285    false
286}
287fn default_debounce() -> u64 {
288    5
289}
290fn default_max_retries() -> u32 {
291    3
292}
293fn default_health_check_interval() -> u64 {
294    300
295}
296fn default_realtime_debounce_ms() -> u64 {
297    500
298}
299fn default_detail_realtime_preview_enabled() -> bool {
300    false
301}
302fn default_detail_auto_expand_selected_event() -> bool {
303    true
304}
305fn default_publish_on() -> PublishMode {
306    PublishMode::Manual
307}
308fn default_summary_content_mode() -> String {
309    "normal".to_string()
310}
311fn default_summary_event_window() -> u32 {
312    0
313}
314fn default_summary_debounce_ms() -> u64 {
315    250
316}
317fn default_summary_max_inflight() -> u32 {
318    2
319}
320fn default_server_url() -> String {
321    "https://opensession.io".to_string()
322}
323fn default_nickname() -> String {
324    "user".to_string()
325}
326fn default_exclude_patterns() -> Vec<String> {
327    vec![
328        "*.env".to_string(),
329        "*secret*".to_string(),
330        "*credential*".to_string(),
331    ]
332}
333
334pub const DEFAULT_WATCH_PATHS: &[&str] = &[
335    "~/.claude/projects",
336    "~/.codex/sessions",
337    "~/.local/share/opencode/storage/session",
338    "~/.cline/data/tasks",
339    "~/.local/share/amp/threads",
340    "~/.gemini/tmp",
341    "~/Library/Application Support/Cursor/User",
342    "~/.config/Cursor/User",
343];
344
345pub fn default_watch_paths() -> Vec<String> {
346    DEFAULT_WATCH_PATHS
347        .iter()
348        .map(|path| (*path).to_string())
349        .collect()
350}
351
352/// Apply compatibility fallbacks after loading raw TOML.
353/// Returns true when any field was updated.
354pub fn apply_compat_fallbacks(config: &mut DaemonConfig, root: Option<&toml::Value>) -> bool {
355    let mut changed = false;
356
357    if config.git_storage.method == GitStorageMethod::Unknown {
358        config.git_storage.method = GitStorageMethod::Native;
359        changed = true;
360    }
361
362    if config.identity.team_id.trim().is_empty() {
363        if let Some(team_id) = root
364            .and_then(toml::Value::as_table)
365            .and_then(|table| table.get("server"))
366            .and_then(toml::Value::as_table)
367            .and_then(|section| section.get("team_id"))
368            .and_then(toml::Value::as_str)
369            .map(str::trim)
370            .filter(|v| !v.is_empty())
371        {
372            config.identity.team_id = team_id.to_string();
373            changed = true;
374        }
375    }
376
377    if config.watchers.custom_paths.is_empty() {
378        config.watchers.custom_paths = default_watch_paths();
379        changed = true;
380    }
381
382    changed
383}
384
385/// True when `[git_storage].method` is absent/invalid in the source TOML.
386///
387/// Retained as a compatibility helper for callers that still inspect legacy
388/// config layouts directly.
389pub fn config_file_missing_git_storage_method(root: Option<&toml::Value>) -> bool {
390    let Some(root) = root else {
391        return false;
392    };
393    let Some(table) = root.as_table() else {
394        return false;
395    };
396    let Some(git_storage) = table.get("git_storage") else {
397        return true;
398    };
399    match git_storage.as_table() {
400        Some(section) => !section.contains_key("method"),
401        None => true,
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    #[test]
410    fn apply_compat_fallbacks_populates_legacy_fields() {
411        let mut cfg = DaemonConfig::default();
412        cfg.git_storage.method = GitStorageMethod::Unknown;
413        cfg.identity.team_id.clear();
414        cfg.watchers.custom_paths.clear();
415
416        let root: toml::Value = toml::from_str(
417            r#"
418[server]
419team_id = "team-legacy"
420
421[git_storage]
422"#,
423        )
424        .expect("parse toml");
425
426        let changed = apply_compat_fallbacks(&mut cfg, Some(&root));
427        assert!(changed);
428        assert_eq!(cfg.git_storage.method, GitStorageMethod::Native);
429        assert_eq!(cfg.identity.team_id, "team-legacy");
430        assert!(!cfg.watchers.custom_paths.is_empty());
431    }
432
433    #[test]
434    fn git_storage_method_legacy_aliases_are_accepted() {
435        let legacy_none: DaemonConfig = toml::from_str(
436            r#"
437[git_storage]
438method = "none"
439"#,
440        )
441        .expect("parse toml");
442        assert_eq!(legacy_none.git_storage.method, GitStorageMethod::Sqlite);
443
444        let legacy_platform_api: DaemonConfig = toml::from_str(
445            r#"
446[git_storage]
447method = "platform_api"
448"#,
449        )
450        .expect("parse toml");
451        assert_eq!(
452            legacy_platform_api.git_storage.method,
453            GitStorageMethod::Native
454        );
455    }
456
457    #[test]
458    fn apply_compat_fallbacks_is_noop_for_modern_values() {
459        let mut cfg = DaemonConfig::default();
460        cfg.identity.team_id = "team-modern".to_string();
461        cfg.watchers.custom_paths = vec!["/tmp/one".to_string()];
462
463        let root: toml::Value = toml::from_str(
464            r#"
465[server]
466team_id = "team-from-file"
467
468[git_storage]
469method = "native"
470"#,
471        )
472        .expect("parse toml");
473
474        let before = cfg.clone();
475        let changed = apply_compat_fallbacks(&mut cfg, Some(&root));
476        assert!(!changed);
477        assert_eq!(cfg.identity.team_id, before.identity.team_id);
478        assert_eq!(cfg.watchers.custom_paths, before.watchers.custom_paths);
479        assert_eq!(cfg.git_storage.method, before.git_storage.method);
480    }
481
482    #[test]
483    fn legacy_watcher_flags_are_not_serialized() {
484        let cfg = DaemonConfig::default();
485        let encoded = toml::to_string(&cfg).expect("serialize config");
486
487        assert!(encoded.contains("custom_paths"));
488        assert!(!encoded.contains("\nclaude_code ="));
489        assert!(!encoded.contains("\nopencode ="));
490        assert!(!encoded.contains("\ncursor ="));
491    }
492
493    #[test]
494    fn daemon_summary_defaults_are_stable() {
495        let cfg = DaemonConfig::default();
496        assert!(cfg.daemon.detail_auto_expand_selected_event);
497        assert!(!cfg.daemon.summary_enabled);
498        assert_eq!(cfg.daemon.summary_provider, None);
499        assert_eq!(cfg.daemon.summary_model, None);
500        assert_eq!(cfg.daemon.summary_content_mode, "normal");
501        assert!(cfg.daemon.summary_disk_cache_enabled);
502        assert_eq!(cfg.daemon.summary_event_window, 0);
503        assert_eq!(cfg.daemon.summary_debounce_ms, 250);
504        assert_eq!(cfg.daemon.summary_max_inflight, 2);
505        assert!(!cfg.daemon.summary_window_migrated_v2);
506    }
507
508    #[test]
509    fn daemon_summary_fields_deserialize_from_toml() {
510        let cfg: DaemonConfig = toml::from_str(
511            r#"
512[daemon]
513summary_enabled = true
514summary_provider = "openai"
515summary_model = "gpt-4o-mini"
516summary_content_mode = "minimal"
517summary_disk_cache_enabled = false
518summary_event_window = 8
519summary_debounce_ms = 100
520summary_max_inflight = 4
521summary_window_migrated_v2 = false
522detail_auto_expand_selected_event = false
523"#,
524        )
525        .expect("parse summary config");
526
527        assert!(!cfg.daemon.detail_auto_expand_selected_event);
528        assert!(cfg.daemon.summary_enabled);
529        assert_eq!(cfg.daemon.summary_provider.as_deref(), Some("openai"));
530        assert_eq!(cfg.daemon.summary_model.as_deref(), Some("gpt-4o-mini"));
531        assert_eq!(cfg.daemon.summary_content_mode, "minimal");
532        assert!(!cfg.daemon.summary_disk_cache_enabled);
533        assert_eq!(cfg.daemon.summary_event_window, 8);
534        assert_eq!(cfg.daemon.summary_debounce_ms, 100);
535        assert_eq!(cfg.daemon.summary_max_inflight, 4);
536        assert!(!cfg.daemon.summary_window_migrated_v2);
537    }
538}