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#[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}