Skip to main content

rigspark_runtime/
sessions.rs

1use crate::memory::MemoryError;
2use serde::{Deserialize, Serialize};
3use std::{
4    fs,
5    path::{Path, PathBuf},
6    time::Duration,
7};
8#[derive(Debug, thiserror::Error)]
9pub enum SessionError {
10    #[error("invalid session data")]
11    Invalid,
12    #[error("session was modified by another writer")]
13    Conflict,
14    #[error("session storage failed")]
15    Storage,
16}
17impl From<MemoryError> for SessionError {
18    fn from(_: MemoryError) -> Self {
19        Self::Storage
20    }
21}
22#[derive(Debug, Clone, Serialize, Deserialize)]
23#[serde(rename_all = "camelCase")]
24pub struct Attachment {
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub kind: Option<String>,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub label: Option<String>,
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub path: Option<String>,
31    pub hash: String,
32    pub size: u64,
33    pub truncated: bool,
34    pub included: bool,
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub range: Option<crate::workspace::LineRange>,
37}
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct StoredMessage {
40    pub role: String,
41    pub content: String,
42    pub at: String,
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub attachments: Option<Vec<Attachment>>,
45}
46#[derive(Debug, Clone, Serialize, Deserialize)]
47#[serde(rename_all = "camelCase")]
48pub struct SessionDoc {
49    pub schema_version: u8,
50    pub id: String,
51    pub title: String,
52    pub created_at: String,
53    pub updated_at: String,
54    pub revision: u64,
55    pub archived: bool,
56    pub messages: Vec<StoredMessage>,
57}
58#[derive(Debug, Clone, Serialize)]
59#[serde(rename_all = "camelCase")]
60pub struct SessionSummary {
61    pub id: String,
62    pub title: String,
63    pub created_at: String,
64    pub updated_at: String,
65    pub revision: u64,
66    pub archived: bool,
67    pub message_count: usize,
68}
69fn chars(text: &str) -> usize {
70    text.encode_utf16().count()
71}
72pub(crate) fn cap(text: &str, maximum: usize) -> String {
73    let mut count = 0;
74    text.chars()
75        .take_while(|character| {
76            count += character.len_utf16();
77            count <= maximum
78        })
79        .collect()
80}
81pub fn gui_text(text: &str) -> String {
82    GuiTextStream::default().push(text)
83}
84#[derive(Default, Clone, Copy, PartialEq, Eq)]
85enum Escape {
86    #[default]
87    None,
88    Started,
89    Csi,
90    Command {
91        osc: bool,
92        terminating: bool,
93    },
94}
95/// Incremental form of [`gui_text`] that keeps escape and CRLF state across chunks.
96#[derive(Default)]
97pub struct GuiTextStream {
98    escape: Escape,
99    after_cr: bool,
100}
101impl GuiTextStream {
102    pub fn push(&mut self, text: &str) -> String {
103        let mut output = String::with_capacity(text.len());
104        for character in text.chars() {
105            self.feed(character, &mut output);
106        }
107        output
108    }
109    fn feed(&mut self, character: char, output: &mut String) {
110        let after_cr = std::mem::take(&mut self.after_cr);
111        match self.escape {
112            Escape::Started => {
113                self.escape = match character {
114                    '[' => Escape::Csi,
115                    ']' => Escape::Command {
116                        osc: true,
117                        terminating: false,
118                    },
119                    'P' | 'X' | '^' | '_' => Escape::Command {
120                        osc: false,
121                        terminating: false,
122                    },
123                    '@'..='Z' | '\\'..='_' => Escape::None,
124                    _ => {
125                        self.escape = Escape::None;
126                        return self.feed(character, output);
127                    }
128                };
129                return;
130            }
131            Escape::Csi => {
132                self.escape = match character {
133                    ' '..='?' => Escape::Csi,
134                    '@'..='~' => Escape::None,
135                    _ => {
136                        self.escape = Escape::None;
137                        return self.feed(character, output);
138                    }
139                };
140                return;
141            }
142            Escape::Command { osc, terminating } => {
143                let ended = character == '\u{9c}'
144                    || (osc && character == '\u{7}')
145                    || (terminating && character == '\\');
146                self.escape = if ended {
147                    Escape::None
148                } else {
149                    Escape::Command {
150                        osc,
151                        terminating: character == '\u{1b}',
152                    }
153                };
154                return;
155            }
156            Escape::None => {}
157        }
158        match character {
159            '\n' if after_cr => {}
160            '\r' => {
161                output.push('\n');
162                self.after_cr = true;
163            }
164            '\n' | '\t' => output.push(character),
165            '\u{1b}' => self.escape = Escape::Started,
166            '\u{9b}' => self.escape = Escape::Csi,
167            '\u{9d}' => {
168                self.escape = Escape::Command {
169                    osc: true,
170                    terminating: false,
171                }
172            }
173            '\u{90}' | '\u{98}' | '\u{9e}' | '\u{9f}' => {
174                self.escape = Escape::Command {
175                    osc: false,
176                    terminating: false,
177                }
178            }
179            _ if character.is_control() || invisible(character) => {}
180            _ => output.push(character),
181        }
182    }
183}
184fn invisible(character: char) -> bool {
185    matches!(
186        character,
187        '\u{ad}'
188            | '\u{61c}'
189            | '\u{200b}'..='\u{200f}'
190            | '\u{2060}'
191            | '\u{202a}'..='\u{202e}'
192            | '\u{2066}'..='\u{2069}'
193            | '\u{2028}'
194            | '\u{2029}'
195            | '\u{feff}'
196    )
197}
198fn title(text: &str) -> String {
199    cap(
200        &rigspark_core::reports::strip_control(text)
201            .split_whitespace()
202            .collect::<Vec<_>>()
203            .join(" "),
204        200,
205    )
206}
207fn timestamp(value: &str) -> bool {
208    !value.is_empty() && value.len() <= 40
209}
210impl SessionDoc {
211    pub fn validate(&self) -> Result<(), SessionError> {
212        if self.schema_version != 1
213            || uuid::Uuid::parse_str(&self.id).is_err()
214            || self.id.len() != 36
215            || self.id != self.id.to_lowercase()
216            || chars(&self.title) > 200
217            || !timestamp(&self.created_at)
218            || !timestamp(&self.updated_at)
219            || self.revision > 9007199254740991
220            || self.messages.len() > 2000
221        {
222            return Err(SessionError::Invalid);
223        }
224        for message in &self.messages {
225            if !["user", "assistant", "system"].contains(&message.role.as_str())
226                || chars(&message.content) > 32768
227                || !timestamp(&message.at)
228            {
229                return Err(SessionError::Invalid);
230            }
231            if let Some(attachments) = &message.attachments {
232                if attachments.len() > 20 {
233                    return Err(SessionError::Invalid);
234                }
235                for attachment in attachments {
236                    if attachment.kind.as_ref().is_some_and(|kind| {
237                        !["file", "terminal", "diagnostics", "git"].contains(&kind.as_str())
238                    }) || attachment.hash.is_empty()
239                        || chars(&attachment.hash) > 128
240                        || attachment.size > 9007199254740991
241                        || attachment
242                            .label
243                            .as_ref()
244                            .is_some_and(|value| value.is_empty() || chars(value) > 200)
245                        || attachment
246                            .path
247                            .as_ref()
248                            .is_some_and(|value| value.is_empty() || chars(value) > 1024)
249                        || attachment
250                            .range
251                            .as_ref()
252                            .is_some_and(|range| range.start_line == 0 || range.end_line == 0)
253                    {
254                        return Err(SessionError::Invalid);
255                    }
256                }
257            }
258        }
259        Ok(())
260    }
261    pub fn summary(&self) -> SessionSummary {
262        SessionSummary {
263            id: self.id.clone(),
264            title: self.title.clone(),
265            created_at: self.created_at.clone(),
266            updated_at: self.updated_at.clone(),
267            revision: self.revision,
268            archived: self.archived,
269            message_count: self.messages.len(),
270        }
271    }
272}
273pub struct SessionRepository {
274    home: PathBuf,
275    pub runs: crate::runs::RunCoordinator,
276}
277impl SessionRepository {
278    pub fn new(home: &Path) -> Self {
279        Self {
280            home: home.into(),
281            runs: crate::runs::RunCoordinator::default(),
282        }
283    }
284    fn path(&self, id: &str) -> Result<PathBuf, SessionError> {
285        self.check_home()?;
286        if uuid::Uuid::parse_str(id).is_err() || id.len() != 36 || id != id.to_lowercase() {
287            return Err(SessionError::Invalid);
288        }
289        let directory = self.home.join("gui-sessions");
290        if let Ok(metadata) = fs::symlink_metadata(&directory)
291            && (!metadata.is_dir() || metadata.file_type().is_symlink())
292        {
293            return Err(SessionError::Storage);
294        }
295        Ok(directory.join(format!("{id}.json")))
296    }
297    fn lock(&self) -> Result<crate::state::LockGuard, SessionError> {
298        crate::state::StateStore::new(
299            crate::state::Config::from_home(&self.home).map_err(|_| SessionError::Storage)?,
300        )
301        .lock(Duration::from_secs(10))
302        .map_err(|_| SessionError::Storage)
303    }
304    fn ids(&self) -> Result<Vec<String>, SessionError> {
305        self.check_home()?;
306        let directory = self.home.join("gui-sessions");
307        if !directory.try_exists().map_err(|_| SessionError::Storage)? {
308            return Ok(Vec::new());
309        }
310        if fs::symlink_metadata(&directory)
311            .map_err(|_| SessionError::Storage)?
312            .file_type()
313            .is_symlink()
314        {
315            return Err(SessionError::Storage);
316        }
317        let mut ids = Vec::new();
318        for (index, entry) in fs::read_dir(directory)
319            .map_err(|_| SessionError::Storage)?
320            .enumerate()
321        {
322            if index > 10000 {
323                return Err(SessionError::Storage);
324            }
325            let entry = entry.map_err(|_| SessionError::Storage)?;
326            let name = entry.file_name().to_string_lossy().into_owned();
327            if let Some(id) = name.strip_suffix(".json")
328                && self.path(id).is_ok()
329            {
330                ids.push(id.into());
331            }
332        }
333        Ok(ids)
334    }
335    fn check_home(&self) -> Result<(), SessionError> {
336        match fs::symlink_metadata(&self.home) {
337            Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => Ok(()),
338            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
339            _ => Err(SessionError::Storage),
340        }
341    }
342    pub fn get(&self, id: &str) -> Result<Option<SessionDoc>, SessionError> {
343        let path = self.path(id)?;
344        let read = (|| {
345            let directory = crate::secure_fs::Directory::open(&self.home)?;
346            directory.read(
347                path.strip_prefix(&self.home)
348                    .map_err(|_| std::io::Error::other("invalid session path"))?,
349                8 * 1024 * 1024,
350                true,
351            )
352        })();
353        let raw = match read {
354            Ok(raw) => String::from_utf8(raw).map_err(|_| SessionError::Invalid)?,
355            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
356            Err(_) => return Err(SessionError::Storage),
357        };
358        let doc: SessionDoc = serde_json::from_str(&raw).map_err(|_| SessionError::Invalid)?;
359        doc.validate()?;
360        if doc.id != id {
361            return Err(SessionError::Invalid);
362        }
363        Ok(Some(doc))
364    }
365    fn write(&self, doc: &SessionDoc) -> Result<(), SessionError> {
366        doc.validate()?;
367        let bytes = format!(
368            "{}\n",
369            serde_json::to_string_pretty(doc).map_err(|_| SessionError::Invalid)?
370        );
371        if bytes.len() > 8 * 1024 * 1024 {
372            return Err(SessionError::Invalid);
373        }
374        let directory =
375            crate::secure_fs::Directory::open(&self.home).map_err(|_| SessionError::Storage)?;
376        directory
377            .ensure_dir(Path::new("gui-sessions"))
378            .map_err(|_| SessionError::Storage)?;
379        let path = self.path(&doc.id)?;
380        directory
381            .write(
382                path.strip_prefix(&self.home)
383                    .map_err(|_| SessionError::Storage)?,
384                bytes.as_bytes(),
385                false,
386                false,
387            )
388            .map_err(|_| SessionError::Storage)?;
389        Ok(())
390    }
391    pub fn create(&self, name: &str, at: &str) -> Result<SessionDoc, SessionError> {
392        let guard = self.lock()?;
393        if self.ids()?.len() >= 500 {
394            return Err(SessionError::Invalid);
395        }
396        let name = title(name);
397        let doc = SessionDoc {
398            schema_version: 1,
399            id: uuid::Uuid::new_v4().to_string(),
400            title: if name.is_empty() {
401                "New chat".into()
402            } else {
403                name
404            },
405            created_at: at.into(),
406            updated_at: at.into(),
407            revision: 0,
408            archived: false,
409            messages: Vec::new(),
410        };
411        self.write(&doc)?;
412        guard.release().map_err(|_| SessionError::Storage)?;
413        Ok(doc)
414    }
415    fn mutate(
416        &self,
417        id: &str,
418        expected: Option<u64>,
419        at: &str,
420        change: impl FnOnce(&mut SessionDoc),
421    ) -> Result<SessionDoc, SessionError> {
422        let guard = self.lock()?;
423        let mut doc = self.get(id)?.ok_or(SessionError::Invalid)?;
424        if expected.is_some_and(|revision| revision != doc.revision) {
425            return Err(SessionError::Conflict);
426        }
427        change(&mut doc);
428        doc.revision = doc.revision.checked_add(1).ok_or(SessionError::Invalid)?;
429        doc.updated_at = at.into();
430        self.write(&doc)?;
431        guard.release().map_err(|_| SessionError::Storage)?;
432        Ok(doc)
433    }
434    pub fn append(
435        &self,
436        id: &str,
437        mut message: StoredMessage,
438        expected: Option<u64>,
439    ) -> Result<SessionDoc, SessionError> {
440        message.content = cap(&gui_text(&message.content), 32768);
441        if let Some(attachments) = &mut message.attachments {
442            attachments.truncate(20);
443        }
444        let at = message.at.clone();
445        self.mutate(id, expected, &at, |doc| {
446            if doc.title == "New chat"
447                && message.role == "user"
448                && !message.content.trim().is_empty()
449            {
450                doc.title = title(&cap(&message.content, 60));
451            }
452            doc.messages.push(message);
453            if doc.messages.len() > 2000 {
454                doc.messages.drain(..doc.messages.len() - 2000);
455            }
456        })
457    }
458    pub fn append_exchange(
459        &self,
460        id: &str,
461        mut user: StoredMessage,
462        mut assistant: StoredMessage,
463        expected: u64,
464    ) -> Result<SessionDoc, SessionError> {
465        if user.role != "user" || assistant.role != "assistant" {
466            return Err(SessionError::Invalid);
467        }
468        for message in [&mut user, &mut assistant] {
469            message.content = cap(&gui_text(&message.content), 32768);
470            if let Some(attachments) = &mut message.attachments {
471                attachments.truncate(20);
472            }
473        }
474        let at = assistant.at.clone();
475        self.mutate(id, Some(expected), &at, |doc| {
476            if doc.title == "New chat" && !user.content.trim().is_empty() {
477                doc.title = title(&cap(&user.content, 60));
478            }
479            doc.messages.extend([user, assistant]);
480            if doc.messages.len() > 2000 {
481                doc.messages.drain(..doc.messages.len() - 2000);
482            }
483        })
484    }
485    pub fn rename(
486        &self,
487        id: &str,
488        name: &str,
489        expected: Option<u64>,
490        at: &str,
491    ) -> Result<SessionDoc, SessionError> {
492        let name = title(name);
493        if name.is_empty() {
494            return Err(SessionError::Invalid);
495        }
496        self.mutate(id, expected, at, |doc| doc.title = name)
497    }
498    pub fn archive(
499        &self,
500        id: &str,
501        archived: bool,
502        expected: Option<u64>,
503        at: &str,
504    ) -> Result<SessionDoc, SessionError> {
505        self.mutate(id, expected, at, |doc| doc.archived = archived)
506    }
507    pub fn remove(&self, id: &str) -> Result<(), SessionError> {
508        let guard = self.lock()?;
509        let directory =
510            crate::secure_fs::Directory::open(&self.home).map_err(|_| SessionError::Storage)?;
511        match directory.remove(
512            self.path(id)?
513                .strip_prefix(&self.home)
514                .map_err(|_| SessionError::Storage)?,
515        ) {
516            Ok(()) => (),
517            Err(error) if error.kind() == std::io::ErrorKind::NotFound => (),
518            Err(_) => return Err(SessionError::Storage),
519        }
520        guard.release().map_err(|_| SessionError::Storage)
521    }
522    pub fn list(
523        &self,
524        archived: bool,
525        offset: usize,
526        limit: usize,
527    ) -> Result<(Vec<SessionSummary>, Option<String>), SessionError> {
528        let mut docs: Vec<_> = self
529            .ids()?
530            .iter()
531            .filter_map(|id| self.get(id).ok().flatten())
532            .filter(|doc| archived || !doc.archived)
533            .collect();
534        docs.sort_by(|left, right| {
535            right
536                .updated_at
537                .cmp(&left.updated_at)
538                .then(right.id.cmp(&left.id))
539        });
540        let limit = limit.clamp(1, 200);
541        let next = (offset.saturating_add(limit) < docs.len())
542            .then(|| offset.saturating_add(limit).to_string());
543        Ok((
544            docs.into_iter()
545                .skip(offset)
546                .take(limit)
547                .map(|doc| doc.summary())
548                .collect(),
549            next,
550        ))
551    }
552    pub fn messages(
553        &self,
554        id: &str,
555        offset: usize,
556        limit: usize,
557    ) -> Result<(Vec<StoredMessage>, Option<String>), SessionError> {
558        let doc = self.get(id)?.ok_or(SessionError::Invalid)?;
559        let limit = limit.clamp(1, 500);
560        let next = (offset.saturating_add(limit) < doc.messages.len())
561            .then(|| offset.saturating_add(limit).to_string());
562        Ok((
563            doc.messages.into_iter().skip(offset).take(limit).collect(),
564            next,
565        ))
566    }
567    pub fn search(
568        &self,
569        query: &str,
570        archived: bool,
571    ) -> Result<Vec<(SessionSummary, String)>, SessionError> {
572        let query = rigspark_core::reports::strip_control(query)
573            .trim()
574            .to_lowercase();
575        if query.is_empty() {
576            return Ok(Vec::new());
577        }
578        let mut matches = Vec::new();
579        for id in self.ids()? {
580            if let Ok(Some(doc)) = self.get(&id) {
581                if doc.archived && !archived {
582                    continue;
583                }
584                if doc.title.to_lowercase().contains(&query) {
585                    matches.push((doc.summary(), doc.title.clone()));
586                } else if let Some(message) = doc
587                    .messages
588                    .iter()
589                    .find(|message| message.content.to_lowercase().contains(&query))
590                {
591                    let lower = message.content.to_lowercase();
592                    let index = lower.find(&query).unwrap_or(0);
593                    let start = lower[..index].encode_utf16().count().saturating_sub(24);
594                    let snippet = String::from_utf16_lossy(
595                        &message
596                            .content
597                            .encode_utf16()
598                            .skip(start)
599                            .take(80)
600                            .collect::<Vec<_>>(),
601                    );
602                    matches.push((doc.summary(), snippet));
603                }
604            }
605        }
606        matches.sort_by(|left, right| right.0.updated_at.cmp(&left.0.updated_at));
607        matches.truncate(50);
608        Ok(matches)
609    }
610}
611
612#[cfg(test)]
613mod boundary_tests {
614    use super::*;
615
616    const AT: &str = "2026-11-08T00:00:00Z";
617
618    fn doc() -> SessionDoc {
619        SessionDoc {
620            schema_version: 1,
621            id: "0b7f2c38-6f1d-4c55-9a27-35f6c9d2a1e4".into(),
622            title: "Title".into(),
623            created_at: AT.into(),
624            updated_at: AT.into(),
625            revision: 0,
626            archived: false,
627            messages: vec![message("user", "hi")],
628        }
629    }
630    fn message(role: &str, content: &str) -> StoredMessage {
631        StoredMessage {
632            role: role.into(),
633            content: content.into(),
634            at: AT.into(),
635            attachments: None,
636        }
637    }
638    fn attachment() -> Attachment {
639        Attachment {
640            kind: Some("file".into()),
641            label: Some("label".into()),
642            path: Some("src/main.rs".into()),
643            hash: "abc".into(),
644            size: 1,
645            truncated: false,
646            included: true,
647            range: None,
648        }
649    }
650    fn valid(change: impl FnOnce(&mut SessionDoc)) -> bool {
651        let mut value = doc();
652        change(&mut value);
653        value.validate().is_ok()
654    }
655    fn with_attachment(change: impl FnOnce(&mut Attachment)) -> bool {
656        valid(|doc| {
657            let mut value = attachment();
658            change(&mut value);
659            doc.messages[0].attachments = Some(vec![value]);
660        })
661    }
662
663    #[test]
664    fn lengths_are_counted_in_utf16_units() {
665        assert_eq!(chars(""), 0);
666        assert_eq!(chars("ab"), 2);
667        assert_eq!(chars("😀"), 2);
668    }
669
670    #[test]
671    fn session_documents_are_bounded_field_by_field() {
672        assert!(valid(|_| {}));
673        assert!(!valid(|d| d.schema_version = 2));
674        assert!(!valid(|d| d.id = "not-a-uuid".into()));
675        assert!(!valid(|d| d.id = d.id.replace('-', "")));
676        assert!(!valid(|d| d.id = d.id.to_uppercase()));
677        assert!(valid(|d| d.title = "t".repeat(200)));
678        assert!(!valid(|d| d.title = "t".repeat(201)));
679        for bad in ["", &"9".repeat(41)] {
680            assert!(!valid(|d| d.created_at = bad.into()), "{bad:?}");
681            assert!(!valid(|d| d.updated_at = bad.into()), "{bad:?}");
682            assert!(!valid(|d| d.messages[0].at = bad.into()), "{bad:?}");
683        }
684        assert!(valid(|d| d.created_at = "9".repeat(40)));
685        assert!(valid(|d| d.revision = 9007199254740991));
686        assert!(!valid(|d| d.revision = 9007199254740992));
687        assert!(valid(|d| d.messages = vec![message("user", "x"); 2000]));
688        assert!(!valid(|d| d.messages = vec![message("user", "x"); 2001]));
689        for role in ["user", "assistant", "system"] {
690            assert!(valid(|d| d.messages[0].role = role.into()), "{role}");
691        }
692        assert!(!valid(|d| d.messages[0].role = "tool".into()));
693        assert!(valid(|d| d.messages[0].content = "c".repeat(32768)));
694        assert!(!valid(|d| d.messages[0].content = "c".repeat(32769)));
695    }
696
697    #[test]
698    fn attachments_are_bounded_field_by_field() {
699        assert!(with_attachment(|_| {}));
700        for kind in ["file", "terminal", "diagnostics", "git"] {
701            assert!(with_attachment(|a| a.kind = Some(kind.into())), "{kind}");
702        }
703        assert!(with_attachment(|a| a.kind = None));
704        assert!(!with_attachment(|a| a.kind = Some("url".into())));
705        assert!(!with_attachment(|a| a.hash = String::new()));
706        assert!(with_attachment(|a| a.hash = "h".repeat(128)));
707        assert!(!with_attachment(|a| a.hash = "h".repeat(129)));
708        assert!(with_attachment(|a| a.size = 9007199254740991));
709        assert!(!with_attachment(|a| a.size = 9007199254740992));
710        assert!(with_attachment(|a| a.label = Some("l".repeat(200))));
711        assert!(!with_attachment(|a| a.label = Some("l".repeat(201))));
712        assert!(!with_attachment(|a| a.label = Some(String::new())));
713        assert!(with_attachment(|a| a.path = Some("p".repeat(1024))));
714        assert!(!with_attachment(|a| a.path = Some("p".repeat(1025))));
715        assert!(!with_attachment(|a| a.path = Some(String::new())));
716        let range = |start, end| crate::workspace::LineRange {
717            start_line: start,
718            end_line: end,
719        };
720        assert!(with_attachment(|a| a.range = Some(range(1, 1))));
721        assert!(!with_attachment(|a| a.range = Some(range(0, 1))));
722        assert!(!with_attachment(|a| a.range = Some(range(1, 0))));
723        assert!(valid(
724            |d| d.messages[0].attachments = Some(vec![attachment(); 20])
725        ));
726        assert!(!valid(
727            |d| d.messages[0].attachments = Some(vec![attachment(); 21])
728        ));
729    }
730
731    #[test]
732    fn gui_text_drops_every_escape_form_and_keeps_the_text_after() {
733        // Two-character escapes end at their final byte.
734        assert_eq!(gui_text("a\u{1b}Mb"), "ab");
735        assert_eq!(gui_text("a\u{1b}\\b"), "ab");
736        // An escape followed by an ordinary character keeps that character.
737        assert_eq!(gui_text("a\u{1b}1b"), "a1b");
738        // C1 CSI, OSC and string introducers.
739        assert_eq!(gui_text("a\u{9b}31mb"), "ab");
740        assert_eq!(gui_text("a\u{9d}title\u{7}b"), "ab");
741        for introducer in ['\u{90}', '\u{98}', '\u{9e}', '\u{9f}'] {
742            assert_eq!(
743                gui_text(&format!("a{introducer}payload\u{9c}b")),
744                "ab",
745                "{introducer:?}"
746            );
747        }
748        // BEL ends only OSC strings; other strings need ST.
749        assert_eq!(gui_text("a\u{1b}Ppay\u{7}load\u{1b}\\b"), "ab");
750        assert_eq!(gui_text("a\u{1b}]t\u{7}b"), "ab");
751        // A backslash ends a string only right after ESC.
752        assert_eq!(gui_text("a\u{1b}Ppa\\yload\u{1b}\\b"), "ab");
753    }
754
755    fn repository() -> (tempfile::TempDir, SessionRepository) {
756        let home = tempfile::tempdir().unwrap();
757        let repository = SessionRepository::new(home.path());
758        (home, repository)
759    }
760
761    #[test]
762    fn session_ids_must_be_lowercase_hyphenated_uuids() {
763        let (_home, sessions) = repository();
764        let id = doc().id;
765        assert!(sessions.get(&id).unwrap().is_none());
766        for other in [
767            id.replace('-', ""),
768            format!("{{{id}}}"),
769            format!("urn:uuid:{id}"),
770            id.to_uppercase(),
771        ] {
772            assert!(
773                matches!(sessions.get(&other), Err(SessionError::Invalid)),
774                "{other}"
775            );
776        }
777    }
778
779    #[test]
780    fn the_home_must_be_a_real_directory_or_not_exist_yet() {
781        let parent = tempfile::tempdir().unwrap();
782        let missing = SessionRepository::new(&parent.path().join("missing"));
783        assert!(missing.list(false, 0, 10).unwrap().0.is_empty());
784        let file = parent.path().join("file");
785        std::fs::write(&file, "x").unwrap();
786        assert!(matches!(
787            SessionRepository::new(&file).list(false, 0, 10),
788            Err(SessionError::Storage)
789        ));
790        #[cfg(unix)]
791        {
792            let real = parent.path().join("real");
793            std::fs::create_dir(&real).unwrap();
794            let link = parent.path().join("link");
795            std::os::unix::fs::symlink(&real, &link).unwrap();
796            assert!(matches!(
797                SessionRepository::new(&link).list(false, 0, 10),
798                Err(SessionError::Storage)
799            ));
800        }
801        // A session directory that is a file is refused too.
802        let (home, sessions) = repository();
803        std::fs::write(home.path().join("gui-sessions"), "x").unwrap();
804        assert!(sessions.get(&doc().id).is_err());
805    }
806
807    #[test]
808    fn documents_up_to_eight_mib_round_trip_and_larger_ones_are_refused() {
809        let (_home, sessions) = repository();
810        let created = sessions.create("big", AT).unwrap();
811        // 2000 messages of 1500 characters: about 3 MiB on disk.
812        let mut doc = sessions.get(&created.id).unwrap().unwrap();
813        doc.messages = vec![message("user", &"m".repeat(1500)); 2000];
814        sessions.write(&doc).unwrap();
815        assert_eq!(
816            sessions.get(&created.id).unwrap().unwrap().messages.len(),
817            2000
818        );
819        // 2000 messages of 4500 characters pass validation but exceed 8 MiB serialized.
820        doc.messages = vec![message("user", &"m".repeat(4500)); 2000];
821        assert!(doc.validate().is_ok());
822        assert!(matches!(sessions.write(&doc), Err(SessionError::Invalid)));
823        // Exactly 8 MiB on disk, newline included, is still written.
824        let size = |doc: &SessionDoc| serde_json::to_string_pretty(doc).unwrap().len() + 1;
825        doc.messages = vec![message("user", ""); 2000];
826        let overhead = size(&doc);
827        let room = 8 * 1024 * 1024 - overhead;
828        for (index, item) in doc.messages.iter_mut().enumerate() {
829            item.content = "m".repeat(room / 2000 + usize::from(index < room % 2000));
830        }
831        assert_eq!(size(&doc), 8 * 1024 * 1024);
832        sessions.write(&doc).unwrap();
833    }
834
835    #[test]
836    fn appends_keep_the_newest_2000_messages() {
837        let (_home, sessions) = repository();
838        let created = sessions.create("", AT).unwrap();
839        let mut doc = sessions.get(&created.id).unwrap().unwrap();
840        doc.messages = (0..1999).map(|n| message("user", &n.to_string())).collect();
841        sessions.write(&doc).unwrap();
842        let doc = sessions
843            .append(&created.id, message("assistant", "1999"), None)
844            .unwrap();
845        assert_eq!(doc.messages.len(), 2000);
846        let doc = sessions
847            .append(&created.id, message("assistant", "2000"), None)
848            .unwrap();
849        assert_eq!(doc.messages.len(), 2000);
850        assert_eq!(doc.messages[0].content, "1");
851        assert_eq!(doc.messages[1999].content, "2000");
852        let doc = sessions
853            .append_exchange(
854                &created.id,
855                message("user", "q"),
856                message("assistant", "a"),
857                doc.revision,
858            )
859            .unwrap();
860        assert_eq!(doc.messages.len(), 2000);
861        assert_eq!(doc.messages[0].content, "3");
862        assert_eq!(doc.messages[1999].content, "a");
863    }
864
865    #[test]
866    fn exchanges_are_a_user_then_an_assistant_message_and_title_a_new_chat() {
867        let (_home, sessions) = repository();
868        let created = sessions.create("", AT).unwrap();
869        for (user, assistant) in [
870            ("assistant", "assistant"),
871            ("user", "user"),
872            ("system", "assistant"),
873        ] {
874            assert!(
875                sessions
876                    .append_exchange(&created.id, message(user, "q"), message(assistant, "a"), 0)
877                    .is_err(),
878                "{user} then {assistant}"
879            );
880        }
881        let titled = sessions
882            .append_exchange(
883                &created.id,
884                message("user", "What is a KV cache?"),
885                message("assistant", "a"),
886                0,
887            )
888            .unwrap();
889        assert_eq!(titled.title, "What is a KV cache?");
890        // A titled chat keeps its title; a blank question leaves "New chat".
891        let kept = sessions
892            .append_exchange(
893                &created.id,
894                message("user", "another"),
895                message("assistant", "a"),
896                titled.revision,
897            )
898            .unwrap();
899        assert_eq!(kept.title, "What is a KV cache?");
900        let blank = sessions.create("", AT).unwrap();
901        let untitled = sessions
902            .append_exchange(
903                &blank.id,
904                message("user", "   "),
905                message("assistant", "a"),
906                0,
907            )
908            .unwrap();
909        assert_eq!(untitled.title, "New chat");
910    }
911
912    #[test]
913    fn removing_reports_storage_errors_other_than_a_missing_file() {
914        let (home, sessions) = repository();
915        let id = doc().id;
916        sessions.remove(&id).unwrap();
917        std::fs::create_dir_all(home.path().join("gui-sessions").join(format!("{id}.json")))
918            .unwrap();
919        assert!(matches!(sessions.remove(&id), Err(SessionError::Storage)));
920    }
921
922    #[test]
923    fn session_listing_stops_past_ten_thousand_entries() {
924        let (home, sessions) = repository();
925        let directory = home.path().join("gui-sessions");
926        std::fs::create_dir(&directory).unwrap();
927        for index in 0..10_001 {
928            std::fs::write(directory.join(format!("{index}.txt")), "").unwrap();
929        }
930        assert!(sessions.list(false, 0, 10).unwrap().0.is_empty());
931        std::fs::write(directory.join("one-more.txt"), "").unwrap();
932        assert!(matches!(
933            sessions.list(false, 0, 10),
934            Err(SessionError::Storage)
935        ));
936    }
937
938    #[test]
939    fn pages_end_exactly_at_the_last_item() {
940        let (_home, sessions) = repository();
941        let first = sessions.create("one", AT).unwrap();
942        sessions.create("two", AT).unwrap();
943        assert_eq!(sessions.list(false, 0, 2).unwrap().1, None);
944        assert_eq!(sessions.list(false, 0, 1).unwrap().1.as_deref(), Some("1"));
945        let doc = sessions
946            .append(&first.id, message("user", "a"), None)
947            .unwrap();
948        sessions
949            .append(&first.id, message("user", "b"), Some(doc.revision))
950            .unwrap();
951        assert_eq!(sessions.messages(&first.id, 0, 2).unwrap().1, None);
952        assert_eq!(
953            sessions.messages(&first.id, 0, 1).unwrap().1.as_deref(),
954            Some("1")
955        );
956    }
957
958    #[test]
959    fn search_skips_archived_chats_unless_asked() {
960        let (_home, sessions) = repository();
961        let created = sessions.create("needle chat", AT).unwrap();
962        assert_eq!(sessions.search("needle", false).unwrap().len(), 1);
963        sessions.archive(&created.id, true, None, AT).unwrap();
964        assert!(sessions.search("needle", false).unwrap().is_empty());
965        assert_eq!(sessions.search("needle", true).unwrap().len(), 1);
966    }
967}