Skip to main content

yk_session/
session.rs

1//! The bridge between the loop's `Vec<Message>` and the session file.
2//!
3//! The loop's history is the truth while a run is happening; the session file is
4//! the truth between runs. This converts one to the other and remembers how much
5//! has been written, so `persist` is idempotent and never rewrites history it
6//! already recorded.
7//!
8//! It lives here rather than in the binary because `yk acp` needs the same walk
9//! to resume a session, and two copies of a file format is how a format forks.
10//!
11//! Ids are sequential (`e1`, `e2`, ...) rather than random. That makes a session
12//! file diffable and a resumed conversation reproducible, which is worth more
13//! here than the collision resistance a uuid would buy, because a session has
14//! exactly one writer.
15
16use crate::{Entry, SessionLog, next_id};
17use yk_core::{Id, Message, Result, ToolResult, Turn};
18
19/// An open session and the history it is backed by.
20///
21/// `Debug` is hand-written so the tests can use `expect_err`; deriving it would
22/// try to print the open file handle.
23pub struct Session {
24    store: SessionLog,
25    history: Vec<Message>,
26    /// How far into `history` this session has got writing.
27    written: usize,
28    /// How many entries the file holds, which is not the same as `written`:
29    /// a resumed session starts at zero having written nothing yet.
30    on_disk: usize,
31    /// The id of the last written entry, which is the next entry's parent.
32    last_id: Option<Id>,
33    /// The model in force, restored from the file so a resumed conversation
34    /// continues on the model it was actually having.
35    model: Option<String>,
36}
37
38impl std::fmt::Debug for Session {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("Session")
41            .field("history", &self.history)
42            .field("written", &self.written)
43            .field("last_id", &self.last_id)
44            .field("model", &self.model)
45            .finish_non_exhaustive()
46    }
47}
48
49impl Session {
50    /// Where the session file is, for diagnostics.
51    #[must_use]
52    pub fn path(&self) -> &std::path::Path {
53        self.store.path()
54    }
55
56    /// How many entries the file holds.
57    #[must_use]
58    pub const fn len(&self) -> usize {
59        self.on_disk
60    }
61
62    /// Whether the file holds nothing yet.
63    ///
64    /// Not dead weight: `clippy::len_without_is_empty` requires it beside `len`,
65    /// and a reader coming to `len` expects to be able to ask the empty case.
66    #[must_use]
67    pub const fn is_empty(&self) -> bool {
68        self.on_disk == 0
69    }
70
71    /// Open or create the session file and replay it into a history.
72    ///
73    /// # Errors
74    ///
75    /// [`yk_core::Error::Read`] if the file cannot be opened, and
76    /// [`yk_core::Error::Malformed`] if a line cannot be read. A corrupt line is
77    /// reported rather than skipped: silently dropping a message makes the model
78    /// look like it forgot something, which is a much harder bug to find.
79    pub fn open(path: &std::path::Path) -> Result<Self> {
80        let store = SessionLog::open(path.to_path_buf())?;
81        let entries = store.all_entries()?;
82
83        // The branch walk, not every line. A forked or rewound session has
84        // entries on disk that are not part of this conversation.
85        let history = store.active_messages()?;
86
87        Ok(Self {
88            written: 0,
89            on_disk: entries.len(),
90            last_id: store.head_id()?,
91            model: store.active_model()?,
92            store,
93            history,
94        })
95    }
96
97    /// The conversation as it currently stands.
98    #[must_use]
99    pub fn history(&self) -> &[Message] {
100        &self.history
101    }
102
103    pub const fn history_mut(&mut self) -> &mut Vec<Message> {
104        &mut self.history
105    }
106
107    pub fn append_user(&mut self, prompt: &str) {
108        self.history.push(Message::user(prompt));
109    }
110
111    /// The model this conversation is on, if the file says.
112    #[must_use]
113    pub fn model(&self) -> Option<&str> {
114        self.model.as_deref()
115    }
116
117    /// The model in force, or `default` when the session records none.
118    ///
119    /// The fallback for a new conversation and for one that never switched: the
120    /// caller's configured model is the answer in both cases.
121    #[must_use]
122    pub fn model_or<'a>(&'a self, default: &'a str) -> &'a str {
123        self.model.as_deref().unwrap_or(default)
124    }
125
126    /// Record a model switch, so a resumed conversation picks it back up.
127    ///
128    /// Appended rather than held only in memory: a client closes the process and
129    /// reopens it, and a model that lived only in memory would be a picker that
130    /// lies, reporting a switched model and then resuming on the configured one.
131    ///
132    /// # Errors
133    ///
134    /// [`yk_core::Error::Read`] if the entry cannot be written.
135    pub fn set_model(&mut self, model: &str) -> Result<()> {
136        let id = self.write(&Entry::Model {
137            id: String::new(),
138            parent: self.last_id.clone(),
139            model: model.to_owned(),
140        })?;
141        self.last_id = Some(id);
142        self.model = Some(model.to_owned());
143        Ok(())
144    }
145
146    /// Replace the active branch with a summary, shadowing what came before.
147    ///
148    /// The summary is written as a `Compaction` entry, so the branch walk stops
149    /// there and everything before it leaves the conversation without leaving the
150    /// file. The in-memory history becomes the summary alone, so a run that
151    /// continues from here sends the summary and not the shadowed turns.
152    ///
153    /// The write cursor moves with the history, because the summary is already on
154    /// disk as the compaction entry and a later `persist` must not write it
155    /// again.
156    ///
157    /// # Errors
158    ///
159    /// [`yk_core::Error::Read`] if the entry cannot be written.
160    pub fn compact(&mut self, summary: &str) -> Result<()> {
161        let id = self.write(&Entry::Compaction {
162            id: String::new(),
163            parent: self.last_id.clone(),
164            summary: summary.to_owned(),
165        })?;
166        self.last_id = Some(id);
167
168        self.history = vec![crate::summary_message(summary)];
169        self.written = self.history.len();
170        Ok(())
171    }
172
173    /// Append whatever the loop produced since the last call.
174    ///
175    /// # Errors
176    ///
177    /// [`yk_core::Error::Read`] if the file cannot be written. The cursor advances
178    /// only for entries that were actually written, so a retry after a failure
179    /// resumes rather than skipping.
180    pub fn persist(&mut self) -> Result<()> {
181        let pending: Vec<Message> = self
182            .history
183            .get(self.written..)
184            .map_or_else(Vec::new, <[Message]>::to_vec);
185
186        for message in pending {
187            let id = self.write(&message_to_entry(&message, self.last_id.as_deref()))?;
188            self.last_id = Some(id);
189            self.written = self.written.saturating_add(1);
190        }
191
192        Ok(())
193    }
194
195    /// Append one entry, stamping the id and advancing the head.
196    ///
197    /// The id lives in every variant of [`Entry`] rather than beside them, so it
198    /// is filled in here once instead of at each call site.
199    fn write(&mut self, entry: &Entry) -> Result<Id> {
200        let id = next_id(self.on_disk);
201        let mut stamped = entry.clone();
202
203        match &mut stamped {
204            Entry::Message { id: slot, .. }
205            | Entry::Assistant { id: slot, .. }
206            | Entry::Result { id: slot, .. }
207            | Entry::Compaction { id: slot, .. }
208            | Entry::Model { id: slot, .. }
209            | Entry::Rewind { id: slot, .. } => slot.clone_from(&id),
210        }
211
212        self.store.append(&stamped)?;
213        self.on_disk = self.on_disk.saturating_add(1);
214        Ok(id)
215    }
216}
217
218/// Convert a history message into the entry shape the file stores.
219fn message_to_entry(message: &Message, parent: Option<&str>) -> Entry {
220    let parent = parent.map(ToOwned::to_owned);
221    let id = String::new();
222
223    match message {
224        Message::User { content } => Entry::Message {
225            id,
226            parent,
227            message: Message::user(content.clone()),
228        },
229        Message::Assistant {
230            content,
231            tool_calls,
232        } => Entry::Assistant {
233            id,
234            parent,
235            turn: Turn {
236                text: content.clone(),
237                tool_calls: tool_calls.clone(),
238                usage: None,
239            },
240        },
241        Message::Tool {
242            tool_call_id,
243            content,
244            is_error,
245        } => Entry::Result {
246            id,
247            parent,
248            result: ToolResult {
249                call_id: tool_call_id.clone(),
250                output: content.clone(),
251                is_error: *is_error,
252            },
253        },
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    #![allow(
260        clippy::unwrap_used,
261        clippy::expect_used,
262        clippy::indexing_slicing,
263        clippy::as_conversions,
264        clippy::arithmetic_side_effects
265    )]
266
267    use std::fs;
268
269    use super::{Session, message_to_entry};
270    use crate::Entry;
271    use yk_core::{AssistantToolCall, Message};
272
273    /// A session file inside a scratch directory, removed on drop.
274    ///
275    /// The caller holds the `TempDir` so the directory outlives the path.
276    /// `tempfile` rather than a fixed path under `std::env::temp_dir`, which
277    /// collided between test binaries.
278    fn temp(name: &str) -> (tempfile::TempDir, std::path::PathBuf) {
279        let dir = tempfile::TempDir::with_prefix(name).expect("makes the directory");
280        let path = dir.path().join("s.jsonl");
281        (dir, path)
282    }
283
284    fn call() -> AssistantToolCall {
285        AssistantToolCall {
286            id: "c1".to_owned(),
287            name: "read".to_owned(),
288            arguments: r#"{"path":"a"}"#.to_owned(),
289        }
290    }
291
292    #[test]
293    fn a_fresh_session_is_empty() {
294        let (_dir, path) = temp("fresh");
295        let session = Session::open(&path).expect("opens");
296        assert_eq!(session.len(), 0);
297        assert!(session.history.is_empty());
298    }
299
300    #[test]
301    fn a_persisted_history_reloads_identically() {
302        let (_dir, path) = temp("roundtrip");
303        {
304            let mut session = Session::open(&path).expect("opens");
305            session.append_user("hello");
306            session.history_mut().push(Message::assistant("hi"));
307            session.persist().expect("writes");
308        }
309
310        let reopened = Session::open(&path).expect("reopens");
311        assert_eq!(reopened.history.len(), 2);
312        assert_eq!(reopened.history[0], Message::user("hello"));
313        assert_eq!(reopened.history[1], Message::assistant("hi"));
314    }
315
316    #[test]
317    fn persisting_twice_does_not_duplicate() {
318        let (_dir, path) = temp("idempotent");
319        let mut session = Session::open(&path).expect("opens");
320
321        session.append_user("one");
322        session.persist().expect("writes");
323        session.persist().expect("writes again");
324        session.persist().expect("and again");
325
326        assert_eq!(Session::open(&path).expect("reopens").len(), 1);
327    }
328
329    #[test]
330    fn only_new_messages_are_written_each_time() {
331        let (_dir, path) = temp("incremental");
332        let mut session = Session::open(&path).expect("opens");
333
334        session.append_user("first");
335        session.persist().expect("writes");
336        session.append_user("second");
337        session.persist().expect("writes");
338
339        let reopened = Session::open(&path).expect("reopens");
340        assert_eq!(reopened.history.len(), 2);
341        assert_eq!(reopened.history[1], Message::user("second"));
342    }
343
344    #[test]
345    fn ids_continue_across_a_reopen() {
346        let (_dir, path) = temp("ids");
347        {
348            let mut session = Session::open(&path).expect("opens");
349            session.append_user("one");
350            session.persist().expect("writes");
351        }
352
353        let mut reopened = Session::open(&path).expect("reopens");
354        reopened.append_user("two");
355        reopened.persist().expect("writes");
356
357        let raw = fs::read_to_string(&path).expect("reads");
358        let entries: Vec<serde_json::Value> = raw
359            .lines()
360            .map(|line| serde_json::from_str(line).expect("parses"))
361            .filter(|value: &serde_json::Value| value["kind"] != "session")
362            .collect();
363        let second = &entries[1];
364
365        assert_eq!(second["id"], "e2", "ids restarted: {second}");
366    }
367
368    #[test]
369    fn every_entry_points_at_the_one_before_it() {
370        let (_dir, path) = temp("chain");
371        let mut session = Session::open(&path).expect("opens");
372        session.append_user("one");
373        session.history_mut().push(Message::assistant("two"));
374        session.history_mut().push(Message::tool("c1", "three"));
375        session.persist().expect("writes");
376
377        let raw = fs::read_to_string(&path).expect("reads");
378        let parsed: Vec<serde_json::Value> = raw
379            .lines()
380            .map(|line| serde_json::from_str(line).expect("parses"))
381            .filter(|value: &serde_json::Value| value["kind"] != "session")
382            .collect();
383
384        assert_eq!(parsed.len(), 3);
385        assert_eq!(parsed[0]["id"], "e1");
386        assert_eq!(parsed[0]["parent"], serde_json::Value::Null);
387        assert_eq!(parsed[1]["id"], "e2");
388        assert_eq!(parsed[1]["parent"], "e1");
389        assert_eq!(parsed[2]["id"], "e3");
390        assert_eq!(parsed[2]["parent"], "e2");
391    }
392
393    #[test]
394    fn a_tool_error_survives_the_file_even_though_the_wire_shape_drops_it() {
395        let (_dir, path) = temp("toolerror");
396        let message = Message::tool_result("c1", "no such file", true);
397
398        // The provider must not see the flag.
399        let wire = serde_json::to_string(&message).expect("serialises");
400        assert!(
401            !wire.contains("is_error"),
402            "flag leaked to the wire: {wire}"
403        );
404
405        {
406            let mut session = Session::open(&path).expect("opens");
407            session.history_mut().push(message);
408            session.persist().expect("writes");
409        }
410
411        let reopened = Session::open(&path).expect("reopens");
412        assert_eq!(
413            reopened.history[0],
414            Message::tool_result("c1", "no such file", true),
415            "the session lost the error flag"
416        );
417    }
418
419    #[test]
420    fn a_whole_conversation_round_trips() {
421        let conversation = [
422            Message::user("read a.txt"),
423            Message::assistant_with_calls("one sec", vec![call()]),
424            Message::tool("c1", "contents"),
425            Message::assistant("done"),
426        ];
427
428        let mut seen = Vec::new();
429        for message in &conversation {
430            let entry = message_to_entry(message, None);
431            seen.push(crate::entry_to_message(&entry));
432        }
433
434        assert_eq!(seen, conversation.into_iter().map(Some).collect::<Vec<_>>());
435    }
436
437    #[test]
438    fn a_switched_model_survives_a_reopen_and_leaves_the_history_alone() {
439        let (_dir, path) = temp("model");
440
441        let fresh = Session::open(&path).expect("opens");
442        assert_eq!(
443            fresh.model(),
444            None,
445            "a session that never switched has no model"
446        );
447
448        {
449            let mut session = Session::open(&path).expect("opens");
450            session.append_user("hi");
451            session.set_model("some/other-model").expect("writes");
452            session.persist().expect("writes");
453        }
454
455        let reopened = Session::open(&path).expect("reopens");
456
457        assert_eq!(reopened.model(), Some("some/other-model"));
458        assert_eq!(reopened.history.len(), 1, "the switch became a message");
459        assert_eq!(reopened.history[0], Message::user("hi"));
460    }
461
462    #[test]
463    fn a_model_entry_continues_the_branch_rather_than_forking_it() {
464        let (_dir, path) = temp("modelbranch");
465        let mut session = Session::open(&path).expect("opens");
466        session.append_user("hi");
467        session.persist().expect("writes");
468        session.set_model("switched").expect("writes");
469
470        let raw = fs::read_to_string(&path).expect("reads");
471        let entries: Vec<serde_json::Value> = raw
472            .lines()
473            .map(|line| serde_json::from_str(line).expect("parses"))
474            .filter(|value: &serde_json::Value| value["kind"] != "session")
475            .collect();
476
477        assert_eq!(entries.len(), 2);
478        assert_eq!(entries[1]["kind"], "model");
479        assert_eq!(entries[1]["parent"], "e1");
480        assert_eq!(entries[1]["model"], "switched");
481    }
482
483    #[test]
484    fn a_corrupt_line_is_reported_rather_than_skipped() {
485        let (_dir, path) = temp("corrupt");
486        // Write before opening, so `SessionLog` never gets to repair the file.
487        if let Some(parent) = path.parent() {
488            fs::create_dir_all(parent).expect("makes the directory");
489        }
490        let good = Entry::Message {
491            id: "e1".to_owned(),
492            parent: None,
493            message: Message::user("hi"),
494        };
495        fs::write(
496            &path,
497            format!(
498                "{}\nnot json\n",
499                serde_json::to_string(&good).expect("serialises")
500            ),
501        )
502        .expect("writes");
503
504        let error = Session::open(&path).expect_err("must fail");
505        assert!(error.to_string().contains("line 2"), "{error}");
506    }
507}