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    PlatformApi,
268    /// Store sessions as git objects on an orphan branch (no external API needed).
269    Native,
270    #[default]
271    #[serde(other)]
272    None,
273}
274
275// ── Serde default functions ─────────────────────────────────────────────
276
277fn default_true() -> bool {
278    true
279}
280fn default_false() -> bool {
281    false
282}
283fn default_debounce() -> u64 {
284    5
285}
286fn default_max_retries() -> u32 {
287    3
288}
289fn default_health_check_interval() -> u64 {
290    300
291}
292fn default_realtime_debounce_ms() -> u64 {
293    500
294}
295fn default_detail_realtime_preview_enabled() -> bool {
296    false
297}
298fn default_detail_auto_expand_selected_event() -> bool {
299    true
300}
301fn default_publish_on() -> PublishMode {
302    PublishMode::Manual
303}
304fn default_summary_content_mode() -> String {
305    "normal".to_string()
306}
307fn default_summary_event_window() -> u32 {
308    0
309}
310fn default_summary_debounce_ms() -> u64 {
311    250
312}
313fn default_summary_max_inflight() -> u32 {
314    2
315}
316fn default_server_url() -> String {
317    "https://opensession.io".to_string()
318}
319fn default_nickname() -> String {
320    "user".to_string()
321}
322fn default_exclude_patterns() -> Vec<String> {
323    vec![
324        "*.env".to_string(),
325        "*secret*".to_string(),
326        "*credential*".to_string(),
327    ]
328}
329
330pub const DEFAULT_WATCH_PATHS: &[&str] = &[
331    "~/.claude/projects",
332    "~/.codex/sessions",
333    "~/.local/share/opencode/storage/session",
334    "~/.cline/data/tasks",
335    "~/.local/share/amp/threads",
336    "~/.gemini/tmp",
337    "~/Library/Application Support/Cursor/User",
338    "~/.config/Cursor/User",
339];
340
341pub fn default_watch_paths() -> Vec<String> {
342    DEFAULT_WATCH_PATHS
343        .iter()
344        .map(|path| (*path).to_string())
345        .collect()
346}
347
348/// Apply compatibility fallbacks after loading raw TOML.
349/// Returns true when any field was updated.
350pub fn apply_compat_fallbacks(config: &mut DaemonConfig, root: Option<&toml::Value>) -> bool {
351    let mut changed = false;
352
353    if config_file_missing_git_storage_method(root)
354        && config.git_storage.method == GitStorageMethod::None
355    {
356        config.git_storage.method = GitStorageMethod::Native;
357        changed = true;
358    }
359
360    if config.identity.team_id.trim().is_empty() {
361        if let Some(team_id) = root
362            .and_then(toml::Value::as_table)
363            .and_then(|table| table.get("server"))
364            .and_then(toml::Value::as_table)
365            .and_then(|section| section.get("team_id"))
366            .and_then(toml::Value::as_str)
367            .map(str::trim)
368            .filter(|v| !v.is_empty())
369        {
370            config.identity.team_id = team_id.to_string();
371            changed = true;
372        }
373    }
374
375    if config.watchers.custom_paths.is_empty() {
376        config.watchers.custom_paths = default_watch_paths();
377        changed = true;
378    }
379
380    changed
381}
382
383/// True when `[git_storage].method` is absent/invalid in the source TOML.
384pub fn config_file_missing_git_storage_method(root: Option<&toml::Value>) -> bool {
385    let Some(root) = root else {
386        return false;
387    };
388    let Some(table) = root.as_table() else {
389        return false;
390    };
391    let Some(git_storage) = table.get("git_storage") else {
392        return true;
393    };
394    match git_storage.as_table() {
395        Some(section) => !section.contains_key("method"),
396        None => true,
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403
404    #[test]
405    fn apply_compat_fallbacks_populates_legacy_fields() {
406        let mut cfg = DaemonConfig::default();
407        cfg.git_storage.method = GitStorageMethod::None;
408        cfg.identity.team_id.clear();
409        cfg.watchers.custom_paths.clear();
410
411        let root: toml::Value = toml::from_str(
412            r#"
413[server]
414team_id = "team-legacy"
415
416[git_storage]
417"#,
418        )
419        .expect("parse toml");
420
421        let changed = apply_compat_fallbacks(&mut cfg, Some(&root));
422        assert!(changed);
423        assert_eq!(cfg.git_storage.method, GitStorageMethod::Native);
424        assert_eq!(cfg.identity.team_id, "team-legacy");
425        assert!(!cfg.watchers.custom_paths.is_empty());
426    }
427
428    #[test]
429    fn apply_compat_fallbacks_is_noop_for_modern_values() {
430        let mut cfg = DaemonConfig::default();
431        cfg.identity.team_id = "team-modern".to_string();
432        cfg.watchers.custom_paths = vec!["/tmp/one".to_string()];
433
434        let root: toml::Value = toml::from_str(
435            r#"
436[server]
437team_id = "team-from-file"
438
439[git_storage]
440method = "native"
441"#,
442        )
443        .expect("parse toml");
444
445        let before = cfg.clone();
446        let changed = apply_compat_fallbacks(&mut cfg, Some(&root));
447        assert!(!changed);
448        assert_eq!(cfg.identity.team_id, before.identity.team_id);
449        assert_eq!(cfg.watchers.custom_paths, before.watchers.custom_paths);
450        assert_eq!(cfg.git_storage.method, before.git_storage.method);
451    }
452
453    #[test]
454    fn legacy_watcher_flags_are_not_serialized() {
455        let cfg = DaemonConfig::default();
456        let encoded = toml::to_string(&cfg).expect("serialize config");
457
458        assert!(encoded.contains("custom_paths"));
459        assert!(!encoded.contains("\nclaude_code ="));
460        assert!(!encoded.contains("\nopencode ="));
461        assert!(!encoded.contains("\ncursor ="));
462    }
463
464    #[test]
465    fn daemon_summary_defaults_are_stable() {
466        let cfg = DaemonConfig::default();
467        assert!(cfg.daemon.detail_auto_expand_selected_event);
468        assert!(!cfg.daemon.summary_enabled);
469        assert_eq!(cfg.daemon.summary_provider, None);
470        assert_eq!(cfg.daemon.summary_model, None);
471        assert_eq!(cfg.daemon.summary_content_mode, "normal");
472        assert!(cfg.daemon.summary_disk_cache_enabled);
473        assert_eq!(cfg.daemon.summary_event_window, 0);
474        assert_eq!(cfg.daemon.summary_debounce_ms, 250);
475        assert_eq!(cfg.daemon.summary_max_inflight, 2);
476        assert!(!cfg.daemon.summary_window_migrated_v2);
477    }
478
479    #[test]
480    fn daemon_summary_fields_deserialize_from_toml() {
481        let cfg: DaemonConfig = toml::from_str(
482            r#"
483[daemon]
484summary_enabled = true
485summary_provider = "openai"
486summary_model = "gpt-4o-mini"
487summary_content_mode = "minimal"
488summary_disk_cache_enabled = false
489summary_event_window = 8
490summary_debounce_ms = 100
491summary_max_inflight = 4
492summary_window_migrated_v2 = false
493detail_auto_expand_selected_event = false
494"#,
495        )
496        .expect("parse summary config");
497
498        assert!(!cfg.daemon.detail_auto_expand_selected_event);
499        assert!(cfg.daemon.summary_enabled);
500        assert_eq!(cfg.daemon.summary_provider.as_deref(), Some("openai"));
501        assert_eq!(cfg.daemon.summary_model.as_deref(), Some("gpt-4o-mini"));
502        assert_eq!(cfg.daemon.summary_content_mode, "minimal");
503        assert!(!cfg.daemon.summary_disk_cache_enabled);
504        assert_eq!(cfg.daemon.summary_event_window, 8);
505        assert_eq!(cfg.daemon.summary_debounce_ms, 100);
506        assert_eq!(cfg.daemon.summary_max_inflight, 4);
507        assert!(!cfg.daemon.summary_window_migrated_v2);
508    }
509}