mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
codex: address thread read review feedback
This commit is contained in:
@@ -434,6 +434,11 @@ enum ThreadShutdownResult {
|
||||
TimedOut,
|
||||
}
|
||||
|
||||
enum ThreadReadViewError {
|
||||
InvalidRequest(String),
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
impl Drop for ActiveLogin {
|
||||
fn drop(&mut self) {
|
||||
self.cancel();
|
||||
@@ -3782,116 +3787,160 @@ impl CodexMessageProcessor {
|
||||
}
|
||||
};
|
||||
|
||||
let loaded_thread = self.thread_manager.get_thread(thread_uuid).await.ok();
|
||||
let stored_thread = match self
|
||||
let thread = match self
|
||||
.read_thread_view(thread_uuid, include_turns, /*include_archived*/ false)
|
||||
.await
|
||||
{
|
||||
Ok(thread) => thread,
|
||||
Err(ThreadReadViewError::InvalidRequest(message)) => {
|
||||
self.send_invalid_request_error(request_id, message).await;
|
||||
return;
|
||||
}
|
||||
Err(ThreadReadViewError::Internal(message)) => {
|
||||
self.send_internal_error(request_id, message).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
let response = ThreadReadResponse { thread };
|
||||
self.outgoing.send_response(request_id, response).await;
|
||||
}
|
||||
|
||||
/// Builds an API thread view by composing persisted store data with loaded live state.
|
||||
async fn read_thread_view(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
include_turns: bool,
|
||||
include_archived: bool,
|
||||
) -> Result<Thread, ThreadReadViewError> {
|
||||
let loaded_thread = self.thread_manager.get_thread(thread_id).await.ok();
|
||||
|
||||
// Thread API views prefer persisted store data because that is the stable
|
||||
// cross-process/cross-host source of truth. A live thread is only used as a
|
||||
// fallback when the store cannot resolve the id but this app-server already has
|
||||
// the thread loaded in memory.
|
||||
let mut thread = match self
|
||||
.thread_store
|
||||
.read_thread(StoreReadThreadParams {
|
||||
thread_id: thread_uuid,
|
||||
include_archived: false,
|
||||
thread_id,
|
||||
include_archived,
|
||||
include_history: include_turns,
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(thread) => Some(thread),
|
||||
Err(ThreadStoreError::InvalidRequest { message }) if loaded_thread.is_some() => {
|
||||
debug!("falling back to loaded thread for {thread_uuid}: {message}");
|
||||
None
|
||||
Ok(stored_thread) => {
|
||||
self.thread_view_from_stored_thread(stored_thread, include_turns)?
|
||||
}
|
||||
Err(ThreadStoreError::ThreadNotFound { .. }) if loaded_thread.is_some() => {
|
||||
debug!("falling back to loaded thread for {thread_uuid}: thread not found");
|
||||
None
|
||||
Err(ThreadStoreError::InvalidRequest { message }) => {
|
||||
if let Some(loaded_thread) = loaded_thread.as_ref() {
|
||||
debug!("falling back to loaded thread for {thread_id}: {message}");
|
||||
self.thread_view_from_loaded_thread(thread_id, loaded_thread, include_turns)
|
||||
.await?
|
||||
} else {
|
||||
return Err(ThreadReadViewError::InvalidRequest(message));
|
||||
}
|
||||
}
|
||||
Err(ThreadStoreError::ThreadNotFound {
|
||||
thread_id: missing_thread_id,
|
||||
}) => {
|
||||
if let Some(loaded_thread) = loaded_thread.as_ref() {
|
||||
debug!("falling back to loaded thread for {thread_id}: thread not found");
|
||||
self.thread_view_from_loaded_thread(thread_id, loaded_thread, include_turns)
|
||||
.await?
|
||||
} else {
|
||||
return Err(ThreadReadViewError::InvalidRequest(format!(
|
||||
"thread not found: {missing_thread_id}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
self.outgoing
|
||||
.send_error(request_id, thread_store_read_error(err))
|
||||
.await;
|
||||
return;
|
||||
return Err(ThreadReadViewError::Internal(format!(
|
||||
"failed to read thread: {err}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
let mut thread = if let Some(stored_thread) = stored_thread {
|
||||
let fallback_provider = self.config.model_provider_id.as_str();
|
||||
let Some((mut thread, history)) =
|
||||
thread_from_stored_thread(stored_thread, fallback_provider, &self.config.cwd)
|
||||
else {
|
||||
self.send_internal_error(
|
||||
request_id,
|
||||
format!("failed to read thread {thread_uuid}"),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
};
|
||||
if include_turns {
|
||||
let Some(history) = history else {
|
||||
self.send_internal_error(
|
||||
request_id,
|
||||
format!("failed to load rollout history for thread {thread_uuid}"),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
};
|
||||
thread.turns = build_turns_from_rollout_items(&history.items);
|
||||
}
|
||||
thread
|
||||
} else {
|
||||
// Only loaded live threads reach this branch. Stored threads should be read through the
|
||||
// thread store above, while live threads may not have materialized a rollout yet.
|
||||
let Some(thread) = loaded_thread.as_ref() else {
|
||||
self.send_invalid_request_error(
|
||||
request_id,
|
||||
format!("thread not loaded: {thread_uuid}"),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
};
|
||||
let config_snapshot = thread.config_snapshot().await;
|
||||
let loaded_rollout_path = thread.rollout_path();
|
||||
if include_turns {
|
||||
let message = if config_snapshot.ephemeral && loaded_rollout_path.is_none() {
|
||||
"ephemeral threads do not support includeTurns".to_string()
|
||||
} else {
|
||||
format!(
|
||||
"thread {thread_uuid} is not materialized yet; includeTurns is unavailable before first user message"
|
||||
)
|
||||
};
|
||||
self.send_invalid_request_error(request_id, message).await;
|
||||
return;
|
||||
}
|
||||
let mut thread =
|
||||
build_thread_from_snapshot(thread_uuid, &config_snapshot, loaded_rollout_path);
|
||||
// Stored-thread metadata is applied inside LocalThreadStore. This is only for loaded
|
||||
// live threads that are not yet readable from the store, such as a newly started thread
|
||||
// with a precomputed rollout path but no materialized rollout file.
|
||||
if let Some(summary) =
|
||||
read_summary_from_state_db_by_thread_id(&self.config, thread_uuid).await
|
||||
{
|
||||
merge_mutable_thread_metadata(
|
||||
&mut thread,
|
||||
summary_to_thread(summary, &self.config.cwd),
|
||||
);
|
||||
}
|
||||
self.attach_thread_name(thread_uuid, &mut thread).await;
|
||||
thread
|
||||
};
|
||||
|
||||
let has_live_in_progress_turn = if let Some(loaded_thread) = loaded_thread.as_ref() {
|
||||
matches!(loaded_thread.agent_status().await, AgentStatus::Running)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
let thread_status = self
|
||||
.thread_watch_manager
|
||||
.loaded_status_for_thread(&thread.id)
|
||||
.await;
|
||||
|
||||
set_thread_status_and_interrupt_stale_turns(
|
||||
&mut thread,
|
||||
thread_status,
|
||||
has_live_in_progress_turn,
|
||||
);
|
||||
let response = ThreadReadResponse { thread };
|
||||
self.outgoing.send_response(request_id, response).await;
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
fn thread_view_from_stored_thread(
|
||||
&self,
|
||||
stored_thread: StoredThread,
|
||||
include_turns: bool,
|
||||
) -> Result<Thread, ThreadReadViewError> {
|
||||
let thread_id = stored_thread.thread_id;
|
||||
let fallback_provider = self.config.model_provider_id.as_str();
|
||||
let (mut thread, history) =
|
||||
thread_from_stored_thread(stored_thread, fallback_provider, &self.config.cwd);
|
||||
if include_turns {
|
||||
let Some(history) = history else {
|
||||
return Err(ThreadReadViewError::Internal(format!(
|
||||
"failed to load rollout history for thread {thread_id}"
|
||||
)));
|
||||
};
|
||||
thread.turns = build_turns_from_rollout_items(&history.items);
|
||||
}
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
async fn thread_view_from_loaded_thread(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
loaded_thread: &Arc<CodexThread>,
|
||||
include_turns: bool,
|
||||
) -> Result<Thread, ThreadReadViewError> {
|
||||
let config_snapshot = loaded_thread.config_snapshot().await;
|
||||
let loaded_rollout_path = loaded_thread.rollout_path();
|
||||
let mut thread =
|
||||
build_thread_from_snapshot(thread_id, &config_snapshot, loaded_rollout_path.clone());
|
||||
|
||||
// Temporary live-thread metadata shim: stored-thread metadata is owned by
|
||||
// ThreadStore, but loaded threads that are not yet readable from the store may
|
||||
// still have local metadata. Keep this compatibility path centralized here so
|
||||
// future remote threadstore implementations have one app-server boundary to replace.
|
||||
if let Some(summary) =
|
||||
read_summary_from_state_db_by_thread_id(&self.config, thread_id).await
|
||||
{
|
||||
merge_mutable_thread_metadata(
|
||||
&mut thread,
|
||||
summary_to_thread(summary, &self.config.cwd),
|
||||
);
|
||||
}
|
||||
self.attach_thread_name(thread_id, &mut thread).await;
|
||||
|
||||
if include_turns {
|
||||
let path = loaded_materialized_rollout_path(
|
||||
thread_id,
|
||||
&config_snapshot,
|
||||
loaded_rollout_path.as_ref(),
|
||||
)?;
|
||||
// This path-based history load is a temporary local compatibility fallback for
|
||||
// live threads resumed from explicit rollout paths outside codex_home. Stored
|
||||
// thread reads should continue to go through ThreadStore; future pathless live
|
||||
// history should come from ThreadManager/CodexThread instead of the filesystem.
|
||||
let items = read_rollout_items_from_rollout(path).await.map_err(|err| {
|
||||
ThreadReadViewError::Internal(format!(
|
||||
"failed to load rollout history {}: {err}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
thread.turns = build_turns_from_rollout_items(&items);
|
||||
}
|
||||
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
pub(crate) fn thread_created_receiver(&self) -> broadcast::Receiver<ThreadId> {
|
||||
@@ -4820,8 +4869,7 @@ impl CodexMessageProcessor {
|
||||
match params {
|
||||
GetConversationSummaryParams::RolloutPath { rollout_path } => {
|
||||
// Legacy compatibility for clients that still hold local rollout paths. New
|
||||
// callsites should prefer thread-id lookups through the thread store so hosted
|
||||
// stores do not need to expose filesystem paths.
|
||||
// callsites should prefer thread-id lookups through the thread store.
|
||||
let path = if rollout_path.is_relative() {
|
||||
self.config.codex_home.join(&rollout_path).to_path_buf()
|
||||
} else {
|
||||
@@ -9172,8 +9220,8 @@ fn thread_from_stored_thread(
|
||||
thread: StoredThread,
|
||||
fallback_provider: &str,
|
||||
fallback_cwd: &AbsolutePathBuf,
|
||||
) -> Option<(Thread, Option<codex_thread_store::StoredThreadHistory>)> {
|
||||
let path = thread.rollout_path?;
|
||||
) -> (Thread, Option<codex_thread_store::StoredThreadHistory>) {
|
||||
let path = thread.rollout_path;
|
||||
let git_info = thread.git_info.map(|info| ApiGitInfo {
|
||||
sha: info.commit_hash.map(|sha| sha.0),
|
||||
branch: info.branch,
|
||||
@@ -9183,10 +9231,7 @@ fn thread_from_stored_thread(
|
||||
thread.cwd,
|
||||
))
|
||||
.unwrap_or_else(|err| {
|
||||
warn!(
|
||||
path = %path.display(),
|
||||
"failed to normalize thread cwd while reading stored thread: {err}"
|
||||
);
|
||||
warn!("failed to normalize thread cwd while reading stored thread: {err}");
|
||||
fallback_cwd.clone()
|
||||
});
|
||||
let source = with_thread_spawn_agent_metadata(
|
||||
@@ -9208,7 +9253,7 @@ fn thread_from_stored_thread(
|
||||
created_at: thread.created_at.timestamp(),
|
||||
updated_at: thread.updated_at.timestamp(),
|
||||
status: ThreadStatus::NotLoaded,
|
||||
path: Some(path),
|
||||
path,
|
||||
cwd,
|
||||
cli_version: thread.cli_version,
|
||||
agent_nickname: source.get_nickname(),
|
||||
@@ -9218,7 +9263,30 @@ fn thread_from_stored_thread(
|
||||
name: thread.name,
|
||||
turns: Vec::new(),
|
||||
};
|
||||
Some((thread, history))
|
||||
(thread, history)
|
||||
}
|
||||
|
||||
fn loaded_materialized_rollout_path<'a>(
|
||||
thread_id: ThreadId,
|
||||
config_snapshot: &ThreadConfigSnapshot,
|
||||
rollout_path: Option<&'a PathBuf>,
|
||||
) -> Result<&'a Path, ThreadReadViewError> {
|
||||
let Some(path) = rollout_path else {
|
||||
let message = if config_snapshot.ephemeral {
|
||||
"ephemeral threads do not support includeTurns".to_string()
|
||||
} else {
|
||||
format!(
|
||||
"thread {thread_id} is not materialized yet; includeTurns is unavailable before first user message"
|
||||
)
|
||||
};
|
||||
return Err(ThreadReadViewError::InvalidRequest(message));
|
||||
};
|
||||
if !path.exists() {
|
||||
return Err(ThreadReadViewError::InvalidRequest(format!(
|
||||
"thread {thread_id} is not materialized yet; includeTurns is unavailable before first user message"
|
||||
)));
|
||||
}
|
||||
Ok(path.as_path())
|
||||
}
|
||||
|
||||
fn thread_store_archive_error(operation: &str, err: ThreadStoreError) -> JSONRPCErrorError {
|
||||
|
||||
@@ -2,6 +2,7 @@ use anyhow::Result;
|
||||
use app_test_support::McpProcess;
|
||||
use app_test_support::create_fake_rollout_with_text_elements;
|
||||
use app_test_support::create_mock_responses_server_repeating_assistant;
|
||||
use app_test_support::rollout_path;
|
||||
use app_test_support::test_absolute_path;
|
||||
use app_test_support::to_response;
|
||||
use codex_app_server_protocol::JSONRPCError;
|
||||
@@ -157,6 +158,90 @@ async fn thread_read_can_include_turns() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_read_include_turns_supports_loaded_explicit_path_thread() -> Result<()> {
|
||||
let server = create_mock_responses_server_repeating_assistant("Done").await;
|
||||
let codex_home = TempDir::new()?;
|
||||
let external_home = TempDir::new()?;
|
||||
create_config_toml(codex_home.path(), &server.uri())?;
|
||||
|
||||
let filename_ts = "2025-01-05T12-00-00";
|
||||
let preview = "External saved user message";
|
||||
let text_elements = vec![TextElement::new(
|
||||
ByteRange { start: 0, end: 8 },
|
||||
Some("<external>".into()),
|
||||
)];
|
||||
let conversation_id = create_fake_rollout_with_text_elements(
|
||||
external_home.path(),
|
||||
filename_ts,
|
||||
"2025-01-05T12:00:00Z",
|
||||
preview,
|
||||
text_elements
|
||||
.iter()
|
||||
.map(|elem| serde_json::to_value(elem).expect("serialize text element"))
|
||||
.collect(),
|
||||
Some("mock_provider"),
|
||||
/*git_info*/ None,
|
||||
)?;
|
||||
let external_rollout_path = rollout_path(external_home.path(), filename_ts, &conversation_id);
|
||||
|
||||
let mut mcp = McpProcess::new(codex_home.path()).await?;
|
||||
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
|
||||
|
||||
let resume_id = mcp
|
||||
.send_thread_resume_request(ThreadResumeParams {
|
||||
thread_id: conversation_id.clone(),
|
||||
path: Some(external_rollout_path),
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
let resume_resp: JSONRPCResponse = timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(resume_id)),
|
||||
)
|
||||
.await??;
|
||||
let ThreadResumeResponse {
|
||||
thread: resumed, ..
|
||||
} = to_response::<ThreadResumeResponse>(resume_resp)?;
|
||||
assert_eq!(resumed.id, conversation_id);
|
||||
|
||||
let read_id = mcp
|
||||
.send_thread_read_request(ThreadReadParams {
|
||||
thread_id: conversation_id,
|
||||
include_turns: true,
|
||||
})
|
||||
.await?;
|
||||
let read_resp: JSONRPCResponse = timeout(
|
||||
DEFAULT_READ_TIMEOUT,
|
||||
mcp.read_stream_until_response_message(RequestId::Integer(read_id)),
|
||||
)
|
||||
.await??;
|
||||
let ThreadReadResponse { thread } = to_response::<ThreadReadResponse>(read_resp)?;
|
||||
|
||||
assert_eq!(
|
||||
thread.turns.len(),
|
||||
1,
|
||||
"expected explicit-path rollout to provide one turn"
|
||||
);
|
||||
let turn = &thread.turns[0];
|
||||
assert_eq!(turn.status, TurnStatus::Completed);
|
||||
assert_eq!(turn.items.len(), 1, "expected user message item");
|
||||
match &turn.items[0] {
|
||||
ThreadItem::UserMessage { content, .. } => {
|
||||
assert_eq!(
|
||||
content,
|
||||
&vec![UserInput::Text {
|
||||
text: preview.to_string(),
|
||||
text_elements: text_elements.into_iter().map(Into::into).collect(),
|
||||
}]
|
||||
);
|
||||
}
|
||||
other => panic!("expected user message item, got {other:?}"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_read_returns_forked_from_id_for_forked_threads() -> Result<()> {
|
||||
let server = create_mock_responses_server_repeating_assistant("Done").await;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use codex_rollout::RolloutRecorder;
|
||||
use codex_rollout::find_archived_thread_path_by_id_str;
|
||||
use codex_rollout::find_thread_name_by_id;
|
||||
@@ -17,6 +19,21 @@ pub(super) async fn read_thread(
|
||||
store: &LocalThreadStore,
|
||||
params: ReadThreadParams,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
// Local store resolution is rollout-first so summary extraction stays aligned
|
||||
// with list/read behavior for normal persisted sessions. SQLite is a fallback
|
||||
// for metadata rows that refer to rollouts not discoverable under codex_home,
|
||||
// such as explicit-path resumes or legacy state.
|
||||
let Some(path) = resolve_rollout_path(store, ¶ms).await? else {
|
||||
return read_thread_from_sqlite_fallback(store, params).await;
|
||||
};
|
||||
|
||||
read_thread_from_rollout_path(store, params, path).await
|
||||
}
|
||||
|
||||
async fn resolve_rollout_path(
|
||||
store: &LocalThreadStore,
|
||||
params: &ReadThreadParams,
|
||||
) -> ThreadStoreResult<Option<std::path::PathBuf>> {
|
||||
let thread_id = params.thread_id;
|
||||
let path = if params.include_archived {
|
||||
match find_thread_path_by_id_str(store.config.codex_home.as_path(), &thread_id.to_string())
|
||||
@@ -40,11 +57,16 @@ pub(super) async fn read_thread(
|
||||
.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}"),
|
||||
})?;
|
||||
};
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
async fn read_thread_from_rollout_path(
|
||||
store: &LocalThreadStore,
|
||||
params: ReadThreadParams,
|
||||
path: std::path::PathBuf,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
let thread_id = params.thread_id;
|
||||
let item = read_thread_item_from_rollout(path.clone())
|
||||
.await
|
||||
.ok_or_else(|| ThreadStoreError::Internal {
|
||||
@@ -77,21 +99,7 @@ pub(super) async fn read_thread(
|
||||
found_sqlite_title = true;
|
||||
set_thread_name_from_title(&mut thread, title);
|
||||
}
|
||||
thread.git_info = if metadata.git_sha.is_none()
|
||||
&& metadata.git_branch.is_none()
|
||||
&& metadata.git_origin_url.is_none()
|
||||
{
|
||||
None
|
||||
} else {
|
||||
Some(codex_protocol::protocol::GitInfo {
|
||||
commit_hash: metadata
|
||||
.git_sha
|
||||
.as_deref()
|
||||
.map(codex_git_utils::GitSha::new),
|
||||
branch: metadata.git_branch,
|
||||
repository_url: metadata.git_origin_url,
|
||||
})
|
||||
};
|
||||
thread.git_info = git_info_from_metadata(&metadata);
|
||||
}
|
||||
if !found_sqlite_title
|
||||
&& let Ok(Some(title)) =
|
||||
@@ -100,16 +108,110 @@ pub(super) async fn read_thread(
|
||||
set_thread_name_from_title(&mut thread, title);
|
||||
}
|
||||
if params.include_history {
|
||||
let (items, _, _) = RolloutRecorder::load_rollout_items(path.as_path())
|
||||
.await
|
||||
.map_err(|err| ThreadStoreError::Internal {
|
||||
message: format!("failed to load thread history {}: {err}", path.display()),
|
||||
})?;
|
||||
let items = load_history_items(&path).await?;
|
||||
thread.history = Some(StoredThreadHistory { thread_id, items });
|
||||
}
|
||||
Ok(thread)
|
||||
}
|
||||
|
||||
async fn read_thread_from_sqlite_fallback(
|
||||
store: &LocalThreadStore,
|
||||
params: ReadThreadParams,
|
||||
) -> ThreadStoreResult<StoredThread> {
|
||||
let thread_id = params.thread_id;
|
||||
let metadata = match codex_state::StateRuntime::init(
|
||||
store.config.sqlite_home.clone(),
|
||||
store.config.model_provider_id.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(runtime) => runtime.get_thread(thread_id).await.ok().flatten(),
|
||||
Err(_) => None,
|
||||
};
|
||||
let Some(metadata) =
|
||||
metadata.filter(|metadata| params.include_archived || metadata.archived_at.is_none())
|
||||
else {
|
||||
return Err(ThreadStoreError::InvalidRequest {
|
||||
message: format!("no rollout found for thread id {thread_id}"),
|
||||
});
|
||||
};
|
||||
|
||||
let mut thread = stored_thread_from_sqlite_metadata(store, metadata).await;
|
||||
if params.include_history {
|
||||
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(thread)
|
||||
}
|
||||
|
||||
async fn stored_thread_from_sqlite_metadata(
|
||||
store: &LocalThreadStore,
|
||||
metadata: codex_state::ThreadMetadata,
|
||||
) -> StoredThread {
|
||||
let mut thread = StoredThread {
|
||||
thread_id: metadata.id,
|
||||
rollout_path: Some(metadata.rollout_path.clone()),
|
||||
forked_from_id: read_session_meta_line(metadata.rollout_path.as_path())
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|meta_line| meta_line.meta.forked_from_id),
|
||||
preview: metadata.first_user_message.clone().unwrap_or_default(),
|
||||
name: None,
|
||||
model_provider: if metadata.model_provider.is_empty() {
|
||||
store.config.model_provider_id.clone()
|
||||
} else {
|
||||
metadata.model_provider.clone()
|
||||
},
|
||||
model: metadata.model.clone(),
|
||||
reasoning_effort: metadata.reasoning_effort,
|
||||
created_at: metadata.created_at,
|
||||
updated_at: metadata.updated_at,
|
||||
archived_at: metadata.archived_at,
|
||||
cwd: metadata.cwd.clone(),
|
||||
cli_version: metadata.cli_version.clone(),
|
||||
source: parse_metadata_enum(&metadata.source)
|
||||
.unwrap_or(codex_protocol::protocol::SessionSource::Unknown),
|
||||
agent_nickname: metadata.agent_nickname.clone(),
|
||||
agent_role: metadata.agent_role.clone(),
|
||||
agent_path: metadata.agent_path.clone(),
|
||||
git_info: git_info_from_metadata(&metadata),
|
||||
approval_mode: parse_metadata_enum(&metadata.approval_mode)
|
||||
.unwrap_or(codex_protocol::protocol::AskForApproval::OnRequest),
|
||||
sandbox_policy: parse_sandbox_policy(metadata.sandbox_policy.as_str()),
|
||||
token_usage: (metadata.tokens_used > 0).then(|| codex_protocol::protocol::TokenUsage {
|
||||
total_tokens: metadata.tokens_used,
|
||||
..Default::default()
|
||||
}),
|
||||
first_user_message: metadata.first_user_message.clone(),
|
||||
history: None,
|
||||
};
|
||||
|
||||
if let Some(title) = distinct_title(&metadata) {
|
||||
set_thread_name_from_title(&mut thread, title);
|
||||
} else if let Ok(Some(title)) =
|
||||
find_thread_name_by_id(store.config.codex_home.as_path(), &metadata.id).await
|
||||
{
|
||||
set_thread_name_from_title(&mut thread, title);
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
fn distinct_title(metadata: &codex_state::ThreadMetadata) -> Option<String> {
|
||||
let title = metadata.title.trim();
|
||||
if title.is_empty() || metadata.first_user_message.as_deref().map(str::trim) == Some(title) {
|
||||
@@ -126,6 +228,44 @@ fn set_thread_name_from_title(thread: &mut StoredThread, title: String) {
|
||||
thread.name = Some(title);
|
||||
}
|
||||
|
||||
fn git_info_from_metadata(
|
||||
metadata: &codex_state::ThreadMetadata,
|
||||
) -> Option<codex_protocol::protocol::GitInfo> {
|
||||
if metadata.git_sha.is_none()
|
||||
&& metadata.git_branch.is_none()
|
||||
&& metadata.git_origin_url.is_none()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(codex_protocol::protocol::GitInfo {
|
||||
commit_hash: metadata
|
||||
.git_sha
|
||||
.as_deref()
|
||||
.map(codex_git_utils::GitSha::new),
|
||||
branch: metadata.git_branch.clone(),
|
||||
repository_url: metadata.git_origin_url.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_metadata_enum<T: DeserializeOwned>(value: &str) -> Option<T> {
|
||||
serde_json::from_str(value)
|
||||
.or_else(|_| serde_json::from_value(serde_json::Value::String(value.to_string())))
|
||||
.ok()
|
||||
}
|
||||
|
||||
fn parse_sandbox_policy(value: &str) -> codex_protocol::protocol::SandboxPolicy {
|
||||
parse_metadata_enum(value)
|
||||
.or_else(|| match value.trim() {
|
||||
"danger-full-access" => Some(codex_protocol::protocol::SandboxPolicy::DangerFullAccess),
|
||||
"read-only" => Some(codex_protocol::protocol::SandboxPolicy::new_read_only_policy()),
|
||||
"workspace-write" => {
|
||||
Some(codex_protocol::protocol::SandboxPolicy::new_workspace_write_policy())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(codex_protocol::protocol::SandboxPolicy::new_read_only_policy)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::Utc;
|
||||
@@ -382,6 +522,183 @@ mod tests {
|
||||
assert_eq!(thread.name, Some("Legacy title".to_string()));
|
||||
}
|
||||
|
||||
#[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());
|
||||
metadata.git_sha = Some("abc123".to_string());
|
||||
metadata.git_branch = Some("sqlite-branch".to_string());
|
||||
metadata.git_origin_url = Some("https://example.com/sqlite.git".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);
|
||||
let git_info = thread.git_info.expect("git info should be applied");
|
||||
assert_eq!(
|
||||
git_info.commit_hash.map(|sha| sha.0),
|
||||
Some("abc123".to_string())
|
||||
);
|
||||
assert_eq!(git_info.branch.as_deref(), Some("sqlite-branch"));
|
||||
assert_eq!(
|
||||
git_info.repository_url.as_deref(),
|
||||
Some("https://example.com/sqlite.git")
|
||||
);
|
||||
assert!(thread.history.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_thread_sqlite_fallback_can_load_history() {
|
||||
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(215);
|
||||
let thread_id = ThreadId::from_string(&uuid.to_string()).expect("valid thread id");
|
||||
let rollout_path = write_session_file_with_fork(
|
||||
external.path(),
|
||||
external.path().join("sessions/2025/01/03"),
|
||||
"2025-01-03T12-00-00",
|
||||
uuid,
|
||||
"History user message",
|
||||
Some("external-provider"),
|
||||
/*forked_from_id*/ None,
|
||||
)
|
||||
.expect("external 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("sqlite-provider".to_string());
|
||||
builder.cwd = external.path().to_path_buf();
|
||||
let mut metadata = builder.build(config.model_provider_id.as_str());
|
||||
metadata.first_user_message = Some("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: false,
|
||||
include_history: true,
|
||||
})
|
||||
.await
|
||||
.expect("read thread");
|
||||
|
||||
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_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_fails_without_rollout() {
|
||||
let home = TempDir::new().expect("temp dir");
|
||||
|
||||
Reference in New Issue
Block a user