use super::config::agent_data_dir;
use super::types::{ChatMessage, ChatSession, SessionEvent};
use crate::command::chat::constants::MESSAGE_PREVIEW_MAX_LEN;
use crate::error;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
pub fn sessions_dir() -> PathBuf {
let dir = agent_data_dir().join("sessions");
let _ = fs::create_dir_all(&dir);
dir
}
pub fn session_file_path(session_id: &str) -> PathBuf {
SessionPaths::new(session_id).transcript()
}
#[derive(Debug)]
pub struct SessionPaths {
id: String,
dir: PathBuf,
}
impl SessionPaths {
pub fn new(session_id: &str) -> Self {
let dir = sessions_dir().join(session_id);
Self {
id: session_id.to_string(),
dir,
}
}
#[allow(dead_code)]
pub fn id(&self) -> &str {
&self.id
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn transcript(&self) -> PathBuf {
self.dir.join("transcript.jsonl")
}
pub fn meta_file(&self) -> PathBuf {
self.dir.join("session.json")
}
pub fn transcripts_dir(&self) -> PathBuf {
self.dir.join(".transcripts")
}
pub fn teammates_file(&self) -> PathBuf {
self.dir.join("teammates.json")
}
pub fn teammates_dir(&self) -> PathBuf {
self.dir.join("teammates")
}
pub fn teammate_dir(&self, sanitized_name: &str) -> PathBuf {
self.teammates_dir().join(sanitized_name)
}
pub fn teammate_transcript(&self, sanitized_name: &str) -> PathBuf {
self.teammate_dir(sanitized_name).join("transcript.jsonl")
}
pub fn teammate_todos_file(&self, sanitized_name: &str) -> PathBuf {
self.teammate_dir(sanitized_name).join("todos.json")
}
pub fn subagents_file(&self) -> PathBuf {
self.dir.join("subagents.json")
}
pub fn subagents_dir(&self) -> PathBuf {
self.dir.join("subagents")
}
pub fn subagent_dir(&self, sub_id: &str) -> PathBuf {
self.subagents_dir().join(sub_id)
}
pub fn subagent_transcript(&self, sub_id: &str) -> PathBuf {
self.subagent_dir(sub_id).join("transcript.jsonl")
}
pub fn subagent_todos_file(&self, sub_id: &str) -> PathBuf {
self.subagent_dir(sub_id).join("todos.json")
}
pub fn tasks_file(&self) -> PathBuf {
self.dir.join("tasks.json")
}
pub fn todos_file(&self) -> PathBuf {
self.dir.join("todos.json")
}
pub fn plan_file(&self) -> PathBuf {
self.dir.join("plan.json")
}
pub fn skills_file(&self) -> PathBuf {
self.dir.join("skills.json")
}
pub fn hooks_file(&self) -> PathBuf {
self.dir.join("hooks.json")
}
pub fn sandbox_file(&self) -> PathBuf {
self.dir.join("sandbox.json")
}
pub fn ensure_dir(&self) -> std::io::Result<()> {
fs::create_dir_all(&self.dir)
}
}
pub fn append_session_event(session_id: &str, event: &SessionEvent) -> bool {
let paths = SessionPaths::new(session_id);
if paths.ensure_dir().is_err() {
return false;
}
let path = paths.transcript();
let ok = match serde_json::to_string(event) {
Ok(line) => match fs::OpenOptions::new().create(true).append(true).open(&path) {
Ok(mut file) => writeln!(file, "{}", line).is_ok(),
Err(_) => false,
},
Err(_) => false,
};
if ok {
update_session_meta_on_event(session_id, event);
}
ok
}
fn update_session_meta_on_event(session_id: &str, event: &SessionEvent) {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let mut meta = load_session_meta_file(session_id).unwrap_or_else(|| SessionMetaFile {
id: session_id.to_string(),
title: String::new(),
message_count: 0,
created_at: now,
updated_at: now,
model: None,
});
meta.updated_at = now;
match event {
SessionEvent::Msg { message: msg, .. } => {
meta.message_count += 1;
if meta.title.is_empty() && msg.role == "user" && !msg.content.is_empty() {
meta.title = msg.content.chars().take(MESSAGE_PREVIEW_MAX_LEN).collect();
}
}
SessionEvent::Clear => {
meta.message_count = 0;
}
SessionEvent::Restore { messages } => {
meta.message_count = messages.len();
if meta.title.is_empty()
&& let Some(first_user) = messages
.iter()
.find(|m| m.role == "user" && !m.content.is_empty())
{
meta.title = first_user
.content
.chars()
.take(MESSAGE_PREVIEW_MAX_LEN)
.collect();
}
}
}
let _ = save_session_meta_file(&meta);
}
pub fn find_latest_session_id() -> Option<String> {
let dir = sessions_dir();
let mut entries: Vec<(std::time::SystemTime, String)> = Vec::new();
let read_dir = match fs::read_dir(&dir) {
Ok(rd) => rd,
Err(_) => return None,
};
for entry in read_dir.flatten() {
let path = entry.path();
if !entry.file_type().is_ok_and(|ft| ft.is_dir()) {
continue;
}
let Some(id) = path.file_name().and_then(|s| s.to_str()) else {
continue;
};
let transcript = path.join("transcript.jsonl");
if let Ok(meta) = transcript.metadata()
&& let Ok(modified) = meta.modified()
{
entries.push((modified, id.to_string()));
}
}
entries.sort_by(|a, b| b.0.cmp(&a.0));
entries.into_iter().next().map(|(_, id)| id)
}
pub fn load_session(session_id: &str) -> ChatSession {
let path = SessionPaths::new(session_id).transcript();
if !path.exists() {
return ChatSession::default();
}
let content = match fs::read_to_string(&path) {
Ok(c) => c,
Err(_) => return ChatSession::default(),
};
let mut messages: Vec<ChatMessage> = Vec::new();
for line in content.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
match serde_json::from_str::<SessionEvent>(line) {
Ok(event) => match event {
SessionEvent::Msg { message, .. } => messages.push(message),
SessionEvent::Clear => messages.clear(),
SessionEvent::Restore { messages: restored } => messages = restored,
},
Err(_) => {
}
}
}
ChatSession { messages }
}
pub fn read_transcript_with_timestamps(path: &Path) -> Vec<(ChatMessage, u64)> {
let content = match fs::read_to_string(path) {
Ok(c) => c,
Err(_) => return Vec::new(),
};
let mut out: Vec<(ChatMessage, u64)> = Vec::new();
for line in content.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
if let Ok(SessionEvent::Msg {
message,
timestamp_ms,
}) = serde_json::from_str::<SessionEvent>(line)
{
out.push((message, timestamp_ms));
}
}
out
}
pub fn append_event_to_path(path: &Path, event: &SessionEvent) -> bool {
if let Some(parent) = path.parent() {
let _ = fs::create_dir_all(parent);
}
let line = match serde_json::to_string(event) {
Ok(s) => s,
Err(_) => return false,
};
match fs::OpenOptions::new().create(true).append(true).open(path) {
Ok(mut file) => writeln!(file, "{}", line).is_ok(),
Err(_) => false,
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionMetaFile {
pub id: String,
#[serde(default)]
pub title: String,
pub message_count: usize,
pub created_at: u64,
pub updated_at: u64,
#[serde(default)]
pub model: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionMeta {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
pub message_count: usize,
pub first_message_preview: Option<String>,
pub updated_at: u64,
}
pub fn load_session_meta_file(session_id: &str) -> Option<SessionMetaFile> {
let path = SessionPaths::new(session_id).meta_file();
let content = fs::read_to_string(path).ok()?;
serde_json::from_str(&content).ok()
}
pub fn save_session_meta_file(meta: &SessionMetaFile) -> bool {
let paths = SessionPaths::new(&meta.id);
if paths.ensure_dir().is_err() {
return false;
}
match serde_json::to_string_pretty(meta) {
Ok(json) => fs::write(paths.meta_file(), json).is_ok(),
Err(_) => false,
}
}
fn derive_session_meta_from_transcript(session_id: &str) -> Option<SessionMetaFile> {
let paths = SessionPaths::new(session_id);
let transcript = paths.transcript();
let content = fs::read_to_string(&transcript).ok()?;
let mut message_count: usize = 0;
let mut first_user_preview: Option<String> = None;
for line in content.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
if let Ok(event) = serde_json::from_str::<SessionEvent>(line) {
match event {
SessionEvent::Msg {
message: ref msg, ..
} => {
message_count += 1;
if first_user_preview.is_none() && msg.role == "user" && !msg.content.is_empty()
{
first_user_preview =
Some(msg.content.chars().take(MESSAGE_PREVIEW_MAX_LEN).collect());
}
}
SessionEvent::Clear => {
message_count = 0;
first_user_preview = None;
}
SessionEvent::Restore { ref messages } => {
message_count = messages.len();
first_user_preview = messages
.iter()
.find(|m| m.role == "user" && !m.content.is_empty())
.map(|m| m.content.chars().take(MESSAGE_PREVIEW_MAX_LEN).collect());
}
}
}
}
let updated_at = transcript
.metadata()
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.map(|d| d.as_secs())
.unwrap_or(0);
Some(SessionMetaFile {
id: session_id.to_string(),
title: first_user_preview.clone().unwrap_or_default(),
message_count,
created_at: updated_at,
updated_at,
model: None,
})
}
pub fn list_sessions() -> Vec<SessionMeta> {
let dir = sessions_dir();
let read_dir = match fs::read_dir(&dir) {
Ok(rd) => rd,
Err(_) => return Vec::new(),
};
let mut ids: Vec<String> = Vec::new();
for entry in read_dir.flatten() {
let path = entry.path();
if !entry.file_type().is_ok_and(|ft| ft.is_dir()) {
continue;
}
let Some(id) = path.file_name().and_then(|s| s.to_str()) else {
continue;
};
if path.join("transcript.jsonl").exists() {
ids.push(id.to_string());
}
}
let mut sessions: Vec<SessionMeta> = Vec::new();
for id in ids {
if let Some(meta_file) = load_session_meta_file(&id) {
sessions.push(SessionMeta {
id: meta_file.id,
title: if meta_file.title.is_empty() {
None
} else {
Some(meta_file.title)
},
message_count: meta_file.message_count,
first_message_preview: None,
updated_at: meta_file.updated_at,
});
continue;
}
if let Some(derived) = derive_session_meta_from_transcript(&id) {
let title = if derived.title.is_empty() {
None
} else {
Some(derived.title.clone())
};
let preview_for_ui = title.clone();
let _ = save_session_meta_file(&derived);
sessions.push(SessionMeta {
id: derived.id,
title,
message_count: derived.message_count,
first_message_preview: preview_for_ui,
updated_at: derived.updated_at,
});
}
}
sessions.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
sessions
}
pub fn generate_session_id() -> String {
let ts = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_micros();
let pid = std::process::id();
format!("{:x}-{:x}", ts, pid)
}
pub fn delete_session(session_id: &str) -> bool {
let paths = SessionPaths::new(session_id);
let dir = paths.dir().to_path_buf();
if dir.exists()
&& let Err(e) = fs::remove_dir_all(&dir)
{
error!("✖️ 删除 session 目录失败: {}", e);
return false;
}
true
}