Skip to main content

trustee_api/
state.rs

1//! Shared server state: per-user multi-session registry, broadcast channels, and auth state.
2//!
3//! ## Multi-Session Per User (MSU)
4//!
5//! Each authenticated user gets their own [`UserSessions`] containing N independent
6//! [`UserSessionEntry`] instances (default max 4). Each entry has:
7//! - An independent `Session` (workflow state, output, etc.)
8//! - A dedicated broadcast channel for WebSocket fan-out
9//! - Creation and last-active timestamps
10//!
11//! Sessions are keyed by user identity (`sub` claim from JWT, or `dev:email` for
12//! dev mode). Unauthenticated deployments use a single `"default"` key, preserving
13//! backward compatibility with single-user CLI operation.
14
15use std::sync::Arc;
16
17use dashmap::DashMap;
18use tokio::sync::{broadcast, mpsc, Mutex};
19use trustee_core::session::Session;
20use trustee_core::types::TuiMessage;
21
22use crate::auth::AuthState;
23
24// ---------------------------------------------------------------------------
25// Multi-session types
26// ---------------------------------------------------------------------------
27
28/// A single session with its own broadcast channel.
29pub struct UserSessionEntry {
30    /// The agent session, protected by a mutex.
31    pub session: Arc<Mutex<Session>>,
32    /// Broadcast sender for this session's WebSocket fan-out.
33    pub ws_tx: broadcast::Sender<String>,
34    /// When this session was created.
35    pub created_at: chrono::DateTime<chrono::Utc>,
36    /// Last time a command was submitted or state changed.
37    /// Updated on every /sessions/{id}/command and /sessions/{id}/cancel call.
38    pub last_active: Arc<Mutex<chrono::DateTime<chrono::Utc>>>,
39}
40
41/// All sessions belonging to one authenticated user.
42pub struct UserSessions {
43    /// session_id → session entry
44    pub sessions: DashMap<String, UserSessionEntry>,
45    /// Shared token store for all this user's sessions (MCP credential isolation).
46    pub token_store: Arc<pep::MemoryTokenStore>,
47    /// Which session_id is "active" for legacy /session/* routes.
48    pub active_session_id: Mutex<String>,
49}
50
51/// Summary of an active session for listing (serializable for API responses).
52#[derive(Debug, serde::Serialize)]
53pub struct SessionListItem {
54    pub session_id: String,
55    pub session_name: Option<String>,
56    pub workflow_state: String,
57    pub created_at: String,
58    pub last_active: String,
59}
60
61/// Errors from multi-session operations.
62#[derive(Debug)]
63pub enum SessionError {
64    /// User has reached max_sessions_per_user limit.
65    MaxSessionsReached(usize),
66    /// Session ID not found for this user.
67    NotFound(String),
68    /// Session is not Idle (cannot destroy/overwrite a running session).
69    NotIdle(String),
70}
71
72impl std::fmt::Display for SessionError {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        match self {
75            SessionError::MaxSessionsReached(n) => {
76                write!(f, "Maximum {} sessions per user reached", n)
77            }
78            SessionError::NotFound(id) => write!(f, "Session {} not found", id),
79            SessionError::NotIdle(state) => write!(f, "Session is not idle (state: {})", state),
80        }
81    }
82}
83
84impl std::error::Error for SessionError {}
85
86/// Top-level registry: user_key → user's session collection.
87pub type SessionRegistry = Arc<DashMap<String, UserSessions>>;
88
89// ---------------------------------------------------------------------------
90// ServerState
91// ---------------------------------------------------------------------------
92
93/// Shared state accessible by all axum handlers.
94#[derive(Clone)]
95pub struct ServerState {
96    /// Per-user multi-session registry (MSU).
97    pub sessions: SessionRegistry,
98    /// Broadcast sender for backward compat — delegates to the default user's channel.
99    pub ws_tx: broadcast::Sender<String>,
100    /// Auth state (None = auth disabled, all endpoints open).
101    pub auth: Option<Arc<AuthState>>,
102    /// Shared config TOML (all users share the same agent config).
103    pub config_toml: Option<String>,
104    /// Shared secrets (injected into every per-user session).
105    pub secrets: Option<std::collections::HashMap<String, String>>,
106    /// Shared build info (injected into every per-user session).
107    pub build_info: Option<trustee_core::types::BuildInfo>,
108    /// Global concurrency limiter — limits the number of simultaneous workflows
109    /// across all users. Default: 8 concurrent workflows.
110    pub workflow_semaphore: Arc<tokio::sync::Semaphore>,
111    /// Maximum number of concurrent sessions per user. Default: 4.
112    pub max_sessions_per_user: usize,
113}
114
115impl ServerState {
116    /// Create new shared state from a default session, broadcast sender, and optional auth.
117    pub fn new(
118        session: Session,
119        ws_tx: broadcast::Sender<String>,
120        auth: Option<Arc<AuthState>>,
121    ) -> Self {
122        let sessions = Arc::new(DashMap::new());
123
124        // Store the default user's UserSessions with an initial session
125        let token_store = Arc::new(pep::MemoryTokenStore::new());
126        let (ws_tx_entry, _) = broadcast::channel::<String>(256);
127
128        let now = chrono::Utc::now();
129        let initial_entry = UserSessionEntry {
130            session: Arc::new(Mutex::new(session)),
131            ws_tx: ws_tx_entry,
132            created_at: now,
133            last_active: Arc::new(Mutex::new(now)),
134        };
135
136        let user_sessions = UserSessions {
137            sessions: DashMap::new(),
138            token_store,
139            active_session_id: Mutex::new(String::new()),
140        };
141        user_sessions.sessions.insert("default".to_string(), initial_entry);
142
143        sessions.insert("default".to_string(), user_sessions);
144
145        Self {
146            sessions,
147            ws_tx,
148            auth,
149            config_toml: None,
150            secrets: None,
151            build_info: None,
152            workflow_semaphore: Arc::new(tokio::sync::Semaphore::new(8)),
153            max_sessions_per_user: 4,
154        }
155    }
156
157    pub fn with_config_toml(mut self, config_toml: String) -> Self {
158        self.config_toml = Some(config_toml);
159        self
160    }
161
162    pub fn with_secrets(mut self, secrets: std::collections::HashMap<String, String>) -> Self {
163        self.secrets = Some(secrets);
164        self
165    }
166
167    pub fn with_build_info(mut self, build_info: trustee_core::types::BuildInfo) -> Self {
168        self.build_info = Some(build_info);
169        self
170    }
171
172    pub fn with_max_concurrent_workflows(mut self, max: usize) -> Self {
173        self.workflow_semaphore = Arc::new(tokio::sync::Semaphore::new(max));
174        self
175    }
176
177    /// Set the max sessions per user.
178    pub fn with_max_sessions_per_user(mut self, max: usize) -> Self {
179        self.max_sessions_per_user = max;
180        self
181    }
182
183    // -----------------------------------------------------------------------
184    // MSU: Multi-session methods
185    // -----------------------------------------------------------------------
186
187    /// Create a new session for a user. Returns the session_id.
188    ///
189    /// Creates a fresh `Session::new()`, copies shared config, sets per-user
190    /// isolation, creates a broadcast channel, spawns a drain task, and inserts
191    /// into the user's session DashMap. The new session becomes the "active" one.
192    pub async fn create_session(
193        &self,
194        user_key: &str,
195        session_name: Option<String>,
196    ) -> Result<String, SessionError> {
197        // Get or create the user's UserSessions entry
198        let user_sessions = self
199            .sessions
200            .entry(user_key.to_string())
201            .or_insert_with(|| UserSessions {
202                sessions: DashMap::new(),
203                token_store: Arc::new(pep::MemoryTokenStore::new()),
204                active_session_id: Mutex::new(String::new()),
205            });
206
207        // Check session limit
208        if user_sessions.sessions.len() >= self.max_sessions_per_user {
209            return Err(SessionError::MaxSessionsReached(self.max_sessions_per_user));
210        }
211
212        // Create new Session
213        let (mut session, workflow_rx) = Session::new();
214
215        // Copy shared config
216        if let Some(ref config_toml) = self.config_toml {
217            session.config_toml = Some(config_toml.clone());
218            session.parse_auto_handoff_config();
219            if let Ok(table) = config_toml.parse::<toml::Value>() {
220                if let Some(name) = table
221                    .get("agent")
222                    .and_then(|a| a.get("name"))
223                    .and_then(|n| n.as_str())
224                {
225                    session.agent_name = name.to_string();
226                }
227            }
228        }
229
230        session.secrets = self.secrets.clone();
231        session.build_info = self.build_info.clone();
232
233        // Per-user isolation
234        self.apply_user_isolation(&mut session, user_key);
235
236        // Apply session_name if provided
237        session.session_name = session_name;
238
239        // Create broadcast channel
240        let (ws_tx_entry, _) = broadcast::channel::<String>(256);
241
242        // Generate session_id
243        let session_id = format!(
244            "session_{}_{}",
245            chrono::Utc::now().format("%Y_%m_%d_%H_%M"),
246            &uuid::Uuid::new_v4().to_string()[..8]
247        );
248
249        let now = chrono::Utc::now();
250
251        // Insert into user's sessions DashMap
252        user_sessions.sessions.insert(
253            session_id.clone(),
254            UserSessionEntry {
255                session: Arc::new(Mutex::new(session)),
256                ws_tx: ws_tx_entry.clone(),
257                created_at: now,
258                last_active: Arc::new(Mutex::new(now)),
259            },
260        );
261
262        // Set as active session
263        *user_sessions.active_session_id.lock().await = session_id.clone();
264
265        // Spawn drain task
266        let session_arc = user_sessions
267            .sessions
268            .get(&session_id)
269            .map(|e| e.session.clone());
270        if let Some(session_arc) = session_arc {
271            self.spawn_user_drain_task(
272                session_id.clone(),
273                session_arc,
274                ws_tx_entry,
275                workflow_rx,
276            );
277        }
278
279        Ok(session_id)
280    }
281
282    /// Get a specific session by user_key + session_id.
283    /// Updates last_active on the session entry.
284    pub async fn get_session(
285        &self,
286        user_key: &str,
287        session_id: &str,
288    ) -> Option<(Arc<Mutex<Session>>, broadcast::Sender<String>)> {
289        let user_sessions = self.sessions.get(user_key)?;
290        let entry = user_sessions.sessions.get(session_id)?;
291
292        // Update last_active
293        let now = chrono::Utc::now();
294        *entry.last_active.lock().await = now;
295
296        Some((entry.session.clone(), entry.ws_tx.clone()))
297    }
298
299    /// List all active sessions for a user, sorted by last_active desc.
300    pub async fn list_sessions(&self, user_key: &str) -> Vec<SessionListItem> {
301        let Some(user_sessions) = self.sessions.get(user_key) else {
302            return Vec::new();
303        };
304
305        let mut items = Vec::new();
306        for entry in user_sessions.sessions.iter() {
307            let session = entry.session.lock().await;
308            let workflow_state = match session.workflow_state {
309                trustee_core::types::WorkflowState::Idle => "Idle",
310                trustee_core::types::WorkflowState::Running => "Running",
311                trustee_core::types::WorkflowState::Cancelling => "Cancelling",
312            };
313            let last_active = entry.last_active.lock().await;
314            items.push(SessionListItem {
315                session_id: entry.key().clone(),
316                session_name: session.session_name.clone(),
317                workflow_state: workflow_state.to_string(),
318                created_at: entry.created_at.to_rfc3339(),
319                last_active: last_active.to_rfc3339(),
320            });
321        }
322        drop(user_sessions);
323
324        // Sort by last_active descending
325        items.sort_by(|a, b| b.last_active.cmp(&a.last_active));
326        items
327    }
328
329    /// Destroy a session. The session must be Idle.
330    pub async fn destroy_session(
331        &self,
332        user_key: &str,
333        session_id: &str,
334    ) -> Result<(), SessionError> {
335        let user_sessions = self
336            .sessions
337            .get(user_key)
338            .ok_or_else(|| SessionError::NotFound(session_id.to_string()))?;
339
340        // Check workflow state before removing
341        {
342            let entry = user_sessions
343                .sessions
344                .get(session_id)
345                .ok_or_else(|| SessionError::NotFound(session_id.to_string()))?;
346            let session = entry.session.lock().await;
347            if session.workflow_state != trustee_core::types::WorkflowState::Idle {
348                let state_str = match session.workflow_state {
349                    trustee_core::types::WorkflowState::Running => "Running",
350                    trustee_core::types::WorkflowState::Cancelling => "Cancelling",
351                    _ => "Unknown",
352                };
353                return Err(SessionError::NotIdle(state_str.to_string()));
354            }
355        }
356
357        // Remove from DashMap
358        user_sessions.sessions.remove(session_id);
359
360        // If this was the active session, pick a new active
361        let mut active_id = user_sessions.active_session_id.lock().await;
362        if &*active_id == session_id {
363            // Pick the most recently active remaining session
364            let mut newest: Option<(String, chrono::DateTime<chrono::Utc>)> = None;
365            for entry in user_sessions.sessions.iter() {
366                let la = entry.last_active.lock().await;
367                if newest.as_ref().map_or(true, |(_, t)| *la > *t) {
368                    newest = Some((entry.key().clone(), *la));
369                }
370            }
371            *active_id = newest.map(|(id, _)| id).unwrap_or_default();
372        }
373
374        Ok(())
375    }
376
377    /// Get or create the user's "active" session for legacy routes.
378    ///
379    /// Behavior:
380    /// 1. If user has no sessions → create one
381    /// 2. If active session exists → return it
382    /// 3. If active session was destroyed → create a new one
383    ///
384    /// Returns: (session_id, session_arc, ws_tx, token_store)
385    pub async fn ensure_active_session(
386        &self,
387        user_key: &str,
388    ) -> (
389        String,
390        Arc<Mutex<Session>>,
391        broadcast::Sender<String>,
392        Arc<pep::MemoryTokenStore>,
393    ) {
394        // Get or create user's UserSessions
395        let token_store = {
396            let user_sessions = self
397                .sessions
398                .entry(user_key.to_string())
399                .or_insert_with(|| UserSessions {
400                    sessions: DashMap::new(),
401                    token_store: Arc::new(pep::MemoryTokenStore::new()),
402                    active_session_id: Mutex::new(String::new()),
403                });
404            user_sessions.token_store.clone()
405        };
406
407        // Check if active session exists
408        let active_id = {
409            let user_sessions = self.sessions.get(user_key).unwrap();
410            let guard = user_sessions.active_session_id.lock().await;
411            guard.clone()
412        };
413
414        if !active_id.is_empty() {
415            if let Some((session, ws_tx)) = self.get_session(user_key, &active_id).await {
416                return (active_id, session, ws_tx, token_store);
417            }
418            // Active session was destroyed, fall through to create
419        }
420
421        // Need to create a new session
422        // For the "default" user, we may already have a "default" session entry
423        // from ServerState::new() — check for it
424        let existing_session: Option<(String, Arc<Mutex<Session>>, broadcast::Sender<String>)> = {
425            let user_sessions = self.sessions.get(user_key).unwrap();
426            let result = user_sessions.sessions.iter().next().map(|first| {
427                (
428                    first.key().clone(),
429                    first.session.clone(),
430                    first.ws_tx.clone(),
431                )
432            });
433            result
434        };
435        if let Some((id, session, ws_tx)) = existing_session {
436            let now = chrono::Utc::now();
437            if let Some(entry) = self.sessions.get(user_key) {
438                if let Some(e) = entry.sessions.get(&id) {
439                    *e.last_active.lock().await = now;
440                }
441                *entry.active_session_id.lock().await = id.clone();
442            }
443
444            return (id, session, ws_tx, token_store);
445        }
446
447        // Create a brand new session
448        let session_id = self
449            .create_session(user_key, None)
450            .await
451            .unwrap_or_else(|_| "default".to_string());
452
453        let (session, ws_tx) = self
454            .get_session(user_key, &session_id)
455            .await
456            .expect("just-created session must exist");
457
458        (session_id, session, ws_tx, token_store)
459    }
460
461    /// DEPRECATED: Use ensure_active_session() instead.
462    /// Kept for backward compatibility — same 3-tuple return type.
463    pub async fn ensure_user_session(
464        &self,
465        user_key: &str,
466    ) -> (Arc<Mutex<Session>>, broadcast::Sender<String>, Arc<pep::MemoryTokenStore>) {
467        let (_id, session, ws_tx, token_store) = self.ensure_active_session(user_key).await;
468        (session, ws_tx, token_store)
469    }
470
471    /// Set a session as the user's active session.
472    pub async fn set_active_session(&self, user_key: &str, session_id: &str) {
473        if let Some(user_sessions) = self.sessions.get(user_key) {
474            if user_sessions.sessions.contains_key(session_id) {
475                *user_sessions.active_session_id.lock().await = session_id.to_string();
476            }
477        }
478    }
479
480    // -----------------------------------------------------------------------
481    // Read-only helpers (no session creation side effects)
482    // -----------------------------------------------------------------------
483
484    /// Resolve a user's home_dir without creating an in-memory session.
485    ///
486    /// This is the read-only equivalent of the isolation logic in
487    /// `apply_user_isolation`. Used by endpoints that only need to read
488    /// checkpoint data from disk (history, session list, session detail)
489    /// and must NOT create ghost sessions as a side effect.
490    pub fn get_user_home_dir(&self, user_key: &str) -> Option<std::path::PathBuf> {
491        use sha2::{Digest, Sha256};
492        let mut hasher = Sha256::new();
493        hasher.update(user_key.as_bytes());
494        let hash_bytes = hasher.finalize();
495        let user_hash = format!(
496            "{:016x}",
497            u64::from_be_bytes(hash_bytes[..8].try_into().unwrap())
498        );
499        dirs::home_dir().map(|home| home.join(".trustee").join("users").join(&user_hash))
500    }
501
502    /// Resolve config_toml and home_dir without creating an in-memory session.
503    ///
504    /// Returns `(config_toml, home_dir)`. If config is not loaded,
505    /// config_toml will be None.
506    pub fn get_user_config_and_home(&self, user_key: &str) -> (Option<String>, Option<std::path::PathBuf>) {
507        (self.config_toml.clone(), self.get_user_home_dir(user_key))
508    }
509
510    // -----------------------------------------------------------------------
511    // Private helpers
512    // -----------------------------------------------------------------------
513
514    /// Apply per-user isolation: SHA-256 hash → home_dir + project_id.
515    fn apply_user_isolation(&self, session: &mut Session, user_key: &str) {
516        use sha2::{Digest, Sha256};
517        let mut hasher = Sha256::new();
518        hasher.update(user_key.as_bytes());
519        let hash_bytes = hasher.finalize();
520        let user_hash = format!(
521            "{:016x}",
522            u64::from_be_bytes(hash_bytes[..8].try_into().unwrap())
523        );
524
525        // Set per-user home directory for checkpoint isolation
526        let user_home = if let Some(home) = dirs::home_dir() {
527            let user_home = home.join(".trustee").join("users").join(&user_hash);
528            session.home_dir = Some(user_home.clone());
529            Some(user_home)
530        } else {
531            None
532        };
533
534        session.project_id = Some(format!("web{}", &user_hash[..16]));
535
536        // ── Per-user .env (Task 2) ──────────────────────────────────────
537        //
538        // Load per-user secrets from ~/.trustee/users/{hash}/.env
539        // These are merged on top of shared secrets (per-user wins).
540        // They are NEVER set as process env vars — used only for ${VAR}
541        // substitution in the config TOML below.
542        let shared_secrets = session.secrets.clone().unwrap_or_default();
543        let mut merged_secrets = shared_secrets.clone();
544
545        if let Some(ref user_home) = user_home {
546            let user_env_path = user_home.join(".env");
547            if user_env_path.exists() {
548                if let Ok(content) = std::fs::read_to_string(&user_env_path) {
549                    for line in content.lines() {
550                        let line = line.trim();
551                        if line.is_empty() || line.starts_with('#') {
552                            continue;
553                        }
554                        if let Some((key, value)) = line.split_once('=') {
555                            let key = key.trim().to_string();
556                            let value = value.trim()
557                                .trim_matches('"')
558                                .trim_matches('\'')
559                                .to_string();
560                            merged_secrets.insert(key, value);
561                        }
562                    }
563                    tracing::debug!(
564                        "Loaded {} per-user secrets from {}",
565                        merged_secrets.len() - shared_secrets.len(),
566                        user_env_path.display()
567                    );
568                }
569            }
570        }
571
572        // ── Per-user config overlay (Task 3) ────────────────────────────
573        //
574        // Load per-user config from ~/.trustee/users/{hash}/config/trustee.toml
575        // and deep-merge it on top of the shared config. Per-user keys
576        // override shared keys; missing keys inherit from shared.
577        if let Some(ref user_home) = user_home {
578            let user_config_path = user_home.join("config").join("trustee.toml");
579            if user_config_path.exists() {
580                if let Ok(user_config_toml) = std::fs::read_to_string(&user_config_path) {
581                    if let (Ok(mut shared), Ok(overlay)) = (
582                        session.config_toml.as_ref()
583                            .unwrap_or(&String::new())
584                            .parse::<toml::Value>(),
585                        user_config_toml.parse::<toml::Value>(),
586                    ) {
587                        deep_merge_toml(&mut shared, &overlay);
588                        session.config_toml = toml::to_string(&shared).ok();
589                        tracing::debug!("Merged per-user config from {}", user_config_path.display());
590                    }
591                }
592            }
593        }
594
595        // ── ${VAR} substitution (Task 4) ────────────────────────────────
596        //
597        // Replace ${VAR_NAME} in the config TOML with values from the
598        // merged secrets HashMap. Falls back to process env if not in
599        // the HashMap. This replaces the need for std::env::set_var.
600        if let Some(ref mut config_toml) = session.config_toml {
601            substitute_env_vars(config_toml, &merged_secrets);
602        }
603
604        // ── Strip per-user secrets (Task 5) ────────────────────────────
605        //
606        // Keep only shared secrets on session.secrets. When abk's
607        // run_task_from_raw_config() processes the session, its set_var
608        // loop only sees shared secrets (identical for all users → no race).
609        // Per-user secrets were already substituted into config_toml above.
610        session.secrets = Some(shared_secrets);
611    }
612
613    /// Spawn a background drain task for a specific session's workflow receiver.
614    fn spawn_user_drain_task(
615        &self,
616        session_id: String,
617        session: Arc<Mutex<Session>>,
618        ws_tx: broadcast::Sender<String>,
619        mut workflow_rx: mpsc::UnboundedReceiver<TuiMessage>,
620    ) {
621        tokio::spawn(async move {
622            while let Some(msg) = workflow_rx.recv().await {
623                {
624                    let mut session = session.lock().await;
625                    session.handle_workflow_message(msg.clone());
626
627                    let state_str = match session.workflow_state {
628                        trustee_core::types::WorkflowState::Idle => "Idle",
629                        trustee_core::types::WorkflowState::Running => "Running",
630                        trustee_core::types::WorkflowState::Cancelling => "Cancelling",
631                    };
632                    let state_msg = serde_json::json!({
633                        "type": "StateChanged",
634                        "state": state_str
635                    });
636                    let _ = ws_tx.send(state_msg.to_string());
637                }
638
639                let json =
640                    serde_json::to_string(&SerializableMessage(&msg)).unwrap_or_default();
641                let _ = ws_tx.send(json);
642            }
643            tracing::debug!("Drain task ended for session: {}", session_id);
644        });
645    }
646
647    /// Spawn the default user's drain task (backward compatibility).
648    /// Called during server startup for the initial session.
649    pub fn spawn_drain_task(self, mut workflow_rx: mpsc::UnboundedReceiver<TuiMessage>) {
650        // Get the default user's first session
651        let default_user = self
652            .sessions
653            .get("default")
654            .expect("default user must exist");
655        let first_entry = default_user
656            .sessions
657            .iter()
658            .next()
659            .expect("default user must have at least one session");
660        let session = first_entry.session.clone();
661        let ws_tx = first_entry.ws_tx.clone();
662        let session_id = first_entry.key().clone();
663        drop(first_entry);
664        drop(default_user);
665
666        tokio::spawn(async move {
667            while let Some(msg) = workflow_rx.recv().await {
668                {
669                    let mut session = session.lock().await;
670                    session.handle_workflow_message(msg.clone());
671
672                    let state_str = match session.workflow_state {
673                        trustee_core::types::WorkflowState::Idle => "Idle",
674                        trustee_core::types::WorkflowState::Running => "Running",
675                        trustee_core::types::WorkflowState::Cancelling => "Cancelling",
676                    };
677                    let state_msg = serde_json::json!({
678                        "type": "StateChanged",
679                        "state": state_str
680                    });
681                    let _ = ws_tx.send(state_msg.to_string());
682                }
683
684                let json =
685                    serde_json::to_string(&SerializableMessage(&msg)).unwrap_or_default();
686                let _ = ws_tx.send(json);
687            }
688            tracing::debug!("Drain task ended for session: {}", session_id);
689        });
690    }
691
692    /// Resolve the user key from request headers.
693    pub async fn resolve_user_key(&self, headers: &axum::http::HeaderMap) -> String {
694        let Some(ref auth) = self.auth else {
695            return "default".to_string();
696        };
697
698        // Try Bearer header first
699        if let Some(token) = headers
700            .get(axum::http::header::AUTHORIZATION)
701            .and_then(|v| v.to_str().ok())
702            .and_then(|v| v.strip_prefix("Bearer "))
703            .map(|s| s.to_string())
704        {
705            if token.starts_with("dev:") {
706                let parts: Vec<&str> = token.splitn(4, ':').collect();
707                if parts.len() >= 4 {
708                    return format!("dev:{}", parts[1]);
709                }
710            }
711            if let Ok(claims) = auth.validate_token(&token).await {
712                return claims.sub;
713            }
714        }
715
716        // Try cookie
717        let cookie_session_id = headers
718            .get(axum::http::header::COOKIE)
719            .and_then(|v| v.to_str().ok())
720            .and_then(|cookies| {
721                cookies
722                    .split(';')
723                    .map(|c| c.trim())
724                    .find_map(|c| {
725                        c.strip_prefix(&format!("{}=", auth.config.cookie_name))
726                            .map(|s| s.to_string())
727                    })
728            });
729
730        if let Some(session_id) = cookie_session_id {
731            if session_id.starts_with("dev:") {
732                let parts: Vec<&str> = session_id.splitn(4, ':').collect();
733                if parts.len() >= 4 {
734                    return format!("dev:{}", parts[1]);
735                }
736            }
737
738            if let Ok(access_token) = auth.session_manager.get_token(&session_id).await {
739                if let Ok(claims) = auth.validate_token(&access_token).await {
740                    return claims.sub;
741                }
742            }
743        }
744
745        "default".to_string()
746    }
747}
748
749// ---------------------------------------------------------------------------
750// SerializableMessage (unchanged)
751// ---------------------------------------------------------------------------
752
753/// Wrapper to serialize `TuiMessage` as JSON with a `type` discriminator.
754struct SerializableMessage<'a>(&'a TuiMessage);
755
756impl<'a> serde::Serialize for SerializableMessage<'a> {
757    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
758    where
759        S: serde::Serializer,
760    {
761        use serde::ser::SerializeStruct;
762
763        match self.0 {
764            TuiMessage::OutputLine(line) => {
765                let mut s = serializer.serialize_struct("msg", 2)?;
766                s.serialize_field("type", "OutputLine")?;
767                s.serialize_field("line", line)?;
768                s.end()
769            }
770            TuiMessage::StreamDelta(delta) => {
771                let mut s = serializer.serialize_struct("msg", 2)?;
772                s.serialize_field("type", "StreamDelta")?;
773                s.serialize_field("delta", delta)?;
774                s.end()
775            }
776            TuiMessage::ReasoningDelta(delta) => {
777                let mut s = serializer.serialize_struct("msg", 2)?;
778                s.serialize_field("type", "ReasoningDelta")?;
779                s.serialize_field("delta", delta)?;
780                s.end()
781            }
782            TuiMessage::WorkflowCompleted => {
783                let mut s = serializer.serialize_struct("msg", 2)?;
784                s.serialize_field("type", "WorkflowCompleted")?;
785                s.serialize_field("state", "Idle")?;
786                s.end()
787            }
788            TuiMessage::WorkflowError(err) => {
789                let mut s = serializer.serialize_struct("msg", 2)?;
790                s.serialize_field("type", "WorkflowError")?;
791                s.serialize_field("error", err)?;
792                s.end()
793            }
794            TuiMessage::ResumeInfo(info) => match info {
795                Some(ri) => {
796                    let mut s = serializer.serialize_struct("msg", 5)?;
797                    s.serialize_field("type", "ResumeInfo")?;
798                    s.serialize_field("state", "Idle")?;
799                    s.serialize_field("session_id", &ri.session_id)?;
800                    s.serialize_field("checkpoint_id", &ri.checkpoint_id)?;
801                    s.serialize_field("iteration", &ri.iteration)?;
802                    s.end()
803                }
804                None => {
805                    let mut s = serializer.serialize_struct("msg", 2)?;
806                    s.serialize_field("type", "ResumeInfo")?;
807                    s.serialize_field("state", "Idle")?;
808                    s.end()
809                }
810            },
811            TuiMessage::TodoUpdate(content) => {
812                let mut s = serializer.serialize_struct("msg", 2)?;
813                s.serialize_field("type", "TodoUpdate")?;
814                s.serialize_field("content", content)?;
815                s.end()
816            }
817            TuiMessage::WorkflowCancelled => {
818                let mut s = serializer.serialize_struct("msg", 2)?;
819                s.serialize_field("type", "WorkflowCancelled")?;
820                s.serialize_field("state", "Idle")?;
821                s.end()
822            }
823            TuiMessage::HandoffReady(_) => {
824                let mut s = serializer.serialize_struct("msg", 2)?;
825                s.serialize_field("type", "HandoffReady")?;
826                s.serialize_field("state", "Idle")?;
827                s.end()
828            }
829            TuiMessage::ToolPending {
830                tool_name,
831                hint,
832            } => {
833                let mut s = serializer.serialize_struct("msg", 3)?;
834                s.serialize_field("type", "ToolPending")?;
835                s.serialize_field("tool_name", tool_name)?;
836                s.serialize_field("hint", hint)?;
837                s.end()
838            }
839            TuiMessage::ToolDone {
840                tool_name,
841                success,
842                hint,
843            } => {
844                let mut s = serializer.serialize_struct("msg", 4)?;
845                s.serialize_field("type", "ToolDone")?;
846                s.serialize_field("tool_name", tool_name)?;
847                s.serialize_field("success", success)?;
848                s.serialize_field("hint", hint)?;
849                s.end()
850            }
851            TuiMessage::ContextTokensUpdated(count) => {
852                let mut s = serializer.serialize_struct("msg", 2)?;
853                s.serialize_field("type", "ContextTokensUpdated")?;
854                s.serialize_field("count", count)?;
855                s.end()
856            }
857            TuiMessage::McpServerStatus {
858                name,
859                connected,
860                tool_count,
861                error,
862            } => {
863                let mut s = serializer.serialize_struct("msg", 5)?;
864                s.serialize_field("type", "McpServerStatus")?;
865                s.serialize_field("name", name)?;
866                s.serialize_field("connected", connected)?;
867                s.serialize_field("tool_count", tool_count)?;
868                s.serialize_field("error", error)?;
869                s.end()
870            }
871        }
872    }
873}
874
875// ---------------------------------------------------------------------------
876// Per-user config helpers
877// ---------------------------------------------------------------------------
878
879/// Deep-merge a TOML overlay on top of a base value (in-place).
880///
881/// - Tables: recursively merge key-by-key (overlay wins on conflict).
882/// - Arrays: overlay replaces base entirely (no merging).
883/// - Scalars: overlay replaces base.
884/// - If a key exists in overlay but not base, it's added.
885fn deep_merge_toml(base: &mut toml::Value, overlay: &toml::Value) {
886    match (base, overlay) {
887        (toml::Value::Table(base_table), toml::Value::Table(overlay_table)) => {
888            for (key, overlay_val) in overlay_table {
889                match base_table.get_mut(key) {
890                    Some(base_val) => {
891                        // Both exist — recurse if both are tables, else replace
892                        deep_merge_toml(base_val, overlay_val);
893                    }
894                    None => {
895                        // Key only in overlay — insert
896                        base_table.insert(key.clone(), overlay_val.clone());
897                    }
898                }
899            }
900        }
901        // Non-table: overlay replaces base
902        (base, overlay) => {
903            *base = overlay.clone();
904        }
905    }
906}
907
908/// Replace `${VAR_NAME}` references in a string with values from a secrets map.
909///
910/// Falls back to process environment if the variable is not in the map.
911/// Variables not found in either are left as-is.
912fn substitute_env_vars(s: &mut String, secrets: &std::collections::HashMap<String, String>) {
913    // Simple state machine: scan for ${, read until }, replace.
914    let mut result = String::with_capacity(s.len());
915    let bytes = s.as_bytes();
916    let mut i = 0;
917
918    while i < bytes.len() {
919        if i + 1 < bytes.len() && bytes[i] == b'$' && bytes[i + 1] == b'{' {
920            // Find closing }
921            if let Some(end) = s[i + 2..].find('}') {
922                let var_name = &s[i + 2..i + 2 + end];
923                // Look up in per-user secrets first, then process env
924                if let Some(value) = secrets.get(var_name) {
925                    result.push_str(value);
926                } else if let Ok(value) = std::env::var(var_name) {
927                    result.push_str(&value);
928                } else {
929                    // Not found — leave as-is
930                    result.push_str(&s[i..i + 2 + end + 1]);
931                }
932                i = i + 2 + end + 1;
933            } else {
934                // No closing } — copy as-is
935                result.push('$');
936                i += 1;
937            }
938        } else {
939            result.push(bytes[i] as char);
940            i += 1;
941        }
942    }
943
944    *s = result;
945}