Skip to main content

lean_ctx_cloud/
queens.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Queen sessions: the sessions LeanCTX | Cloud Desktop started as a Queen,
3//! registered by the app over the 0600 local socket (an app-only call).
4//!
5//! A bus role is self-declared, so it never grants anything. A session may
6//! set a task's priority and labels through `ctx_tasks` only when the
7//! launching app's session id of its MCP server (`LEAN_CTX_SESSION_ID`) is
8//! registered here. The app removes the id when the session ends.
9//!
10//! Stored 0600 in the Instance's data dir; at most [`MAX_QUEENS`] ids.
11
12use std::path::{Path, PathBuf};
13
14use serde::{Deserialize, Serialize};
15
16use crate::CloudError;
17use crate::state::write_private;
18
19pub const QUEENS_FILE: &str = "queen-sessions.json";
20pub const MAX_QUEENS: usize = 64;
21const MAX_NAME_CHARS: usize = 80;
22
23/// One registered Queen session.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct QueenSession {
26    pub session_id: String,
27    pub name: Option<String>,
28    /// When it was first registered (RFC 3339, UTC).
29    pub since: String,
30}
31
32#[derive(Debug, Default, Serialize, Deserialize)]
33struct QueensFile {
34    sessions: Vec<QueenSession>,
35}
36
37/// 8-128 of `[A-Za-z0-9._:-]`.
38pub fn validate_session_id(id: &str) -> Result<(), CloudError> {
39    let ok = (8..=128).contains(&id.len())
40        && id
41            .bytes()
42            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':' | b'-'));
43    if ok {
44        Ok(())
45    } else {
46        Err(CloudError::Config(
47            "session_id is 8-128 of [A-Za-z0-9._:-]".into(),
48        ))
49    }
50}
51
52fn clean_name(name: Option<&str>) -> Result<Option<String>, CloudError> {
53    let Some(name) = name.map(str::trim).filter(|n| !n.is_empty()) else {
54        return Ok(None);
55    };
56    if name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) {
57        return Err(CloudError::Config(
58            "name is at most 80 characters, no control characters".into(),
59        ));
60    }
61    Ok(Some(name.to_owned()))
62}
63
64fn load(dir: &Path) -> QueensFile {
65    std::fs::read(dir.join(QUEENS_FILE))
66        .ok()
67        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
68        .unwrap_or_default()
69}
70
71fn save(dir: &Path, file: &QueensFile) -> Result<(), CloudError> {
72    let bytes = serde_json::to_vec_pretty(file).map_err(|e| CloudError::Local(e.to_string()))?;
73    write_private(dir, QUEENS_FILE, &bytes)
74}
75
76/// The registered sessions in `dir`, sorted by id.
77#[must_use]
78pub fn list_in(dir: &Path) -> Vec<QueenSession> {
79    let mut sessions = load(dir).sessions;
80    sessions.sort_by(|a, b| a.session_id.cmp(&b.session_id));
81    sessions
82}
83
84/// Register `session_id` (again: it keeps its `since`, the name is updated).
85pub fn register_in(
86    dir: &Path,
87    session_id: &str,
88    name: Option<&str>,
89    now: &str,
90) -> Result<Vec<QueenSession>, CloudError> {
91    validate_session_id(session_id)?;
92    let name = clean_name(name)?;
93    let mut file = load(dir);
94    if let Some(known) = file
95        .sessions
96        .iter_mut()
97        .find(|s| s.session_id == session_id)
98    {
99        known.name = name;
100    } else {
101        if file.sessions.len() >= MAX_QUEENS {
102            return Err(CloudError::Refused(format!(
103                "at most {MAX_QUEENS} coordinator sessions are registered; remove ended ones first"
104            )));
105        }
106        file.sessions.push(QueenSession {
107            session_id: session_id.to_owned(),
108            name,
109            since: now.to_owned(),
110        });
111    }
112    save(dir, &file)?;
113    Ok(list_in(dir))
114}
115
116/// Remove `session_id` (no error when it is not registered).
117pub fn remove_in(dir: &Path, session_id: &str) -> Result<Vec<QueenSession>, CloudError> {
118    validate_session_id(session_id)?;
119    let mut file = load(dir);
120    let before = file.sessions.len();
121    file.sessions.retain(|s| s.session_id != session_id);
122    if file.sessions.len() != before {
123        save(dir, &file)?;
124    }
125    Ok(list_in(dir))
126}
127
128/// Whether `session_id` is a registered Queen session in `dir`.
129#[must_use]
130pub fn is_queen_in(dir: &Path, session_id: &str) -> bool {
131    validate_session_id(session_id).is_ok()
132        && load(dir)
133            .sessions
134            .iter()
135            .any(|s| s.session_id == session_id)
136}
137
138/// The Instance's data dir, where the registrations live.
139pub fn data_dir() -> Result<PathBuf, CloudError> {
140    lean_ctx::core::data_dir::lean_ctx_data_dir().map_err(CloudError::Local)
141}
142
143/// Whether this process runs for a registered Queen session: the launching
144/// app's session id (`LEAN_CTX_SESSION_ID`) of this process is registered.
145#[must_use]
146pub fn this_session_is_queen() -> bool {
147    let Some(id) = lean_ctx::core::activity::session_id_from_env() else {
148        return false;
149    };
150    data_dir().is_ok_and(|dir| is_queen_in(&dir, &id))
151}
152
153/// The refusal for a session that may read but not set priority.
154pub const NOT_A_QUEEN: &str = "priority and labels are set by a person or a coordinator session \
155     the app registered; this session can read them";
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    const NOW: &str = "2026-11-05T12:00:00Z";
162
163    #[test]
164    fn a_registered_session_is_a_queen_until_removed() {
165        let dir = tempfile::tempdir().expect("temp dir");
166        let id = "sess-0f3a9c2e";
167        assert!(!is_queen_in(dir.path(), id));
168        let listed = register_in(dir.path(), id, Some("LeanCTX core"), NOW).expect("ok");
169        assert_eq!(listed.len(), 1);
170        assert!(is_queen_in(dir.path(), id));
171        // Again: idempotent, keeps since, updates the name.
172        let again = register_in(dir.path(), id, None, "2026-11-05T13:00:00Z").expect("ok");
173        assert_eq!(again[0].since, NOW);
174        assert_eq!(again[0].name, None);
175        assert!(remove_in(dir.path(), id).expect("ok").is_empty());
176        assert!(!is_queen_in(dir.path(), id));
177        assert!(remove_in(dir.path(), id).expect("ok").is_empty());
178    }
179
180    #[test]
181    fn a_bad_id_or_name_is_refused_and_never_matches() {
182        let dir = tempfile::tempdir().expect("temp dir");
183        for bad in ["short", "has space here", "semi;colon-id", &"x".repeat(129)] {
184            assert!(register_in(dir.path(), bad, None, NOW).is_err(), "{bad}");
185            assert!(!is_queen_in(dir.path(), bad));
186        }
187        assert!(register_in(dir.path(), "sess-12345678", Some("a\u{1b}[31m"), NOW).is_err());
188        assert!(register_in(dir.path(), "sess-12345678", Some(&"n".repeat(81)), NOW).is_err());
189        assert!(list_in(dir.path()).is_empty());
190    }
191
192    #[test]
193    fn registrations_are_bounded() {
194        let dir = tempfile::tempdir().expect("temp dir");
195        for n in 0..MAX_QUEENS {
196            register_in(dir.path(), &format!("sess-{n:08}"), None, NOW).expect("ok");
197        }
198        assert!(register_in(dir.path(), "sess-overflow", None, NOW).is_err());
199        assert!(register_in(dir.path(), "sess-00000003", Some("again"), NOW).is_ok());
200    }
201
202    #[cfg(unix)]
203    #[test]
204    fn the_file_is_private() {
205        use std::os::unix::fs::PermissionsExt as _;
206        let dir = tempfile::tempdir().expect("temp dir");
207        register_in(dir.path(), "sess-12345678", None, NOW).expect("ok");
208        let mode = std::fs::metadata(dir.path().join(QUEENS_FILE))
209            .expect("ok")
210            .permissions()
211            .mode();
212        assert_eq!(mode & 0o777, 0o600);
213    }
214}