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#[cfg(test)]
396mod tests {
397    use super::*;
398
399    #[test]
400    fn apply_compat_fallbacks_populates_legacy_fields() {
401        let mut cfg = DaemonConfig::default();
402        cfg.git_storage.method = GitStorageMethod::Unknown;
403        cfg.watchers.custom_paths.clear();
404
405        let root: toml::Value = toml::from_str(
406            r#"
407[git_storage]
408"#,
409        )
410        .expect("parse toml");
411
412        let changed = apply_compat_fallbacks(&mut cfg, Some(&root));
413        assert!(changed);
414        assert_eq!(cfg.git_storage.method, GitStorageMethod::Native);
415        assert!(!cfg.watchers.custom_paths.is_empty());
416    }
417
418    #[test]
419    fn git_storage_method_legacy_aliases_are_accepted() {
420        let legacy_none: DaemonConfig = toml::from_str(
421            r#"
422[git_storage]
423method = "none"
424"#,
425        )
426        .expect("parse toml");
427        assert_eq!(legacy_none.git_storage.method, GitStorageMethod::Sqlite);
428
429        let legacy_platform_api: DaemonConfig = toml::from_str(
430            r#"
431[git_storage]
432method = "platform_api"
433"#,
434        )
435        .expect("parse toml");
436        assert_eq!(
437            legacy_platform_api.git_storage.method,
438            GitStorageMethod::Native
439        );
440    }
441
442    #[test]
443    fn apply_compat_fallbacks_is_noop_for_modern_values() {
444        let mut cfg = DaemonConfig::default();
445        cfg.watchers.custom_paths = vec!["/tmp/one".to_string()];
446
447        let root: toml::Value = toml::from_str(
448            r#"
449[git_storage]
450method = "native"
451"#,
452        )
453        .expect("parse toml");
454
455        let before = cfg.clone();
456        let changed = apply_compat_fallbacks(&mut cfg, Some(&root));
457        assert!(!changed);
458        assert_eq!(cfg.watchers.custom_paths, before.watchers.custom_paths);
459        assert_eq!(cfg.git_storage.method, before.git_storage.method);
460    }
461
462    #[test]
463    fn legacy_watcher_flags_are_not_serialized() {
464        let cfg = DaemonConfig::default();
465        let encoded = toml::to_string(&cfg).expect("serialize config");
466
467        assert!(encoded.contains("custom_paths"));
468        assert!(!encoded.contains("\nclaude_code ="));
469        assert!(!encoded.contains("\nopencode ="));
470        assert!(!encoded.contains("\ncursor ="));
471    }
472
473    #[test]
474    fn daemon_summary_defaults_are_stable() {
475        let cfg = DaemonConfig::default();
476        assert!(cfg.daemon.detail_auto_expand_selected_event);
477        assert!(!cfg.daemon.summary_enabled);
478        assert_eq!(cfg.daemon.summary_provider, None);
479        assert_eq!(cfg.daemon.summary_model, None);
480        assert_eq!(cfg.daemon.summary_content_mode, "normal");
481        assert!(cfg.daemon.summary_disk_cache_enabled);
482        assert_eq!(cfg.daemon.summary_event_window, 0);
483        assert_eq!(cfg.daemon.summary_debounce_ms, 250);
484        assert_eq!(cfg.daemon.summary_max_inflight, 2);
485        assert!(!cfg.daemon.summary_window_migrated_v2);
486    }
487
488    #[test]
489    fn daemon_summary_fields_deserialize_from_toml() {
490        let cfg: DaemonConfig = toml::from_str(
491            r#"
492[daemon]
493summary_enabled = true
494summary_provider = "openai"
495summary_model = "gpt-4o-mini"
496summary_content_mode = "minimal"
497summary_disk_cache_enabled = false
498summary_event_window = 8
499summary_debounce_ms = 100
500summary_max_inflight = 4
501summary_window_migrated_v2 = false
502detail_auto_expand_selected_event = false
503"#,
504        )
505        .expect("parse summary config");
506
507        assert!(!cfg.daemon.detail_auto_expand_selected_event);
508        assert!(cfg.daemon.summary_enabled);
509        assert_eq!(cfg.daemon.summary_provider.as_deref(), Some("openai"));
510        assert_eq!(cfg.daemon.summary_model.as_deref(), Some("gpt-4o-mini"));
511        assert_eq!(cfg.daemon.summary_content_mode, "minimal");
512        assert!(!cfg.daemon.summary_disk_cache_enabled);
513        assert_eq!(cfg.daemon.summary_event_window, 8);
514        assert_eq!(cfg.daemon.summary_debounce_ms, 100);
515        assert_eq!(cfg.daemon.summary_max_inflight, 4);
516        assert!(!cfg.daemon.summary_window_migrated_v2);
517    }
518
519    #[test]
520    fn git_retention_defaults_are_stable() {
521        let cfg = DaemonConfig::default();
522        assert!(!cfg.git_storage.retention.enabled);
523        assert_eq!(cfg.git_storage.retention.keep_days, 30);
524        assert_eq!(cfg.git_storage.retention.interval_secs, 86_400);
525    }
526
527    #[test]
528    fn git_retention_fields_deserialize_from_toml() {
529        let cfg: DaemonConfig = toml::from_str(
530            r#"
531[git_storage]
532method = "native"
533
534[git_storage.retention]
535enabled = true
536keep_days = 14
537interval_secs = 43200
538"#,
539        )
540        .expect("parse retention config");
541
542        assert_eq!(cfg.git_storage.method, GitStorageMethod::Native);
543        assert!(cfg.git_storage.retention.enabled);
544        assert_eq!(cfg.git_storage.retention.keep_days, 14);
545        assert_eq!(cfg.git_storage.retention.interval_secs, 43_200);
546    }
547}