use std::path::{Path, PathBuf};
use pretty_assertions::assert_eq;
use rho_sdk::model::Message;
use super::{list_in_root, listable, owned_in_root, page, Cursor, DEFAULT_PAGE_SIZE};
use crate::session::{
layout::session_dir_in_root, Session as StoredSession, SessionOrigin, SessionProvenance,
SessionSummary, SessionTarget,
};
fn summary(id: &str, cwd: &Path, updated_at: u64, message_count: u64) -> SessionSummary {
SessionSummary {
id: id.to_owned(),
path: cwd.join(format!("{id}.jsonl")),
cwd: cwd.to_path_buf(),
created_at: 0,
updated_at,
message_count,
title: Some(format!("title {id}")),
first_user_message: None,
last_user_message: None,
added_dirs: Vec::new(),
origin: None,
agent: None,
started_by: None,
mark: None,
}
}
fn saved_session(root: &Path, cwd: &Path) -> String {
let saved = StoredSession::create_in_root(root, cwd).unwrap();
saved
.append_message(&Message::user_text("list me"))
.unwrap();
saved.id().to_owned()
}
#[test]
fn following_cursors_lists_each_resumable_session_once() {
let size = DEFAULT_PAGE_SIZE.get();
let root = tempfile::tempdir().unwrap();
let (first, second) = (root.path().join("a"), root.path().join("b"));
std::fs::create_dir(&first).unwrap();
std::fs::create_dir(&second).unwrap();
let gone = root.path().join("deleted-workspace");
let mut saved = (0..size * 2 + 1)
.map(|n| summary(&format!("{n:04}"), &first, 10_000 - n as u64 / 3, 2))
.collect::<Vec<_>>();
let twin = summary(&saved[size - 1].id, &second, saved[size - 1].updated_at, 2);
saved.insert(size, twin);
let mut store = saved.clone();
store.push(summary("empty", &first, 20_000, 0));
store.push(summary("orphan", &gone, 20_000, 2));
store.reverse();
let mut listed = Vec::new();
let mut cursor: Option<String> = None;
let mut pages = 0;
loop {
let after = cursor
.as_deref()
.map(|cursor| Cursor::parse(cursor).unwrap());
let next = page(store.clone(), listable, after.as_ref(), DEFAULT_PAGE_SIZE);
pages += 1;
listed.extend(
next.sessions
.into_iter()
.map(|summary| (summary.id, summary.cwd)),
);
match next.next_cursor {
Some(next) => cursor = Some(next),
None => break,
}
}
let expected = saved
.iter()
.map(|summary| (summary.id.clone(), summary.cwd.clone()))
.collect::<Vec<_>>();
assert_eq!((pages, listed), (3, expected));
}
#[test]
fn a_foreign_cursor_is_unknown() {
for cursor in ["", "page-2", "later/0001", "[1, \"0001\"]"] {
assert_eq!(Cursor::parse(cursor), None, "{cursor}");
}
}
#[test]
fn listed_store_sessions_open_by_their_listed_id() {
let root = tempfile::tempdir().unwrap();
let workspace = tempfile::tempdir().unwrap();
let cwd = crate::paths::canonicalize(workspace.path()).unwrap();
let saved_id = saved_session(root.path(), &cwd);
drop(StoredSession::create_in_root(root.path(), &cwd).unwrap());
let listed = list_in_root(root.path(), Some(&cwd), None, DEFAULT_PAGE_SIZE)
.unwrap()
.sessions;
assert_eq!(
listed
.iter()
.map(|summary| (summary.id.clone(), summary.cwd.clone()))
.collect::<Vec<_>>(),
vec![(saved_id.clone(), PathBuf::from(&cwd))]
);
let (opened, _) =
StoredSession::open_by_id_in_root(root.path(), &listed[0].cwd, &listed[0].id).unwrap();
let display: Vec<_> = opened
.active_display_history()
.unwrap()
.into_iter()
.map(|row| row.message)
.collect();
assert_eq!(
(opened.id(), display),
(saved_id.as_str(), vec![Message::user_text("list me")])
);
}
#[cfg(unix)]
#[test]
fn a_workspace_lists_by_its_canonical_path() {
let root = tempfile::tempdir().unwrap();
let workspace = tempfile::tempdir().unwrap();
let cwd = workspace.path().canonicalize().unwrap();
let saved_id = saved_session(root.path(), &cwd);
let links = tempfile::tempdir().unwrap();
let link = links.path().join("workspace-link");
std::os::unix::fs::symlink(&cwd, &link).unwrap();
let missing = links.path().join("missing");
let through_link = list_in_root(root.path(), Some(&link), None, DEFAULT_PAGE_SIZE)
.unwrap()
.sessions
.into_iter()
.map(|summary| (summary.id, summary.cwd))
.collect::<Vec<_>>();
let nowhere = list_in_root(root.path(), Some(&missing), None, DEFAULT_PAGE_SIZE).unwrap();
assert_eq!(
(
through_link,
nowhere.sessions,
nowhere.next_cursor,
session_dir_in_root(root.path(), &missing).exists()
),
(vec![(saved_id, cwd)], Vec::new(), None, false)
);
}
fn saved(root: &Path, cwd: &Path, id: &str, provenance: SessionProvenance) {
let saved = StoredSession::create_with_id_in_root(root, cwd, id, None, provenance).unwrap();
saved
.append_message(&Message::user_text("list me"))
.unwrap();
}
#[test]
fn an_owner_lists_the_sessions_it_owns_and_no_others() {
let root = tempfile::tempdir().unwrap();
let (here, there, gone) = (
tempfile::tempdir().unwrap(),
tempfile::tempdir().unwrap(),
tempfile::tempdir().unwrap(),
);
let here = crate::paths::canonicalize(here.path()).unwrap();
let there = crate::paths::canonicalize(there.path()).unwrap();
let gone_dir = crate::paths::canonicalize(gone.path()).unwrap();
let owner = SessionTarget::new("owner", &here);
let subagent = SessionTarget::new("subagent", &here);
let owned_by = |origin, parent: &SessionTarget| SessionProvenance {
origin,
parent: Some(parent.clone()),
started_by: None,
};
saved(root.path(), &here, "owner", SessionOrigin::Daemon.into());
saved(
root.path(),
&here,
"subagent",
owned_by(SessionOrigin::Subagent, &owner),
);
saved(
root.path(),
&there,
"fork",
owned_by(SessionOrigin::Fork, &owner),
);
saved(
root.path(),
&gone_dir,
"worktree",
owned_by(SessionOrigin::Subagent, &owner),
);
saved(
root.path(),
&here,
"nested",
owned_by(SessionOrigin::Subagent, &subagent),
);
let started = SessionProvenance {
origin: SessionOrigin::Daemon,
parent: None,
started_by: Some("owner".to_owned()),
};
saved(root.path(), &here, "started", started);
saved(root.path(), &here, "other", SessionOrigin::Daemon.into());
StoredSession::create_with_id_in_root(
root.path(),
&here,
"empty",
None,
owned_by(SessionOrigin::Subagent, &owner),
)
.unwrap();
drop(gone);
let mut owned = owned_in_root(root.path(), "owner", None, DEFAULT_PAGE_SIZE)
.unwrap()
.expect("the owner is saved")
.sessions
.into_iter()
.map(|summary| (summary.id, summary.cwd))
.collect::<Vec<_>>();
owned.sort();
let unknown = owned_in_root(root.path(), "nobody", None, DEFAULT_PAGE_SIZE).unwrap();
assert_eq!(
(owned, unknown),
(
vec![
("empty".to_owned(), here.clone()),
("fork".to_owned(), there.clone()),
("subagent".to_owned(), here.clone()),
("worktree".to_owned(), gone_dir.clone()),
],
None
)
);
}