use crate::{Entry, SessionLog, next_id};
use yk_core::{Id, Message, Result, ToolResult, Turn};
pub struct Session {
store: SessionLog,
history: Vec<Message>,
written: usize,
on_disk: usize,
last_id: Option<Id>,
model: Option<String>,
}
impl std::fmt::Debug for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session")
.field("history", &self.history)
.field("written", &self.written)
.field("last_id", &self.last_id)
.field("model", &self.model)
.finish_non_exhaustive()
}
}
impl Session {
#[must_use]
pub fn path(&self) -> &std::path::Path {
self.store.path()
}
#[must_use]
pub const fn len(&self) -> usize {
self.on_disk
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.on_disk == 0
}
pub fn open(path: &std::path::Path) -> Result<Self> {
let store = SessionLog::open(path.to_path_buf())?;
let entries = store.all_entries()?;
let history = store.active_messages()?;
Ok(Self {
written: 0,
on_disk: entries.len(),
last_id: store.head_id()?,
model: store.active_model()?,
store,
history,
})
}
#[must_use]
pub fn history(&self) -> &[Message] {
&self.history
}
pub const fn history_mut(&mut self) -> &mut Vec<Message> {
&mut self.history
}
pub fn append_user(&mut self, prompt: &str) {
self.history.push(Message::user(prompt));
}
#[must_use]
pub fn model(&self) -> Option<&str> {
self.model.as_deref()
}
#[must_use]
pub fn model_or<'a>(&'a self, default: &'a str) -> &'a str {
self.model.as_deref().unwrap_or(default)
}
pub fn set_model(&mut self, model: &str) -> Result<()> {
let id = self.write(&Entry::Model {
id: String::new(),
parent: self.last_id.clone(),
model: model.to_owned(),
})?;
self.last_id = Some(id);
self.model = Some(model.to_owned());
Ok(())
}
pub fn compact(&mut self, summary: &str) -> Result<()> {
let id = self.write(&Entry::Compaction {
id: String::new(),
parent: self.last_id.clone(),
summary: summary.to_owned(),
})?;
self.last_id = Some(id);
self.history = vec![crate::summary_message(summary)];
self.written = self.history.len();
Ok(())
}
pub fn persist(&mut self) -> Result<()> {
let pending: Vec<Message> = self
.history
.get(self.written..)
.map_or_else(Vec::new, <[Message]>::to_vec);
for message in pending {
let id = self.write(&message_to_entry(&message, self.last_id.as_deref()))?;
self.last_id = Some(id);
self.written = self.written.saturating_add(1);
}
Ok(())
}
fn write(&mut self, entry: &Entry) -> Result<Id> {
let id = next_id(self.on_disk);
let mut stamped = entry.clone();
match &mut stamped {
Entry::Message { id: slot, .. }
| Entry::Assistant { id: slot, .. }
| Entry::Result { id: slot, .. }
| Entry::Compaction { id: slot, .. }
| Entry::Model { id: slot, .. }
| Entry::Rewind { id: slot, .. } => slot.clone_from(&id),
}
self.store.append(&stamped)?;
self.on_disk = self.on_disk.saturating_add(1);
Ok(id)
}
}
fn message_to_entry(message: &Message, parent: Option<&str>) -> Entry {
let parent = parent.map(ToOwned::to_owned);
let id = String::new();
match message {
Message::User { content } => Entry::Message {
id,
parent,
message: Message::user(content.clone()),
},
Message::Assistant {
content,
tool_calls,
} => Entry::Assistant {
id,
parent,
turn: Turn {
text: content.clone(),
tool_calls: tool_calls.clone(),
usage: None,
},
},
Message::Tool {
tool_call_id,
content,
is_error,
} => Entry::Result {
id,
parent,
result: ToolResult {
call_id: tool_call_id.clone(),
output: content.clone(),
is_error: *is_error,
},
},
}
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::as_conversions,
clippy::arithmetic_side_effects
)]
use std::fs;
use super::{Session, message_to_entry};
use crate::Entry;
use yk_core::{AssistantToolCall, Message};
fn temp(name: &str) -> (tempfile::TempDir, std::path::PathBuf) {
let dir = tempfile::TempDir::with_prefix(name).expect("makes the directory");
let path = dir.path().join("s.jsonl");
(dir, path)
}
fn call() -> AssistantToolCall {
AssistantToolCall {
id: "c1".to_owned(),
name: "read".to_owned(),
arguments: r#"{"path":"a"}"#.to_owned(),
}
}
#[test]
fn a_fresh_session_is_empty() {
let (_dir, path) = temp("fresh");
let session = Session::open(&path).expect("opens");
assert_eq!(session.len(), 0);
assert!(session.history.is_empty());
}
#[test]
fn a_persisted_history_reloads_identically() {
let (_dir, path) = temp("roundtrip");
{
let mut session = Session::open(&path).expect("opens");
session.append_user("hello");
session.history_mut().push(Message::assistant("hi"));
session.persist().expect("writes");
}
let reopened = Session::open(&path).expect("reopens");
assert_eq!(reopened.history.len(), 2);
assert_eq!(reopened.history[0], Message::user("hello"));
assert_eq!(reopened.history[1], Message::assistant("hi"));
}
#[test]
fn persisting_twice_does_not_duplicate() {
let (_dir, path) = temp("idempotent");
let mut session = Session::open(&path).expect("opens");
session.append_user("one");
session.persist().expect("writes");
session.persist().expect("writes again");
session.persist().expect("and again");
assert_eq!(Session::open(&path).expect("reopens").len(), 1);
}
#[test]
fn only_new_messages_are_written_each_time() {
let (_dir, path) = temp("incremental");
let mut session = Session::open(&path).expect("opens");
session.append_user("first");
session.persist().expect("writes");
session.append_user("second");
session.persist().expect("writes");
let reopened = Session::open(&path).expect("reopens");
assert_eq!(reopened.history.len(), 2);
assert_eq!(reopened.history[1], Message::user("second"));
}
#[test]
fn ids_continue_across_a_reopen() {
let (_dir, path) = temp("ids");
{
let mut session = Session::open(&path).expect("opens");
session.append_user("one");
session.persist().expect("writes");
}
let mut reopened = Session::open(&path).expect("reopens");
reopened.append_user("two");
reopened.persist().expect("writes");
let raw = fs::read_to_string(&path).expect("reads");
let entries: Vec<serde_json::Value> = raw
.lines()
.map(|line| serde_json::from_str(line).expect("parses"))
.filter(|value: &serde_json::Value| value["kind"] != "session")
.collect();
let second = &entries[1];
assert_eq!(second["id"], "e2", "ids restarted: {second}");
}
#[test]
fn every_entry_points_at_the_one_before_it() {
let (_dir, path) = temp("chain");
let mut session = Session::open(&path).expect("opens");
session.append_user("one");
session.history_mut().push(Message::assistant("two"));
session.history_mut().push(Message::tool("c1", "three"));
session.persist().expect("writes");
let raw = fs::read_to_string(&path).expect("reads");
let parsed: Vec<serde_json::Value> = raw
.lines()
.map(|line| serde_json::from_str(line).expect("parses"))
.filter(|value: &serde_json::Value| value["kind"] != "session")
.collect();
assert_eq!(parsed.len(), 3);
assert_eq!(parsed[0]["id"], "e1");
assert_eq!(parsed[0]["parent"], serde_json::Value::Null);
assert_eq!(parsed[1]["id"], "e2");
assert_eq!(parsed[1]["parent"], "e1");
assert_eq!(parsed[2]["id"], "e3");
assert_eq!(parsed[2]["parent"], "e2");
}
#[test]
fn a_tool_error_survives_the_file_even_though_the_wire_shape_drops_it() {
let (_dir, path) = temp("toolerror");
let message = Message::tool_result("c1", "no such file", true);
let wire = serde_json::to_string(&message).expect("serialises");
assert!(
!wire.contains("is_error"),
"flag leaked to the wire: {wire}"
);
{
let mut session = Session::open(&path).expect("opens");
session.history_mut().push(message);
session.persist().expect("writes");
}
let reopened = Session::open(&path).expect("reopens");
assert_eq!(
reopened.history[0],
Message::tool_result("c1", "no such file", true),
"the session lost the error flag"
);
}
#[test]
fn a_whole_conversation_round_trips() {
let conversation = [
Message::user("read a.txt"),
Message::assistant_with_calls("one sec", vec![call()]),
Message::tool("c1", "contents"),
Message::assistant("done"),
];
let mut seen = Vec::new();
for message in &conversation {
let entry = message_to_entry(message, None);
seen.push(crate::entry_to_message(&entry));
}
assert_eq!(seen, conversation.into_iter().map(Some).collect::<Vec<_>>());
}
#[test]
fn a_switched_model_survives_a_reopen_and_leaves_the_history_alone() {
let (_dir, path) = temp("model");
let fresh = Session::open(&path).expect("opens");
assert_eq!(
fresh.model(),
None,
"a session that never switched has no model"
);
{
let mut session = Session::open(&path).expect("opens");
session.append_user("hi");
session.set_model("some/other-model").expect("writes");
session.persist().expect("writes");
}
let reopened = Session::open(&path).expect("reopens");
assert_eq!(reopened.model(), Some("some/other-model"));
assert_eq!(reopened.history.len(), 1, "the switch became a message");
assert_eq!(reopened.history[0], Message::user("hi"));
}
#[test]
fn a_model_entry_continues_the_branch_rather_than_forking_it() {
let (_dir, path) = temp("modelbranch");
let mut session = Session::open(&path).expect("opens");
session.append_user("hi");
session.persist().expect("writes");
session.set_model("switched").expect("writes");
let raw = fs::read_to_string(&path).expect("reads");
let entries: Vec<serde_json::Value> = raw
.lines()
.map(|line| serde_json::from_str(line).expect("parses"))
.filter(|value: &serde_json::Value| value["kind"] != "session")
.collect();
assert_eq!(entries.len(), 2);
assert_eq!(entries[1]["kind"], "model");
assert_eq!(entries[1]["parent"], "e1");
assert_eq!(entries[1]["model"], "switched");
}
#[test]
fn a_corrupt_line_is_reported_rather_than_skipped() {
let (_dir, path) = temp("corrupt");
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).expect("makes the directory");
}
let good = Entry::Message {
id: "e1".to_owned(),
parent: None,
message: Message::user("hi"),
};
fs::write(
&path,
format!(
"{}\nnot json\n",
serde_json::to_string(&good).expect("serialises")
),
)
.expect("writes");
let error = Session::open(&path).expect_err("must fail");
assert!(error.to_string().contains("line 2"), "{error}");
}
}