capri-agent: add journal module
This commit is contained in:
1 file changed
+149
@@ -0,0 +1,149 @@
|
||||
//! Display transcript (`<data>/desktop/transcript.json`), same format as Capri 1.0.4 `storage.mjs`.
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Result;
|
||||
use capri_core::fsutil;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const MAX_MESSAGES: usize = 200;
|
||||
const MAX_TEXT: usize = 65536;
|
||||
const MAX_FILE_BYTES: u64 = 2 * 1024 * 1024;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AvatarRef {
|
||||
pub id: String,
|
||||
pub pose: String,
|
||||
pub expression: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JournalMessage {
|
||||
pub id: String,
|
||||
pub turn_id: String,
|
||||
/// `user` or `assistant`.
|
||||
pub role: String,
|
||||
pub text: String,
|
||||
/// `complete`, `streaming`, `interrupted` or `error`.
|
||||
pub status: String,
|
||||
pub created_at: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub avatar: Option<AvatarRef>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub follow_up: Option<bool>,
|
||||
/// Fields written by Capri 1.0.4 that this version does not interpret yet are kept as is.
|
||||
#[serde(flatten)]
|
||||
pub extra: serde_json::Map<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct File {
|
||||
schema_version: u32,
|
||||
messages: Vec<JournalMessage>,
|
||||
}
|
||||
|
||||
pub struct Journal {
|
||||
file: PathBuf,
|
||||
pub messages: Vec<JournalMessage>,
|
||||
/// Set when an existing transcript could not be read; it is then never overwritten.
|
||||
pub warning: Option<String>,
|
||||
}
|
||||
|
||||
impl Journal {
|
||||
pub fn open(file: PathBuf) -> Self {
|
||||
let read = || -> Result<Vec<JournalMessage>> {
|
||||
let Some(bytes) = fsutil::read_regular(&file, MAX_FILE_BYTES)? else { return Ok(vec![]) };
|
||||
let saved: File = serde_json::from_slice(&bytes)?;
|
||||
anyhow::ensure!(saved.schema_version == 1, "Invalid transcript");
|
||||
let mut messages = saved.messages;
|
||||
let skip = messages.len().saturating_sub(MAX_MESSAGES);
|
||||
messages.drain(..skip);
|
||||
for m in &mut messages {
|
||||
anyhow::ensure!(matches!(m.role.as_str(), "user" | "assistant"), "Invalid transcript");
|
||||
if m.status == "streaming" {
|
||||
m.status = "interrupted".into();
|
||||
}
|
||||
}
|
||||
Ok(messages)
|
||||
};
|
||||
match read() {
|
||||
Ok(messages) => Self { file, messages, warning: None },
|
||||
Err(e) => {
|
||||
tracing::warn!("transcript unreadable: {e}");
|
||||
Self { file, messages: vec![], warning: Some("Previous conversation history could not be restored. It was left untouched.".into()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts or replaces a message by id and saves.
|
||||
pub fn put(&mut self, mut message: JournalMessage) -> Result<()> {
|
||||
if message.text.chars().count() > MAX_TEXT {
|
||||
message.text = message.text.chars().take(MAX_TEXT).collect();
|
||||
}
|
||||
match self.messages.iter_mut().find(|m| m.id == message.id) {
|
||||
Some(slot) => *slot = message,
|
||||
None => self.messages.push(message),
|
||||
}
|
||||
let skip = self.messages.len().saturating_sub(MAX_MESSAGES);
|
||||
self.messages.drain(..skip);
|
||||
self.save()
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) -> Result<()> {
|
||||
self.messages.clear();
|
||||
self.warning = None;
|
||||
self.save()
|
||||
}
|
||||
|
||||
fn save(&self) -> Result<()> {
|
||||
if self.warning.is_some() {
|
||||
return Ok(()); // never replace recoverable history; only explicit clearing may
|
||||
}
|
||||
fsutil::write_json_atomic(&self.file, &File { schema_version: 1, messages: self.messages.clone() })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn msg(id: &str, status: &str) -> JournalMessage {
|
||||
JournalMessage {
|
||||
id: id.into(),
|
||||
turn_id: "t".into(),
|
||||
role: "assistant".into(),
|
||||
text: "x".into(),
|
||||
status: status.into(),
|
||||
created_at: "2026-01-01T00:00:00.000Z".into(),
|
||||
avatar: None,
|
||||
follow_up: None,
|
||||
extra: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_keeps_unknown_fields_and_interrupts_streaming() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("transcript.json");
|
||||
std::fs::write(&file, r#"{"schemaVersion":1,"messages":[{"id":"a","turnId":"t","role":"assistant","text":"x","status":"streaming","createdAt":"c","computerTask":{"status":"done"}}]}"#).unwrap();
|
||||
let mut j = Journal::open(file.clone());
|
||||
assert_eq!(j.messages[0].status, "interrupted");
|
||||
j.put(msg("b", "complete")).unwrap();
|
||||
let again = Journal::open(file);
|
||||
assert_eq!(again.messages.len(), 2);
|
||||
assert!(again.messages[0].extra.contains_key("computerTask"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_history_is_never_overwritten() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("transcript.json");
|
||||
std::fs::write(&file, "garbage").unwrap();
|
||||
let mut j = Journal::open(file.clone());
|
||||
assert!(j.warning.is_some());
|
||||
j.put(msg("b", "complete")).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), "garbage");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user