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        identity: Option<String>,
197    ) -> Result<String, SessionError> {
198        // Get or create the user's UserSessions entry
199        let user_sessions = self
200            .sessions
201            .entry(user_key.to_string())
202            .or_insert_with(|| UserSessions {
203                sessions: DashMap::new(),
204                token_store: Arc::new(pep::MemoryTokenStore::new()),
205                active_session_id: Mutex::new(String::new()),
206            });
207
208        // Check session limit
209        if user_sessions.sessions.len() >= self.max_sessions_per_user {
210            return Err(SessionError::MaxSessionsReached(self.max_sessions_per_user));
211        }
212
213        // Create new Session
214        let (mut session, workflow_rx) = Session::new();
215
216        // Copy shared config
217        if let Some(ref config_toml) = self.config_toml {
218            session.config_toml = Some(config_toml.clone());
219            session.parse_auto_handoff_config();
220            if let Ok(table) = config_toml.parse::<toml::Value>() {
221                if let Some(name) = table
222                    .get("agent")
223                    .and_then(|a| a.get("name"))
224                    .and_then(|n| n.as_str())
225                {
226                    session.agent_name = name.to_string();
227                }
228            }
229        }
230
231        session.secrets = self.secrets.clone();
232        session.build_info = self.build_info.clone();
233
234        // Per-user isolation
235        self.apply_user_isolation(&mut session, user_key);
236
237        // Apply session_name if provided
238        session.session_name = session_name;
239
240        // Apply agent identity if provided
241        session.identity = identity;
242
243        // Create broadcast channel
244        let (ws_tx_entry, _) = broadcast::channel::<String>(256);
245
246        // Generate session_id
247        let session_id = format!(
248            "session_{}_{}",
249            chrono::Utc::now().format("%Y_%m_%d_%H_%M"),
250            &uuid::Uuid::new_v4().to_string()[..8]
251        );
252
253        let now = chrono::Utc::now();
254
255        // Insert into user's sessions DashMap
256        user_sessions.sessions.insert(
257            session_id.clone(),
258            UserSessionEntry {
259                session: Arc::new(Mutex::new(session)),
260                ws_tx: ws_tx_entry.clone(),
261                created_at: now,
262                last_active: Arc::new(Mutex::new(now)),
263            },
264        );
265
266        // Set as active session
267        *user_sessions.active_session_id.lock().await = session_id.clone();
268
269        // Spawn drain task
270        let session_arc = user_sessions
271            .sessions
272            .get(&session_id)
273            .map(|e| e.session.clone());
274        if let Some(session_arc) = session_arc {
275            self.spawn_user_drain_task(
276                session_id.clone(),
277                session_arc,
278                ws_tx_entry,
279                workflow_rx,
280            );
281        }
282
283        Ok(session_id)
284    }
285
286    /// Get a specific session by user_key + session_id.
287    /// Updates last_active on the session entry.
288    pub async fn get_session(
289        &self,
290        user_key: &str,
291        session_id: &str,
292    ) -> Option<(Arc<Mutex<Session>>, broadcast::Sender<String>)> {
293        let user_sessions = self.sessions.get(user_key)?;
294        let entry = user_sessions.sessions.get(session_id)?;
295
296        // Update last_active
297        let now = chrono::Utc::now();
298        *entry.last_active.lock().await = now;
299
300        Some((entry.session.clone(), entry.ws_tx.clone()))
301    }
302
303    /// Get a session by EITHER its live MSU registry key OR its
304    /// checkpoint/session identity (`session.session_id`).
305    ///
306    /// The web frontend tracks `currentSessionId` from the `ResumeInfo` WS
307    /// message, which carries the auto-derived checkpoint id
308    /// (`session_YYYY_MM_DD_HH_MM_uuid8`) — NOT the live MSU registry key
309    /// (`"default"` or the key from `create_session()`). External clients
310    /// like Torpi/THQ pass the live registry key. This resolver accepts both:
311    ///
312    /// 1. Try registry-key lookup first (precise, used by Torpi/THQ).
313    /// 2. Fall back to scanning the user's live sessions for one whose
314    ///    `session.session_id` matches the requested id (used by the
315    ///    embedded web UI after a command or resume).
316    ///
317    /// Returns `(live_registry_key, session_arc, ws_tx)`, or `None` if not
318    /// found. The live key is returned so callers that need to set it as
319    /// active (or otherwise reference the registry) use the real key.
320    pub async fn get_session_by_any_id(
321        &self,
322        user_key: &str,
323        id: &str,
324    ) -> Option<(String, Arc<Mutex<Session>>, broadcast::Sender<String>)> {
325        // Fast path: registry key match.
326        let user_sessions = self.sessions.get(user_key)?;
327        if let Some(entry) = user_sessions.sessions.get(id) {
328            // Update last_active
329            let now = chrono::Utc::now();
330            *entry.last_active.lock().await = now;
331            return Some((id.to_string(), entry.session.clone(), entry.ws_tx.clone()));
332        }
333
334        // Slow path: scan live sessions for a matching session.session_id.
335        for entry in user_sessions.sessions.iter() {
336            let session = entry.session.lock().await;
337            if session.session_id.as_deref() == Some(id) {
338                let key = entry.key().clone();
339                let ws_tx = entry.ws_tx.clone();
340                drop(session);
341                // Update last_active
342                let now = chrono::Utc::now();
343                *entry.last_active.lock().await = now;
344                return Some((key, entry.session.clone(), ws_tx));
345            }
346        }
347
348        None
349    }
350
351    /// List all active sessions for a user, sorted by last_active desc.
352    pub async fn list_sessions(&self, user_key: &str) -> Vec<SessionListItem> {
353        let Some(user_sessions) = self.sessions.get(user_key) else {
354            return Vec::new();
355        };
356
357        let mut items = Vec::new();
358        for entry in user_sessions.sessions.iter() {
359            let session = entry.session.lock().await;
360            let workflow_state = match session.workflow_state {
361                trustee_core::types::WorkflowState::Idle => "Idle",
362                trustee_core::types::WorkflowState::Running => "Running",
363                trustee_core::types::WorkflowState::Cancelling => "Cancelling",
364            };
365            let last_active = entry.last_active.lock().await;
366            items.push(SessionListItem {
367                session_id: entry.key().clone(),
368                session_name: session.session_name.clone(),
369                workflow_state: workflow_state.to_string(),
370                created_at: entry.created_at.to_rfc3339(),
371                last_active: last_active.to_rfc3339(),
372            });
373        }
374        drop(user_sessions);
375
376        // Sort by last_active descending
377        items.sort_by(|a, b| b.last_active.cmp(&a.last_active));
378        items
379    }
380
381    /// Destroy a session. The session must be Idle.
382    pub async fn destroy_session(
383        &self,
384        user_key: &str,
385        session_id: &str,
386    ) -> Result<(), SessionError> {
387        let user_sessions = self
388            .sessions
389            .get(user_key)
390            .ok_or_else(|| SessionError::NotFound(session_id.to_string()))?;
391
392        // Check workflow state before removing
393        {
394            let entry = user_sessions
395                .sessions
396                .get(session_id)
397                .ok_or_else(|| SessionError::NotFound(session_id.to_string()))?;
398            let session = entry.session.lock().await;
399            if session.workflow_state != trustee_core::types::WorkflowState::Idle {
400                let state_str = match session.workflow_state {
401                    trustee_core::types::WorkflowState::Running => "Running",
402                    trustee_core::types::WorkflowState::Cancelling => "Cancelling",
403                    _ => "Unknown",
404                };
405                return Err(SessionError::NotIdle(state_str.to_string()));
406            }
407        }
408
409        // Remove from DashMap
410        user_sessions.sessions.remove(session_id);
411
412        // If this was the active session, pick a new active
413        let mut active_id = user_sessions.active_session_id.lock().await;
414        if &*active_id == session_id {
415            // Pick the most recently active remaining session
416            let mut newest: Option<(String, chrono::DateTime<chrono::Utc>)> = None;
417            for entry in user_sessions.sessions.iter() {
418                let la = entry.last_active.lock().await;
419                if newest.as_ref().map_or(true, |(_, t)| *la > *t) {
420                    newest = Some((entry.key().clone(), *la));
421                }
422            }
423            *active_id = newest.map(|(id, _)| id).unwrap_or_default();
424        }
425
426        Ok(())
427    }
428
429    /// Get or create the user's "active" session for legacy routes.
430    ///
431    /// Behavior:
432    /// 1. If user has no sessions → create one
433    /// 2. If active session exists → return it
434    /// 3. If active session was destroyed → create a new one
435    ///
436    /// Returns: (session_id, session_arc, ws_tx, token_store)
437    pub async fn ensure_active_session(
438        &self,
439        user_key: &str,
440    ) -> (
441        String,
442        Arc<Mutex<Session>>,
443        broadcast::Sender<String>,
444        Arc<pep::MemoryTokenStore>,
445    ) {
446        // Get or create user's UserSessions
447        let token_store = {
448            let user_sessions = self
449                .sessions
450                .entry(user_key.to_string())
451                .or_insert_with(|| UserSessions {
452                    sessions: DashMap::new(),
453                    token_store: Arc::new(pep::MemoryTokenStore::new()),
454                    active_session_id: Mutex::new(String::new()),
455                });
456            user_sessions.token_store.clone()
457        };
458
459        // Check if active session exists
460        let active_id = {
461            let user_sessions = self.sessions.get(user_key).unwrap();
462            let guard = user_sessions.active_session_id.lock().await;
463            guard.clone()
464        };
465
466        if !active_id.is_empty() {
467            if let Some((session, ws_tx)) = self.get_session(user_key, &active_id).await {
468                return (active_id, session, ws_tx, token_store);
469            }
470            // Active session was destroyed, fall through to create
471        }
472
473        // Need to create a new session
474        // For the "default" user, we may already have a "default" session entry
475        // from ServerState::new() — check for it
476        let existing_session: Option<(String, Arc<Mutex<Session>>, broadcast::Sender<String>)> = {
477            let user_sessions = self.sessions.get(user_key).unwrap();
478            let result = user_sessions.sessions.iter().next().map(|first| {
479                (
480                    first.key().clone(),
481                    first.session.clone(),
482                    first.ws_tx.clone(),
483                )
484            });
485            result
486        };
487        if let Some((id, session, ws_tx)) = existing_session {
488            let now = chrono::Utc::now();
489            if let Some(entry) = self.sessions.get(user_key) {
490                if let Some(e) = entry.sessions.get(&id) {
491                    *e.last_active.lock().await = now;
492                }
493                *entry.active_session_id.lock().await = id.clone();
494            }
495
496            return (id, session, ws_tx, token_store);
497        }
498
499        // Create a brand new session
500        let session_id = self
501            .create_session(user_key, None, None)
502            .await
503            .unwrap_or_else(|_| "default".to_string());
504
505        let (session, ws_tx) = self
506            .get_session(user_key, &session_id)
507            .await
508            .expect("just-created session must exist");
509
510        (session_id, session, ws_tx, token_store)
511    }
512
513    /// DEPRECATED: Use ensure_active_session() instead.
514    /// Kept for backward compatibility — same 3-tuple return type.
515    pub async fn ensure_user_session(
516        &self,
517        user_key: &str,
518    ) -> (Arc<Mutex<Session>>, broadcast::Sender<String>, Arc<pep::MemoryTokenStore>) {
519        let (_id, session, ws_tx, token_store) = self.ensure_active_session(user_key).await;
520        (session, ws_tx, token_store)
521    }
522
523    /// Set a session as the user's active session.
524    pub async fn set_active_session(&self, user_key: &str, session_id: &str) {
525        if let Some(user_sessions) = self.sessions.get(user_key) {
526            if user_sessions.sessions.contains_key(session_id) {
527                *user_sessions.active_session_id.lock().await = session_id.to_string();
528            }
529        }
530    }
531
532    // -----------------------------------------------------------------------
533    // Read-only helpers (no session creation side effects)
534    // -----------------------------------------------------------------------
535
536    /// Resolve a user's home_dir without creating an in-memory session.
537    ///
538    /// This is the read-only equivalent of the isolation logic in
539    /// `apply_user_isolation`. Used by endpoints that only need to read
540    /// checkpoint data from disk (history, session list, session detail)
541    /// and must NOT create ghost sessions as a side effect.
542    pub fn get_user_home_dir(&self, user_key: &str) -> Option<std::path::PathBuf> {
543        use sha2::{Digest, Sha256};
544        let mut hasher = Sha256::new();
545        hasher.update(user_key.as_bytes());
546        let hash_bytes = hasher.finalize();
547        let user_hash = format!(
548            "{:016x}",
549            u64::from_be_bytes(hash_bytes[..8].try_into().unwrap())
550        );
551        dirs::home_dir().map(|home| home.join(".trustee").join("users").join(&user_hash))
552    }
553
554    /// Resolve config_toml and home_dir without creating an in-memory session.
555    ///
556    /// Returns `(config_toml, home_dir)`. If config is not loaded,
557    /// config_toml will be None.
558    pub fn get_user_config_and_home(&self, user_key: &str) -> (Option<String>, Option<std::path::PathBuf>) {
559        (self.config_toml.clone(), self.get_user_home_dir(user_key))
560    }
561
562    // -----------------------------------------------------------------------
563    // Private helpers
564    // -----------------------------------------------------------------------
565
566    /// Apply per-user isolation: SHA-256 hash → home_dir + project_id.
567    fn apply_user_isolation(&self, session: &mut Session, user_key: &str) {
568        use sha2::{Digest, Sha256};
569        let mut hasher = Sha256::new();
570        hasher.update(user_key.as_bytes());
571        let hash_bytes = hasher.finalize();
572        let user_hash = format!(
573            "{:016x}",
574            u64::from_be_bytes(hash_bytes[..8].try_into().unwrap())
575        );
576
577        // Set per-user home directory for checkpoint isolation
578        let user_home = if let Some(home) = dirs::home_dir() {
579            let user_home = home.join(".trustee").join("users").join(&user_hash);
580            session.home_dir = Some(user_home.clone());
581            Some(user_home)
582        } else {
583            None
584        };
585
586        session.project_id = Some(format!("web{}", &user_hash[..16]));
587
588        // ── Per-user .env (Task 2) ──────────────────────────────────────
589        //
590        // Load per-user secrets from ~/.trustee/users/{hash}/.env
591        // These are merged on top of shared secrets (per-user wins).
592        // They are NEVER set as process env vars — used only for ${VAR}
593        // substitution in the config TOML below.
594        let shared_secrets = session.secrets.clone().unwrap_or_default();
595        let mut merged_secrets = shared_secrets.clone();
596
597        if let Some(ref user_home) = user_home {
598            let user_env_path = user_home.join(".env");
599            if user_env_path.exists() {
600                if let Ok(content) = std::fs::read_to_string(&user_env_path) {
601                    for line in content.lines() {
602                        let line = line.trim();
603                        if line.is_empty() || line.starts_with('#') {
604                            continue;
605                        }
606                        if let Some((key, value)) = line.split_once('=') {
607                            let key = key.trim().to_string();
608                            let value = value.trim()
609                                .trim_matches('"')
610                                .trim_matches('\'')
611                                .to_string();
612                            merged_secrets.insert(key, value);
613                        }
614                    }
615                    tracing::debug!(
616                        "Loaded {} per-user secrets from {}",
617                        merged_secrets.len() - shared_secrets.len(),
618                        user_env_path.display()
619                    );
620                }
621            }
622        }
623
624        // ── Per-user config overlay (Task 3) ────────────────────────────
625        //
626        // Load per-user config from ~/.trustee/users/{hash}/config/trustee.toml
627        // and deep-merge it on top of the shared config. Per-user keys
628        // override shared keys; missing keys inherit from shared.
629        if let Some(ref user_home) = user_home {
630            let user_config_path = user_home.join("config").join("trustee.toml");
631            if user_config_path.exists() {
632                if let Ok(user_config_toml) = std::fs::read_to_string(&user_config_path) {
633                    if let (Ok(mut shared), Ok(overlay)) = (
634                        session.config_toml.as_ref()
635                            .unwrap_or(&String::new())
636                            .parse::<toml::Value>(),
637                        user_config_toml.parse::<toml::Value>(),
638                    ) {
639                        deep_merge_toml(&mut shared, &overlay);
640                        session.config_toml = toml::to_string(&shared).ok();
641                        tracing::debug!("Merged per-user config from {}", user_config_path.display());
642                    }
643                }
644            }
645        }
646
647        // ── ${VAR} substitution (Task 4) ────────────────────────────────
648        //
649        // Replace ${VAR_NAME} in the config TOML with values from the
650        // merged secrets HashMap. Falls back to process env if not in
651        // the HashMap. This replaces the need for std::env::set_var.
652        if let Some(ref mut config_toml) = session.config_toml {
653            substitute_env_vars(config_toml, &merged_secrets);
654        }
655
656        // ── Strip per-user secrets (Task 5) ────────────────────────────
657        //
658        // Keep only shared secrets on session.secrets. When abk's
659        // run_task_from_raw_config() processes the session, its set_var
660        // loop only sees shared secrets (identical for all users → no race).
661        // Per-user secrets were already substituted into config_toml above.
662        session.secrets = Some(shared_secrets);
663    }
664
665    /// Spawn a background drain task for a specific session's workflow receiver.
666    fn spawn_user_drain_task(
667        &self,
668        session_id: String,
669        session: Arc<Mutex<Session>>,
670        ws_tx: broadcast::Sender<String>,
671        mut workflow_rx: mpsc::UnboundedReceiver<TuiMessage>,
672    ) {
673        tokio::spawn(async move {
674            while let Some(msg) = workflow_rx.recv().await {
675                {
676                    let mut session = session.lock().await;
677                    session.handle_workflow_message(msg.clone());
678
679                    let state_str = match session.workflow_state {
680                        trustee_core::types::WorkflowState::Idle => "Idle",
681                        trustee_core::types::WorkflowState::Running => "Running",
682                        trustee_core::types::WorkflowState::Cancelling => "Cancelling",
683                    };
684                    let state_msg = serde_json::json!({
685                        "type": "StateChanged",
686                        "state": state_str
687                    });
688                    let _ = ws_tx.send(state_msg.to_string());
689                }
690
691                let json =
692                    serde_json::to_string(&SerializableMessage(&msg)).unwrap_or_default();
693                let _ = ws_tx.send(json);
694            }
695            tracing::debug!("Drain task ended for session: {}", session_id);
696        });
697    }
698
699    /// Spawn the default user's drain task (backward compatibility).
700    /// Called during server startup for the initial session.
701    pub fn spawn_drain_task(self, mut workflow_rx: mpsc::UnboundedReceiver<TuiMessage>) {
702        // Get the default user's first session
703        let default_user = self
704            .sessions
705            .get("default")
706            .expect("default user must exist");
707        let first_entry = default_user
708            .sessions
709            .iter()
710            .next()
711            .expect("default user must have at least one session");
712        let session = first_entry.session.clone();
713        let ws_tx = first_entry.ws_tx.clone();
714        let session_id = first_entry.key().clone();
715        drop(first_entry);
716        drop(default_user);
717
718        tokio::spawn(async move {
719            while let Some(msg) = workflow_rx.recv().await {
720                {
721                    let mut session = session.lock().await;
722                    session.handle_workflow_message(msg.clone());
723
724                    let state_str = match session.workflow_state {
725                        trustee_core::types::WorkflowState::Idle => "Idle",
726                        trustee_core::types::WorkflowState::Running => "Running",
727                        trustee_core::types::WorkflowState::Cancelling => "Cancelling",
728                    };
729                    let state_msg = serde_json::json!({
730                        "type": "StateChanged",
731                        "state": state_str
732                    });
733                    let _ = ws_tx.send(state_msg.to_string());
734                }
735
736                let json =
737                    serde_json::to_string(&SerializableMessage(&msg)).unwrap_or_default();
738                let _ = ws_tx.send(json);
739            }
740            tracing::debug!("Drain task ended for session: {}", session_id);
741        });
742    }
743
744    /// Resolve the user key from request headers.
745    pub async fn resolve_user_key(&self, headers: &axum::http::HeaderMap) -> String {
746        let Some(ref auth) = self.auth else {
747            return "default".to_string();
748        };
749
750        // Try Bearer header first
751        if let Some(token) = headers
752            .get(axum::http::header::AUTHORIZATION)
753            .and_then(|v| v.to_str().ok())
754            .and_then(|v| v.strip_prefix("Bearer "))
755            .map(|s| s.to_string())
756        {
757            if token.starts_with("dev:") {
758                let parts: Vec<&str> = token.splitn(4, ':').collect();
759                if parts.len() >= 4 {
760                    return format!("dev:{}", parts[1]);
761                }
762            }
763            if let Ok(claims) = auth.validate_token(&token).await {
764                return claims.sub;
765            }
766        }
767
768        // Try cookie
769        let cookie_session_id = headers
770            .get(axum::http::header::COOKIE)
771            .and_then(|v| v.to_str().ok())
772            .and_then(|cookies| {
773                cookies
774                    .split(';')
775                    .map(|c| c.trim())
776                    .find_map(|c| {
777                        c.strip_prefix(&format!("{}=", auth.config.cookie_name))
778                            .map(|s| s.to_string())
779                    })
780            });
781
782        if let Some(session_id) = cookie_session_id {
783            if session_id.starts_with("dev:") {
784                let parts: Vec<&str> = session_id.splitn(4, ':').collect();
785                if parts.len() >= 4 {
786                    return format!("dev:{}", parts[1]);
787                }
788            }
789
790            if let Ok(access_token) = auth.session_manager.get_token(&session_id).await {
791                if let Ok(claims) = auth.validate_token(&access_token).await {
792                    return claims.sub;
793                }
794            }
795        }
796
797        "default".to_string()
798    }
799}
800
801// ---------------------------------------------------------------------------
802// SerializableMessage (unchanged)
803// ---------------------------------------------------------------------------
804
805/// Wrapper to serialize `TuiMessage` as JSON with a `type` discriminator.
806struct SerializableMessage<'a>(&'a TuiMessage);
807
808impl<'a> serde::Serialize for SerializableMessage<'a> {
809    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
810    where
811        S: serde::Serializer,
812    {
813        use serde::ser::SerializeStruct;
814
815        match self.0 {
816            TuiMessage::OutputLine(line) => {
817                let mut s = serializer.serialize_struct("msg", 2)?;
818                s.serialize_field("type", "OutputLine")?;
819                s.serialize_field("line", line)?;
820                s.end()
821            }
822            TuiMessage::StreamDelta(delta) => {
823                let mut s = serializer.serialize_struct("msg", 2)?;
824                s.serialize_field("type", "StreamDelta")?;
825                s.serialize_field("delta", delta)?;
826                s.end()
827            }
828            TuiMessage::ReasoningDelta(delta) => {
829                let mut s = serializer.serialize_struct("msg", 2)?;
830                s.serialize_field("type", "ReasoningDelta")?;
831                s.serialize_field("delta", delta)?;
832                s.end()
833            }
834            TuiMessage::WorkflowCompleted => {
835                let mut s = serializer.serialize_struct("msg", 2)?;
836                s.serialize_field("type", "WorkflowCompleted")?;
837                s.serialize_field("state", "Idle")?;
838                s.end()
839            }
840            TuiMessage::WorkflowError(err) => {
841                let mut s = serializer.serialize_struct("msg", 2)?;
842                s.serialize_field("type", "WorkflowError")?;
843                s.serialize_field("error", err)?;
844                s.end()
845            }
846            TuiMessage::ResumeInfo(info) => match info {
847                Some(ri) => {
848                    let mut s = serializer.serialize_struct("msg", 5)?;
849                    s.serialize_field("type", "ResumeInfo")?;
850                    s.serialize_field("state", "Idle")?;
851                    s.serialize_field("session_id", &ri.session_id)?;
852                    s.serialize_field("checkpoint_id", &ri.checkpoint_id)?;
853                    s.serialize_field("iteration", &ri.iteration)?;
854                    s.end()
855                }
856                None => {
857                    let mut s = serializer.serialize_struct("msg", 2)?;
858                    s.serialize_field("type", "ResumeInfo")?;
859                    s.serialize_field("state", "Idle")?;
860                    s.end()
861                }
862            },
863            TuiMessage::TodoUpdate(content) => {
864                let mut s = serializer.serialize_struct("msg", 2)?;
865                s.serialize_field("type", "TodoUpdate")?;
866                s.serialize_field("content", content)?;
867                s.end()
868            }
869            TuiMessage::WorkflowCancelled => {
870                let mut s = serializer.serialize_struct("msg", 2)?;
871                s.serialize_field("type", "WorkflowCancelled")?;
872                s.serialize_field("state", "Idle")?;
873                s.end()
874            }
875            TuiMessage::HandoffReady(briefing) => {
876                let mut s = serializer.serialize_struct("msg", 3)?;
877                s.serialize_field("type", "HandoffReady")?;
878                s.serialize_field("state", "Idle")?;
879                s.serialize_field("briefing", briefing)?;
880                s.end()
881            }
882            TuiMessage::HandoffFailed => {
883                let mut s = serializer.serialize_struct("msg", 2)?;
884                s.serialize_field("type", "HandoffFailed")?;
885                s.serialize_field("state", "Idle")?;
886                s.end()
887            }
888            TuiMessage::ToolPending {
889                tool_name,
890                hint,
891            } => {
892                let mut s = serializer.serialize_struct("msg", 3)?;
893                s.serialize_field("type", "ToolPending")?;
894                s.serialize_field("tool_name", tool_name)?;
895                s.serialize_field("hint", hint)?;
896                s.end()
897            }
898            TuiMessage::ToolDone {
899                tool_name,
900                success,
901                hint,
902            } => {
903                let mut s = serializer.serialize_struct("msg", 4)?;
904                s.serialize_field("type", "ToolDone")?;
905                s.serialize_field("tool_name", tool_name)?;
906                s.serialize_field("success", success)?;
907                s.serialize_field("hint", hint)?;
908                s.end()
909            }
910            TuiMessage::ContextTokensUpdated(count) => {
911                let mut s = serializer.serialize_struct("msg", 2)?;
912                s.serialize_field("type", "ContextTokensUpdated")?;
913                s.serialize_field("count", count)?;
914                s.end()
915            }
916            TuiMessage::McpServerStatus {
917                name,
918                connected,
919                tool_count,
920                error,
921            } => {
922                let mut s = serializer.serialize_struct("msg", 5)?;
923                s.serialize_field("type", "McpServerStatus")?;
924                s.serialize_field("name", name)?;
925                s.serialize_field("connected", connected)?;
926                s.serialize_field("tool_count", tool_count)?;
927                s.serialize_field("error", error)?;
928                s.end()
929            }
930            TuiMessage::SessionTitleUpdated(title) => {
931                let mut s = serializer.serialize_struct("msg", 2)?;
932                s.serialize_field("type", "SessionTitleUpdated")?;
933                s.serialize_field("title", title)?;
934                s.end()
935            }
936        }
937    }
938}
939
940// ---------------------------------------------------------------------------
941// Per-user config helpers
942// ---------------------------------------------------------------------------
943
944/// Deep-merge a TOML overlay on top of a base value (in-place).
945///
946/// - Tables: recursively merge key-by-key (overlay wins on conflict).
947/// - Arrays: overlay replaces base entirely (no merging).
948/// - Scalars: overlay replaces base.
949/// - If a key exists in overlay but not base, it's added.
950fn deep_merge_toml(base: &mut toml::Value, overlay: &toml::Value) {
951    match (base, overlay) {
952        (toml::Value::Table(base_table), toml::Value::Table(overlay_table)) => {
953            for (key, overlay_val) in overlay_table {
954                match base_table.get_mut(key) {
955                    Some(base_val) => {
956                        // Both exist — recurse if both are tables, else replace
957                        deep_merge_toml(base_val, overlay_val);
958                    }
959                    None => {
960                        // Key only in overlay — insert
961                        base_table.insert(key.clone(), overlay_val.clone());
962                    }
963                }
964            }
965        }
966        // Non-table: overlay replaces base
967        (base, overlay) => {
968            *base = overlay.clone();
969        }
970    }
971}
972
973/// Replace `${VAR_NAME}` references in a string with values from a secrets map.
974///
975/// Falls back to process environment if the variable is not in the map.
976/// Variables not found in either are left as-is.
977fn substitute_env_vars(s: &mut String, secrets: &std::collections::HashMap<String, String>) {
978    // Simple state machine: scan for ${, read until }, replace.
979    let mut result = String::with_capacity(s.len());
980    let bytes = s.as_bytes();
981    let mut i = 0;
982
983    while i < bytes.len() {
984        if i + 1 < bytes.len() && bytes[i] == b'$' && bytes[i + 1] == b'{' {
985            // Find closing }
986            if let Some(end) = s[i + 2..].find('}') {
987                let var_name = &s[i + 2..i + 2 + end];
988                // Look up in per-user secrets first, then process env
989                if let Some(value) = secrets.get(var_name) {
990                    result.push_str(value);
991                } else if let Ok(value) = std::env::var(var_name) {
992                    result.push_str(&value);
993                } else {
994                    // Not found — leave as-is
995                    result.push_str(&s[i..i + 2 + end + 1]);
996                }
997                i = i + 2 + end + 1;
998            } else {
999                // No closing } — copy as-is
1000                result.push('$');
1001                i += 1;
1002            }
1003        } else {
1004            result.push(bytes[i] as char);
1005            i += 1;
1006        }
1007    }
1008
1009    *s = result;
1010}