Vendor Codex and land Phase 1 Epiphany state slice
This commit is contained in:
parent
130e074c69
commit
2042687e30
3959 changed files with 953751 additions and 7 deletions
36
vendor/codex/codex-rs/thread-store/src/error.rs
vendored
Normal file
36
vendor/codex/codex-rs/thread-store/src/error.rs
vendored
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
use codex_protocol::ThreadId;
|
||||
|
||||
/// Result type returned by thread-store operations.
|
||||
pub type ThreadStoreResult<T> = Result<T, ThreadStoreError>;
|
||||
|
||||
/// Error type shared by thread-store implementations.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ThreadStoreError {
|
||||
/// The requested thread does not exist in this store.
|
||||
#[error("thread {thread_id} not found")]
|
||||
ThreadNotFound {
|
||||
/// Thread id requested by the caller.
|
||||
thread_id: ThreadId,
|
||||
},
|
||||
|
||||
/// The caller supplied invalid request data.
|
||||
#[error("invalid thread-store request: {message}")]
|
||||
InvalidRequest {
|
||||
/// User-facing explanation of the invalid request.
|
||||
message: String,
|
||||
},
|
||||
|
||||
/// The operation conflicted with current store state.
|
||||
#[error("thread-store conflict: {message}")]
|
||||
Conflict {
|
||||
/// User-facing explanation of the conflict.
|
||||
message: String,
|
||||
},
|
||||
|
||||
/// Catch-all for implementation failures that do not fit a more specific category.
|
||||
#[error("thread-store internal error: {message}")]
|
||||
Internal {
|
||||
/// User-facing explanation of the implementation failure.
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
36
vendor/codex/codex-rs/thread-store/src/lib.rs
vendored
Normal file
36
vendor/codex/codex-rs/thread-store/src/lib.rs
vendored
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
//! Storage-neutral thread persistence interfaces.
|
||||
//!
|
||||
//! Application code should treat [`codex_protocol::ThreadId`] as the only durable thread handle.
|
||||
//! Implementations are responsible for resolving that id to local rollout files, RPC requests, or
|
||||
//! any other backing store.
|
||||
|
||||
mod error;
|
||||
mod local;
|
||||
mod recorder;
|
||||
mod remote;
|
||||
mod store;
|
||||
mod types;
|
||||
|
||||
pub use error::ThreadStoreError;
|
||||
pub use error::ThreadStoreResult;
|
||||
pub use local::LocalThreadStore;
|
||||
pub use recorder::ThreadRecorder;
|
||||
pub use remote::RemoteThreadStore;
|
||||
pub use store::ThreadStore;
|
||||
pub use types::AppendThreadItemsParams;
|
||||
pub use types::ArchiveThreadParams;
|
||||
pub use types::CreateThreadParams;
|
||||
pub use types::GitInfoPatch;
|
||||
pub use types::ListThreadsParams;
|
||||
pub use types::LoadThreadHistoryParams;
|
||||
pub use types::OptionalStringPatch;
|
||||
pub use types::ReadThreadParams;
|
||||
pub use types::ResumeThreadRecorderParams;
|
||||
pub use types::SortDirection;
|
||||
pub use types::StoredThread;
|
||||
pub use types::StoredThreadHistory;
|
||||
pub use types::ThreadEventPersistenceMode;
|
||||
pub use types::ThreadMetadataPatch;
|
||||
pub use types::ThreadPage;
|
||||
pub use types::ThreadSortKey;
|
||||
pub use types::UpdateThreadMetadataParams;
|
||||
173
vendor/codex/codex-rs/thread-store/src/local/archive_thread.rs
vendored
Normal file
173
vendor/codex/codex-rs/thread-store/src/local/archive_thread.rs
vendored
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
use chrono::Utc;
|
||||
use codex_rollout::find_thread_path_by_id_str;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::helpers::matching_rollout_file_name;
|
||||
use super::helpers::scoped_rollout_path;
|
||||
use crate::ArchiveThreadParams;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(super) async fn archive_thread(
|
||||
store: &LocalThreadStore,
|
||||
params: ArchiveThreadParams,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let thread_id = params.thread_id;
|
||||
let rollout_path =
|
||||
find_thread_path_by_id_str(store.config.codex_home.as_path(), &thread_id.to_string())
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::InvalidRequest {
|
||||
message: format!("failed to locate thread id {thread_id}: {err}"),
|
||||
})?
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: format!("no rollout found for thread id {thread_id}"),
|
||||
})?;
|
||||
|
||||
let canonical_rollout_path = scoped_rollout_path(
|
||||
store.config.codex_home.join(codex_rollout::SESSIONS_SUBDIR),
|
||||
rollout_path.as_path(),
|
||||
"sessions",
|
||||
)?;
|
||||
let file_name = matching_rollout_file_name(
|
||||
canonical_rollout_path.as_path(),
|
||||
thread_id,
|
||||
rollout_path.as_path(),
|
||||
)?;
|
||||
|
||||
let archive_folder = store
|
||||
.config
|
||||
.codex_home
|
||||
.join(codex_rollout::ARCHIVED_SESSIONS_SUBDIR);
|
||||
std::fs::create_dir_all(&archive_folder).map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to archive thread: {err}"),
|
||||
})?;
|
||||
let archived_path = archive_folder.join(&file_name);
|
||||
std::fs::rename(&canonical_rollout_path, &archived_path).map_err(|err| {
|
||||
ThreadStoreError::Internal {
|
||||
message: format!("failed to archive thread: {err}"),
|
||||
}
|
||||
})?;
|
||||
|
||||
if let Some(ctx) = codex_rollout::state_db::get_state_db(&store.config).await {
|
||||
let _ = ctx
|
||||
.mark_archived(thread_id, archived_path.as_path(), Utc::now())
|
||||
.await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_rollout::ARCHIVED_SESSIONS_SUBDIR;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
use crate::ListThreadsParams;
|
||||
use crate::ThreadSortKey;
|
||||
use crate::ThreadStore;
|
||||
use crate::local::LocalThreadStore;
|
||||
use crate::local::test_support::test_config;
|
||||
use crate::local::test_support::write_session_file;
|
||||
|
||||
#[tokio::test]
|
||||
async fn archive_thread_moves_rollout_to_archived_collection() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let uuid = Uuid::from_u128(201);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let active_path =
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file");
|
||||
|
||||
store
|
||||
.archive_thread(ArchiveThreadParams { thread_id })
|
||||
.await
|
||||
.expect("archive thread");
|
||||
|
||||
assert!(!active_path.exists());
|
||||
let archived_path = home
|
||||
.path()
|
||||
.join(ARCHIVED_SESSIONS_SUBDIR)
|
||||
.join(active_path.file_name().expect("file name"));
|
||||
assert!(archived_path.exists());
|
||||
|
||||
let archived = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: crate::SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
archived: true,
|
||||
search_term: None,
|
||||
use_state_db_only: false,
|
||||
})
|
||||
.await
|
||||
.expect("archived listing");
|
||||
assert_eq!(archived.items.len(), 1);
|
||||
assert_eq!(archived.items[0].thread_id, thread_id);
|
||||
assert_eq!(archived.items[0].rollout_path, Some(archived_path));
|
||||
assert_eq!(
|
||||
archived.items[0].archived_at,
|
||||
Some(archived.items[0].updated_at)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn archive_thread_updates_sqlite_metadata_when_present() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let store = LocalThreadStore::new(config.clone());
|
||||
let uuid = Uuid::from_u128(202);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let active_path =
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file");
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
home.path().to_path_buf(),
|
||||
config.model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
runtime
|
||||
.mark_backfill_complete(/*last_watermark*/ None)
|
||||
.await
|
||||
.expect("backfill should be complete");
|
||||
let mut builder = codex_state::ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
active_path.clone(),
|
||||
Utc::now(),
|
||||
SessionSource::Cli,
|
||||
);
|
||||
builder.model_provider = Some(config.model_provider_id.clone());
|
||||
builder.cwd = home.path().to_path_buf();
|
||||
builder.cli_version = Some("test_version".to_string());
|
||||
let metadata = builder.build(config.model_provider_id.as_str());
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("state db upsert should succeed");
|
||||
|
||||
store
|
||||
.archive_thread(ArchiveThreadParams { thread_id })
|
||||
.await
|
||||
.expect("archive thread");
|
||||
|
||||
let archived_path = home
|
||||
.path()
|
||||
.join(ARCHIVED_SESSIONS_SUBDIR)
|
||||
.join(active_path.file_name().expect("file name"));
|
||||
let updated = runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("state db read should succeed")
|
||||
.expect("thread metadata should exist");
|
||||
assert_eq!(updated.rollout_path, archived_path);
|
||||
assert!(updated.archived_at.is_some());
|
||||
}
|
||||
}
|
||||
168
vendor/codex/codex-rs/thread-store/src/local/helpers.rs
vendored
Normal file
168
vendor/codex/codex-rs/thread-store/src/local/helpers.rs
vendored
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
use std::ffi::OsStr;
|
||||
use std::fs::FileTimes;
|
||||
use std::fs::OpenOptions;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_git_utils::GitSha;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::GitInfo;
|
||||
use codex_protocol::protocol::SandboxPolicy;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_rollout::ThreadItem;
|
||||
|
||||
use crate::StoredThread;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(super) fn scoped_rollout_path(
|
||||
root: PathBuf,
|
||||
rollout_path: &Path,
|
||||
root_name: &str,
|
||||
) -> ThreadStoreResult<PathBuf> {
|
||||
let canonical_root =
|
||||
std::fs::canonicalize(&root).map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to resolve {root_name} directory `{}`: {err}",
|
||||
root.display()
|
||||
),
|
||||
})?;
|
||||
let canonical_rollout_path =
|
||||
std::fs::canonicalize(rollout_path).map_err(|_| ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"rollout path `{}` must be in {root_name} directory",
|
||||
rollout_path.display()
|
||||
),
|
||||
})?;
|
||||
if canonical_rollout_path.starts_with(&canonical_root) {
|
||||
Ok(canonical_rollout_path)
|
||||
} else {
|
||||
Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"rollout path `{}` must be in {root_name} directory",
|
||||
rollout_path.display()
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn matching_rollout_file_name(
|
||||
rollout_path: &Path,
|
||||
thread_id: ThreadId,
|
||||
display_path: &Path,
|
||||
) -> ThreadStoreResult<std::ffi::OsString> {
|
||||
let Some(file_name) = rollout_path.file_name().map(OsStr::to_owned) else {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"rollout path `{}` missing file name",
|
||||
display_path.display()
|
||||
),
|
||||
});
|
||||
};
|
||||
let required_suffix = format!("{thread_id}.jsonl");
|
||||
if file_name
|
||||
.to_string_lossy()
|
||||
.ends_with(required_suffix.as_str())
|
||||
{
|
||||
Ok(file_name)
|
||||
} else {
|
||||
Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"rollout path `{}` does not match thread id {thread_id}",
|
||||
display_path.display()
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn touch_modified_time(path: &Path) -> std::io::Result<()> {
|
||||
let times = FileTimes::new().set_modified(SystemTime::now());
|
||||
OpenOptions::new().append(true).open(path)?.set_times(times)
|
||||
}
|
||||
|
||||
pub(super) fn stored_thread_from_rollout_item(
|
||||
item: ThreadItem,
|
||||
archived: bool,
|
||||
default_provider: &str,
|
||||
) -> Option<StoredThread> {
|
||||
let thread_id = item
|
||||
.thread_id
|
||||
.or_else(|| thread_id_from_rollout_path(item.path.as_path()))?;
|
||||
let created_at = parse_rfc3339(item.created_at.as_deref()).unwrap_or_else(Utc::now);
|
||||
let updated_at = parse_rfc3339(item.updated_at.as_deref()).unwrap_or(created_at);
|
||||
let archived_at = archived.then_some(updated_at);
|
||||
let git_info = git_info_from_parts(
|
||||
item.git_sha.clone(),
|
||||
item.git_branch.clone(),
|
||||
item.git_origin_url.clone(),
|
||||
);
|
||||
let source = item.source.unwrap_or(SessionSource::Unknown);
|
||||
let preview = item.first_user_message.clone().unwrap_or_default();
|
||||
|
||||
Some(StoredThread {
|
||||
thread_id,
|
||||
rollout_path: Some(item.path),
|
||||
forked_from_id: None,
|
||||
preview,
|
||||
name: None,
|
||||
model_provider: item
|
||||
.model_provider
|
||||
.filter(|provider| !provider.is_empty())
|
||||
.unwrap_or_else(|| default_provider.to_string()),
|
||||
model: None,
|
||||
reasoning_effort: None,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at,
|
||||
cwd: item.cwd.unwrap_or_default(),
|
||||
cli_version: item.cli_version.unwrap_or_default(),
|
||||
source,
|
||||
agent_nickname: item.agent_nickname,
|
||||
agent_role: item.agent_role,
|
||||
agent_path: None,
|
||||
git_info,
|
||||
approval_mode: AskForApproval::OnRequest,
|
||||
sandbox_policy: SandboxPolicy::new_read_only_policy(),
|
||||
token_usage: None,
|
||||
first_user_message: item.first_user_message,
|
||||
history: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_rfc3339(value: Option<&str>) -> Option<DateTime<Utc>> {
|
||||
DateTime::parse_from_rfc3339(value?)
|
||||
.ok()
|
||||
.map(|dt| dt.with_timezone(&Utc))
|
||||
}
|
||||
|
||||
pub(super) fn git_info_from_parts(
|
||||
sha: Option<String>,
|
||||
branch: Option<String>,
|
||||
origin_url: Option<String>,
|
||||
) -> Option<GitInfo> {
|
||||
if sha.is_none() && branch.is_none() && origin_url.is_none() {
|
||||
return None;
|
||||
}
|
||||
Some(GitInfo {
|
||||
commit_hash: sha.as_deref().map(GitSha::new),
|
||||
branch,
|
||||
repository_url: origin_url,
|
||||
})
|
||||
}
|
||||
|
||||
fn thread_id_from_rollout_path(path: &Path) -> Option<ThreadId> {
|
||||
let file_name = path.file_name()?.to_str()?;
|
||||
let stem = file_name.strip_suffix(".jsonl")?;
|
||||
if stem.len() < 37 {
|
||||
return None;
|
||||
}
|
||||
let uuid_start = stem.len().saturating_sub(36);
|
||||
if !stem[..uuid_start].ends_with('-') {
|
||||
return None;
|
||||
}
|
||||
ThreadId::from_string(&stem[uuid_start..]).ok()
|
||||
}
|
||||
382
vendor/codex/codex-rs/thread-store/src/local/list_threads.rs
vendored
Normal file
382
vendor/codex/codex-rs/thread-store/src/local/list_threads.rs
vendored
Normal file
|
|
@ -0,0 +1,382 @@
|
|||
use codex_rollout::RolloutConfig;
|
||||
use codex_rollout::RolloutRecorder;
|
||||
use codex_rollout::parse_cursor;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::helpers::stored_thread_from_rollout_item;
|
||||
use crate::ListThreadsParams;
|
||||
use crate::SortDirection;
|
||||
use crate::ThreadPage;
|
||||
use crate::ThreadSortKey;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(super) async fn list_threads(
|
||||
store: &LocalThreadStore,
|
||||
params: ListThreadsParams,
|
||||
) -> ThreadStoreResult<ThreadPage> {
|
||||
let cursor = params
|
||||
.cursor
|
||||
.as_deref()
|
||||
.map(|cursor| {
|
||||
parse_cursor(cursor).ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: format!("invalid cursor: {cursor}"),
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
let sort_key = match params.sort_key {
|
||||
ThreadSortKey::CreatedAt => codex_rollout::ThreadSortKey::CreatedAt,
|
||||
ThreadSortKey::UpdatedAt => codex_rollout::ThreadSortKey::UpdatedAt,
|
||||
};
|
||||
let sort_direction = match params.sort_direction {
|
||||
SortDirection::Asc => codex_rollout::SortDirection::Asc,
|
||||
SortDirection::Desc => codex_rollout::SortDirection::Desc,
|
||||
};
|
||||
let page = list_rollout_threads(
|
||||
&store.config,
|
||||
¶ms,
|
||||
cursor.as_ref(),
|
||||
sort_key,
|
||||
sort_direction,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let next_cursor = page
|
||||
.next_cursor
|
||||
.as_ref()
|
||||
.and_then(|cursor| serde_json::to_value(cursor).ok())
|
||||
.and_then(|value| value.as_str().map(str::to_owned));
|
||||
let items = page
|
||||
.items
|
||||
.into_iter()
|
||||
.filter_map(|item| {
|
||||
stored_thread_from_rollout_item(
|
||||
item,
|
||||
params.archived,
|
||||
store.config.model_provider_id.as_str(),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok(ThreadPage { items, next_cursor })
|
||||
}
|
||||
|
||||
async fn list_rollout_threads(
|
||||
config: &RolloutConfig,
|
||||
params: &ListThreadsParams,
|
||||
cursor: Option<&codex_rollout::Cursor>,
|
||||
sort_key: codex_rollout::ThreadSortKey,
|
||||
sort_direction: codex_rollout::SortDirection,
|
||||
) -> ThreadStoreResult<codex_rollout::ThreadsPage> {
|
||||
let page = if params.use_state_db_only && params.archived {
|
||||
RolloutRecorder::list_archived_threads_from_state_db(
|
||||
config,
|
||||
params.page_size,
|
||||
cursor,
|
||||
sort_key,
|
||||
sort_direction,
|
||||
params.allowed_sources.as_slice(),
|
||||
params.model_providers.as_deref(),
|
||||
params.cwd_filters.as_deref(),
|
||||
config.model_provider_id.as_str(),
|
||||
params.search_term.as_deref(),
|
||||
)
|
||||
.await
|
||||
} else if params.use_state_db_only {
|
||||
RolloutRecorder::list_threads_from_state_db(
|
||||
config,
|
||||
params.page_size,
|
||||
cursor,
|
||||
sort_key,
|
||||
sort_direction,
|
||||
params.allowed_sources.as_slice(),
|
||||
params.model_providers.as_deref(),
|
||||
params.cwd_filters.as_deref(),
|
||||
config.model_provider_id.as_str(),
|
||||
params.search_term.as_deref(),
|
||||
)
|
||||
.await
|
||||
} else if params.archived {
|
||||
RolloutRecorder::list_archived_threads(
|
||||
config,
|
||||
params.page_size,
|
||||
cursor,
|
||||
sort_key,
|
||||
sort_direction,
|
||||
params.allowed_sources.as_slice(),
|
||||
params.model_providers.as_deref(),
|
||||
params.cwd_filters.as_deref(),
|
||||
config.model_provider_id.as_str(),
|
||||
params.search_term.as_deref(),
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
RolloutRecorder::list_threads(
|
||||
config,
|
||||
params.page_size,
|
||||
cursor,
|
||||
sort_key,
|
||||
sort_direction,
|
||||
params.allowed_sources.as_slice(),
|
||||
params.model_providers.as_deref(),
|
||||
params.cwd_filters.as_deref(),
|
||||
config.model_provider_id.as_str(),
|
||||
params.search_term.as_deref(),
|
||||
)
|
||||
.await
|
||||
};
|
||||
page.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to list threads: {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
use crate::ThreadStore;
|
||||
use crate::local::LocalThreadStore;
|
||||
use crate::local::test_support::test_config;
|
||||
use crate::local::test_support::write_archived_session_file;
|
||||
use crate::local::test_support::write_session_file;
|
||||
use crate::local::test_support::write_session_file_with;
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_threads_uses_default_provider_when_rollout_omits_provider() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
write_session_file_with(
|
||||
home.path(),
|
||||
home.path().join("sessions/2025/01/03"),
|
||||
"2025-01-03T12-00-00",
|
||||
Uuid::from_u128(102),
|
||||
"Hello from user",
|
||||
/*model_provider*/ None,
|
||||
)
|
||||
.expect("session file");
|
||||
|
||||
let page = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
archived: false,
|
||||
search_term: None,
|
||||
use_state_db_only: false,
|
||||
})
|
||||
.await
|
||||
.expect("thread listing");
|
||||
|
||||
assert_eq!(page.items.len(), 1);
|
||||
assert_eq!(page.items[0].model_provider, "test-provider");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_threads_preserves_sqlite_title_search_results() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let store = LocalThreadStore::new(config.clone());
|
||||
let uuid = Uuid::from_u128(103);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let rollout_path = home.path().join("rollout-title-search.jsonl");
|
||||
fs::write(&rollout_path, "").expect("placeholder rollout file");
|
||||
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
home.path().to_path_buf(),
|
||||
config.model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
runtime
|
||||
.mark_backfill_complete(/*last_watermark*/ None)
|
||||
.await
|
||||
.expect("backfill should be complete");
|
||||
let created_at = Utc::now();
|
||||
let mut builder = codex_state::ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
rollout_path,
|
||||
created_at,
|
||||
SessionSource::Cli,
|
||||
);
|
||||
builder.model_provider = Some(config.model_provider_id.clone());
|
||||
builder.cwd = home.path().to_path_buf();
|
||||
builder.cli_version = Some("test_version".to_string());
|
||||
let mut metadata = builder.build(config.model_provider_id.as_str());
|
||||
metadata.title = "needle title".to_string();
|
||||
metadata.first_user_message = Some("plain preview".to_string());
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("state db upsert should succeed");
|
||||
|
||||
let page = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
archived: false,
|
||||
search_term: Some("needle".to_string()),
|
||||
use_state_db_only: true,
|
||||
})
|
||||
.await
|
||||
.expect("thread listing");
|
||||
|
||||
let ids = page
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| item.thread_id)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(ids, vec![thread_id]);
|
||||
assert_eq!(
|
||||
page.items[0].first_user_message.as_deref(),
|
||||
Some("plain preview")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_threads_selects_active_or_archived_collection() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let active_uuid = Uuid::from_u128(105);
|
||||
let archived_uuid = Uuid::from_u128(106);
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", active_uuid)
|
||||
.expect("active session file");
|
||||
write_archived_session_file(home.path(), "2025-01-03T13-00-00", archived_uuid)
|
||||
.expect("archived session file");
|
||||
|
||||
let active = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
archived: false,
|
||||
search_term: None,
|
||||
use_state_db_only: false,
|
||||
})
|
||||
.await
|
||||
.expect("active listing");
|
||||
let archived = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
archived: true,
|
||||
search_term: None,
|
||||
use_state_db_only: false,
|
||||
})
|
||||
.await
|
||||
.expect("archived listing");
|
||||
|
||||
let active_id = ThreadId::from_string(&active_uuid.to_string()).expect("valid thread id");
|
||||
let archived_id =
|
||||
ThreadId::from_string(&archived_uuid.to_string()).expect("valid thread id");
|
||||
assert_eq!(
|
||||
active
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| item.thread_id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![active_id]
|
||||
);
|
||||
assert_eq!(
|
||||
archived
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| item.thread_id)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![archived_id]
|
||||
);
|
||||
assert_eq!(active.items[0].archived_at, None);
|
||||
assert_eq!(
|
||||
archived.items[0].archived_at,
|
||||
Some(archived.items[0].updated_at)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_threads_returns_local_rollout_summary() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let store = LocalThreadStore::new(config);
|
||||
let uuid = Uuid::from_u128(101);
|
||||
let path =
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file");
|
||||
|
||||
let page = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: None,
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: vec![SessionSource::Cli],
|
||||
model_providers: Some(vec!["test-provider".to_string()]),
|
||||
cwd_filters: None,
|
||||
archived: false,
|
||||
search_term: None,
|
||||
use_state_db_only: false,
|
||||
})
|
||||
.await
|
||||
.expect("thread listing");
|
||||
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
assert_eq!(page.next_cursor, None);
|
||||
assert_eq!(page.items.len(), 1);
|
||||
assert_eq!(page.items[0].thread_id, thread_id);
|
||||
assert_eq!(page.items[0].rollout_path, Some(path));
|
||||
assert_eq!(page.items[0].preview, "Hello from user");
|
||||
assert_eq!(
|
||||
page.items[0].first_user_message.as_deref(),
|
||||
Some("Hello from user")
|
||||
);
|
||||
assert_eq!(page.items[0].model_provider, "test-provider");
|
||||
assert_eq!(page.items[0].cli_version, "test_version");
|
||||
assert_eq!(page.items[0].source, SessionSource::Cli);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_threads_rejects_invalid_cursor() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
|
||||
let err = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 10,
|
||||
cursor: Some("not-a-cursor".to_string()),
|
||||
sort_key: ThreadSortKey::CreatedAt,
|
||||
sort_direction: SortDirection::Desc,
|
||||
allowed_sources: Vec::new(),
|
||||
model_providers: None,
|
||||
cwd_filters: None,
|
||||
archived: false,
|
||||
search_term: None,
|
||||
use_state_db_only: false,
|
||||
})
|
||||
.await
|
||||
.expect_err("invalid cursor should fail");
|
||||
|
||||
assert!(matches!(err, ThreadStoreError::InvalidRequest { .. }));
|
||||
}
|
||||
}
|
||||
121
vendor/codex/codex-rs/thread-store/src/local/mod.rs
vendored
Normal file
121
vendor/codex/codex-rs/thread-store/src/local/mod.rs
vendored
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
mod archive_thread;
|
||||
mod helpers;
|
||||
mod list_threads;
|
||||
mod read_thread;
|
||||
mod unarchive_thread;
|
||||
mod update_thread_metadata;
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_support;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use codex_rollout::RolloutConfig;
|
||||
|
||||
use crate::AppendThreadItemsParams;
|
||||
use crate::ArchiveThreadParams;
|
||||
use crate::CreateThreadParams;
|
||||
use crate::ListThreadsParams;
|
||||
use crate::LoadThreadHistoryParams;
|
||||
use crate::ReadThreadParams;
|
||||
use crate::ResumeThreadRecorderParams;
|
||||
use crate::StoredThread;
|
||||
use crate::StoredThreadHistory;
|
||||
use crate::ThreadPage;
|
||||
use crate::ThreadRecorder;
|
||||
use crate::ThreadStore;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
use crate::UpdateThreadMetadataParams;
|
||||
|
||||
/// Local filesystem/SQLite-backed implementation of [`ThreadStore`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LocalThreadStore {
|
||||
pub(super) config: RolloutConfig,
|
||||
}
|
||||
|
||||
impl LocalThreadStore {
|
||||
/// Create a local store from the rollout configuration used by existing local persistence.
|
||||
pub fn new(config: RolloutConfig) -> Self {
|
||||
Self { config }
|
||||
}
|
||||
|
||||
/// Read a local rollout-backed thread by path.
|
||||
pub async fn read_thread_by_rollout_path(
|
||||
&self,
|
||||
rollout_path: std::path::PathBuf,
|
||||
include_archived: bool,
|
||||
include_history: bool,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
read_thread::read_thread_by_rollout_path(
|
||||
self,
|
||||
rollout_path,
|
||||
include_archived,
|
||||
include_history,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ThreadStore for LocalThreadStore {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
async fn create_thread(
|
||||
&self,
|
||||
_params: CreateThreadParams,
|
||||
) -> ThreadStoreResult<Box<dyn ThreadRecorder>> {
|
||||
unsupported("create_thread")
|
||||
}
|
||||
|
||||
async fn resume_thread_recorder(
|
||||
&self,
|
||||
_params: ResumeThreadRecorderParams,
|
||||
) -> ThreadStoreResult<Box<dyn ThreadRecorder>> {
|
||||
unsupported("resume_thread_recorder")
|
||||
}
|
||||
|
||||
async fn append_items(&self, _params: AppendThreadItemsParams) -> ThreadStoreResult<()> {
|
||||
unsupported("append_items")
|
||||
}
|
||||
|
||||
async fn load_history(
|
||||
&self,
|
||||
_params: LoadThreadHistoryParams,
|
||||
) -> ThreadStoreResult<StoredThreadHistory> {
|
||||
unsupported("load_history")
|
||||
}
|
||||
|
||||
async fn read_thread(&self, params: ReadThreadParams) -> ThreadStoreResult<StoredThread> {
|
||||
read_thread::read_thread(self, params).await
|
||||
}
|
||||
|
||||
async fn list_threads(&self, params: ListThreadsParams) -> ThreadStoreResult<ThreadPage> {
|
||||
list_threads::list_threads(self, params).await
|
||||
}
|
||||
|
||||
async fn update_thread_metadata(
|
||||
&self,
|
||||
params: UpdateThreadMetadataParams,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
update_thread_metadata::update_thread_metadata(self, params).await
|
||||
}
|
||||
|
||||
async fn archive_thread(&self, params: ArchiveThreadParams) -> ThreadStoreResult<()> {
|
||||
archive_thread::archive_thread(self, params).await
|
||||
}
|
||||
|
||||
async fn unarchive_thread(
|
||||
&self,
|
||||
params: ArchiveThreadParams,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
unarchive_thread::unarchive_thread(self, params).await
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported<T>(operation: &str) -> ThreadStoreResult<T> {
|
||||
Err(ThreadStoreError::Internal {
|
||||
message: format!("local thread store does not implement {operation} in this slice"),
|
||||
})
|
||||
}
|
||||
882
vendor/codex/codex-rs/thread-store/src/local/read_thread.rs
vendored
Normal file
882
vendor/codex/codex-rs/thread-store/src/local/read_thread.rs
vendored
Normal file
|
|
@ -0,0 +1,882 @@
|
|||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::SandboxPolicy;
|
||||
use codex_protocol::protocol::SessionMetaLine;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_rollout::RolloutRecorder;
|
||||
use codex_rollout::find_archived_thread_path_by_id_str;
|
||||
use codex_rollout::find_thread_name_by_id;
|
||||
use codex_rollout::find_thread_path_by_id_str;
|
||||
use codex_rollout::read_session_meta_line;
|
||||
use codex_rollout::read_thread_item_from_rollout;
|
||||
use codex_state::StateRuntime;
|
||||
use codex_state::ThreadMetadata;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::helpers::git_info_from_parts;
|
||||
use super::helpers::stored_thread_from_rollout_item;
|
||||
use crate::ReadThreadParams;
|
||||
use crate::StoredThread;
|
||||
use crate::StoredThreadHistory;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(super) async fn read_thread(
|
||||
store: &LocalThreadStore,
|
||||
params: ReadThreadParams,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
let thread_id = params.thread_id;
|
||||
if let Some(metadata) = read_sqlite_metadata(store, thread_id).await
|
||||
&& (params.include_archived || metadata.archived_at.is_none())
|
||||
{
|
||||
let mut thread = stored_thread_from_sqlite_metadata(store, metadata).await;
|
||||
attach_history_if_requested(&mut thread, params.include_history).await?;
|
||||
return Ok(thread);
|
||||
}
|
||||
|
||||
let path = resolve_rollout_path(store, thread_id, params.include_archived)
|
||||
.await?
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: format!("no rollout found for thread id {thread_id}"),
|
||||
})?;
|
||||
|
||||
let mut thread = read_thread_from_rollout_path(store, path).await?;
|
||||
attach_history_if_requested(&mut thread, params.include_history).await?;
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
pub(super) async fn read_thread_by_rollout_path(
|
||||
store: &LocalThreadStore,
|
||||
rollout_path: std::path::PathBuf,
|
||||
include_archived: bool,
|
||||
include_history: bool,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
let path = resolve_requested_rollout_path(store, rollout_path)?;
|
||||
let mut thread = read_thread_from_rollout_path(store, path).await?;
|
||||
if !include_archived && thread.archived_at.is_some() {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("thread {} is archived", thread.thread_id),
|
||||
});
|
||||
}
|
||||
attach_history_if_requested(&mut thread, include_history).await?;
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
fn resolve_requested_rollout_path(
|
||||
store: &LocalThreadStore,
|
||||
rollout_path: std::path::PathBuf,
|
||||
) -> ThreadStoreResult<std::path::PathBuf> {
|
||||
let path = if rollout_path.is_relative() {
|
||||
store.config.codex_home.join(rollout_path)
|
||||
} else {
|
||||
rollout_path
|
||||
};
|
||||
std::fs::canonicalize(&path).map_err(|err| ThreadStoreError::InvalidRequest {
|
||||
message: format!("failed to resolve rollout path `{}`: {err}", path.display()),
|
||||
})
|
||||
}
|
||||
|
||||
async fn attach_history_if_requested(
|
||||
thread: &mut StoredThread,
|
||||
include_history: bool,
|
||||
) -> ThreadStoreResult<()> {
|
||||
if !include_history {
|
||||
return Ok(());
|
||||
}
|
||||
let thread_id = thread.thread_id;
|
||||
let Some(path) = thread.rollout_path.clone() else {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!("failed to load thread history for thread {thread_id}"),
|
||||
});
|
||||
};
|
||||
let items = load_history_items(&path).await?;
|
||||
thread.history = Some(StoredThreadHistory { thread_id, items });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn resolve_rollout_path(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: codex_protocol::ThreadId,
|
||||
include_archived: bool,
|
||||
) -> ThreadStoreResult<Option<std::path::PathBuf>> {
|
||||
if include_archived {
|
||||
match find_thread_path_by_id_str(store.config.codex_home.as_path(), &thread_id.to_string())
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::InvalidRequest {
|
||||
message: format!("failed to locate thread id {thread_id}: {err}"),
|
||||
})? {
|
||||
Some(path) => Ok(Some(path)),
|
||||
None => find_archived_thread_path_by_id_str(
|
||||
store.config.codex_home.as_path(),
|
||||
&thread_id.to_string(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::InvalidRequest {
|
||||
message: format!("failed to locate archived thread id {thread_id}: {err}"),
|
||||
}),
|
||||
}
|
||||
} else {
|
||||
find_thread_path_by_id_str(store.config.codex_home.as_path(), &thread_id.to_string())
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::InvalidRequest {
|
||||
message: format!("failed to locate thread id {thread_id}: {err}"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_thread_from_rollout_path(
|
||||
store: &LocalThreadStore,
|
||||
path: std::path::PathBuf,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
let Some(item) = read_thread_item_from_rollout(path.clone()).await else {
|
||||
return stored_thread_from_session_meta(store, path).await;
|
||||
};
|
||||
let archived = path.starts_with(
|
||||
store
|
||||
.config
|
||||
.codex_home
|
||||
.join(codex_rollout::ARCHIVED_SESSIONS_SUBDIR),
|
||||
);
|
||||
let mut thread =
|
||||
stored_thread_from_rollout_item(item, archived, store.config.model_provider_id.as_str())
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: format!("failed to read thread id from {}", path.display()),
|
||||
})?;
|
||||
thread.forked_from_id = read_session_meta_line(path.as_path())
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|meta_line| meta_line.meta.forked_from_id);
|
||||
if let Ok(Some(title)) =
|
||||
find_thread_name_by_id(store.config.codex_home.as_path(), &thread.thread_id).await
|
||||
{
|
||||
set_thread_name_from_title(&mut thread, title);
|
||||
}
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
async fn load_history_items(
|
||||
path: &std::path::Path,
|
||||
) -> ThreadStoreResult<Vec<codex_protocol::protocol::RolloutItem>> {
|
||||
let (items, _, _) = RolloutRecorder::load_rollout_items(path)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to load thread history {}: {err}", path.display()),
|
||||
})?;
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
async fn read_sqlite_metadata(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: codex_protocol::ThreadId,
|
||||
) -> Option<ThreadMetadata> {
|
||||
let runtime = StateRuntime::init(
|
||||
store.config.sqlite_home.clone(),
|
||||
store.config.model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.ok()?;
|
||||
runtime.get_thread(thread_id).await.ok().flatten()
|
||||
}
|
||||
|
||||
async fn stored_thread_from_sqlite_metadata(
|
||||
store: &LocalThreadStore,
|
||||
metadata: ThreadMetadata,
|
||||
) -> StoredThread {
|
||||
let name = match distinct_title(&metadata) {
|
||||
Some(title) => Some(title),
|
||||
None => find_thread_name_by_id(store.config.codex_home.as_path(), &metadata.id)
|
||||
.await
|
||||
.ok()
|
||||
.flatten(),
|
||||
};
|
||||
let forked_from_id = read_session_meta_line(metadata.rollout_path.as_path())
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|meta_line| meta_line.meta.forked_from_id);
|
||||
StoredThread {
|
||||
thread_id: metadata.id,
|
||||
rollout_path: Some(metadata.rollout_path),
|
||||
forked_from_id,
|
||||
preview: metadata.first_user_message.clone().unwrap_or_default(),
|
||||
name,
|
||||
model_provider: if metadata.model_provider.is_empty() {
|
||||
store.config.model_provider_id.clone()
|
||||
} else {
|
||||
metadata.model_provider
|
||||
},
|
||||
model: metadata.model,
|
||||
reasoning_effort: metadata.reasoning_effort,
|
||||
created_at: metadata.created_at,
|
||||
updated_at: metadata.updated_at,
|
||||
archived_at: metadata.archived_at,
|
||||
cwd: metadata.cwd,
|
||||
cli_version: metadata.cli_version,
|
||||
source: parse_session_source(&metadata.source),
|
||||
agent_nickname: metadata.agent_nickname,
|
||||
agent_role: metadata.agent_role,
|
||||
agent_path: metadata.agent_path,
|
||||
git_info: git_info_from_parts(
|
||||
metadata.git_sha,
|
||||
metadata.git_branch,
|
||||
metadata.git_origin_url,
|
||||
),
|
||||
approval_mode: parse_or_default(&metadata.approval_mode, AskForApproval::OnRequest),
|
||||
sandbox_policy: parse_or_default(
|
||||
&metadata.sandbox_policy,
|
||||
SandboxPolicy::new_read_only_policy(),
|
||||
),
|
||||
token_usage: None,
|
||||
first_user_message: metadata.first_user_message,
|
||||
history: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn stored_thread_from_session_meta(
|
||||
store: &LocalThreadStore,
|
||||
path: std::path::PathBuf,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
let meta_line = read_session_meta_line(path.as_path())
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to read thread {}: {err}", path.display()),
|
||||
})?;
|
||||
let archived = path.starts_with(
|
||||
store
|
||||
.config
|
||||
.codex_home
|
||||
.join(codex_rollout::ARCHIVED_SESSIONS_SUBDIR),
|
||||
);
|
||||
Ok(stored_thread_from_meta_line(
|
||||
store, meta_line, path, archived,
|
||||
))
|
||||
}
|
||||
|
||||
fn stored_thread_from_meta_line(
|
||||
store: &LocalThreadStore,
|
||||
meta_line: SessionMetaLine,
|
||||
path: std::path::PathBuf,
|
||||
archived: bool,
|
||||
) -> StoredThread {
|
||||
let created_at = parse_rfc3339_non_optional(&meta_line.meta.timestamp).unwrap_or_else(Utc::now);
|
||||
let updated_at = std::fs::metadata(path.as_path())
|
||||
.ok()
|
||||
.and_then(|meta| meta.modified().ok())
|
||||
.map(DateTime::<Utc>::from)
|
||||
.unwrap_or(created_at);
|
||||
StoredThread {
|
||||
thread_id: meta_line.meta.id,
|
||||
rollout_path: Some(path),
|
||||
forked_from_id: meta_line.meta.forked_from_id,
|
||||
preview: String::new(),
|
||||
name: None,
|
||||
model_provider: meta_line
|
||||
.meta
|
||||
.model_provider
|
||||
.filter(|provider| !provider.is_empty())
|
||||
.unwrap_or_else(|| store.config.model_provider_id.clone()),
|
||||
model: None,
|
||||
reasoning_effort: None,
|
||||
created_at,
|
||||
updated_at,
|
||||
archived_at: archived.then_some(updated_at),
|
||||
cwd: meta_line.meta.cwd,
|
||||
cli_version: meta_line.meta.cli_version,
|
||||
source: meta_line.meta.source,
|
||||
agent_nickname: meta_line.meta.agent_nickname,
|
||||
agent_role: meta_line.meta.agent_role,
|
||||
agent_path: meta_line.meta.agent_path,
|
||||
git_info: meta_line.git,
|
||||
approval_mode: AskForApproval::OnRequest,
|
||||
sandbox_policy: SandboxPolicy::new_read_only_policy(),
|
||||
token_usage: None,
|
||||
first_user_message: None,
|
||||
history: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn distinct_title(metadata: &ThreadMetadata) -> Option<String> {
|
||||
let title = metadata.title.trim();
|
||||
if title.is_empty() || metadata.first_user_message.as_deref().map(str::trim) == Some(title) {
|
||||
None
|
||||
} else {
|
||||
Some(title.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn set_thread_name_from_title(thread: &mut StoredThread, title: String) {
|
||||
if title.trim().is_empty() || thread.preview.trim() == title.trim() {
|
||||
return;
|
||||
}
|
||||
thread.name = Some(title);
|
||||
}
|
||||
|
||||
fn parse_session_source(source: &str) -> SessionSource {
|
||||
serde_json::from_str(source)
|
||||
.or_else(|_| serde_json::from_value(serde_json::Value::String(source.to_string())))
|
||||
.unwrap_or(SessionSource::Unknown)
|
||||
}
|
||||
|
||||
fn parse_or_default<T>(value: &str, default: T) -> T
|
||||
where
|
||||
T: serde::de::DeserializeOwned,
|
||||
{
|
||||
serde_json::from_str(value)
|
||||
.or_else(|_| serde_json::from_value(serde_json::Value::String(value.to_string())))
|
||||
.unwrap_or(default)
|
||||
}
|
||||
|
||||
fn parse_rfc3339_non_optional(value: &str) -> Option<DateTime<Utc>> {
|
||||
DateTime::parse_from_rfc3339(value)
|
||||
.ok()
|
||||
.map(|dt| dt.with_timezone(&Utc))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Write;
|
||||
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_state::ThreadMetadataBuilder;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
use crate::ThreadStore;
|
||||
use crate::local::LocalThreadStore;
|
||||
use crate::local::test_support::test_config;
|
||||
use crate::local::test_support::write_archived_session_file;
|
||||
use crate::local::test_support::write_session_file;
|
||||
use crate::local::test_support::write_session_file_with_fork;
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_returns_active_rollout_summary() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let uuid = Uuid::from_u128(205);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let active_path =
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file");
|
||||
|
||||
let thread = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
include_history: true,
|
||||
})
|
||||
.await
|
||||
.expect("read thread");
|
||||
|
||||
assert_eq!(thread.thread_id, thread_id);
|
||||
assert_eq!(thread.rollout_path, Some(active_path));
|
||||
assert_eq!(thread.archived_at, None);
|
||||
assert_eq!(thread.preview, "Hello from user");
|
||||
assert_eq!(
|
||||
thread.history.expect("history should load").thread_id,
|
||||
thread_id
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_returns_rollout_path_summary() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let uuid = Uuid::from_u128(211);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let active_path =
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file");
|
||||
let relative_path = active_path
|
||||
.strip_prefix(home.path())
|
||||
.expect("path should be under codex home")
|
||||
.to_path_buf();
|
||||
|
||||
let thread = store
|
||||
.read_thread_by_rollout_path(
|
||||
relative_path,
|
||||
/*include_archived*/ false,
|
||||
/*include_history*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("read thread by rollout path");
|
||||
|
||||
assert_eq!(thread.thread_id, thread_id);
|
||||
assert_eq!(
|
||||
thread.rollout_path,
|
||||
Some(std::fs::canonicalize(active_path).expect("canonical path"))
|
||||
);
|
||||
assert_eq!(thread.preview, "Hello from user");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_returns_archived_rollout_when_requested() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let uuid = Uuid::from_u128(207);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let archived_path = write_archived_session_file(home.path(), "2025-01-03T12-00-00", uuid)
|
||||
.expect("archived session file");
|
||||
|
||||
let active_only_err = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
.expect_err("active-only read should fail for archived rollout");
|
||||
let ThreadStoreError::InvalidRequest { message } = active_only_err else {
|
||||
panic!("expected invalid request error");
|
||||
};
|
||||
assert_eq!(
|
||||
message,
|
||||
format!("no rollout found for thread id {thread_id}")
|
||||
);
|
||||
|
||||
let thread = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: true,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
.expect("read archived thread");
|
||||
|
||||
assert_eq!(thread.thread_id, thread_id);
|
||||
assert_eq!(thread.rollout_path, Some(archived_path));
|
||||
assert!(thread.archived_at.is_some());
|
||||
assert_eq!(thread.preview, "Archived user message");
|
||||
assert!(thread.history.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_prefers_active_rollout_over_archived() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let uuid = Uuid::from_u128(208);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let active_path =
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file");
|
||||
write_archived_session_file(home.path(), "2025-01-03T12-00-00", uuid)
|
||||
.expect("archived session file");
|
||||
|
||||
let thread = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: true,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
.expect("read thread");
|
||||
|
||||
assert_eq!(thread.rollout_path, Some(active_path));
|
||||
assert_eq!(thread.archived_at, None);
|
||||
assert_eq!(thread.preview, "Hello from user");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_returns_forked_from_id() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let uuid = Uuid::from_u128(209);
|
||||
let parent_uuid = Uuid::from_u128(210);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let parent_thread_id =
|
||||
ThreadId::from_string(&parent_uuid.to_string()).expect("valid parent thread id");
|
||||
write_session_file_with_fork(
|
||||
home.path(),
|
||||
home.path().join("sessions/2025/01/03"),
|
||||
"2025-01-03T12-00-00",
|
||||
uuid,
|
||||
"Forked user message",
|
||||
Some("test-provider"),
|
||||
Some(parent_uuid),
|
||||
)
|
||||
.expect("forked session file");
|
||||
|
||||
let thread = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
.expect("read thread");
|
||||
|
||||
assert_eq!(thread.forked_from_id, Some(parent_thread_id));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_applies_sqlite_thread_name() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let store = LocalThreadStore::new(config.clone());
|
||||
let uuid = Uuid::from_u128(212);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let rollout_path =
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file");
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite_home.clone(),
|
||||
config.model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let mut builder =
|
||||
ThreadMetadataBuilder::new(thread_id, rollout_path, Utc::now(), SessionSource::Cli);
|
||||
builder.model_provider = Some(config.model_provider_id.clone());
|
||||
builder.cwd = home.path().to_path_buf();
|
||||
builder.cli_version = Some("test_version".to_string());
|
||||
let mut metadata = builder.build(config.model_provider_id.as_str());
|
||||
metadata.title = "Saved title".to_string();
|
||||
metadata.first_user_message = Some("Hello from user".to_string());
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("state db upsert should succeed");
|
||||
|
||||
let thread = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
.expect("read thread");
|
||||
|
||||
assert_eq!(thread.name, Some("Saved title".to_string()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_uses_legacy_thread_name_when_sqlite_title_is_missing() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let uuid = Uuid::from_u128(213);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
write_session_file(home.path(), "2025-01-03T12-00-00", uuid).expect("session file");
|
||||
codex_rollout::append_thread_name(home.path(), thread_id, "Legacy title")
|
||||
.await
|
||||
.expect("append legacy thread name");
|
||||
|
||||
let thread = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
.expect("read thread");
|
||||
|
||||
assert_eq!(thread.name, Some("Legacy title".to_string()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_uses_sqlite_metadata_for_rollout_without_user_preview() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let store = LocalThreadStore::new(config.clone());
|
||||
let uuid = Uuid::from_u128(217);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let day_dir = home.path().join("sessions/2025/01/03");
|
||||
std::fs::create_dir_all(&day_dir).expect("sessions dir");
|
||||
let rollout_path = day_dir.join(format!("rollout-2025-01-03T12-00-00-{uuid}.jsonl"));
|
||||
let mut file = std::fs::File::create(&rollout_path).expect("session file");
|
||||
let meta = serde_json::json!({
|
||||
"timestamp": "2025-01-03T12-00-00",
|
||||
"type": "session_meta",
|
||||
"payload": {
|
||||
"id": uuid,
|
||||
"timestamp": "2025-01-03T12-00-00",
|
||||
"cwd": home.path(),
|
||||
"originator": "test_originator",
|
||||
"cli_version": "test_version",
|
||||
"source": "cli",
|
||||
"model_provider": "rollout-provider"
|
||||
},
|
||||
});
|
||||
writeln!(file, "{meta}").expect("write session meta");
|
||||
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite_home.clone(),
|
||||
config.model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let mut builder = ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
rollout_path.clone(),
|
||||
Utc::now(),
|
||||
SessionSource::Cli,
|
||||
);
|
||||
builder.model_provider = Some("sqlite-provider".to_string());
|
||||
builder.cwd = home.path().join("workspace");
|
||||
builder.cli_version = Some("sqlite-cli".to_string());
|
||||
let mut metadata = builder.build(config.model_provider_id.as_str());
|
||||
metadata.title = "Command-only thread".to_string();
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("state db upsert should succeed");
|
||||
|
||||
let thread = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
include_history: true,
|
||||
})
|
||||
.await
|
||||
.expect("read thread");
|
||||
|
||||
assert_eq!(thread.thread_id, thread_id);
|
||||
assert_eq!(thread.rollout_path, Some(rollout_path));
|
||||
assert_eq!(thread.preview, "");
|
||||
assert_eq!(thread.name.as_deref(), Some("Command-only thread"));
|
||||
assert_eq!(thread.model_provider, "sqlite-provider");
|
||||
assert_eq!(thread.cwd, home.path().join("workspace"));
|
||||
assert_eq!(thread.cli_version, "sqlite-cli");
|
||||
let history = thread.history.expect("history should load");
|
||||
assert_eq!(history.thread_id, thread_id);
|
||||
assert_eq!(history.items.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_uses_session_meta_for_rollout_without_user_preview_or_sqlite_metadata() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let uuid = Uuid::from_u128(218);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let day_dir = home.path().join("sessions/2025/01/03");
|
||||
std::fs::create_dir_all(&day_dir).expect("sessions dir");
|
||||
let rollout_path = day_dir.join(format!("rollout-2025-01-03T12-00-00-{uuid}.jsonl"));
|
||||
let mut file = std::fs::File::create(&rollout_path).expect("session file");
|
||||
let meta = serde_json::json!({
|
||||
"timestamp": "2025-01-03T12:00:00Z",
|
||||
"type": "session_meta",
|
||||
"payload": {
|
||||
"id": uuid,
|
||||
"timestamp": "2025-01-03T12:00:00Z",
|
||||
"cwd": home.path(),
|
||||
"originator": "test_originator",
|
||||
"cli_version": "test_version",
|
||||
"source": "cli",
|
||||
"model_provider": "rollout-provider"
|
||||
},
|
||||
});
|
||||
writeln!(file, "{meta}").expect("write session meta");
|
||||
|
||||
let thread = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
include_history: true,
|
||||
})
|
||||
.await
|
||||
.expect("read thread");
|
||||
|
||||
assert_eq!(thread.thread_id, thread_id);
|
||||
assert_eq!(thread.rollout_path, Some(rollout_path));
|
||||
assert_eq!(thread.preview, "");
|
||||
assert_eq!(thread.name, None);
|
||||
assert_eq!(thread.model_provider, "rollout-provider");
|
||||
assert_eq!(
|
||||
thread.created_at,
|
||||
parse_rfc3339_non_optional("2025-01-03T12:00:00Z").unwrap()
|
||||
);
|
||||
assert!(thread.updated_at >= thread.created_at);
|
||||
assert_eq!(thread.archived_at, None);
|
||||
assert_eq!(thread.cwd, home.path());
|
||||
assert_eq!(thread.cli_version, "test_version");
|
||||
assert_eq!(thread.source, SessionSource::Cli);
|
||||
let history = thread.history.expect("history should load");
|
||||
assert_eq!(history.thread_id, thread_id);
|
||||
assert_eq!(history.items.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_falls_back_to_sqlite_summary() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let external = TempDir::new().expect("external temp dir");
|
||||
let config = test_config(home.path());
|
||||
let store = LocalThreadStore::new(config.clone());
|
||||
let uuid = Uuid::from_u128(214);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let rollout_path = external
|
||||
.path()
|
||||
.join(format!("rollout-2025-01-03T12-00-00-{uuid}.jsonl"));
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite_home.clone(),
|
||||
config.model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let mut builder = ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
rollout_path.clone(),
|
||||
Utc::now(),
|
||||
SessionSource::Exec,
|
||||
);
|
||||
builder.model_provider = Some("sqlite-provider".to_string());
|
||||
builder.cwd = external.path().join("workspace");
|
||||
builder.cli_version = Some("sqlite-cli".to_string());
|
||||
let mut metadata = builder.build(config.model_provider_id.as_str());
|
||||
metadata.title = "SQLite title".to_string();
|
||||
metadata.first_user_message = Some("SQLite preview".to_string());
|
||||
metadata.model = Some("sqlite-model".to_string());
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("state db upsert should succeed");
|
||||
|
||||
let thread = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
.expect("read thread");
|
||||
|
||||
assert_eq!(thread.thread_id, thread_id);
|
||||
assert_eq!(thread.rollout_path, Some(rollout_path));
|
||||
assert_eq!(thread.preview, "SQLite preview");
|
||||
assert_eq!(thread.first_user_message.as_deref(), Some("SQLite preview"));
|
||||
assert_eq!(thread.name.as_deref(), Some("SQLite title"));
|
||||
assert_eq!(thread.model_provider, "sqlite-provider");
|
||||
assert_eq!(thread.model.as_deref(), Some("sqlite-model"));
|
||||
assert_eq!(thread.cwd, external.path().join("workspace"));
|
||||
assert_eq!(thread.cli_version, "sqlite-cli");
|
||||
assert_eq!(thread.source, SessionSource::Exec);
|
||||
assert_eq!(thread.archived_at, None);
|
||||
assert!(thread.history.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_sqlite_fallback_respects_include_archived() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let external = TempDir::new().expect("external temp dir");
|
||||
let config = test_config(home.path());
|
||||
let store = LocalThreadStore::new(config.clone());
|
||||
let uuid = Uuid::from_u128(216);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let rollout_path = external
|
||||
.path()
|
||||
.join(format!("rollout-2025-01-03T12-00-00-{uuid}.jsonl"));
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite_home.clone(),
|
||||
config.model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let mut builder =
|
||||
ThreadMetadataBuilder::new(thread_id, rollout_path, Utc::now(), SessionSource::Cli);
|
||||
builder.archived_at = Some(Utc::now());
|
||||
let mut metadata = builder.build(config.model_provider_id.as_str());
|
||||
metadata.first_user_message = Some("Archived SQLite preview".to_string());
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("state db upsert should succeed");
|
||||
|
||||
let active_only_err = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
.expect_err("active-only read should fail for archived metadata");
|
||||
let ThreadStoreError::InvalidRequest { message } = active_only_err else {
|
||||
panic!("expected invalid request error");
|
||||
};
|
||||
assert_eq!(
|
||||
message,
|
||||
format!("no rollout found for thread id {thread_id}")
|
||||
);
|
||||
|
||||
let thread = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: true,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
.expect("read archived thread");
|
||||
|
||||
assert_eq!(thread.thread_id, thread_id);
|
||||
assert_eq!(thread.preview, "Archived SQLite preview");
|
||||
assert!(thread.archived_at.is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_sqlite_fallback_loads_archived_history() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let store = LocalThreadStore::new(config.clone());
|
||||
let uuid = Uuid::from_u128(219);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let archived_path = write_archived_session_file(home.path(), "2025-01-03T12-00-00", uuid)
|
||||
.expect("archived session file");
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
config.sqlite_home.clone(),
|
||||
config.model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
let mut builder = ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
archived_path.clone(),
|
||||
Utc::now(),
|
||||
SessionSource::Cli,
|
||||
);
|
||||
builder.archived_at = Some(Utc::now());
|
||||
let mut metadata = builder.build(config.model_provider_id.as_str());
|
||||
metadata.first_user_message = Some("Archived SQLite preview".to_string());
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("state db upsert should succeed");
|
||||
|
||||
let thread = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: true,
|
||||
include_history: true,
|
||||
})
|
||||
.await
|
||||
.expect("read archived thread");
|
||||
|
||||
assert_eq!(thread.thread_id, thread_id);
|
||||
assert_eq!(thread.rollout_path, Some(archived_path));
|
||||
assert_eq!(thread.preview, "Archived SQLite preview");
|
||||
assert!(thread.archived_at.is_some());
|
||||
let history = thread.history.expect("history should load");
|
||||
assert_eq!(history.thread_id, thread_id);
|
||||
assert_eq!(history.items.len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_fails_without_rollout() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let uuid = Uuid::from_u128(206);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
|
||||
let err = store
|
||||
.read_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: false,
|
||||
include_history: false,
|
||||
})
|
||||
.await
|
||||
.expect_err("read should fail without rollout");
|
||||
|
||||
let ThreadStoreError::InvalidRequest { message } = err else {
|
||||
panic!("expected invalid request error");
|
||||
};
|
||||
assert_eq!(
|
||||
message,
|
||||
format!("no rollout found for thread id {thread_id}")
|
||||
);
|
||||
}
|
||||
}
|
||||
108
vendor/codex/codex-rs/thread-store/src/local/test_support.rs
vendored
Normal file
108
vendor/codex/codex-rs/thread-store/src/local/test_support.rs
vendored
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_rollout::ARCHIVED_SESSIONS_SUBDIR;
|
||||
use codex_rollout::RolloutConfig;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(super) fn test_config(codex_home: &Path) -> RolloutConfig {
|
||||
RolloutConfig {
|
||||
codex_home: codex_home.to_path_buf(),
|
||||
sqlite_home: codex_home.to_path_buf(),
|
||||
cwd: codex_home.to_path_buf(),
|
||||
model_provider_id: "test-provider".to_string(),
|
||||
generate_memories: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn write_session_file(root: &Path, ts: &str, uuid: Uuid) -> std::io::Result<PathBuf> {
|
||||
write_session_file_with(
|
||||
root,
|
||||
root.join("sessions/2025/01/03"),
|
||||
ts,
|
||||
uuid,
|
||||
"Hello from user",
|
||||
Some("test-provider"),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn write_archived_session_file(
|
||||
root: &Path,
|
||||
ts: &str,
|
||||
uuid: Uuid,
|
||||
) -> std::io::Result<PathBuf> {
|
||||
write_session_file_with(
|
||||
root,
|
||||
root.join(ARCHIVED_SESSIONS_SUBDIR),
|
||||
ts,
|
||||
uuid,
|
||||
"Archived user message",
|
||||
Some("test-provider"),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn write_session_file_with(
|
||||
root: &Path,
|
||||
day_dir: PathBuf,
|
||||
ts: &str,
|
||||
uuid: Uuid,
|
||||
first_user_message: &str,
|
||||
model_provider: Option<&str>,
|
||||
) -> std::io::Result<PathBuf> {
|
||||
write_session_file_with_fork(
|
||||
root,
|
||||
day_dir,
|
||||
ts,
|
||||
uuid,
|
||||
first_user_message,
|
||||
model_provider,
|
||||
/*forked_from_id*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn write_session_file_with_fork(
|
||||
root: &Path,
|
||||
day_dir: PathBuf,
|
||||
ts: &str,
|
||||
uuid: Uuid,
|
||||
first_user_message: &str,
|
||||
model_provider: Option<&str>,
|
||||
forked_from_id: Option<Uuid>,
|
||||
) -> std::io::Result<PathBuf> {
|
||||
fs::create_dir_all(&day_dir)?;
|
||||
let path = day_dir.join(format!("rollout-{ts}-{uuid}.jsonl"));
|
||||
let mut file = fs::File::create(&path)?;
|
||||
let meta = serde_json::json!({
|
||||
"timestamp": ts,
|
||||
"type": "session_meta",
|
||||
"payload": {
|
||||
"id": uuid,
|
||||
"forked_from_id": forked_from_id,
|
||||
"timestamp": ts,
|
||||
"cwd": root,
|
||||
"originator": "test_originator",
|
||||
"cli_version": "test_version",
|
||||
"source": "cli",
|
||||
"model_provider": model_provider,
|
||||
"git": {
|
||||
"commit_hash": "abcdef",
|
||||
"branch": "main",
|
||||
"repository_url": "https://example.com/repo.git"
|
||||
}
|
||||
},
|
||||
});
|
||||
writeln!(file, "{meta}")?;
|
||||
let user_event = serde_json::json!({
|
||||
"timestamp": ts,
|
||||
"type": "event_msg",
|
||||
"payload": {
|
||||
"type": "user_message",
|
||||
"message": first_user_message,
|
||||
"kind": "plain",
|
||||
},
|
||||
});
|
||||
writeln!(file, "{user_event}")?;
|
||||
Ok(path)
|
||||
}
|
||||
198
vendor/codex/codex-rs/thread-store/src/local/unarchive_thread.rs
vendored
Normal file
198
vendor/codex/codex-rs/thread-store/src/local/unarchive_thread.rs
vendored
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
use codex_rollout::find_archived_thread_path_by_id_str;
|
||||
use codex_rollout::read_thread_item_from_rollout;
|
||||
use codex_rollout::rollout_date_parts;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use super::helpers::matching_rollout_file_name;
|
||||
use super::helpers::scoped_rollout_path;
|
||||
use super::helpers::stored_thread_from_rollout_item;
|
||||
use super::helpers::touch_modified_time;
|
||||
use crate::ArchiveThreadParams;
|
||||
use crate::StoredThread;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(super) async fn unarchive_thread(
|
||||
store: &LocalThreadStore,
|
||||
params: ArchiveThreadParams,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
let thread_id = params.thread_id;
|
||||
let archived_path = find_archived_thread_path_by_id_str(
|
||||
store.config.codex_home.as_path(),
|
||||
&thread_id.to_string(),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::InvalidRequest {
|
||||
message: format!("failed to locate archived thread id {thread_id}: {err}"),
|
||||
})?
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: format!("no archived rollout found for thread id {thread_id}"),
|
||||
})?;
|
||||
|
||||
let canonical_archived_path = scoped_rollout_path(
|
||||
store
|
||||
.config
|
||||
.codex_home
|
||||
.join(codex_rollout::ARCHIVED_SESSIONS_SUBDIR),
|
||||
archived_path.as_path(),
|
||||
"archived",
|
||||
)?;
|
||||
let file_name = matching_rollout_file_name(
|
||||
canonical_archived_path.as_path(),
|
||||
thread_id,
|
||||
archived_path.as_path(),
|
||||
)?;
|
||||
let Some((year, month, day)) = rollout_date_parts(&file_name) else {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"rollout path `{}` missing filename timestamp",
|
||||
archived_path.display()
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
let dest_dir = store
|
||||
.config
|
||||
.codex_home
|
||||
.join(codex_rollout::SESSIONS_SUBDIR)
|
||||
.join(year)
|
||||
.join(month)
|
||||
.join(day);
|
||||
std::fs::create_dir_all(&dest_dir).map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to unarchive thread: {err}"),
|
||||
})?;
|
||||
let restored_path = dest_dir.join(&file_name);
|
||||
std::fs::rename(&canonical_archived_path, &restored_path).map_err(|err| {
|
||||
ThreadStoreError::Internal {
|
||||
message: format!("failed to unarchive thread: {err}"),
|
||||
}
|
||||
})?;
|
||||
touch_modified_time(restored_path.as_path()).map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to update unarchived thread timestamp: {err}"),
|
||||
})?;
|
||||
|
||||
if let Some(ctx) = codex_rollout::state_db::get_state_db(&store.config).await {
|
||||
let _ = ctx
|
||||
.mark_unarchived(thread_id, restored_path.as_path())
|
||||
.await;
|
||||
}
|
||||
|
||||
let item = read_thread_item_from_rollout(restored_path.clone())
|
||||
.await
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to read unarchived thread {}",
|
||||
restored_path.display()
|
||||
),
|
||||
})?;
|
||||
stored_thread_from_rollout_item(
|
||||
item,
|
||||
/*archived*/ false,
|
||||
store.config.model_provider_id.as_str(),
|
||||
)
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to read unarchived thread id from {}",
|
||||
restored_path.display()
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
use crate::ThreadStore;
|
||||
use crate::local::LocalThreadStore;
|
||||
use crate::local::test_support::test_config;
|
||||
use crate::local::test_support::write_archived_session_file;
|
||||
|
||||
#[tokio::test]
|
||||
async fn unarchive_thread_restores_rollout_and_returns_updated_thread() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let uuid = Uuid::from_u128(203);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let archived_path = write_archived_session_file(home.path(), "2025-01-03T13-00-00", uuid)
|
||||
.expect("archived session file");
|
||||
|
||||
let thread = store
|
||||
.unarchive_thread(ArchiveThreadParams { thread_id })
|
||||
.await
|
||||
.expect("unarchive thread");
|
||||
|
||||
assert!(!archived_path.exists());
|
||||
let restored_path = home
|
||||
.path()
|
||||
.join("sessions/2025/01/03")
|
||||
.join(archived_path.file_name().expect("file name"));
|
||||
assert!(restored_path.exists());
|
||||
assert_eq!(thread.thread_id, thread_id);
|
||||
assert_eq!(thread.rollout_path, Some(restored_path));
|
||||
assert_eq!(thread.archived_at, None);
|
||||
assert_eq!(thread.preview, "Archived user message");
|
||||
assert_eq!(
|
||||
thread.first_user_message.as_deref(),
|
||||
Some("Archived user message")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unarchive_thread_updates_sqlite_metadata_when_present() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let store = LocalThreadStore::new(config.clone());
|
||||
let uuid = Uuid::from_u128(204);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let archived_path = write_archived_session_file(home.path(), "2025-01-03T13-00-00", uuid)
|
||||
.expect("archived session file");
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
home.path().to_path_buf(),
|
||||
config.model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
runtime
|
||||
.mark_backfill_complete(/*last_watermark*/ None)
|
||||
.await
|
||||
.expect("backfill should be complete");
|
||||
let mut builder = codex_state::ThreadMetadataBuilder::new(
|
||||
thread_id,
|
||||
archived_path.clone(),
|
||||
Utc::now(),
|
||||
SessionSource::Cli,
|
||||
);
|
||||
builder.model_provider = Some(config.model_provider_id.clone());
|
||||
builder.cwd = home.path().to_path_buf();
|
||||
builder.cli_version = Some("test_version".to_string());
|
||||
let mut metadata = builder.build(config.model_provider_id.as_str());
|
||||
metadata.archived_at = Some(metadata.updated_at);
|
||||
runtime
|
||||
.upsert_thread(&metadata)
|
||||
.await
|
||||
.expect("state db upsert should succeed");
|
||||
|
||||
store
|
||||
.unarchive_thread(ArchiveThreadParams { thread_id })
|
||||
.await
|
||||
.expect("unarchive thread");
|
||||
|
||||
let restored_path = home
|
||||
.path()
|
||||
.join("sessions/2025/01/03")
|
||||
.join(archived_path.file_name().expect("file name"));
|
||||
let updated = runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("state db read should succeed")
|
||||
.expect("thread metadata should exist");
|
||||
assert_eq!(updated.rollout_path, restored_path);
|
||||
assert_eq!(updated.archived_at, None);
|
||||
}
|
||||
}
|
||||
397
vendor/codex/codex-rs/thread-store/src/local/update_thread_metadata.rs
vendored
Normal file
397
vendor/codex/codex-rs/thread-store/src/local/update_thread_metadata.rs
vendored
Normal file
|
|
@ -0,0 +1,397 @@
|
|||
use std::path::PathBuf;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
use codex_protocol::protocol::ThreadMemoryMode;
|
||||
use codex_protocol::protocol::ThreadNameUpdatedEvent;
|
||||
use codex_rollout::StateDbHandle;
|
||||
use codex_rollout::append_rollout_item_to_path;
|
||||
use codex_rollout::append_thread_name;
|
||||
use codex_rollout::find_archived_thread_path_by_id_str;
|
||||
use codex_rollout::find_thread_path_by_id_str;
|
||||
use codex_rollout::read_session_meta_line;
|
||||
|
||||
use super::LocalThreadStore;
|
||||
use crate::ReadThreadParams;
|
||||
use crate::StoredThread;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
use crate::UpdateThreadMetadataParams;
|
||||
use crate::local::read_thread;
|
||||
|
||||
struct ResolvedRolloutPath {
|
||||
path: PathBuf,
|
||||
archived: bool,
|
||||
}
|
||||
|
||||
pub(super) async fn update_thread_metadata(
|
||||
store: &LocalThreadStore,
|
||||
params: UpdateThreadMetadataParams,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
if params.patch.git_info.is_some() {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: "local thread store does not implement git metadata updates in this slice"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
if params.patch.name.is_some() && params.patch.memory_mode.is_some() {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: "local thread store applies one metadata field per patch in this slice"
|
||||
.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let thread_id = params.thread_id;
|
||||
let resolved_rollout_path =
|
||||
resolve_rollout_path(store, thread_id, params.include_archived).await?;
|
||||
if let Some(name) = params.patch.name {
|
||||
apply_thread_name(store, resolved_rollout_path.path.as_path(), thread_id, name).await?;
|
||||
}
|
||||
if let Some(memory_mode) = params.patch.memory_mode {
|
||||
apply_thread_memory_mode(resolved_rollout_path.path.as_path(), thread_id, memory_mode)
|
||||
.await?;
|
||||
}
|
||||
|
||||
let state_db_ctx = open_state_db_for_direct_thread_lookup(store).await;
|
||||
codex_rollout::state_db::reconcile_rollout(
|
||||
state_db_ctx.as_deref(),
|
||||
resolved_rollout_path.path.as_path(),
|
||||
store.config.model_provider_id.as_str(),
|
||||
/*builder*/ None,
|
||||
&[],
|
||||
/*archived_only*/ resolved_rollout_path.archived.then_some(true),
|
||||
/*new_thread_memory_mode*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
read_thread::read_thread(
|
||||
store,
|
||||
ReadThreadParams {
|
||||
thread_id,
|
||||
include_archived: params.include_archived,
|
||||
include_history: false,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn apply_thread_name(
|
||||
store: &LocalThreadStore,
|
||||
rollout_path: &std::path::Path,
|
||||
thread_id: ThreadId,
|
||||
name: String,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let item = RolloutItem::EventMsg(EventMsg::ThreadNameUpdated(ThreadNameUpdatedEvent {
|
||||
thread_id,
|
||||
thread_name: Some(name.clone()),
|
||||
}));
|
||||
|
||||
append_rollout_item_to_path(rollout_path, &item)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to set thread name: {err}"),
|
||||
})?;
|
||||
append_thread_name(store.config.codex_home.as_path(), thread_id, &name)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to index thread name: {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
async fn apply_thread_memory_mode(
|
||||
rollout_path: &std::path::Path,
|
||||
thread_id: ThreadId,
|
||||
memory_mode: ThreadMemoryMode,
|
||||
) -> ThreadStoreResult<()> {
|
||||
let mut session_meta =
|
||||
read_session_meta_line(rollout_path)
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to set thread memory mode: {err}"),
|
||||
})?;
|
||||
if session_meta.meta.id != thread_id {
|
||||
return Err(ThreadStoreError::Internal {
|
||||
message: format!(
|
||||
"failed to set thread memory mode: rollout session metadata id mismatch: expected {thread_id}, found {}",
|
||||
session_meta.meta.id
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
session_meta.meta.memory_mode = Some(memory_mode_as_str(memory_mode).to_string());
|
||||
append_rollout_item_to_path(rollout_path, &RolloutItem::SessionMeta(session_meta))
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to set thread memory mode: {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
async fn open_state_db_for_direct_thread_lookup(store: &LocalThreadStore) -> Option<StateDbHandle> {
|
||||
codex_state::StateRuntime::init(
|
||||
store.config.sqlite_home.clone(),
|
||||
store.config.model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
}
|
||||
|
||||
fn memory_mode_as_str(mode: ThreadMemoryMode) -> &'static str {
|
||||
match mode {
|
||||
ThreadMemoryMode::Enabled => "enabled",
|
||||
ThreadMemoryMode::Disabled => "disabled",
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_rollout_path(
|
||||
store: &LocalThreadStore,
|
||||
thread_id: ThreadId,
|
||||
include_archived: bool,
|
||||
) -> ThreadStoreResult<ResolvedRolloutPath> {
|
||||
let active_path =
|
||||
find_thread_path_by_id_str(store.config.codex_home.as_path(), &thread_id.to_string())
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::InvalidRequest {
|
||||
message: format!("failed to locate thread id {thread_id}: {err}"),
|
||||
})?;
|
||||
if let Some(path) = active_path {
|
||||
return Ok(ResolvedRolloutPath {
|
||||
path,
|
||||
archived: false,
|
||||
});
|
||||
}
|
||||
if !include_archived {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("thread not found: {thread_id}"),
|
||||
});
|
||||
}
|
||||
find_archived_thread_path_by_id_str(store.config.codex_home.as_path(), &thread_id.to_string())
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::InvalidRequest {
|
||||
message: format!("failed to locate archived thread id {thread_id}: {err}"),
|
||||
})?
|
||||
.map(|path| ResolvedRolloutPath {
|
||||
path,
|
||||
archived: true,
|
||||
})
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: format!("thread not found: {thread_id}"),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use tempfile::TempDir;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::*;
|
||||
use crate::ThreadMetadataPatch;
|
||||
use crate::ThreadStore;
|
||||
use crate::local::LocalThreadStore;
|
||||
use crate::local::test_support::test_config;
|
||||
use crate::local::test_support::write_archived_session_file;
|
||||
use crate::local::test_support::write_session_file;
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_thread_metadata_sets_name_on_active_rollout_and_indexes_name() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let uuid = Uuid::from_u128(301);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let path =
|
||||
write_session_file(home.path(), "2025-01-03T14-00-00", uuid).expect("session file");
|
||||
|
||||
let thread = store
|
||||
.update_thread_metadata(UpdateThreadMetadataParams {
|
||||
thread_id,
|
||||
patch: ThreadMetadataPatch {
|
||||
name: Some("A sharper name".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
include_archived: false,
|
||||
})
|
||||
.await
|
||||
.expect("set thread name");
|
||||
|
||||
assert_eq!(thread.name.as_deref(), Some("A sharper name"));
|
||||
let latest_name = codex_rollout::find_thread_name_by_id(home.path(), &thread_id)
|
||||
.await
|
||||
.expect("find thread name");
|
||||
assert_eq!(latest_name.as_deref(), Some("A sharper name"));
|
||||
|
||||
let appended = last_rollout_item(path.as_path());
|
||||
assert_eq!(appended["type"], "event_msg");
|
||||
assert_eq!(appended["payload"]["type"], "thread_name_updated");
|
||||
assert_eq!(appended["payload"]["thread_id"], thread_id.to_string());
|
||||
assert_eq!(appended["payload"]["thread_name"], "A sharper name");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_thread_metadata_sets_memory_mode_on_active_rollout() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let uuid = Uuid::from_u128(302);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let path =
|
||||
write_session_file(home.path(), "2025-01-03T14-30-00", uuid).expect("session file");
|
||||
|
||||
let thread = store
|
||||
.update_thread_metadata(UpdateThreadMetadataParams {
|
||||
thread_id,
|
||||
patch: ThreadMetadataPatch {
|
||||
memory_mode: Some(ThreadMemoryMode::Disabled),
|
||||
..Default::default()
|
||||
},
|
||||
include_archived: false,
|
||||
})
|
||||
.await
|
||||
.expect("set thread memory mode");
|
||||
|
||||
assert_eq!(thread.thread_id, thread_id);
|
||||
let appended = last_rollout_item(path.as_path());
|
||||
assert_eq!(appended["type"], "session_meta");
|
||||
assert_eq!(appended["payload"]["id"], thread_id.to_string());
|
||||
assert_eq!(appended["payload"]["memory_mode"], "disabled");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_thread_metadata_rejects_mismatched_session_meta_id() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let filename_uuid = Uuid::from_u128(303);
|
||||
let metadata_uuid = Uuid::from_u128(304);
|
||||
let thread_id = ThreadId::from_string(&filename_uuid.to_string()).expect("valid thread id");
|
||||
let path = write_session_file(home.path(), "2025-01-03T15-00-00", filename_uuid)
|
||||
.expect("session file");
|
||||
let content = std::fs::read_to_string(&path).expect("read rollout");
|
||||
std::fs::write(
|
||||
&path,
|
||||
content.replace(&filename_uuid.to_string(), &metadata_uuid.to_string()),
|
||||
)
|
||||
.expect("rewrite rollout");
|
||||
|
||||
let err = store
|
||||
.update_thread_metadata(UpdateThreadMetadataParams {
|
||||
thread_id,
|
||||
patch: ThreadMetadataPatch {
|
||||
memory_mode: Some(ThreadMemoryMode::Enabled),
|
||||
..Default::default()
|
||||
},
|
||||
include_archived: false,
|
||||
})
|
||||
.await
|
||||
.expect_err("mismatch should fail");
|
||||
|
||||
assert!(matches!(err, ThreadStoreError::Internal { .. }));
|
||||
assert!(err.to_string().contains("metadata id mismatch"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_thread_metadata_rejects_multi_field_patch_without_partial_write() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let store = LocalThreadStore::new(test_config(home.path()));
|
||||
let uuid = Uuid::from_u128(305);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let path =
|
||||
write_session_file(home.path(), "2025-01-03T15-30-00", uuid).expect("session file");
|
||||
let original = std::fs::read_to_string(&path).expect("read rollout");
|
||||
|
||||
let err = store
|
||||
.update_thread_metadata(UpdateThreadMetadataParams {
|
||||
thread_id,
|
||||
patch: ThreadMetadataPatch {
|
||||
name: Some("Should not persist".to_string()),
|
||||
memory_mode: Some(ThreadMemoryMode::Disabled),
|
||||
..Default::default()
|
||||
},
|
||||
include_archived: false,
|
||||
})
|
||||
.await
|
||||
.expect_err("multi-field patch should fail");
|
||||
|
||||
assert!(matches!(err, ThreadStoreError::InvalidRequest { .. }));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&path).expect("read rollout"),
|
||||
original
|
||||
);
|
||||
let latest_name = codex_rollout::find_thread_name_by_id(home.path(), &thread_id)
|
||||
.await
|
||||
.expect("find thread name");
|
||||
assert_eq!(latest_name, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn update_thread_metadata_keeps_archived_thread_archived_in_sqlite() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
let config = test_config(home.path());
|
||||
let store = LocalThreadStore::new(config.clone());
|
||||
let uuid = Uuid::from_u128(306);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let archived_path = write_archived_session_file(home.path(), "2025-01-03T16-00-00", uuid)
|
||||
.expect("archived session file");
|
||||
let runtime = codex_state::StateRuntime::init(
|
||||
home.path().to_path_buf(),
|
||||
config.model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
.expect("state db should initialize");
|
||||
runtime
|
||||
.mark_backfill_complete(/*last_watermark*/ None)
|
||||
.await
|
||||
.expect("backfill should be complete");
|
||||
codex_rollout::state_db::reconcile_rollout(
|
||||
Some(runtime.as_ref()),
|
||||
archived_path.as_path(),
|
||||
config.model_provider_id.as_str(),
|
||||
/*builder*/ None,
|
||||
&[],
|
||||
/*archived_only*/ Some(true),
|
||||
/*new_thread_memory_mode*/ None,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("get metadata")
|
||||
.expect("metadata")
|
||||
.archived_at
|
||||
.is_some()
|
||||
);
|
||||
|
||||
let thread = store
|
||||
.update_thread_metadata(UpdateThreadMetadataParams {
|
||||
thread_id,
|
||||
patch: ThreadMetadataPatch {
|
||||
name: Some("Archived title".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
include_archived: true,
|
||||
})
|
||||
.await
|
||||
.expect("set archived thread name");
|
||||
|
||||
assert!(thread.archived_at.is_some());
|
||||
assert!(
|
||||
runtime
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.expect("get metadata")
|
||||
.expect("metadata")
|
||||
.archived_at
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
|
||||
fn last_rollout_item(path: &std::path::Path) -> Value {
|
||||
let last_line = std::fs::read_to_string(path)
|
||||
.expect("read rollout")
|
||||
.lines()
|
||||
.last()
|
||||
.expect("last line")
|
||||
.to_string();
|
||||
serde_json::from_str(&last_line).expect("json line")
|
||||
}
|
||||
}
|
||||
28
vendor/codex/codex-rs/thread-store/src/recorder.rs
vendored
Normal file
28
vendor/codex/codex-rs/thread-store/src/recorder.rs
vendored
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
use async_trait::async_trait;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
/// Live append handle for a thread.
|
||||
///
|
||||
/// This is the storage-neutral version of the existing rollout recorder API. The local
|
||||
/// implementation is expected to wrap `codex_rollout::RolloutRecorder` and preserve its lazy
|
||||
/// materialization, filtering, flush, and shutdown behavior.
|
||||
#[async_trait]
|
||||
pub trait ThreadRecorder: Send + Sync {
|
||||
/// Returns the thread id this recorder appends to.
|
||||
fn thread_id(&self) -> ThreadId;
|
||||
|
||||
/// Queues items for persistence according to this recorder's filtering policy.
|
||||
async fn record_items(&self, items: &[RolloutItem]) -> ThreadStoreResult<()>;
|
||||
|
||||
/// Materializes the thread if persistence is lazy, then persists all queued items.
|
||||
async fn persist(&self) -> ThreadStoreResult<()>;
|
||||
|
||||
/// Flushes all queued items and returns once they are durable/readable.
|
||||
async fn flush(&self) -> ThreadStoreResult<()>;
|
||||
|
||||
/// Flushes pending items and closes the recorder.
|
||||
async fn shutdown(&self) -> ThreadStoreResult<()>;
|
||||
}
|
||||
13
vendor/codex/codex-rs/thread-store/src/remote/AGENTS.md
vendored
Normal file
13
vendor/codex/codex-rs/thread-store/src/remote/AGENTS.md
vendored
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
# Remote Thread Store
|
||||
|
||||
- The Rust protobuf output in `proto/codex.thread_store.v1.rs` is checked in.
|
||||
- Do not add build-time protobuf generation to `codex-thread-store` unless the Bazel/Cargo story is intentionally changed.
|
||||
- When `proto/codex.thread_store.v1.proto` changes, regenerate the Rust file manually and include both files in the same commit.
|
||||
|
||||
Run this from the repository root:
|
||||
|
||||
```sh
|
||||
./codex-rs/thread-store/scripts/generate-proto.sh
|
||||
```
|
||||
|
||||
The command requires `protoc` to be available on `PATH`.
|
||||
255
vendor/codex/codex-rs/thread-store/src/remote/helpers.rs
vendored
Normal file
255
vendor/codex/codex-rs/thread-store/src/remote/helpers.rs
vendored
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_git_utils::GitSha;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::GitInfo;
|
||||
use codex_protocol::protocol::SandboxPolicy;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
|
||||
use super::proto;
|
||||
use crate::StoredThread;
|
||||
use crate::ThreadSortKey;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(super) fn remote_status_to_error(status: tonic::Status) -> ThreadStoreError {
|
||||
match status.code() {
|
||||
tonic::Code::InvalidArgument => ThreadStoreError::InvalidRequest {
|
||||
message: status.message().to_string(),
|
||||
},
|
||||
tonic::Code::AlreadyExists | tonic::Code::FailedPrecondition | tonic::Code::Aborted => {
|
||||
ThreadStoreError::Conflict {
|
||||
message: status.message().to_string(),
|
||||
}
|
||||
}
|
||||
_ => ThreadStoreError::Internal {
|
||||
message: format!("remote thread store request failed: {status}"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn proto_sort_key(sort_key: ThreadSortKey) -> proto::ThreadSortKey {
|
||||
match sort_key {
|
||||
ThreadSortKey::CreatedAt => proto::ThreadSortKey::CreatedAt,
|
||||
ThreadSortKey::UpdatedAt => proto::ThreadSortKey::UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn proto_session_source(source: &SessionSource) -> proto::SessionSource {
|
||||
match source {
|
||||
SessionSource::Cli => proto_source(proto::SessionSourceKind::Cli),
|
||||
SessionSource::VSCode => proto_source(proto::SessionSourceKind::Vscode),
|
||||
SessionSource::Exec => proto_source(proto::SessionSourceKind::Exec),
|
||||
SessionSource::Mcp => proto_source(proto::SessionSourceKind::AppServer),
|
||||
SessionSource::Custom(custom) => proto::SessionSource {
|
||||
kind: proto::SessionSourceKind::Custom.into(),
|
||||
custom: Some(custom.clone()),
|
||||
..Default::default()
|
||||
},
|
||||
SessionSource::SubAgent(SubAgentSource::Review) => {
|
||||
proto_source(proto::SessionSourceKind::SubAgentReview)
|
||||
}
|
||||
SessionSource::SubAgent(SubAgentSource::Compact) => {
|
||||
proto_source(proto::SessionSourceKind::SubAgentCompact)
|
||||
}
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id,
|
||||
depth,
|
||||
agent_path,
|
||||
agent_nickname,
|
||||
agent_role,
|
||||
}) => proto::SessionSource {
|
||||
kind: proto::SessionSourceKind::SubAgentThreadSpawn.into(),
|
||||
sub_agent_parent_thread_id: Some(parent_thread_id.to_string()),
|
||||
sub_agent_depth: Some(*depth),
|
||||
sub_agent_path: agent_path.as_ref().map(|path| path.as_str().to_string()),
|
||||
sub_agent_nickname: agent_nickname.clone(),
|
||||
sub_agent_role: agent_role.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
SessionSource::SubAgent(SubAgentSource::MemoryConsolidation) => {
|
||||
proto_source(proto::SessionSourceKind::SubAgentMemoryConsolidation)
|
||||
}
|
||||
SessionSource::SubAgent(SubAgentSource::Other(other)) => proto::SessionSource {
|
||||
kind: proto::SessionSourceKind::SubAgentOther.into(),
|
||||
sub_agent_other: Some(other.clone()),
|
||||
..Default::default()
|
||||
},
|
||||
SessionSource::Unknown => proto_source(proto::SessionSourceKind::Unknown),
|
||||
}
|
||||
}
|
||||
|
||||
fn proto_source(kind: proto::SessionSourceKind) -> proto::SessionSource {
|
||||
proto::SessionSource {
|
||||
kind: kind.into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn stored_thread_from_proto(
|
||||
thread: proto::StoredThread,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
// Keep this mapping boring: the proto mirrors StoredThread for remote-readable
|
||||
// summary fields, except for Rust domain types that cross gRPC as stable scalar
|
||||
// values. Local-only fields such as rollout_path intentionally stay local.
|
||||
let source = thread
|
||||
.source
|
||||
.as_ref()
|
||||
.map(session_source_from_proto)
|
||||
.transpose()?
|
||||
.unwrap_or(SessionSource::Unknown);
|
||||
let thread_id = ThreadId::from_string(&thread.thread_id).map_err(|err| {
|
||||
ThreadStoreError::InvalidRequest {
|
||||
message: format!("remote thread store returned invalid thread_id: {err}"),
|
||||
}
|
||||
})?;
|
||||
let forked_from_id = thread
|
||||
.forked_from_id
|
||||
.as_deref()
|
||||
.map(ThreadId::from_string)
|
||||
.transpose()
|
||||
.map_err(|err| ThreadStoreError::InvalidRequest {
|
||||
message: format!("remote thread store returned invalid forked_from_id: {err}"),
|
||||
})?;
|
||||
|
||||
Ok(StoredThread {
|
||||
thread_id,
|
||||
rollout_path: None,
|
||||
forked_from_id,
|
||||
preview: thread.preview,
|
||||
name: thread.name,
|
||||
model_provider: thread.model_provider,
|
||||
model: thread.model,
|
||||
reasoning_effort: thread
|
||||
.reasoning_effort
|
||||
.as_deref()
|
||||
.map(parse_reasoning_effort)
|
||||
.transpose()?,
|
||||
created_at: datetime_from_unix(thread.created_at)?,
|
||||
updated_at: datetime_from_unix(thread.updated_at)?,
|
||||
archived_at: thread.archived_at.map(datetime_from_unix).transpose()?,
|
||||
cwd: PathBuf::from(thread.cwd),
|
||||
cli_version: thread.cli_version,
|
||||
source,
|
||||
agent_nickname: thread.agent_nickname,
|
||||
agent_role: thread.agent_role,
|
||||
agent_path: thread.agent_path,
|
||||
git_info: thread.git_info.map(git_info_from_proto),
|
||||
approval_mode: AskForApproval::OnRequest,
|
||||
sandbox_policy: SandboxPolicy::new_read_only_policy(),
|
||||
token_usage: None,
|
||||
first_user_message: thread.first_user_message,
|
||||
history: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn stored_thread_to_proto(thread: StoredThread) -> proto::StoredThread {
|
||||
proto::StoredThread {
|
||||
thread_id: thread.thread_id.to_string(),
|
||||
forked_from_id: thread.forked_from_id.map(|thread_id| thread_id.to_string()),
|
||||
preview: thread.preview,
|
||||
name: thread.name,
|
||||
model_provider: thread.model_provider,
|
||||
model: thread.model,
|
||||
created_at: thread.created_at.timestamp(),
|
||||
updated_at: thread.updated_at.timestamp(),
|
||||
archived_at: thread.archived_at.map(|timestamp| timestamp.timestamp()),
|
||||
cwd: thread.cwd.to_string_lossy().into_owned(),
|
||||
cli_version: thread.cli_version,
|
||||
source: Some(proto_session_source(&thread.source)),
|
||||
git_info: thread.git_info.map(git_info_to_proto),
|
||||
agent_nickname: thread.agent_nickname,
|
||||
agent_role: thread.agent_role,
|
||||
agent_path: thread.agent_path,
|
||||
reasoning_effort: thread.reasoning_effort.map(|effort| effort.to_string()),
|
||||
first_user_message: thread.first_user_message,
|
||||
}
|
||||
}
|
||||
|
||||
fn datetime_from_unix(timestamp: i64) -> ThreadStoreResult<DateTime<Utc>> {
|
||||
DateTime::from_timestamp(timestamp, 0).ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: format!("remote thread store returned invalid timestamp: {timestamp}"),
|
||||
})
|
||||
}
|
||||
|
||||
fn session_source_from_proto(source: &proto::SessionSource) -> ThreadStoreResult<SessionSource> {
|
||||
let kind = proto::SessionSourceKind::try_from(source.kind).unwrap_or_default();
|
||||
Ok(match kind {
|
||||
proto::SessionSourceKind::Unknown => SessionSource::Unknown,
|
||||
proto::SessionSourceKind::Cli => SessionSource::Cli,
|
||||
proto::SessionSourceKind::Vscode => SessionSource::VSCode,
|
||||
proto::SessionSourceKind::Exec => SessionSource::Exec,
|
||||
proto::SessionSourceKind::AppServer => SessionSource::Mcp,
|
||||
proto::SessionSourceKind::Custom => {
|
||||
SessionSource::Custom(source.custom.clone().unwrap_or_default())
|
||||
}
|
||||
proto::SessionSourceKind::SubAgentReview => SessionSource::SubAgent(SubAgentSource::Review),
|
||||
proto::SessionSourceKind::SubAgentCompact => {
|
||||
SessionSource::SubAgent(SubAgentSource::Compact)
|
||||
}
|
||||
proto::SessionSourceKind::SubAgentThreadSpawn => {
|
||||
let parent_thread_id = source
|
||||
.sub_agent_parent_thread_id
|
||||
.as_deref()
|
||||
.map(ThreadId::from_string)
|
||||
.transpose()
|
||||
.map_err(|err| ThreadStoreError::InvalidRequest {
|
||||
message: format!(
|
||||
"remote thread store returned invalid sub-agent parent thread id: {err}"
|
||||
),
|
||||
})?
|
||||
.ok_or_else(|| ThreadStoreError::InvalidRequest {
|
||||
message: "remote thread store omitted sub-agent parent thread id".to_string(),
|
||||
})?;
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id,
|
||||
depth: source.sub_agent_depth.unwrap_or_default(),
|
||||
agent_path: source
|
||||
.sub_agent_path
|
||||
.clone()
|
||||
.map(AgentPath::from_string)
|
||||
.transpose()
|
||||
.map_err(|message| ThreadStoreError::InvalidRequest { message })?,
|
||||
agent_nickname: source.sub_agent_nickname.clone(),
|
||||
agent_role: source.sub_agent_role.clone(),
|
||||
})
|
||||
}
|
||||
proto::SessionSourceKind::SubAgentMemoryConsolidation => {
|
||||
SessionSource::SubAgent(SubAgentSource::MemoryConsolidation)
|
||||
}
|
||||
proto::SessionSourceKind::SubAgentOther => SessionSource::SubAgent(SubAgentSource::Other(
|
||||
source.sub_agent_other.clone().unwrap_or_default(),
|
||||
)),
|
||||
})
|
||||
}
|
||||
|
||||
fn git_info_from_proto(info: proto::GitInfo) -> GitInfo {
|
||||
GitInfo {
|
||||
commit_hash: info.sha.as_deref().map(GitSha::new),
|
||||
branch: info.branch,
|
||||
repository_url: info.origin_url,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn git_info_to_proto(info: GitInfo) -> proto::GitInfo {
|
||||
proto::GitInfo {
|
||||
sha: info.commit_hash.map(|sha| sha.0),
|
||||
branch: info.branch,
|
||||
origin_url: info.repository_url,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_reasoning_effort(value: &str) -> ThreadStoreResult<ReasoningEffort> {
|
||||
ReasoningEffort::from_str(value).map_err(|message| ThreadStoreError::InvalidRequest {
|
||||
message: format!("remote thread store returned {message}"),
|
||||
})
|
||||
}
|
||||
260
vendor/codex/codex-rs/thread-store/src/remote/list_threads.rs
vendored
Normal file
260
vendor/codex/codex-rs/thread-store/src/remote/list_threads.rs
vendored
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
use super::RemoteThreadStore;
|
||||
use super::helpers::proto_session_source;
|
||||
use super::helpers::proto_sort_key;
|
||||
use super::helpers::remote_status_to_error;
|
||||
use super::helpers::stored_thread_from_proto;
|
||||
use super::proto;
|
||||
use crate::ListThreadsParams;
|
||||
use crate::ThreadPage;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
|
||||
pub(super) async fn list_threads(
|
||||
store: &RemoteThreadStore,
|
||||
params: ListThreadsParams,
|
||||
) -> ThreadStoreResult<ThreadPage> {
|
||||
let request = proto::ListThreadsRequest {
|
||||
page_size: params
|
||||
.page_size
|
||||
.try_into()
|
||||
.map_err(|_| ThreadStoreError::InvalidRequest {
|
||||
message: format!("page_size is too large: {}", params.page_size),
|
||||
})?,
|
||||
cursor: params.cursor,
|
||||
sort_key: proto_sort_key(params.sort_key).into(),
|
||||
allowed_sources: params
|
||||
.allowed_sources
|
||||
.iter()
|
||||
.map(proto_session_source)
|
||||
.collect(),
|
||||
model_provider_filter: params
|
||||
.model_providers
|
||||
.map(|values| proto::ModelProviderFilter { values }),
|
||||
cwd_filter: params.cwd_filters.map(|values| proto::CwdFilter {
|
||||
values: values
|
||||
.into_iter()
|
||||
.map(|cwd| cwd.display().to_string())
|
||||
.collect(),
|
||||
}),
|
||||
archived: params.archived,
|
||||
search_term: params.search_term,
|
||||
use_state_db_only: params.use_state_db_only,
|
||||
};
|
||||
|
||||
let response = store
|
||||
.client()
|
||||
.await?
|
||||
.list_threads(request)
|
||||
.await
|
||||
.map_err(remote_status_to_error)?
|
||||
.into_inner();
|
||||
|
||||
let items = response
|
||||
.threads
|
||||
.into_iter()
|
||||
.map(stored_thread_from_proto)
|
||||
.collect::<ThreadStoreResult<Vec<_>>>()?;
|
||||
|
||||
Ok(ThreadPage {
|
||||
items,
|
||||
next_cursor: response.next_cursor,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tonic::Request;
|
||||
use tonic::Response;
|
||||
use tonic::Status;
|
||||
use tonic::transport::Server;
|
||||
|
||||
use super::super::helpers::stored_thread_to_proto;
|
||||
use super::super::proto::thread_store_server;
|
||||
use super::super::proto::thread_store_server::ThreadStoreServer;
|
||||
use super::*;
|
||||
use crate::ThreadSortKey;
|
||||
use crate::ThreadStore;
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestServer;
|
||||
|
||||
#[tonic::async_trait]
|
||||
impl thread_store_server::ThreadStore for TestServer {
|
||||
async fn list_threads(
|
||||
&self,
|
||||
request: Request<proto::ListThreadsRequest>,
|
||||
) -> Result<Response<proto::ListThreadsResponse>, Status> {
|
||||
let request = request.into_inner();
|
||||
assert_eq!(request.page_size, 2);
|
||||
assert_eq!(request.cursor.as_deref(), Some("cursor-1"));
|
||||
assert_eq!(
|
||||
proto::ThreadSortKey::try_from(request.sort_key),
|
||||
Ok(proto::ThreadSortKey::UpdatedAt)
|
||||
);
|
||||
assert_eq!(request.archived, true);
|
||||
assert_eq!(request.search_term.as_deref(), Some("needle"));
|
||||
assert!(request.use_state_db_only);
|
||||
assert_eq!(
|
||||
request.model_provider_filter,
|
||||
Some(proto::ModelProviderFilter {
|
||||
values: vec!["openai".to_string()],
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
request.cwd_filter,
|
||||
Some(proto::CwdFilter {
|
||||
values: vec!["/workspace".to_string()],
|
||||
})
|
||||
);
|
||||
assert_eq!(request.allowed_sources.len(), 1);
|
||||
assert_eq!(
|
||||
proto::SessionSourceKind::try_from(request.allowed_sources[0].kind),
|
||||
Ok(proto::SessionSourceKind::Cli)
|
||||
);
|
||||
|
||||
Ok(Response::new(proto::ListThreadsResponse {
|
||||
threads: vec![proto::StoredThread {
|
||||
thread_id: "11111111-1111-1111-1111-111111111111".to_string(),
|
||||
forked_from_id: None,
|
||||
preview: "hello".to_string(),
|
||||
name: Some("named thread".to_string()),
|
||||
model_provider: "openai".to_string(),
|
||||
model: Some("gpt-5".to_string()),
|
||||
created_at: 100,
|
||||
updated_at: 200,
|
||||
archived_at: Some(300),
|
||||
cwd: "/workspace".to_string(),
|
||||
cli_version: "1.2.3".to_string(),
|
||||
source: Some(proto::SessionSource {
|
||||
kind: proto::SessionSourceKind::Cli.into(),
|
||||
..Default::default()
|
||||
}),
|
||||
git_info: Some(proto::GitInfo {
|
||||
sha: Some("abc123".to_string()),
|
||||
branch: Some("main".to_string()),
|
||||
origin_url: Some("https://example.test/repo.git".to_string()),
|
||||
}),
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
agent_path: None,
|
||||
reasoning_effort: Some("medium".to_string()),
|
||||
first_user_message: Some("hello".to_string()),
|
||||
}],
|
||||
next_cursor: Some("cursor-2".to_string()),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_threads_calls_remote_service() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind test server");
|
||||
let addr = listener.local_addr().expect("test server addr");
|
||||
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
Server::builder()
|
||||
.add_service(ThreadStoreServer::new(TestServer))
|
||||
.serve_with_incoming_shutdown(
|
||||
tokio_stream::wrappers::TcpListenerStream::new(listener),
|
||||
async {
|
||||
let _ = shutdown_rx.await;
|
||||
},
|
||||
)
|
||||
.await
|
||||
});
|
||||
|
||||
let store = RemoteThreadStore::new(format!("http://{addr}"));
|
||||
let page = store
|
||||
.list_threads(ListThreadsParams {
|
||||
page_size: 2,
|
||||
cursor: Some("cursor-1".to_string()),
|
||||
sort_key: ThreadSortKey::UpdatedAt,
|
||||
sort_direction: crate::SortDirection::Desc,
|
||||
allowed_sources: vec![SessionSource::Cli],
|
||||
model_providers: Some(vec!["openai".to_string()]),
|
||||
cwd_filters: Some(vec![PathBuf::from("/workspace")]),
|
||||
archived: true,
|
||||
search_term: Some("needle".to_string()),
|
||||
use_state_db_only: true,
|
||||
})
|
||||
.await
|
||||
.expect("list threads");
|
||||
|
||||
assert_eq!(page.next_cursor.as_deref(), Some("cursor-2"));
|
||||
assert_eq!(page.items.len(), 1);
|
||||
let item = &page.items[0];
|
||||
assert_eq!(
|
||||
item.thread_id.to_string(),
|
||||
"11111111-1111-1111-1111-111111111111"
|
||||
);
|
||||
assert_eq!(item.name.as_deref(), Some("named thread"));
|
||||
assert_eq!(item.preview, "hello");
|
||||
assert_eq!(item.first_user_message.as_deref(), Some("hello"));
|
||||
assert_eq!(item.model_provider, "openai");
|
||||
assert_eq!(item.model.as_deref(), Some("gpt-5"));
|
||||
assert_eq!(item.created_at.timestamp(), 100);
|
||||
assert_eq!(item.updated_at.timestamp(), 200);
|
||||
assert_eq!(item.archived_at.map(|ts| ts.timestamp()), Some(300));
|
||||
assert_eq!(item.cwd, PathBuf::from("/workspace"));
|
||||
assert_eq!(item.cli_version, "1.2.3");
|
||||
assert_eq!(item.source, SessionSource::Cli);
|
||||
assert_eq!(item.reasoning_effort, Some(ReasoningEffort::Medium));
|
||||
assert_eq!(
|
||||
item.git_info.as_ref().and_then(|git| git.branch.as_deref()),
|
||||
Some("main")
|
||||
);
|
||||
|
||||
let _ = shutdown_tx.send(());
|
||||
server.await.expect("join server").expect("server");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_thread_proto_roundtrips_through_domain_type() {
|
||||
let thread = proto::StoredThread {
|
||||
thread_id: "11111111-1111-1111-1111-111111111111".to_string(),
|
||||
forked_from_id: Some("22222222-2222-2222-2222-222222222222".to_string()),
|
||||
preview: "preview text".to_string(),
|
||||
name: Some("named thread".to_string()),
|
||||
model_provider: "openai".to_string(),
|
||||
model: Some("gpt-5".to_string()),
|
||||
created_at: 100,
|
||||
updated_at: 200,
|
||||
archived_at: Some(300),
|
||||
cwd: "/workspace/project".to_string(),
|
||||
cli_version: "1.2.3".to_string(),
|
||||
source: Some(proto::SessionSource {
|
||||
kind: proto::SessionSourceKind::SubAgentThreadSpawn.into(),
|
||||
sub_agent_parent_thread_id: Some(
|
||||
"33333333-3333-3333-3333-333333333333".to_string(),
|
||||
),
|
||||
sub_agent_depth: Some(2),
|
||||
sub_agent_path: Some("/root/review/backend".to_string()),
|
||||
sub_agent_nickname: Some("Navigator".to_string()),
|
||||
sub_agent_role: Some("explorer".to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
git_info: Some(proto::GitInfo {
|
||||
sha: Some("abc123".to_string()),
|
||||
branch: Some("main".to_string()),
|
||||
origin_url: Some("https://example.test/repo.git".to_string()),
|
||||
}),
|
||||
agent_nickname: Some("Navigator".to_string()),
|
||||
agent_role: Some("explorer".to_string()),
|
||||
agent_path: Some("/root/review/backend".to_string()),
|
||||
reasoning_effort: Some("high".to_string()),
|
||||
first_user_message: Some("first message".to_string()),
|
||||
};
|
||||
|
||||
let stored = stored_thread_from_proto(thread.clone()).expect("proto to stored thread");
|
||||
|
||||
assert_eq!(stored.rollout_path, None);
|
||||
assert!(stored.history.is_none());
|
||||
assert_eq!(stored_thread_to_proto(stored), thread);
|
||||
}
|
||||
}
|
||||
111
vendor/codex/codex-rs/thread-store/src/remote/mod.rs
vendored
Normal file
111
vendor/codex/codex-rs/thread-store/src/remote/mod.rs
vendored
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
mod helpers;
|
||||
mod list_threads;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::AppendThreadItemsParams;
|
||||
use crate::ArchiveThreadParams;
|
||||
use crate::CreateThreadParams;
|
||||
use crate::ListThreadsParams;
|
||||
use crate::LoadThreadHistoryParams;
|
||||
use crate::ReadThreadParams;
|
||||
use crate::ResumeThreadRecorderParams;
|
||||
use crate::StoredThread;
|
||||
use crate::StoredThreadHistory;
|
||||
use crate::ThreadPage;
|
||||
use crate::ThreadRecorder;
|
||||
use crate::ThreadStore;
|
||||
use crate::ThreadStoreError;
|
||||
use crate::ThreadStoreResult;
|
||||
use crate::UpdateThreadMetadataParams;
|
||||
use proto::thread_store_client::ThreadStoreClient;
|
||||
|
||||
#[path = "proto/codex.thread_store.v1.rs"]
|
||||
mod proto;
|
||||
|
||||
/// gRPC-backed [`ThreadStore`] implementation for deployments whose durable thread data lives
|
||||
/// outside the app-server process.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RemoteThreadStore {
|
||||
endpoint: String,
|
||||
}
|
||||
|
||||
impl RemoteThreadStore {
|
||||
pub fn new(endpoint: impl Into<String>) -> Self {
|
||||
Self {
|
||||
endpoint: endpoint.into(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn client(&self) -> ThreadStoreResult<ThreadStoreClient<tonic::transport::Channel>> {
|
||||
ThreadStoreClient::connect(self.endpoint.clone())
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to connect to remote thread store: {err}"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ThreadStore for RemoteThreadStore {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
async fn create_thread(
|
||||
&self,
|
||||
_params: CreateThreadParams,
|
||||
) -> ThreadStoreResult<Box<dyn ThreadRecorder>> {
|
||||
Err(not_implemented("create_thread"))
|
||||
}
|
||||
|
||||
async fn resume_thread_recorder(
|
||||
&self,
|
||||
_params: ResumeThreadRecorderParams,
|
||||
) -> ThreadStoreResult<Box<dyn ThreadRecorder>> {
|
||||
Err(not_implemented("resume_thread_recorder"))
|
||||
}
|
||||
|
||||
async fn append_items(&self, _params: AppendThreadItemsParams) -> ThreadStoreResult<()> {
|
||||
Err(not_implemented("append_items"))
|
||||
}
|
||||
|
||||
async fn load_history(
|
||||
&self,
|
||||
_params: LoadThreadHistoryParams,
|
||||
) -> ThreadStoreResult<StoredThreadHistory> {
|
||||
Err(not_implemented("load_history"))
|
||||
}
|
||||
|
||||
async fn read_thread(&self, _params: ReadThreadParams) -> ThreadStoreResult<StoredThread> {
|
||||
Err(not_implemented("read_thread"))
|
||||
}
|
||||
|
||||
async fn list_threads(&self, params: ListThreadsParams) -> ThreadStoreResult<ThreadPage> {
|
||||
list_threads::list_threads(self, params).await
|
||||
}
|
||||
|
||||
async fn update_thread_metadata(
|
||||
&self,
|
||||
_params: UpdateThreadMetadataParams,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
Err(not_implemented("update_thread_metadata"))
|
||||
}
|
||||
|
||||
async fn archive_thread(&self, _params: ArchiveThreadParams) -> ThreadStoreResult<()> {
|
||||
Err(not_implemented("archive_thread"))
|
||||
}
|
||||
|
||||
async fn unarchive_thread(
|
||||
&self,
|
||||
_params: ArchiveThreadParams,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
Err(not_implemented("unarchive_thread"))
|
||||
}
|
||||
}
|
||||
|
||||
fn not_implemented(method: &str) -> ThreadStoreError {
|
||||
ThreadStoreError::Internal {
|
||||
message: format!("remote thread store does not implement {method} yet"),
|
||||
}
|
||||
}
|
||||
92
vendor/codex/codex-rs/thread-store/src/remote/proto/codex.thread_store.v1.proto
vendored
Normal file
92
vendor/codex/codex-rs/thread-store/src/remote/proto/codex.thread_store.v1.proto
vendored
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
syntax = "proto3";
|
||||
|
||||
package codex.thread_store.v1;
|
||||
|
||||
service ThreadStore {
|
||||
rpc ListThreads(ListThreadsRequest) returns (ListThreadsResponse);
|
||||
}
|
||||
|
||||
message ListThreadsRequest {
|
||||
uint32 page_size = 1;
|
||||
optional string cursor = 2;
|
||||
ThreadSortKey sort_key = 3;
|
||||
repeated SessionSource allowed_sources = 4;
|
||||
optional ModelProviderFilter model_provider_filter = 5;
|
||||
bool archived = 6;
|
||||
optional string search_term = 7;
|
||||
optional CwdFilter cwd_filter = 8;
|
||||
bool use_state_db_only = 9;
|
||||
}
|
||||
|
||||
message ModelProviderFilter {
|
||||
repeated string values = 1;
|
||||
}
|
||||
|
||||
message CwdFilter {
|
||||
repeated string values = 1;
|
||||
}
|
||||
|
||||
enum ThreadSortKey {
|
||||
THREAD_SORT_KEY_CREATED_AT = 0;
|
||||
THREAD_SORT_KEY_UPDATED_AT = 1;
|
||||
}
|
||||
|
||||
message ListThreadsResponse {
|
||||
repeated StoredThread threads = 1;
|
||||
optional string next_cursor = 2;
|
||||
}
|
||||
|
||||
message StoredThread {
|
||||
// Mirrors Rust's StoredThread. Domain types that are not protobuf-native,
|
||||
// such as ThreadId, DateTime<Utc>, and PathBuf, are represented as their
|
||||
// stable scalar forms on the wire.
|
||||
string thread_id = 1;
|
||||
optional string forked_from_id = 2;
|
||||
string preview = 3;
|
||||
optional string name = 4;
|
||||
string model_provider = 5;
|
||||
optional string model = 6;
|
||||
int64 created_at = 7;
|
||||
int64 updated_at = 8;
|
||||
optional int64 archived_at = 9;
|
||||
string cwd = 10;
|
||||
string cli_version = 11;
|
||||
SessionSource source = 12;
|
||||
optional GitInfo git_info = 13;
|
||||
optional string agent_nickname = 14;
|
||||
optional string agent_role = 15;
|
||||
optional string agent_path = 16;
|
||||
optional string reasoning_effort = 17;
|
||||
optional string first_user_message = 18;
|
||||
}
|
||||
|
||||
message SessionSource {
|
||||
SessionSourceKind kind = 1;
|
||||
optional string custom = 2;
|
||||
optional string sub_agent_parent_thread_id = 3;
|
||||
optional int32 sub_agent_depth = 4;
|
||||
optional string sub_agent_other = 5;
|
||||
optional string sub_agent_path = 6;
|
||||
optional string sub_agent_nickname = 7;
|
||||
optional string sub_agent_role = 8;
|
||||
}
|
||||
|
||||
enum SessionSourceKind {
|
||||
SESSION_SOURCE_KIND_UNKNOWN = 0;
|
||||
SESSION_SOURCE_KIND_CLI = 1;
|
||||
SESSION_SOURCE_KIND_VSCODE = 2;
|
||||
SESSION_SOURCE_KIND_EXEC = 3;
|
||||
SESSION_SOURCE_KIND_APP_SERVER = 4;
|
||||
SESSION_SOURCE_KIND_CUSTOM = 5;
|
||||
SESSION_SOURCE_KIND_SUB_AGENT_REVIEW = 6;
|
||||
SESSION_SOURCE_KIND_SUB_AGENT_COMPACT = 7;
|
||||
SESSION_SOURCE_KIND_SUB_AGENT_THREAD_SPAWN = 8;
|
||||
SESSION_SOURCE_KIND_SUB_AGENT_MEMORY_CONSOLIDATION = 9;
|
||||
SESSION_SOURCE_KIND_SUB_AGENT_OTHER = 10;
|
||||
}
|
||||
|
||||
message GitInfo {
|
||||
optional string sha = 1;
|
||||
optional string branch = 2;
|
||||
optional string origin_url = 3;
|
||||
}
|
||||
469
vendor/codex/codex-rs/thread-store/src/remote/proto/codex.thread_store.v1.rs
vendored
Normal file
469
vendor/codex/codex-rs/thread-store/src/remote/proto/codex.thread_store.v1.rs
vendored
Normal file
|
|
@ -0,0 +1,469 @@
|
|||
// This file is @generated by prost-build.
|
||||
#![allow(clippy::trivially_copy_pass_by_ref)]
|
||||
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct ListThreadsRequest {
|
||||
#[prost(uint32, tag = "1")]
|
||||
pub page_size: u32,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub cursor: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(enumeration = "ThreadSortKey", tag = "3")]
|
||||
pub sort_key: i32,
|
||||
#[prost(message, repeated, tag = "4")]
|
||||
pub allowed_sources: ::prost::alloc::vec::Vec<SessionSource>,
|
||||
#[prost(message, optional, tag = "5")]
|
||||
pub model_provider_filter: ::core::option::Option<ModelProviderFilter>,
|
||||
#[prost(bool, tag = "6")]
|
||||
pub archived: bool,
|
||||
#[prost(string, optional, tag = "7")]
|
||||
pub search_term: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(message, optional, tag = "8")]
|
||||
pub cwd_filter: ::core::option::Option<CwdFilter>,
|
||||
#[prost(bool, tag = "9")]
|
||||
pub use_state_db_only: bool,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
|
||||
pub struct ModelProviderFilter {
|
||||
#[prost(string, repeated, tag = "1")]
|
||||
pub values: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
|
||||
pub struct CwdFilter {
|
||||
#[prost(string, repeated, tag = "1")]
|
||||
pub values: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
|
||||
}
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct ListThreadsResponse {
|
||||
#[prost(message, repeated, tag = "1")]
|
||||
pub threads: ::prost::alloc::vec::Vec<StoredThread>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub next_cursor: ::core::option::Option<::prost::alloc::string::String>,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
|
||||
pub struct StoredThread {
|
||||
/// Mirrors Rust's StoredThread. Domain types that are not protobuf-native,
|
||||
/// such as ThreadId, DateTime<Utc>, and PathBuf, are represented as their
|
||||
/// stable scalar forms on the wire.
|
||||
#[prost(string, tag = "1")]
|
||||
pub thread_id: ::prost::alloc::string::String,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub forked_from_id: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, tag = "3")]
|
||||
pub preview: ::prost::alloc::string::String,
|
||||
#[prost(string, optional, tag = "4")]
|
||||
pub name: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, tag = "5")]
|
||||
pub model_provider: ::prost::alloc::string::String,
|
||||
#[prost(string, optional, tag = "6")]
|
||||
pub model: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(int64, tag = "7")]
|
||||
pub created_at: i64,
|
||||
#[prost(int64, tag = "8")]
|
||||
pub updated_at: i64,
|
||||
#[prost(int64, optional, tag = "9")]
|
||||
pub archived_at: ::core::option::Option<i64>,
|
||||
#[prost(string, tag = "10")]
|
||||
pub cwd: ::prost::alloc::string::String,
|
||||
#[prost(string, tag = "11")]
|
||||
pub cli_version: ::prost::alloc::string::String,
|
||||
#[prost(message, optional, tag = "12")]
|
||||
pub source: ::core::option::Option<SessionSource>,
|
||||
#[prost(message, optional, tag = "13")]
|
||||
pub git_info: ::core::option::Option<GitInfo>,
|
||||
#[prost(string, optional, tag = "14")]
|
||||
pub agent_nickname: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "15")]
|
||||
pub agent_role: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "16")]
|
||||
pub agent_path: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "17")]
|
||||
pub reasoning_effort: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "18")]
|
||||
pub first_user_message: ::core::option::Option<::prost::alloc::string::String>,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
|
||||
pub struct SessionSource {
|
||||
#[prost(enumeration = "SessionSourceKind", tag = "1")]
|
||||
pub kind: i32,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub custom: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub sub_agent_parent_thread_id: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(int32, optional, tag = "4")]
|
||||
pub sub_agent_depth: ::core::option::Option<i32>,
|
||||
#[prost(string, optional, tag = "5")]
|
||||
pub sub_agent_other: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "6")]
|
||||
pub sub_agent_path: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "7")]
|
||||
pub sub_agent_nickname: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "8")]
|
||||
pub sub_agent_role: ::core::option::Option<::prost::alloc::string::String>,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
|
||||
pub struct GitInfo {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub sha: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub branch: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub origin_url: ::core::option::Option<::prost::alloc::string::String>,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
|
||||
#[repr(i32)]
|
||||
pub enum ThreadSortKey {
|
||||
CreatedAt = 0,
|
||||
UpdatedAt = 1,
|
||||
}
|
||||
impl ThreadSortKey {
|
||||
/// String value of the enum field names used in the ProtoBuf definition.
|
||||
///
|
||||
/// The values are not transformed in any way and thus are considered stable
|
||||
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
|
||||
pub fn as_str_name(&self) -> &'static str {
|
||||
match self {
|
||||
Self::CreatedAt => "THREAD_SORT_KEY_CREATED_AT",
|
||||
Self::UpdatedAt => "THREAD_SORT_KEY_UPDATED_AT",
|
||||
}
|
||||
}
|
||||
/// Creates an enum from field names used in the ProtoBuf definition.
|
||||
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
|
||||
match value {
|
||||
"THREAD_SORT_KEY_CREATED_AT" => Some(Self::CreatedAt),
|
||||
"THREAD_SORT_KEY_UPDATED_AT" => Some(Self::UpdatedAt),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
|
||||
#[repr(i32)]
|
||||
pub enum SessionSourceKind {
|
||||
Unknown = 0,
|
||||
Cli = 1,
|
||||
Vscode = 2,
|
||||
Exec = 3,
|
||||
AppServer = 4,
|
||||
Custom = 5,
|
||||
SubAgentReview = 6,
|
||||
SubAgentCompact = 7,
|
||||
SubAgentThreadSpawn = 8,
|
||||
SubAgentMemoryConsolidation = 9,
|
||||
SubAgentOther = 10,
|
||||
}
|
||||
impl SessionSourceKind {
|
||||
/// String value of the enum field names used in the ProtoBuf definition.
|
||||
///
|
||||
/// The values are not transformed in any way and thus are considered stable
|
||||
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
|
||||
pub fn as_str_name(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Unknown => "SESSION_SOURCE_KIND_UNKNOWN",
|
||||
Self::Cli => "SESSION_SOURCE_KIND_CLI",
|
||||
Self::Vscode => "SESSION_SOURCE_KIND_VSCODE",
|
||||
Self::Exec => "SESSION_SOURCE_KIND_EXEC",
|
||||
Self::AppServer => "SESSION_SOURCE_KIND_APP_SERVER",
|
||||
Self::Custom => "SESSION_SOURCE_KIND_CUSTOM",
|
||||
Self::SubAgentReview => "SESSION_SOURCE_KIND_SUB_AGENT_REVIEW",
|
||||
Self::SubAgentCompact => "SESSION_SOURCE_KIND_SUB_AGENT_COMPACT",
|
||||
Self::SubAgentThreadSpawn => "SESSION_SOURCE_KIND_SUB_AGENT_THREAD_SPAWN",
|
||||
Self::SubAgentMemoryConsolidation => {
|
||||
"SESSION_SOURCE_KIND_SUB_AGENT_MEMORY_CONSOLIDATION"
|
||||
}
|
||||
Self::SubAgentOther => "SESSION_SOURCE_KIND_SUB_AGENT_OTHER",
|
||||
}
|
||||
}
|
||||
/// Creates an enum from field names used in the ProtoBuf definition.
|
||||
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
|
||||
match value {
|
||||
"SESSION_SOURCE_KIND_UNKNOWN" => Some(Self::Unknown),
|
||||
"SESSION_SOURCE_KIND_CLI" => Some(Self::Cli),
|
||||
"SESSION_SOURCE_KIND_VSCODE" => Some(Self::Vscode),
|
||||
"SESSION_SOURCE_KIND_EXEC" => Some(Self::Exec),
|
||||
"SESSION_SOURCE_KIND_APP_SERVER" => Some(Self::AppServer),
|
||||
"SESSION_SOURCE_KIND_CUSTOM" => Some(Self::Custom),
|
||||
"SESSION_SOURCE_KIND_SUB_AGENT_REVIEW" => Some(Self::SubAgentReview),
|
||||
"SESSION_SOURCE_KIND_SUB_AGENT_COMPACT" => Some(Self::SubAgentCompact),
|
||||
"SESSION_SOURCE_KIND_SUB_AGENT_THREAD_SPAWN" => Some(Self::SubAgentThreadSpawn),
|
||||
"SESSION_SOURCE_KIND_SUB_AGENT_MEMORY_CONSOLIDATION" => {
|
||||
Some(Self::SubAgentMemoryConsolidation)
|
||||
}
|
||||
"SESSION_SOURCE_KIND_SUB_AGENT_OTHER" => Some(Self::SubAgentOther),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Generated client implementations.
|
||||
pub mod thread_store_client {
|
||||
#![allow(
|
||||
unused_variables,
|
||||
dead_code,
|
||||
missing_docs,
|
||||
clippy::wildcard_imports,
|
||||
clippy::let_unit_value
|
||||
)]
|
||||
use tonic::codegen::http::Uri;
|
||||
use tonic::codegen::*;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ThreadStoreClient<T> {
|
||||
inner: tonic::client::Grpc<T>,
|
||||
}
|
||||
impl ThreadStoreClient<tonic::transport::Channel> {
|
||||
/// Attempt to create a new client by connecting to a given endpoint.
|
||||
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
|
||||
where
|
||||
D: TryInto<tonic::transport::Endpoint>,
|
||||
D::Error: Into<StdError>,
|
||||
{
|
||||
let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
|
||||
Ok(Self::new(conn))
|
||||
}
|
||||
}
|
||||
impl<T> ThreadStoreClient<T>
|
||||
where
|
||||
T: tonic::client::GrpcService<tonic::body::Body>,
|
||||
T::Error: Into<StdError>,
|
||||
T::ResponseBody: Body<Data = Bytes> + std::marker::Send + 'static,
|
||||
<T::ResponseBody as Body>::Error: Into<StdError> + std::marker::Send,
|
||||
{
|
||||
pub fn new(inner: T) -> Self {
|
||||
let inner = tonic::client::Grpc::new(inner);
|
||||
Self { inner }
|
||||
}
|
||||
pub fn with_origin(inner: T, origin: Uri) -> Self {
|
||||
let inner = tonic::client::Grpc::with_origin(inner, origin);
|
||||
Self { inner }
|
||||
}
|
||||
pub fn with_interceptor<F>(
|
||||
inner: T,
|
||||
interceptor: F,
|
||||
) -> ThreadStoreClient<InterceptedService<T, F>>
|
||||
where
|
||||
F: tonic::service::Interceptor,
|
||||
T::ResponseBody: Default,
|
||||
T: tonic::codegen::Service<
|
||||
http::Request<tonic::body::Body>,
|
||||
Response = http::Response<
|
||||
<T as tonic::client::GrpcService<tonic::body::Body>>::ResponseBody,
|
||||
>,
|
||||
>,
|
||||
<T as tonic::codegen::Service<http::Request<tonic::body::Body>>>::Error:
|
||||
Into<StdError> + std::marker::Send + std::marker::Sync,
|
||||
{
|
||||
ThreadStoreClient::new(InterceptedService::new(inner, interceptor))
|
||||
}
|
||||
/// Compress requests with the given encoding.
|
||||
///
|
||||
/// This requires the server to support it otherwise it might respond with an
|
||||
/// error.
|
||||
#[must_use]
|
||||
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.inner = self.inner.send_compressed(encoding);
|
||||
self
|
||||
}
|
||||
/// Enable decompressing responses.
|
||||
#[must_use]
|
||||
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.inner = self.inner.accept_compressed(encoding);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of a decoded message.
|
||||
///
|
||||
/// Default: `4MB`
|
||||
#[must_use]
|
||||
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.inner = self.inner.max_decoding_message_size(limit);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of an encoded message.
|
||||
///
|
||||
/// Default: `usize::MAX`
|
||||
#[must_use]
|
||||
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.inner = self.inner.max_encoding_message_size(limit);
|
||||
self
|
||||
}
|
||||
pub async fn list_threads(
|
||||
&mut self,
|
||||
request: impl tonic::IntoRequest<super::ListThreadsRequest>,
|
||||
) -> std::result::Result<tonic::Response<super::ListThreadsResponse>, tonic::Status>
|
||||
{
|
||||
self.inner.ready().await.map_err(|e| {
|
||||
tonic::Status::unknown(format!("Service was not ready: {}", e.into()))
|
||||
})?;
|
||||
let codec = tonic_prost::ProstCodec::default();
|
||||
let path = http::uri::PathAndQuery::from_static(
|
||||
"/codex.thread_store.v1.ThreadStore/ListThreads",
|
||||
);
|
||||
let mut req = request.into_request();
|
||||
req.extensions_mut().insert(GrpcMethod::new(
|
||||
"codex.thread_store.v1.ThreadStore",
|
||||
"ListThreads",
|
||||
));
|
||||
self.inner.unary(req, path, codec).await
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Generated server implementations.
|
||||
pub mod thread_store_server {
|
||||
#![allow(
|
||||
unused_variables,
|
||||
dead_code,
|
||||
missing_docs,
|
||||
clippy::wildcard_imports,
|
||||
clippy::let_unit_value
|
||||
)]
|
||||
use tonic::codegen::*;
|
||||
/// Generated trait containing gRPC methods that should be implemented for use with ThreadStoreServer.
|
||||
#[async_trait]
|
||||
pub trait ThreadStore: std::marker::Send + std::marker::Sync + 'static {
|
||||
async fn list_threads(
|
||||
&self,
|
||||
request: tonic::Request<super::ListThreadsRequest>,
|
||||
) -> std::result::Result<tonic::Response<super::ListThreadsResponse>, tonic::Status>;
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct ThreadStoreServer<T> {
|
||||
inner: Arc<T>,
|
||||
accept_compression_encodings: EnabledCompressionEncodings,
|
||||
send_compression_encodings: EnabledCompressionEncodings,
|
||||
max_decoding_message_size: Option<usize>,
|
||||
max_encoding_message_size: Option<usize>,
|
||||
}
|
||||
impl<T> ThreadStoreServer<T> {
|
||||
pub fn new(inner: T) -> Self {
|
||||
Self::from_arc(Arc::new(inner))
|
||||
}
|
||||
pub fn from_arc(inner: Arc<T>) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
accept_compression_encodings: Default::default(),
|
||||
send_compression_encodings: Default::default(),
|
||||
max_decoding_message_size: None,
|
||||
max_encoding_message_size: None,
|
||||
}
|
||||
}
|
||||
pub fn with_interceptor<F>(inner: T, interceptor: F) -> InterceptedService<Self, F>
|
||||
where
|
||||
F: tonic::service::Interceptor,
|
||||
{
|
||||
InterceptedService::new(Self::new(inner), interceptor)
|
||||
}
|
||||
/// Enable decompressing requests with the given encoding.
|
||||
#[must_use]
|
||||
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.accept_compression_encodings.enable(encoding);
|
||||
self
|
||||
}
|
||||
/// Compress responses with the given encoding, if the client supports it.
|
||||
#[must_use]
|
||||
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.send_compression_encodings.enable(encoding);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of a decoded message.
|
||||
///
|
||||
/// Default: `4MB`
|
||||
#[must_use]
|
||||
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.max_decoding_message_size = Some(limit);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of an encoded message.
|
||||
///
|
||||
/// Default: `usize::MAX`
|
||||
#[must_use]
|
||||
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.max_encoding_message_size = Some(limit);
|
||||
self
|
||||
}
|
||||
}
|
||||
impl<T, B> tonic::codegen::Service<http::Request<B>> for ThreadStoreServer<T>
|
||||
where
|
||||
T: ThreadStore,
|
||||
B: Body + std::marker::Send + 'static,
|
||||
B::Error: Into<StdError> + std::marker::Send + 'static,
|
||||
{
|
||||
type Response = http::Response<tonic::body::Body>;
|
||||
type Error = std::convert::Infallible;
|
||||
type Future = BoxFuture<Self::Response, Self::Error>;
|
||||
fn poll_ready(
|
||||
&mut self,
|
||||
_cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
fn call(&mut self, req: http::Request<B>) -> Self::Future {
|
||||
match req.uri().path() {
|
||||
"/codex.thread_store.v1.ThreadStore/ListThreads" => {
|
||||
#[allow(non_camel_case_types)]
|
||||
struct ListThreadsSvc<T: ThreadStore>(pub Arc<T>);
|
||||
impl<T: ThreadStore> tonic::server::UnaryService<super::ListThreadsRequest> for ListThreadsSvc<T> {
|
||||
type Response = super::ListThreadsResponse;
|
||||
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
|
||||
fn call(
|
||||
&mut self,
|
||||
request: tonic::Request<super::ListThreadsRequest>,
|
||||
) -> Self::Future {
|
||||
let inner = Arc::clone(&self.0);
|
||||
let fut = async move {
|
||||
<T as ThreadStore>::list_threads(&inner, request).await
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
}
|
||||
let accept_compression_encodings = self.accept_compression_encodings;
|
||||
let send_compression_encodings = self.send_compression_encodings;
|
||||
let max_decoding_message_size = self.max_decoding_message_size;
|
||||
let max_encoding_message_size = self.max_encoding_message_size;
|
||||
let inner = self.inner.clone();
|
||||
let fut = async move {
|
||||
let method = ListThreadsSvc(inner);
|
||||
let codec = tonic_prost::ProstCodec::default();
|
||||
let mut grpc = tonic::server::Grpc::new(codec)
|
||||
.apply_compression_config(
|
||||
accept_compression_encodings,
|
||||
send_compression_encodings,
|
||||
)
|
||||
.apply_max_message_size_config(
|
||||
max_decoding_message_size,
|
||||
max_encoding_message_size,
|
||||
);
|
||||
let res = grpc.unary(method, req).await;
|
||||
Ok(res)
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
_ => Box::pin(async move {
|
||||
let mut response = http::Response::new(tonic::body::Body::default());
|
||||
let headers = response.headers_mut();
|
||||
headers.insert(
|
||||
tonic::Status::GRPC_STATUS,
|
||||
(tonic::Code::Unimplemented as i32).into(),
|
||||
);
|
||||
headers.insert(
|
||||
http::header::CONTENT_TYPE,
|
||||
tonic::metadata::GRPC_CONTENT_TYPE,
|
||||
);
|
||||
Ok(response)
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<T> Clone for ThreadStoreServer<T> {
|
||||
fn clone(&self) -> Self {
|
||||
let inner = self.inner.clone();
|
||||
Self {
|
||||
inner,
|
||||
accept_compression_encodings: self.accept_compression_encodings,
|
||||
send_compression_encodings: self.send_compression_encodings,
|
||||
max_decoding_message_size: self.max_decoding_message_size,
|
||||
max_encoding_message_size: self.max_encoding_message_size,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Generated gRPC service name
|
||||
pub const SERVICE_NAME: &str = "codex.thread_store.v1.ThreadStore";
|
||||
impl<T> tonic::server::NamedService for ThreadStoreServer<T> {
|
||||
const NAME: &'static str = SERVICE_NAME;
|
||||
}
|
||||
}
|
||||
67
vendor/codex/codex-rs/thread-store/src/store.rs
vendored
Normal file
67
vendor/codex/codex-rs/thread-store/src/store.rs
vendored
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
use std::any::Any;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::AppendThreadItemsParams;
|
||||
use crate::ArchiveThreadParams;
|
||||
use crate::CreateThreadParams;
|
||||
use crate::ListThreadsParams;
|
||||
use crate::LoadThreadHistoryParams;
|
||||
use crate::ReadThreadParams;
|
||||
use crate::ResumeThreadRecorderParams;
|
||||
use crate::StoredThread;
|
||||
use crate::StoredThreadHistory;
|
||||
use crate::ThreadPage;
|
||||
use crate::ThreadRecorder;
|
||||
use crate::ThreadStoreResult;
|
||||
use crate::UpdateThreadMetadataParams;
|
||||
|
||||
/// Storage-neutral thread persistence boundary.
|
||||
#[async_trait]
|
||||
pub trait ThreadStore: Any + Send + Sync {
|
||||
/// Return this store as [`Any`] so callers at API boundaries can reject requests that only
|
||||
/// make sense for a concrete store implementation.
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
|
||||
/// Creates a new thread and returns a live recorder for future appends.
|
||||
async fn create_thread(
|
||||
&self,
|
||||
params: CreateThreadParams,
|
||||
) -> ThreadStoreResult<Box<dyn ThreadRecorder>>;
|
||||
|
||||
/// Reopens a live recorder for an existing thread.
|
||||
async fn resume_thread_recorder(
|
||||
&self,
|
||||
params: ResumeThreadRecorderParams,
|
||||
) -> ThreadStoreResult<Box<dyn ThreadRecorder>>;
|
||||
|
||||
/// Appends items to a stored thread outside the live-recorder path.
|
||||
async fn append_items(&self, params: AppendThreadItemsParams) -> ThreadStoreResult<()>;
|
||||
|
||||
/// Loads persisted history for resume, fork, rollback, and memory jobs.
|
||||
async fn load_history(
|
||||
&self,
|
||||
params: LoadThreadHistoryParams,
|
||||
) -> ThreadStoreResult<StoredThreadHistory>;
|
||||
|
||||
/// Reads a thread summary and optionally its persisted history.
|
||||
async fn read_thread(&self, params: ReadThreadParams) -> ThreadStoreResult<StoredThread>;
|
||||
|
||||
/// Lists stored threads matching the supplied filters.
|
||||
async fn list_threads(&self, params: ListThreadsParams) -> ThreadStoreResult<ThreadPage>;
|
||||
|
||||
/// Applies a mutable metadata patch and returns the updated thread.
|
||||
async fn update_thread_metadata(
|
||||
&self,
|
||||
params: UpdateThreadMetadataParams,
|
||||
) -> ThreadStoreResult<StoredThread>;
|
||||
|
||||
/// Archives a thread.
|
||||
async fn archive_thread(&self, params: ArchiveThreadParams) -> ThreadStoreResult<()>;
|
||||
|
||||
/// Unarchives a thread and returns its updated metadata.
|
||||
async fn unarchive_thread(
|
||||
&self,
|
||||
params: ArchiveThreadParams,
|
||||
) -> ThreadStoreResult<StoredThread>;
|
||||
}
|
||||
243
vendor/codex/codex-rs/thread-store/src/types.rs
vendored
Normal file
243
vendor/codex/codex-rs/thread-store/src/types.rs
vendored
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
use std::path::PathBuf;
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::dynamic_tools::DynamicToolSpec;
|
||||
use codex_protocol::models::BaseInstructions;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::GitInfo;
|
||||
use codex_protocol::protocol::RolloutItem;
|
||||
use codex_protocol::protocol::SandboxPolicy;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadMemoryMode as MemoryMode;
|
||||
use codex_protocol::protocol::TokenUsage;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
/// Controls how many event variants should be persisted for future replay.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ThreadEventPersistenceMode {
|
||||
/// Persist only the legacy minimal replay surface.
|
||||
#[default]
|
||||
Limited,
|
||||
/// Persist the richer event surface used by app-server history reconstruction.
|
||||
Extended,
|
||||
}
|
||||
|
||||
/// Parameters required to create a persisted thread and its recorder.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct CreateThreadParams {
|
||||
/// Thread id generated by Codex before opening persistence.
|
||||
pub thread_id: ThreadId,
|
||||
/// Source thread id when this thread is created as a fork.
|
||||
pub forked_from_id: Option<ThreadId>,
|
||||
/// Runtime source for the thread.
|
||||
pub source: SessionSource,
|
||||
/// Base instructions persisted in session metadata.
|
||||
pub base_instructions: BaseInstructions,
|
||||
/// Dynamic tools available to the thread at startup.
|
||||
pub dynamic_tools: Vec<DynamicToolSpec>,
|
||||
/// Whether the recorder should persist the extended event surface.
|
||||
pub event_persistence_mode: ThreadEventPersistenceMode,
|
||||
}
|
||||
|
||||
/// Parameters required to reopen persistence for an existing thread.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResumeThreadRecorderParams {
|
||||
/// Existing thread id whose future items should be appended.
|
||||
pub thread_id: ThreadId,
|
||||
/// Whether archived threads may be reopened.
|
||||
pub include_archived: bool,
|
||||
/// Whether the recorder should persist the extended event surface.
|
||||
pub event_persistence_mode: ThreadEventPersistenceMode,
|
||||
}
|
||||
|
||||
/// Parameters for appending rollout items outside a live recorder.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct AppendThreadItemsParams {
|
||||
/// Thread id to append to.
|
||||
pub thread_id: ThreadId,
|
||||
/// Items to append in order.
|
||||
pub items: Vec<RolloutItem>,
|
||||
}
|
||||
|
||||
/// Parameters for loading persisted history for resume, fork, rollback, and memory jobs.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LoadThreadHistoryParams {
|
||||
/// Thread id to load.
|
||||
pub thread_id: ThreadId,
|
||||
/// Whether archived threads are eligible.
|
||||
pub include_archived: bool,
|
||||
}
|
||||
|
||||
/// Persisted rollout history for a thread, without any filesystem path requirement.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct StoredThreadHistory {
|
||||
/// Thread id represented by the history.
|
||||
pub thread_id: ThreadId,
|
||||
/// Persisted rollout items in replay order.
|
||||
pub items: Vec<RolloutItem>,
|
||||
}
|
||||
|
||||
/// Parameters for reading a thread summary and optionally its replay history.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ReadThreadParams {
|
||||
/// Thread id to read.
|
||||
pub thread_id: ThreadId,
|
||||
/// Whether archived threads are eligible.
|
||||
pub include_archived: bool,
|
||||
/// Whether persisted rollout items should be included in the response.
|
||||
pub include_history: bool,
|
||||
}
|
||||
|
||||
/// The sort key to use when listing stored threads.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ThreadSortKey {
|
||||
/// Sort by the thread creation timestamp.
|
||||
#[default]
|
||||
CreatedAt,
|
||||
/// Sort by the thread last-update timestamp.
|
||||
UpdatedAt,
|
||||
}
|
||||
|
||||
/// The direction to use when listing stored threads.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum SortDirection {
|
||||
/// Return older threads before newer threads.
|
||||
Asc,
|
||||
/// Return newer threads before older threads.
|
||||
#[default]
|
||||
Desc,
|
||||
}
|
||||
|
||||
/// Parameters for listing threads.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ListThreadsParams {
|
||||
/// Maximum number of threads to return.
|
||||
pub page_size: usize,
|
||||
/// Opaque cursor returned by a previous list call.
|
||||
pub cursor: Option<String>,
|
||||
/// Sort order requested by the caller.
|
||||
pub sort_key: ThreadSortKey,
|
||||
/// Sort direction requested by the caller.
|
||||
pub sort_direction: SortDirection,
|
||||
/// Allowed session sources. Empty means implementation default.
|
||||
pub allowed_sources: Vec<SessionSource>,
|
||||
/// Optional model provider filter. `None` means implementation default, while an empty vector
|
||||
/// means all providers.
|
||||
pub model_providers: Option<Vec<String>>,
|
||||
/// Optional cwd filters. `None` means all working directories, while an empty vector matches no
|
||||
/// threads.
|
||||
pub cwd_filters: Option<Vec<PathBuf>>,
|
||||
/// Whether archived threads should be listed instead of active threads.
|
||||
pub archived: bool,
|
||||
/// Optional substring/full-text search term for thread title/preview.
|
||||
pub search_term: Option<String>,
|
||||
/// Return directly from the state DB without scanning JSONL rollouts to repair metadata.
|
||||
pub use_state_db_only: bool,
|
||||
}
|
||||
|
||||
/// A page of stored thread records.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct ThreadPage {
|
||||
/// Threads returned for this page.
|
||||
pub items: Vec<StoredThread>,
|
||||
/// Opaque cursor to continue listing.
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
/// Store-owned thread metadata used by list/read/resume responses.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct StoredThread {
|
||||
/// Thread id.
|
||||
pub thread_id: ThreadId,
|
||||
/// Local rollout path when the backing store is filesystem-based.
|
||||
pub rollout_path: Option<PathBuf>,
|
||||
/// Source thread id when this thread was forked from another thread.
|
||||
pub forked_from_id: Option<ThreadId>,
|
||||
/// Best available user-facing preview, usually the first user message.
|
||||
pub preview: String,
|
||||
/// Optional user-facing thread name/title.
|
||||
pub name: Option<String>,
|
||||
/// Model provider id associated with the thread.
|
||||
pub model_provider: String,
|
||||
/// Latest observed model, if known.
|
||||
pub model: Option<String>,
|
||||
/// Latest observed reasoning effort, if known.
|
||||
pub reasoning_effort: Option<ReasoningEffort>,
|
||||
/// Thread creation timestamp.
|
||||
pub created_at: DateTime<Utc>,
|
||||
/// Thread last-update timestamp.
|
||||
pub updated_at: DateTime<Utc>,
|
||||
/// Thread archive timestamp, if archived.
|
||||
pub archived_at: Option<DateTime<Utc>>,
|
||||
/// Working directory captured for the thread.
|
||||
pub cwd: PathBuf,
|
||||
/// CLI version captured for the thread.
|
||||
pub cli_version: String,
|
||||
/// Runtime source for the thread.
|
||||
pub source: SessionSource,
|
||||
/// Optional random nickname for thread-spawn sub-agents.
|
||||
pub agent_nickname: Option<String>,
|
||||
/// Optional role for thread-spawn sub-agents.
|
||||
pub agent_role: Option<String>,
|
||||
/// Optional canonical path for thread-spawn sub-agents.
|
||||
pub agent_path: Option<String>,
|
||||
/// Optional Git metadata captured for the thread.
|
||||
pub git_info: Option<GitInfo>,
|
||||
/// Approval mode captured for the thread.
|
||||
pub approval_mode: AskForApproval,
|
||||
/// Sandbox policy captured for the thread.
|
||||
pub sandbox_policy: SandboxPolicy,
|
||||
/// Last observed token usage.
|
||||
pub token_usage: Option<TokenUsage>,
|
||||
/// First user message observed for this thread, if any.
|
||||
pub first_user_message: Option<String>,
|
||||
/// Persisted history, populated only when requested.
|
||||
pub history: Option<StoredThreadHistory>,
|
||||
}
|
||||
|
||||
/// Optional field patch where omission leaves a value unchanged and `Some(None)` clears it.
|
||||
pub type OptionalStringPatch = Option<Option<String>>;
|
||||
|
||||
/// Patch for thread Git metadata.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct GitInfoPatch {
|
||||
/// Replacement commit SHA, clear request, or no-op.
|
||||
pub sha: OptionalStringPatch,
|
||||
/// Replacement branch name, clear request, or no-op.
|
||||
pub branch: OptionalStringPatch,
|
||||
/// Replacement origin URL, clear request, or no-op.
|
||||
pub origin_url: OptionalStringPatch,
|
||||
}
|
||||
|
||||
/// Patch for mutable thread metadata.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ThreadMetadataPatch {
|
||||
/// Replacement user-facing thread name.
|
||||
pub name: Option<String>,
|
||||
/// Replacement thread memory behavior.
|
||||
pub memory_mode: Option<MemoryMode>,
|
||||
/// Optional Git metadata patch.
|
||||
pub git_info: Option<GitInfoPatch>,
|
||||
}
|
||||
|
||||
/// Parameters for patching mutable thread metadata.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct UpdateThreadMetadataParams {
|
||||
/// Thread id to update.
|
||||
pub thread_id: ThreadId,
|
||||
/// Patch to apply.
|
||||
pub patch: ThreadMetadataPatch,
|
||||
/// Whether archived threads are eligible.
|
||||
pub include_archived: bool,
|
||||
}
|
||||
|
||||
/// Parameters for archiving or unarchiving a thread.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ArchiveThreadParams {
|
||||
/// Thread id to archive or unarchive.
|
||||
pub thread_id: ThreadId,
|
||||
}
|
||||
Reference in a new issue