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}
185
186impl Default for IdentitySettings {
187    fn default() -> Self {
188        Self {
189            nickname: default_nickname(),
190        }
191    }
192}
193
194#[derive(Debug, Clone, Serialize, Deserialize)]
195pub struct PrivacySettings {
196    #[serde(default = "default_true")]
197    pub strip_paths: bool,
198    #[serde(default = "default_true")]
199    pub strip_env_vars: bool,
200    #[serde(default = "default_exclude_patterns")]
201    pub exclude_patterns: Vec<String>,
202    #[serde(default)]
203    pub exclude_tools: Vec<String>,
204}
205
206impl Default for PrivacySettings {
207    fn default() -> Self {
208        Self {
209            strip_paths: true,
210            strip_env_vars: true,
211            exclude_patterns: default_exclude_patterns(),
212            exclude_tools: Vec::new(),
213        }
214    }
215}
216
217#[derive(Debug, Clone, Serialize, Deserialize)]
218pub struct WatcherSettings {
219    /// Deprecated agent toggles kept for backward-compatible config parsing.
220    #[serde(default = "default_true", skip_serializing)]
221    pub claude_code: bool,
222    /// Deprecated agent toggles kept for backward-compatible config parsing.
223    #[serde(default = "default_true", skip_serializing)]
224    pub opencode: bool,
225    /// Deprecated agent toggles kept for backward-compatible config parsing.
226    #[serde(default = "default_true", skip_serializing)]
227    pub cursor: bool,
228    #[serde(default = "default_watch_paths")]
229    pub custom_paths: Vec<String>,
230}
231
232impl Default for WatcherSettings {
233    fn default() -> Self {
234        Self {
235            claude_code: true,
236            opencode: true,
237            cursor: true,
238            custom_paths: default_watch_paths(),
239        }
240    }
241}
242
243#[derive(Debug, Clone, Serialize, Deserialize)]
244pub struct GitStorageSettings {
245    #[serde(default)]
246    pub method: GitStorageMethod,
247    #[serde(default)]
248    pub token: String,
249    #[serde(default)]
250    pub retention: GitRetentionSettings,
251}
252
253impl Default for GitStorageSettings {
254    fn default() -> Self {
255        Self {
256            method: GitStorageMethod::Native,
257            token: String::new(),
258            retention: GitRetentionSettings::default(),
259        }
260    }
261}
262
263#[derive(Debug, Clone, Serialize, Deserialize)]
264pub struct GitRetentionSettings {
265    #[serde(default = "default_false")]
266    pub enabled: bool,
267    #[serde(default = "default_git_retention_keep_days")]
268    pub keep_days: u32,
269    #[serde(default = "default_git_retention_interval_secs")]
270    pub interval_secs: u64,
271}
272
273impl Default for GitRetentionSettings {
274    fn default() -> Self {
275        Self {
276            enabled: false,
277            keep_days: default_git_retention_keep_days(),
278            interval_secs: default_git_retention_interval_secs(),
279        }
280    }
281}
282
283#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
284#[serde(rename_all = "snake_case")]
285pub enum GitStorageMethod {
286    /// Store sessions as git objects on an orphan branch (branch-based git-native).
287    #[default]
288    #[serde(alias = "platform_api", alias = "platform-api", alias = "api")]
289    Native,
290    /// Store session bodies in SQLite-backed storage.
291    #[serde(alias = "none", alias = "sqlite_local", alias = "sqlite-local")]
292    Sqlite,
293    /// Unknown/invalid values are normalized by compatibility fallbacks.
294    #[serde(other)]
295    Unknown,
296}
297
298// ── Serde default functions ─────────────────────────────────────────────
299
300fn default_true() -> bool {
301    true
302}
303fn default_false() -> bool {
304    false
305}
306fn default_debounce() -> u64 {
307    5
308}
309fn default_max_retries() -> u32 {
310    3
311}
312fn default_health_check_interval() -> u64 {
313    300
314}
315fn default_realtime_debounce_ms() -> u64 {
316    500
317}
318fn default_detail_realtime_preview_enabled() -> bool {
319    false
320}
321fn default_detail_auto_expand_selected_event() -> bool {
322    true
323}
324fn default_publish_on() -> PublishMode {
325    PublishMode::Manual
326}
327fn default_summary_content_mode() -> String {
328    "normal".to_string()
329}
330fn default_summary_event_window() -> u32 {
331    0
332}
333fn default_summary_debounce_ms() -> u64 {
334    250
335}
336fn default_summary_max_inflight() -> u32 {
337    2
338}
339fn default_git_retention_keep_days() -> u32 {
340    30
341}
342fn default_git_retention_interval_secs() -> u64 {
343    86_400
344}
345fn default_server_url() -> String {
346    "https://opensession.io".to_string()
347}
348fn default_nickname() -> String {
349    "user".to_string()
350}
351fn default_exclude_patterns() -> Vec<String> {
352    vec![
353        "*.env".to_string(),
354        "*secret*".to_string(),
355        "*credential*".to_string(),
356    ]
357}
358
359pub const DEFAULT_WATCH_PATHS: &[&str] = &[
360    "~/.claude/projects",
361    "~/.codex/sessions",
362    "~/.local/share/opencode/storage/session",
363    "~/.cline/data/tasks",
364    "~/.local/share/amp/threads",
365    "~/.gemini/tmp",
366    "~/Library/Application Support/Cursor/User",
367    "~/.config/Cursor/User",
368];
369
370pub fn default_watch_paths() -> Vec<String> {
371    DEFAULT_WATCH_PATHS
372        .iter()
373        .map(|path| (*path).to_string())
374        .collect()
375}
376
377/// Apply compatibility fallbacks after loading raw TOML.
378/// Returns true when any field was updated.
379pub fn apply_compat_fallbacks(config: &mut DaemonConfig, _root: Option<&toml::Value>) -> bool {
380    let mut changed = false;
381
382    if config.git_storage.method == GitStorageMethod::Unknown {
383        config.git_storage.method = GitStorageMethod::Native;
384        changed = true;
385    }
386
387    if config.watchers.custom_paths.is_empty() {
388        config.watchers.custom_paths = default_watch_paths();
389        changed = true;
390    }
391
392    changed
393}
394
395/// True when `[git_storage].method` is absent/invalid in the source TOML.
396///
397/// Retained as a compatibility helper for callers that still inspect legacy
398/// config layouts directly.
399pub fn config_file_missing_git_storage_method(root: Option<&toml::Value>) -> bool {
400    let Some(root) = root else {
401        return false;
402    };
403    let Some(table) = root.as_table() else {
404        return false;
405    };
406    let Some(git_storage) = table.get("git_storage") else {
407        return true;
408    };
409    match git_storage.as_table() {
410        Some(section) => !section.contains_key("method"),
411        None => true,
412    }
413}
414
415#[cfg(test)]
416mod tests {
417    use super::*;
418
419    #[test]
420    fn apply_compat_fallbacks_populates_legacy_fields() {
421        let mut cfg = DaemonConfig::default();
422        cfg.git_storage.method = GitStorageMethod::Unknown;
423        cfg.watchers.custom_paths.clear();
424
425        let root: toml::Value = toml::from_str(
426            r#"
427[git_storage]
428"#,
429        )
430        .expect("parse toml");
431
432        let changed = apply_compat_fallbacks(&mut cfg, Some(&root));
433        assert!(changed);
434        assert_eq!(cfg.git_storage.method, GitStorageMethod::Native);
435        assert!(!cfg.watchers.custom_paths.is_empty());
436    }
437
438    #[test]
439    fn git_storage_method_legacy_aliases_are_accepted() {
440        let legacy_none: DaemonConfig = toml::from_str(
441            r#"
442[git_storage]
443method = "none"
444"#,
445        )
446        .expect("parse toml");
447        assert_eq!(legacy_none.git_storage.method, GitStorageMethod::Sqlite);
448
449        let legacy_platform_api: DaemonConfig = toml::from_str(
450            r#"
451[git_storage]
452method = "platform_api"
453"#,
454        )
455        .expect("parse toml");
456        assert_eq!(
457            legacy_platform_api.git_storage.method,
458            GitStorageMethod::Native
459        );
460    }
461
462    #[test]
463    fn apply_compat_fallbacks_is_noop_for_modern_values() {
464        let mut cfg = DaemonConfig::default();
465        cfg.watchers.custom_paths = vec!["/tmp/one".to_string()];
466
467        let root: toml::Value = toml::from_str(
468            r#"
469[git_storage]
470method = "native"
471"#,
472        )
473        .expect("parse toml");
474
475        let before = cfg.clone();
476        let changed = apply_compat_fallbacks(&mut cfg, Some(&root));
477        assert!(!changed);
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
539    #[test]
540    fn git_retention_defaults_are_stable() {
541        let cfg = DaemonConfig::default();
542        assert!(!cfg.git_storage.retention.enabled);
543        assert_eq!(cfg.git_storage.retention.keep_days, 30);
544        assert_eq!(cfg.git_storage.retention.interval_secs, 86_400);
545    }
546
547    #[test]
548    fn git_retention_fields_deserialize_from_toml() {
549        let cfg: DaemonConfig = toml::from_str(
550            r#"
551[git_storage]
552method = "native"
553
554[git_storage.retention]
555enabled = true
556keep_days = 14
557interval_secs = 43200
558"#,
559        )
560        .expect("parse retention config");
561
562        assert_eq!(cfg.git_storage.method, GitStorageMethod::Native);
563        assert!(cfg.git_storage.retention.enabled);
564        assert_eq!(cfg.git_storage.retention.keep_days, 14);
565        assert_eq!(cfg.git_storage.retention.interval_secs, 43_200);
566    }
567}