Skip to main content

winx_code_agent/server/
sessions.rs

1use std::collections::HashMap;
2use std::sync::atomic::{AtomicUsize, Ordering};
3use std::sync::Arc;
4use std::time::Instant;
5
6use rmcp::service::{NotificationContext, RoleServer};
7use tokio::sync::Mutex;
8use tracing::{info, warn};
9
10use super::{SharedBashState, WinxService};
11use crate::runtime::{EmbeddedShellRuntime, ShellRuntime};
12use crate::state::bash_state::generate_thread_id;
13use crate::state::task_state::TaskRegistry;
14use crate::types::{Initialize, InitializeType, ModeName};
15
16/// Upper bound on concurrently-live adapter sessions. Each embedded session owns
17/// a PTY; daemon-backed sessions also release their guardian when evicted.
18pub(super) const MAX_SESSIONS: usize = 32;
19
20/// Per-`thread_id` shell sessions. Each `thread_id` gets its own
21/// `BashState`/PTY, so concurrent threads (or HTTP clients sharing the service)
22/// never execute in each other's shell. Tools that don't carry a `thread_id`
23/// (legacy clients) fall back to the most recently active session.
24#[derive(Default)]
25pub(super) struct SessionRegistry {
26    pub(super) slots: HashMap<String, SharedBashState>,
27    /// Last-use timestamps for LRU eviction.
28    pub(super) last_used: HashMap<String, Instant>,
29    /// In-flight operation count per session. A session whose count is > 0 (it
30    /// has a live [`SessionGuard`]) is never chosen as an LRU eviction victim.
31    pub(super) in_flight: HashMap<String, SessionPin>,
32    /// Most recently addressed session, used as the fallback for tool calls
33    /// that omit a `thread_id`.
34    pub(super) last_active: Option<String>,
35}
36
37/// Lock-free pin counter for one session. A live [`SessionGuard`] keeps the
38/// count `> 0`, which marks the session as in-flight so LRU eviction skips it.
39/// Clones share the same counter — the registry hands a clone to each
40/// concurrent call. Keep this discipline in lockstep with the loom model.
41#[derive(Clone)]
42pub(super) struct SessionPin {
43    count: Arc<AtomicUsize>,
44}
45
46impl Default for SessionPin {
47    fn default() -> Self {
48        Self { count: Arc::new(AtomicUsize::new(0)) }
49    }
50}
51
52impl SessionPin {
53    fn acquire(&self) -> SessionGuard {
54        self.count.fetch_add(1, Ordering::SeqCst);
55        SessionGuard { count: self.count.clone() }
56    }
57
58    fn is_pinned(&self) -> bool {
59        self.count.load(Ordering::SeqCst) > 0
60    }
61}
62
63/// RAII marker that a session has an operation in flight. Bumps the session's
64/// in-flight counter on creation and releases it from synchronous `Drop`.
65pub(super) struct SessionGuard {
66    count: Arc<AtomicUsize>,
67}
68
69impl Drop for SessionGuard {
70    fn drop(&mut self) {
71        self.count.fetch_sub(1, Ordering::SeqCst);
72    }
73}
74
75/// How an empty `thread_id` is resolved by the session registry.
76#[derive(Clone, Copy, PartialEq, Eq, Debug)]
77pub enum SessionIsolation {
78    /// Local stdio transport — a single client. An empty `thread_id` falls back
79    /// to the last-active session (legacy single-client convenience).
80    Lenient,
81    /// Remote HTTP transport — multiple clients behind one shared bearer token.
82    /// The last-active fallback is disabled, so an empty `thread_id` from one
83    /// client can never resolve to another client's shell; such calls get a
84    /// dedicated anonymous slot instead.
85    ///
86    /// Residual: two clients that deliberately send the same explicit
87    /// `thread_id` still share a shell. Closing that needs per-client identities.
88    Strict,
89}
90
91impl Default for WinxService {
92    fn default() -> Self {
93        Self::new()
94    }
95}
96
97impl WinxService {
98    /// Create a new `WinxService` for local stdio transport.
99    pub fn new() -> Self {
100        Self::with_isolation(SessionIsolation::Lenient)
101    }
102
103    /// Create a service with an explicit session-isolation policy. The HTTP
104    /// transport uses [`SessionIsolation::Strict`].
105    pub fn with_isolation(isolation: SessionIsolation) -> Self {
106        Self::with_runtime(isolation, Arc::new(EmbeddedShellRuntime))
107    }
108
109    /// Create a service with an explicit shell-runtime boundary.
110    pub fn with_runtime(isolation: SessionIsolation, shell_runtime: Arc<dyn ShellRuntime>) -> Self {
111        info!(?isolation, "Creating new WinxService instance");
112        Self {
113            sessions: Arc::new(Mutex::new(SessionRegistry::default())),
114            tasks: Arc::new(Mutex::new(TaskRegistry::default())),
115            root_bootstrap: Arc::new(Mutex::new(())),
116            shell_runtime,
117            mutations: super::mutations::MutationCoordinator::default(),
118            execution_history: Arc::new(super::executions::history::WorkflowHistory::default()),
119            version: crate::build_info::display_version().to_string(),
120            isolation,
121        }
122    }
123
124    /// Resolve the session slot for a `thread_id`, creating it if absent.
125    /// Marks the slot as most-recently-used and evicts the LRU idle session when
126    /// adding a new key would exceed [`MAX_SESSIONS`].
127    pub(super) async fn session_for(&self, thread_id: &str) -> (SharedBashState, SessionGuard) {
128        let thread_id = crate::types::normalize_thread_id(thread_id);
129        let mut registry = self.sessions.lock().await;
130        let key = if thread_id.is_empty() {
131            match self.isolation {
132                SessionIsolation::Lenient => {
133                    registry.last_active.clone().unwrap_or_else(|| "default".to_string())
134                }
135                SessionIsolation::Strict => "anonymous".to_string(),
136            }
137        } else {
138            thread_id.clone()
139        };
140
141        if !registry.slots.contains_key(&key) && registry.slots.len() >= MAX_SESSIONS {
142            let victim = registry
143                .last_used
144                .iter()
145                .filter(|(candidate, _)| **candidate != key)
146                .filter(|(candidate, _)| {
147                    registry.in_flight.get(candidate.as_str()).is_none_or(|pin| !pin.is_pinned())
148                })
149                .min_by_key(|(_, last_used)| **last_used)
150                .map(|(candidate, _)| candidate.clone());
151
152            if let Some(victim) = victim {
153                // The daemon runtime owns a process outside this registry. Release
154                // it while the registry lock prevents the same thread_id from being
155                // recreated underneath the termination request.
156                if let Err(error) = self.shell_runtime.terminate_session(&victim).await {
157                    warn!(%error, "failed to terminate LRU shell session '{victim}'");
158                }
159                registry.slots.remove(&victim);
160                registry.last_used.remove(&victim);
161                registry.in_flight.remove(&victim);
162                if registry.last_active.as_deref() == Some(victim.as_str()) {
163                    registry.last_active = None;
164                }
165                warn!("Evicted LRU shell session '{victim}' (session cap {MAX_SESSIONS})");
166            } else {
167                warn!(
168                    "All {MAX_SESSIONS} sessions busy; exceeding the cap rather than evicting an in-flight session"
169                );
170            }
171        }
172
173        let slot =
174            registry.slots.entry(key.clone()).or_insert_with(|| Arc::new(Mutex::new(None))).clone();
175        let pin = registry.in_flight.entry(key.clone()).or_default().clone();
176        registry.last_used.insert(key.clone(), Instant::now());
177        if !thread_id.is_empty() {
178            registry.last_active = Some(key);
179        }
180        (slot, pin.acquire())
181    }
182
183    /// [`Self::session_for`] plus transparent rehydration: the entry point for
184    /// every tool EXCEPT `Initialize`. After an adapter restart the registry is
185    /// empty, but the per-thread snapshot survives on disk and (daemon runtime)
186    /// the guardian may still own the live PTY — so a tool call carrying a
187    /// known `thread_id` self-heals here instead of failing with
188    /// `BashStateNotInitialized` and burning a model round-trip on re-Initialize.
189    ///
190    /// `Initialize` deliberately keeps the raw [`Self::session_for`]: its
191    /// recovery semantics (downgrading `reset_shell`/`user_asked_mode_change`
192    /// to `first_call`) depend on observing the missing live state.
193    pub(super) async fn tool_session_for(
194        &self,
195        thread_id: &str,
196    ) -> (SharedBashState, SessionGuard) {
197        let (slot, guard) = self.session_for(thread_id).await;
198        self.rehydrate_slot_if_persisted(&slot, thread_id).await;
199        (slot, guard)
200    }
201
202    /// Rebuild a missing adapter-side `BashState` from its persisted snapshot
203    /// and attach-or-create the runtime session behind it. No-op when the slot
204    /// is live, the `thread_id` is empty/anonymous, or nothing was persisted.
205    /// Failure leaves the slot empty so callers fail exactly as before.
206    async fn rehydrate_slot_if_persisted(&self, slot: &SharedBashState, thread_id: &str) {
207        use crate::runtime::ShellSessionTransition;
208
209        let thread_id = crate::types::normalize_thread_id(thread_id);
210        if thread_id.is_empty() {
211            return;
212        }
213        let mut state_guard = slot.lock().await;
214        if state_guard.is_some() {
215            return;
216        }
217        let snapshot = match crate::state::persistence::load_bash_state(&thread_id) {
218            Ok(Some(snapshot)) => snapshot,
219            Ok(None) => return,
220            Err(error) => {
221                warn!(%error, thread_id, "failed to read persisted session snapshot");
222                return;
223            }
224        };
225
226        let mut state = crate::state::bash_state::BashState::new();
227        state.apply_snapshot(&snapshot);
228        // The registry key is authoritative for which session this is.
229        state.current_thread_id.clone_from(&thread_id);
230        if !state.workspace_root.exists() {
231            warn!(
232                thread_id,
233                workspace_root = %state.workspace_root.display(),
234                "not rehydrating session: persisted workspace no longer exists"
235            );
236            return;
237        }
238
239        // FirstCall is attach-or-create in both runtimes: the daemon guardian
240        // that survived the adapter restart hands back its authoritative
241        // snapshot with the live PTY untouched; a dead guardian (or the
242        // embedded runtime) gets a fresh PTY at the persisted cwd/mode.
243        match self
244            .shell_runtime
245            .configure_session(&mut state, ShellSessionTransition::FirstCall)
246            .await
247        {
248            Ok(configured) => {
249                info!(
250                    thread_id,
251                    attached_existing = configured.attached_existing,
252                    "rehydrated session from persisted state after adapter restart"
253                );
254                if !configured.attached_existing {
255                    state.recovery_note = Some(lost_shell_recovery_note(&thread_id, &state));
256                }
257                *state_guard = Some(state);
258            }
259            Err(error) => {
260                warn!(%error, thread_id, "failed to rehydrate persisted session");
261            }
262        }
263    }
264
265    /// The most recently active session slot, optionally confined to one HTTP
266    /// principal's internal thread-id prefix.
267    pub(super) async fn active_slot(
268        &self,
269        session_prefix: Option<&str>,
270    ) -> Option<SharedBashState> {
271        let registry = self.sessions.lock().await;
272        if let Some(prefix) = session_prefix {
273            return registry
274                .last_used
275                .iter()
276                .filter(|(key, _)| key.starts_with(prefix))
277                .max_by_key(|(_, last_used)| **last_used)
278                .and_then(|(key, _)| registry.slots.get(key).cloned());
279        }
280        registry.last_active.as_ref().and_then(|key| registry.slots.get(key).cloned())
281    }
282
283    /// Read the immutable project identity of an already initialized adapter
284    /// session without creating a slot or changing LRU state. Remote coherence
285    /// checks use this before any tool can touch the shell or filesystem.
286    pub(super) async fn bound_workspace(&self, thread_id: &str) -> Option<std::path::PathBuf> {
287        let thread_id = crate::types::normalize_thread_id(thread_id);
288        if thread_id.is_empty() {
289            return None;
290        }
291        let slot = {
292            let registry = self.sessions.lock().await;
293            registry.slots.get(&thread_id).cloned()
294        }?;
295        let state = slot.lock().await;
296        state.as_ref().filter(|state| state.initialized).map(|state| state.workspace_root.clone())
297    }
298
299    pub(super) async fn has_initialized_session(&self) -> bool {
300        let slots = {
301            let registry = self.sessions.lock().await;
302            registry.slots.values().cloned().collect::<Vec<_>>()
303        };
304        for slot in slots {
305            if slot.lock().await.as_ref().is_some_and(|state| state.initialized) {
306                return true;
307            }
308        }
309        false
310    }
311
312    /// Bootstrap a local single-client session from the client's first MCP Root.
313    /// The negotiated MCP protocol still exposes Roots, although `rmcp` marks this
314    /// compatibility API as deprecated in anticipation of the later SEP-2577 draft.
315    #[allow(deprecated)]
316    pub(super) async fn initialize_from_client_roots(
317        &self,
318        context: NotificationContext<RoleServer>,
319    ) {
320        if self.isolation != SessionIsolation::Lenient {
321            return;
322        }
323        let _bootstrap_guard = self.root_bootstrap.lock().await;
324        if self.has_initialized_session().await {
325            return;
326        }
327        let supports_roots =
328            context.peer.peer_info().is_some_and(|info| info.capabilities.roots.is_some());
329        if !supports_roots {
330            return;
331        }
332        let roots = match context.peer.list_roots().await {
333            Ok(result) => result.roots,
334            Err(error) => {
335                warn!(%error, "client advertised Roots but roots/list failed");
336                return;
337            }
338        };
339        let cwd = std::env::current_dir().ok();
340        let mut paths =
341            roots.iter().filter_map(|root| root_uri_to_path(&root.uri)).collect::<Vec<_>>();
342        let selected = cwd
343            .as_ref()
344            .and_then(|cwd| paths.iter().position(|path| cwd.starts_with(path)))
345            .map(|index| paths.remove(index))
346            .or_else(|| paths.into_iter().next());
347        let Some(workspace) = selected else {
348            warn!("client returned no usable local file Roots; Initialize remains required");
349            return;
350        };
351
352        let initialize = Initialize {
353            init_type: InitializeType::FirstCall,
354            any_workspace_path: workspace.to_string_lossy().into_owned(),
355            initial_files_to_read: Vec::new(),
356            task_id_to_resume: String::new(),
357            mode_name: ModeName::Wcgw,
358            thread_id: generate_thread_id(),
359            code_writer_config: None,
360        };
361        let arguments = match serde_json::to_value(initialize) {
362            Ok(arguments) => arguments,
363            Err(error) => {
364                warn!(%error, "failed to serialize Roots bootstrap request");
365                return;
366            }
367        };
368        match self.handle_initialize(Some(arguments)).await {
369            Ok(_) => info!(workspace = %workspace.display(), "initialized Winx from MCP Roots"),
370            Err(error) => warn!(%error.message, "failed to initialize Winx from MCP Roots"),
371        }
372    }
373}
374
375/// The show-once note for a session whose live shell did NOT survive the
376/// restart (a fresh PTY was created). When an interactive agent was running
377/// in the lost PTY, include how to resume its conversation.
378fn lost_shell_recovery_note(
379    thread_id: &str,
380    state: &crate::state::bash_state::BashState,
381) -> String {
382    let base = format!(
383        "Recovered session {thread_id} from its persisted snapshot after a restart: mode, \
384         permissions, and edit receipts were restored, and a fresh shell was started at {}.",
385        state.cwd.display()
386    );
387    match crate::state::agent_resume::load_agent_session(thread_id) {
388        Ok(Some(record)) => {
389            let advice = record.recovery_advice_for(thread_id, &state.workspace_root);
390            let classification = advice.classification.as_str();
391            let detail = match advice.resume_argv {
392                Some(argv) => format!(
393                    "The recorded `{}` launch explicitly selected a conversation target. \
394                     Recovery classification={classification}, source=launch_argument, \
395                     current_conversation_verified=false. To target that recorded ID, use `{}` \
396                     (recorded cwd {}). Winx has not verified backend acceptance or the \
397                     conversation currently selected after an in-TUI switch; no recovery \
398                     command was executed.",
399                    record.agent,
400                    argv.join(" "),
401                    record.cwd
402                ),
403                None => format!(
404                    "Recorded agent: `{}`. Recovery classification={classification}, \
405                     current_conversation_verified=false. No supported, scope-bound \
406                     conversation selector is available. Directory-most-recent continuation \
407                     may select a different conversation; no recovery command was executed.",
408                    record.agent
409                ),
410            };
411            format!("{base} {detail}")
412        }
413        Ok(None) => base,
414        Err(error) => {
415            warn!(%error, thread_id, "failed to read agent-session record");
416            base
417        }
418    }
419}
420
421pub(super) fn root_uri_to_path(uri: &str) -> Option<std::path::PathBuf> {
422    let encoded = uri.strip_prefix("file://")?;
423    let encoded = if let Some(path) = encoded.strip_prefix("localhost/") {
424        format!("/{path}")
425    } else if encoded.starts_with('/') {
426        encoded.to_string()
427    } else {
428        // Refuse non-local file authorities (file://host/path).
429        return None;
430    };
431    let decoded = percent_encoding::percent_decode_str(&encoded).decode_utf8().ok()?;
432    // `file:///C:/dir` carries the drive after the authority slash on Windows.
433    let decoded: &str = if cfg!(windows) {
434        decoded.strip_prefix('/').filter(|rest| is_drive_prefixed(rest)).unwrap_or(&decoded)
435    } else {
436        &decoded
437    };
438    let path = std::path::PathBuf::from(decoded);
439    path.is_absolute().then_some(path)
440}
441
442fn is_drive_prefixed(path: &str) -> bool {
443    let mut chars = path.chars();
444    matches!((chars.next(), chars.next()), (Some(drive), Some(':')) if drive.is_ascii_alphabetic())
445}
446
447#[cfg(test)]
448#[allow(clippy::expect_used)]
449mod rehydration_tests {
450    use std::sync::Arc;
451
452    use super::SessionIsolation;
453    use crate::errors::WinxError;
454    use crate::runtime::{
455        ShellRuntime, ShellRuntimeConfigureFuture, ShellRuntimeFuture, ShellRuntimeUnitFuture,
456        ShellSessionConfiguration, ShellSessionTransition,
457    };
458    use crate::server::WinxService;
459    use crate::state::agent_resume::{save_agent_session, AgentSessionRecord};
460    use crate::state::bash_state::BashState;
461    use crate::state::persistence::{delete_bash_state, save_bash_state};
462
463    /// Runtime double: attach-or-create succeeds without a real PTY and
464    /// reports whether the "live" session survived.
465    struct StubRuntime {
466        attached_existing: bool,
467    }
468
469    impl ShellRuntime for StubRuntime {
470        fn configure_session<'a>(
471            &'a self,
472            _bash_state: &'a mut BashState,
473            _transition: ShellSessionTransition,
474        ) -> ShellRuntimeConfigureFuture<'a> {
475            let attached_existing = self.attached_existing;
476            Box::pin(async move {
477                Ok(ShellSessionConfiguration { attach_hint: None, attached_existing })
478            })
479        }
480
481        fn run_action<'a>(
482            &'a self,
483            _bash_state: &'a Arc<tokio::sync::Mutex<Option<BashState>>>,
484            _command: crate::types::BashCommand,
485        ) -> ShellRuntimeFuture<'a> {
486            Box::pin(async { Err(WinxError::CommandExecutionError("stub".to_string())) })
487        }
488
489        fn interrupt<'a>(
490            &'a self,
491            _bash_state: &'a Arc<tokio::sync::Mutex<Option<BashState>>>,
492        ) -> ShellRuntimeUnitFuture<'a> {
493            Box::pin(async { Ok(()) })
494        }
495
496        fn terminate_session<'a>(&'a self, _thread_id: &'a str) -> ShellRuntimeUnitFuture<'a> {
497            Box::pin(async { Ok(()) })
498        }
499    }
500
501    fn service(attached_existing: bool) -> WinxService {
502        WinxService::with_runtime(
503            SessionIsolation::Strict,
504            Arc::new(StubRuntime { attached_existing }),
505        )
506    }
507
508    fn unique_thread_id(tag: &str) -> String {
509        let nanos = std::time::SystemTime::now()
510            .duration_since(std::time::UNIX_EPOCH)
511            .expect("system time after epoch")
512            .as_nanos();
513        // Alphanumeric + underscore only, so `normalize_thread_id` keeps the
514        // id verbatim and the on-disk snapshot file matches.
515        format!("winxtest_rehydrate_{tag}_{}_{nanos}", std::process::id())
516    }
517
518    fn persist_snapshot(thread_id: &str, workspace: &std::path::Path) {
519        let mut state = BashState::new();
520        state.current_thread_id = thread_id.to_string();
521        state.workspace_root = workspace.to_path_buf();
522        state.cwd = workspace.to_path_buf();
523        state.initialized = true;
524        save_bash_state(thread_id, &state.snapshot()).expect("persist snapshot");
525    }
526
527    #[tokio::test]
528    async fn tool_call_rehydrates_a_persisted_session_transparently() {
529        let workspace = tempfile::tempdir().expect("workspace");
530        let thread_id = unique_thread_id("attach");
531        persist_snapshot(&thread_id, workspace.path());
532
533        // Fresh service = adapter restart: empty registry, snapshot on disk.
534        let (slot, _guard) = service(true).tool_session_for(&thread_id).await;
535        {
536            let state = slot.lock().await;
537            let state = state.as_ref().expect("session should rehydrate from disk");
538            assert!(state.initialized);
539            assert_eq!(state.current_thread_id, thread_id);
540            assert_eq!(state.workspace_root, workspace.path());
541            // The live session survived (guardian attach) — nothing to report.
542            assert!(state.recovery_note.is_none());
543        }
544        delete_bash_state(&thread_id).ok();
545    }
546
547    #[tokio::test]
548    async fn lost_shell_rehydration_surfaces_the_agent_resume_hint() {
549        let workspace = tempfile::tempdir().expect("workspace");
550        let thread_id = unique_thread_id("resume");
551        persist_snapshot(&thread_id, workspace.path());
552        save_agent_session(
553            &thread_id,
554            &AgentSessionRecord {
555                agent: "claude".to_string(),
556                command: "claude".to_string(),
557                cwd: workspace.path().to_string_lossy().into_owned(),
558                launched_at_unix_ms: 1,
559                workspace_root: None,
560                scoped_thread_id: None,
561                execution_token: None,
562                conversation_selector: None,
563            },
564        )
565        .expect("persist agent record");
566
567        // attached_existing=false = the PTY did not survive (reboot / dead
568        // guardian): the note must carry the resume command.
569        let (slot, _guard) = service(false).tool_session_for(&thread_id).await;
570        {
571            let state = slot.lock().await;
572            let note = state
573                .as_ref()
574                .expect("session should rehydrate")
575                .recovery_note
576                .clone()
577                .expect("lost shell must set a recovery note");
578            assert!(note.contains("best_effort"), "missing recovery classification: {note}");
579            assert!(!note.contains("claude --continue"), "unbound hint selected latest: {note}");
580            assert!(!note.contains("resume its conversation"), "unverified identity claim: {note}");
581        }
582        delete_bash_state(&thread_id).ok();
583        crate::state::agent_resume::clear_agent_session(&thread_id).ok();
584    }
585
586    #[tokio::test]
587    async fn without_a_persisted_snapshot_the_slot_stays_empty() {
588        let thread_id = unique_thread_id("missing");
589        let (slot, _guard) = service(true).tool_session_for(&thread_id).await;
590        assert!(slot.lock().await.is_none(), "no snapshot on disk must not fabricate state");
591    }
592
593    #[tokio::test]
594    async fn empty_thread_id_never_rehydrates() {
595        let (slot, _guard) = service(true).tool_session_for("").await;
596        assert!(slot.lock().await.is_none());
597    }
598}