refactor(worktree): simplify app-server client boundaries

This commit is contained in:
Felipe Coury
2026-05-10 12:53:01 -03:00
parent 1276652068
commit 3e1a5e7275
11 changed files with 243 additions and 278 deletions
-1
View File
@@ -2682,7 +2682,6 @@ dependencies = [
"codex-utils-cargo-bin",
"codex-utils-cli",
"codex-utils-oss",
"codex-worktree",
"core_test_support",
"libc",
"opentelemetry",
@@ -99,19 +99,11 @@ impl WorktreeRequestProcessor {
&self,
params: WorktreePruneParams,
) -> Result<WorktreePruneResponse, JSONRPCErrorError> {
let stale_paths =
codex_worktree::stale_managed_worktree_dirs(self.config_manager.codex_home())
.map_err(map_worktree_error)?;
if !params.dry_run {
for path in &stale_paths {
std::fs::remove_dir_all(path).map_err(|err| {
map_worktree_error(anyhow::anyhow!(
"failed to remove stale worktree directory {}: {err}",
path.display()
))
})?;
}
}
let stale_paths = codex_worktree::prune_stale_managed_worktree_dirs(
self.config_manager.codex_home(),
params.dry_run,
)
.map_err(map_worktree_error)?;
Ok(WorktreePruneResponse {
paths: stale_paths
.into_iter()
+30 -62
View File
@@ -17,12 +17,15 @@ use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::WorktreeCreateParams;
use codex_app_server_protocol::WorktreeCreateResponse;
use codex_app_server_protocol::WorktreeDirtyPolicy as ApiWorktreeDirtyPolicy;
use codex_app_server_protocol::WorktreeDirtyState;
use codex_app_server_protocol::WorktreeInfo;
use codex_app_server_protocol::WorktreeListParams;
use codex_app_server_protocol::WorktreeListResponse;
use codex_app_server_protocol::WorktreePruneParams;
use codex_app_server_protocol::WorktreePruneResponse;
use codex_app_server_protocol::WorktreeRemoveParams;
use codex_app_server_protocol::WorktreeRemoveResponse;
use codex_app_server_protocol::WorktreeSource;
use codex_arg0::Arg0DispatchPaths;
use codex_arg0::arg0_dispatch_or_else;
use codex_chatgpt::apply_command::ApplyCommand;
@@ -56,8 +59,6 @@ use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_cli::CliConfigOverrides;
use codex_utils_cli::SharedCliOptions;
use codex_utils_cli::WorktreeDirtyCliArg;
use codex_worktree::WorktreeInfo;
use codex_worktree::WorktreeResolution;
use owo_colors::OwoColorize;
use std::io::IsTerminal;
use std::path::PathBuf;
@@ -780,9 +781,9 @@ async fn resolve_worktree_options_for_shared_cli(
remote: Option<&str>,
remote_auth_token_env: Option<&str>,
arg0_paths: Arg0DispatchPaths,
) -> anyhow::Result<Option<WorktreeResolution>> {
) -> anyhow::Result<()> {
let Some(branch) = shared.worktree.take() else {
return Ok(None);
return Ok(());
};
if remote.is_some() || remote_auth_token_env.is_some() {
@@ -805,25 +806,14 @@ async fn resolve_worktree_options_for_shared_cli(
},
})
.await?;
let resolution = WorktreeResolution {
reused: response.reused,
info: worktree_info_from_api(response.info)?,
warnings: response
.warnings
.into_iter()
.map(|warning| codex_worktree::WorktreeWarning {
message: warning.message,
})
.collect(),
};
shared.cwd = Some(resolution.info.workspace_cwd.clone());
shared.cwd = Some(PathBuf::from(response.info.workspace_cwd));
#[allow(clippy::print_stderr)]
for warning in &resolution.warnings {
for warning in &response.warnings {
eprintln!("warning: {}", warning.message);
}
Ok(Some(resolution))
Ok(())
}
async fn run_worktree_command(
@@ -863,10 +853,15 @@ async fn run_worktree_command(
print_worktree_list(entries, command.json)?;
}
WorktreeSubcommand::Path(command) => {
let entries =
cli_list_worktrees(&client, cwd.clone(), false, &mut next_request_id).await?;
let entries = cli_list_worktrees(
&client,
cwd.clone(),
/*all*/ false,
&mut next_request_id,
)
.await?;
let entry = find_named_worktree(entries, &command.name)?;
println!("{}", entry.workspace_cwd.display());
println!("{}", entry.workspace_cwd);
}
WorktreeSubcommand::Remove(command) => {
let result: WorktreeRemoveResponse = client
@@ -894,11 +889,7 @@ async fn run_worktree_command(
},
})
.await?;
let stale_paths = response
.paths
.into_iter()
.map(PathBuf::from)
.collect::<Vec<_>>();
let stale_paths = response.paths;
if command.json {
println!("{}", serde_json::to_string_pretty(&stale_paths)?);
} else if stale_paths.is_empty() {
@@ -906,9 +897,9 @@ async fn run_worktree_command(
} else {
for path in &stale_paths {
if command.dry_run {
println!("would remove {}", path.display());
println!("would remove {path}");
} else {
println!("removed {}", path.display());
println!("removed {path}");
}
}
}
@@ -929,11 +920,7 @@ async fn cli_list_worktrees(
params: WorktreeListParams { cwd, all },
})
.await?;
response
.data
.into_iter()
.map(worktree_info_from_api)
.collect()
Ok(response.data)
}
fn next_cli_request_id(next: &mut i64) -> RequestId {
@@ -1021,29 +1008,6 @@ async fn worktree_app_server_client(
))
}
fn worktree_info_from_api(
info: codex_app_server_protocol::WorktreeInfo,
) -> anyhow::Result<WorktreeInfo> {
Ok(WorktreeInfo {
id: info.id,
name: info.name,
slug: info.slug,
source: serde_json::from_value(serde_json::to_value(info.source)?)?,
location: serde_json::from_value(serde_json::to_value(info.location)?)?,
repo_name: info.repo_name,
repo_root: PathBuf::from(info.repo_root),
common_git_dir: PathBuf::from(info.common_git_dir),
worktree_git_root: PathBuf::from(info.worktree_git_root),
workspace_cwd: PathBuf::from(info.workspace_cwd),
original_relative_cwd: PathBuf::from(info.original_relative_cwd),
branch: info.branch,
head: info.head,
owner_thread_id: info.owner_thread_id,
metadata_path: PathBuf::from(info.metadata_path),
dirty: serde_json::from_value(serde_json::to_value(info.dirty)?)?,
})
}
fn print_worktree_list(entries: Vec<WorktreeInfo>, json: bool) -> anyhow::Result<()> {
if json {
println!("{}", serde_json::to_string_pretty(&entries)?);
@@ -1052,7 +1016,7 @@ fn print_worktree_list(entries: Vec<WorktreeInfo>, json: bool) -> anyhow::Result
let mut rows = Vec::new();
for entry in &entries {
let status = if entry.dirty.is_dirty() {
let status = if dirty_state_is_dirty(&entry.dirty) {
"dirty"
} else {
"clean"
@@ -1066,7 +1030,7 @@ fn print_worktree_list(entries: Vec<WorktreeInfo>, json: bool) -> anyhow::Result
.as_deref()
.unwrap_or("none")
.to_string(),
entry.workspace_cwd.display().to_string(),
entry.workspace_cwd.clone(),
]);
}
let headers = ["BRANCH", "STATUS", "SOURCE", "THREAD", "PATH"];
@@ -1107,13 +1071,17 @@ fn print_worktree_list(entries: Vec<WorktreeInfo>, json: bool) -> anyhow::Result
fn worktree_source_label(entry: &WorktreeInfo) -> &'static str {
match entry.source {
codex_worktree::WorktreeSource::Cli => "cli",
codex_worktree::WorktreeSource::App => "app",
codex_worktree::WorktreeSource::Legacy => "legacy",
codex_worktree::WorktreeSource::Git => "git",
WorktreeSource::Cli => "cli",
WorktreeSource::App => "app",
WorktreeSource::Legacy => "legacy",
WorktreeSource::Git => "git",
}
}
fn dirty_state_is_dirty(dirty: &WorktreeDirtyState) -> bool {
dirty.has_staged_changes || dirty.has_unstaged_changes || dirty.has_untracked_files
}
fn find_named_worktree(entries: Vec<WorktreeInfo>, name: &str) -> anyhow::Result<WorktreeInfo> {
let matches = entries
.into_iter()
-1
View File
@@ -37,7 +37,6 @@ codex-otel = { workspace = true }
codex-protocol = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-cli = { workspace = true }
codex-worktree = { workspace = true }
codex-utils-oss = { workspace = true }
owo-colors = { workspace = true }
serde = { workspace = true, features = ["derive"] }
-17
View File
@@ -696,7 +696,6 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
)
.await
.map_err(anyhow::Error::msg)?;
bind_worktree_thread_best_effort(&config, response.cwd.as_path(), &response.thread.id);
let session_configured =
session_configured_from_thread_resume_response(&response, &config)
.map_err(anyhow::Error::msg)?;
@@ -712,7 +711,6 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
)
.await
.map_err(anyhow::Error::msg)?;
bind_worktree_thread_best_effort(&config, response.cwd.as_path(), &response.thread.id);
let session_configured =
session_configured_from_thread_start_response(&response, &config)
.map_err(anyhow::Error::msg)?;
@@ -729,7 +727,6 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {
)
.await
.map_err(anyhow::Error::msg)?;
bind_worktree_thread_best_effort(&config, response.cwd.as_path(), &response.thread.id);
let session_configured = session_configured_from_thread_start_response(&response, &config)
.map_err(anyhow::Error::msg)?;
(session_configured.thread_id, session_configured)
@@ -1111,20 +1108,6 @@ fn session_configured_from_thread_resume_response(
)
}
fn bind_worktree_thread_best_effort(config: &Config, cwd: &Path, thread_id: &str) {
match codex_worktree::resolve_worktree(config.codex_home.as_path(), cwd) {
Ok(Some(_)) => {
if let Err(err) = codex_worktree::bind_thread(cwd, thread_id) {
tracing::warn!(?err, "failed to bind managed worktree to thread");
}
}
Ok(None) => {}
Err(err) => {
tracing::warn!(?err, "failed to resolve managed worktree metadata");
}
}
}
fn review_target_to_api(target: ReviewTarget) -> ApiReviewTarget {
match target {
ReviewTarget::UncommittedChanges => ApiReviewTarget::UncommittedChanges,
+17 -4
View File
@@ -213,15 +213,20 @@ impl App {
tui.frame_requester().schedule_frame();
}
AppEvent::SwitchToWorktree { target } => {
self.begin_switch_to_worktree_target(tui, target);
self.begin_switch_to_worktree_target(tui, app_server, target)
.await;
tui.frame_requester().schedule_frame();
}
AppEvent::SwitchToWorktreeInfo { info } => {
self.begin_switch_to_worktree_info(tui, info);
tui.frame_requester().schedule_frame();
}
AppEvent::CurrentWorktreeSelected { target } => {
self.current_worktree_selected(target);
tui.frame_requester().schedule_frame();
}
AppEvent::SwitchToWorktreeAfterLoading { target } => {
self.switch_to_worktree_target_after_loading(tui, app_server, target)
AppEvent::SwitchToWorktreeAfterLoading { info } => {
self.switch_to_worktree_info_after_loading(tui, app_server, info)
.await;
tui.frame_requester().schedule_frame();
}
@@ -233,7 +238,15 @@ impl App {
result,
} => {
self.on_worktree_session_ready(
tui, app_server, info, config, forked, warnings, result,
tui,
app_server,
super::worktree::WorktreeSessionReadyArgs {
info,
config,
forked,
warnings,
result,
},
)
.await;
tui.frame_requester().schedule_frame();
+90 -151
View File
@@ -4,25 +4,17 @@ use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::WorktreeCreateParams;
use codex_app_server_protocol::WorktreeCreateResponse;
use codex_app_server_protocol::WorktreeDirtyPolicy as ApiWorktreeDirtyPolicy;
use codex_app_server_protocol::WorktreeDirtyState as ApiWorktreeDirtyState;
use codex_app_server_protocol::WorktreeInfo as ApiWorktreeInfo;
use codex_app_server_protocol::WorktreeDirtyPolicy;
use codex_app_server_protocol::WorktreeDirtyState;
use codex_app_server_protocol::WorktreeInfo;
use codex_app_server_protocol::WorktreeInspectSourceParams;
use codex_app_server_protocol::WorktreeInspectSourceResponse;
use codex_app_server_protocol::WorktreeListParams;
use codex_app_server_protocol::WorktreeListResponse;
use codex_app_server_protocol::WorktreeLocation as ApiWorktreeLocation;
use codex_app_server_protocol::WorktreeRemoveParams;
use codex_app_server_protocol::WorktreeRemoveResponse;
use codex_app_server_protocol::WorktreeSource as ApiWorktreeSource;
use codex_app_server_protocol::WorktreeSource;
use codex_protocol::ThreadId;
use codex_worktree::DirtyPolicy;
use codex_worktree::WorktreeInfo;
use codex_worktree::WorktreeLocation;
use codex_worktree::WorktreeRequest;
use codex_worktree::WorktreeResolution;
use codex_worktree::WorktreeSource;
use codex_worktree::WorktreeWarning;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
@@ -45,6 +37,14 @@ enum WorktreeSessionTransition {
Started,
}
pub(super) struct WorktreeSessionReadyArgs {
pub(super) info: WorktreeInfo,
pub(super) config: Config,
pub(super) forked: bool,
pub(super) warnings: Vec<String>,
pub(super) result: Result<AppServerStartedThread, String>,
}
impl WorktreeSessionTransition {
fn message_prefix(self) -> &'static str {
match self {
@@ -133,17 +133,17 @@ impl App {
app_server: &AppServerSession,
branch: String,
base_ref: Option<String>,
dirty_policy: Option<DirtyPolicy>,
dirty_policy: Option<WorktreeDirtyPolicy>,
) {
let dirty_policy = match dirty_policy {
Some(policy) => policy,
None => match self.source_worktree_dirty_state(app_server).await {
Ok(state) if state.is_dirty() => {
Ok(state) if dirty_state_is_dirty(&state) => {
let params = crate::worktree::dirty_policy_prompt_params(branch, base_ref);
self.chat_widget.show_selection_view(params);
return;
}
Ok(_) => DirtyPolicy::Fail,
Ok(_) => WorktreeDirtyPolicy::Fail,
Err(err) => {
self.chat_widget
.add_error_message(format!("Failed to inspect source checkout: {err}"));
@@ -155,13 +155,10 @@ impl App {
self.show_worktree_creating_view(tui, branch.clone());
self.spawn_worktree_create_request(
app_server,
WorktreeRequest {
codex_home: self.config.codex_home.to_path_buf(),
source_cwd: self.session_workspace_cwd(app_server).to_path_buf(),
branch,
base_ref,
dirty_policy,
},
self.session_workspace_cwd(app_server).to_path_buf(),
branch,
base_ref,
dirty_policy,
);
}
@@ -170,29 +167,29 @@ impl App {
tui: &mut tui::Tui,
app_server: &mut AppServerSession,
cwd: PathBuf,
result: Result<WorktreeResolution, String>,
result: Result<WorktreeCreateResponse, String>,
) {
if cwd.as_path() != self.session_workspace_cwd(app_server) {
return;
}
let resolution = match result {
Ok(resolution) => resolution,
let response = match result {
Ok(response) => response,
Err(err) => {
self.show_worktree_error("Failed to create worktree.".to_string(), err);
return;
}
};
let target = resolution
let target = response
.info
.branch
.clone()
.unwrap_or_else(|| resolution.info.name.clone());
.unwrap_or_else(|| response.info.name.clone());
self.show_worktree_switching_view(tui, target);
self.switch_to_worktree_info(
tui,
app_server,
resolution.info,
resolution
response.info,
response
.warnings
.into_iter()
.map(|warning| warning.message)
@@ -201,20 +198,10 @@ impl App {
.await;
}
pub(super) fn begin_switch_to_worktree_target(&mut self, tui: &mut tui::Tui, target: String) {
self.show_worktree_switching_view(tui, target.clone());
self.defer_switch_to_worktree_target(target);
}
pub(super) fn current_worktree_selected(&mut self, target: String) {
self.chat_widget
.add_info_message(format!("Already in worktree {target}."), /*hint*/ None);
}
pub(super) async fn switch_to_worktree_target_after_loading(
pub(super) async fn begin_switch_to_worktree_target(
&mut self,
tui: &mut tui::Tui,
app_server: &mut AppServerSession,
app_server: &AppServerSession,
target: String,
) {
let entries = match self
@@ -234,6 +221,26 @@ impl App {
return;
}
};
self.begin_switch_to_worktree_info(tui, info);
}
pub(super) fn begin_switch_to_worktree_info(&mut self, tui: &mut tui::Tui, info: WorktreeInfo) {
let target = info.branch.clone().unwrap_or_else(|| info.name.clone());
self.show_worktree_switching_view(tui, target);
self.defer_switch_to_worktree_info(info);
}
pub(super) fn current_worktree_selected(&mut self, target: String) {
self.chat_widget
.add_info_message(format!("Already in worktree {target}."), /*hint*/ None);
}
pub(super) async fn switch_to_worktree_info_after_loading(
&mut self,
tui: &mut tui::Tui,
app_server: &mut AppServerSession,
info: WorktreeInfo,
) {
self.switch_to_worktree_info(tui, app_server, info, Vec::new())
.await;
}
@@ -249,10 +256,8 @@ impl App {
{
Ok(entries) => match crate::worktree::find_worktree(&entries, &target) {
Ok(info) => {
self.chat_widget.add_info_message(
info.workspace_cwd.display().to_string(),
/*hint*/ None,
);
self.chat_widget
.add_info_message(info.workspace_cwd.clone(), /*hint*/ None);
}
Err(err) => self.chat_widget.add_error_message(err),
},
@@ -334,17 +339,13 @@ impl App {
},
})
.await?;
Ok(response
.data
.into_iter()
.map(worktree_info_from_api)
.collect())
Ok(response.data)
}
async fn source_worktree_dirty_state(
&self,
app_server: &AppServerSession,
) -> anyhow::Result<codex_worktree::DirtyState> {
) -> anyhow::Result<WorktreeDirtyState> {
let response: WorktreeInspectSourceResponse = app_server
.request_handle()
.request_typed(ClientRequest::WorktreeInspectSource {
@@ -354,7 +355,7 @@ impl App {
},
})
.await?;
Ok(dirty_state_from_api(response.dirty))
Ok(response.dirty)
}
fn session_workspace_cwd<'a>(&'a self, app_server: &'a AppServerSession) -> &'a Path {
@@ -375,9 +376,12 @@ impl App {
fn spawn_worktree_create_request(
&self,
app_server: &AppServerSession,
request: WorktreeRequest,
source_cwd: PathBuf,
branch: String,
base_ref: Option<String>,
dirty_policy: WorktreeDirtyPolicy,
) {
let cwd = request.source_cwd.clone();
let cwd = source_cwd.clone();
let app_event_tx = self.app_event_tx.clone();
let request_handle = app_server.request_handle();
tokio::spawn(async move {
@@ -385,16 +389,14 @@ impl App {
.request_typed(ClientRequest::WorktreeCreate {
request_id: worktree_request_id("worktree-create"),
params: WorktreeCreateParams {
cwd: Some(request.source_cwd.display().to_string()),
branch: request.branch,
base_ref: request.base_ref,
dirty_policy: dirty_policy_to_api(request.dirty_policy),
cwd: Some(source_cwd.display().to_string()),
branch,
base_ref,
dirty_policy,
},
})
.await;
let result = result
.map(worktree_resolution_from_api)
.map_err(|err| err.to_string());
let result = result.map_err(|err| err.to_string());
app_event_tx.send(AppEvent::WorktreeCreated { cwd, result });
});
}
@@ -410,7 +412,7 @@ impl App {
self.config.clone()
} else {
match self
.rebuild_config_for_cwd(info.workspace_cwd.clone())
.rebuild_config_for_cwd(PathBuf::from(info.workspace_cwd.clone()))
.await
{
Ok(config) => config,
@@ -434,12 +436,15 @@ impl App {
&mut self,
tui: &mut tui::Tui,
app_server: &mut AppServerSession,
info: WorktreeInfo,
config: Config,
forked: bool,
warnings: Vec<String>,
result: Result<AppServerStartedThread, String>,
args: WorktreeSessionReadyArgs,
) {
let WorktreeSessionReadyArgs {
info,
config,
forked,
warnings,
result,
} = args;
match result {
Ok(started) => {
self.shutdown_current_thread(app_server).await;
@@ -456,7 +461,9 @@ impl App {
);
} else {
if app_server.is_remote() {
app_server.set_remote_cwd_override(Some(info.workspace_cwd.clone()));
app_server.set_remote_cwd_override(Some(PathBuf::from(
info.workspace_cwd.clone(),
)));
}
let transition = if forked {
WorktreeSessionTransition::Forked
@@ -491,7 +498,7 @@ impl App {
) {
let request_handle = app_server.request_handle();
let remote_cwd_override = if app_server.is_remote() {
Some(info.workspace_cwd.clone())
Some(PathBuf::from(info.workspace_cwd.clone()))
} else {
app_server.remote_cwd_override().map(Path::to_path_buf)
};
@@ -600,11 +607,11 @@ impl App {
tui.frame_requester().schedule_frame();
}
fn defer_switch_to_worktree_target(&self, target: String) {
fn defer_switch_to_worktree_info(&self, info: WorktreeInfo) {
let app_event_tx = self.app_event_tx.clone();
tokio::spawn(async move {
tokio::time::sleep(WORKTREE_SWITCH_RENDER_DELAY).await;
app_event_tx.send(AppEvent::SwitchToWorktreeAfterLoading { target });
app_event_tx.send(AppEvent::SwitchToWorktreeAfterLoading { info });
});
}
@@ -658,75 +665,8 @@ fn worktree_request_id(prefix: &str) -> RequestId {
RequestId::String(format!("{prefix}-{}", Uuid::new_v4()))
}
fn dirty_policy_to_api(value: DirtyPolicy) -> ApiWorktreeDirtyPolicy {
match value {
DirtyPolicy::Fail => ApiWorktreeDirtyPolicy::Fail,
DirtyPolicy::Ignore => ApiWorktreeDirtyPolicy::Ignore,
DirtyPolicy::CopyTracked => ApiWorktreeDirtyPolicy::CopyTracked,
DirtyPolicy::CopyAll => ApiWorktreeDirtyPolicy::CopyAll,
DirtyPolicy::MoveTracked => ApiWorktreeDirtyPolicy::MoveTracked,
DirtyPolicy::MoveAll => ApiWorktreeDirtyPolicy::MoveAll,
}
}
fn dirty_state_from_api(value: ApiWorktreeDirtyState) -> codex_worktree::DirtyState {
codex_worktree::DirtyState {
has_staged_changes: value.has_staged_changes,
has_unstaged_changes: value.has_unstaged_changes,
has_untracked_files: value.has_untracked_files,
}
}
fn worktree_info_from_api(value: ApiWorktreeInfo) -> WorktreeInfo {
WorktreeInfo {
id: value.id,
name: value.name,
slug: value.slug,
source: worktree_source_from_api(value.source),
location: worktree_location_from_api(value.location),
repo_name: value.repo_name,
repo_root: PathBuf::from(value.repo_root),
common_git_dir: PathBuf::from(value.common_git_dir),
worktree_git_root: PathBuf::from(value.worktree_git_root),
workspace_cwd: PathBuf::from(value.workspace_cwd),
original_relative_cwd: PathBuf::from(value.original_relative_cwd),
branch: value.branch,
head: value.head,
owner_thread_id: value.owner_thread_id,
metadata_path: PathBuf::from(value.metadata_path),
dirty: dirty_state_from_api(value.dirty),
}
}
fn worktree_source_from_api(value: ApiWorktreeSource) -> WorktreeSource {
match value {
ApiWorktreeSource::Cli => WorktreeSource::Cli,
ApiWorktreeSource::App => WorktreeSource::App,
ApiWorktreeSource::Legacy => WorktreeSource::Legacy,
ApiWorktreeSource::Git => WorktreeSource::Git,
}
}
fn worktree_location_from_api(value: ApiWorktreeLocation) -> WorktreeLocation {
match value {
ApiWorktreeLocation::Sibling => WorktreeLocation::Sibling,
ApiWorktreeLocation::CodexHome => WorktreeLocation::CodexHome,
ApiWorktreeLocation::External => WorktreeLocation::External,
}
}
fn worktree_resolution_from_api(value: WorktreeCreateResponse) -> WorktreeResolution {
WorktreeResolution {
reused: value.reused,
info: worktree_info_from_api(value.info),
warnings: value
.warnings
.into_iter()
.map(|warning| WorktreeWarning {
message: warning.message,
})
.collect(),
}
fn dirty_state_is_dirty(dirty: &WorktreeDirtyState) -> bool {
dirty.has_staged_changes || dirty.has_unstaged_changes || dirty.has_untracked_files
}
fn worktree_session_message(
@@ -734,7 +674,7 @@ fn worktree_session_message(
transition: WorktreeSessionTransition,
) -> (String, String) {
let worktree_name = info.branch.as_deref().unwrap_or(info.name.as_str());
let state = if info.dirty.is_dirty() {
let state = if dirty_state_is_dirty(&info.dirty) {
"dirty"
} else {
"clean"
@@ -746,7 +686,7 @@ fn worktree_session_message(
transition.message_prefix(),
info.repo_name
),
info.workspace_cwd.display().to_string(),
info.workspace_cwd.clone(),
)
}
@@ -754,11 +694,10 @@ fn worktree_session_message(
mod tests {
use super::*;
use codex_app_server_protocol::AskForApproval;
use codex_app_server_protocol::WorktreeLocation;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::models::PermissionProfile;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_worktree::DirtyState;
use codex_worktree::WorktreeLocation;
use tempfile::TempDir;
#[tokio::test]
@@ -918,16 +857,16 @@ mod tests {
source,
location: WorktreeLocation::Sibling,
repo_name: "codex".to_string(),
repo_root: path.clone(),
common_git_dir: PathBuf::from("/repo/codex/.git"),
worktree_git_root: path.clone(),
workspace_cwd: path,
original_relative_cwd: PathBuf::new(),
repo_root: path.to_string_lossy().to_string(),
common_git_dir: "/repo/codex/.git".to_string(),
worktree_git_root: path.to_string_lossy().to_string(),
workspace_cwd: path.to_string_lossy().to_string(),
original_relative_cwd: String::new(),
branch,
head: Some("abcdef".to_string()),
owner_thread_id: None,
metadata_path: PathBuf::from("/repo/codex/.git/codex-worktree.json"),
dirty: DirtyState {
metadata_path: "/repo/codex/.git/codex-worktree.json".to_string(),
dirty: WorktreeDirtyState {
has_staged_changes: false,
has_unstaged_changes: dirty,
has_untracked_files: false,
+12 -5
View File
@@ -26,12 +26,14 @@ use codex_app_server_protocol::PluginUninstallResponse;
use codex_app_server_protocol::RateLimitSnapshot;
use codex_app_server_protocol::SkillsListResponse;
use codex_app_server_protocol::ThreadGoalStatus;
use codex_app_server_protocol::WorktreeCreateResponse;
use codex_app_server_protocol::WorktreeDirtyPolicy;
use codex_app_server_protocol::WorktreeInfo;
use codex_file_search::FileMatch;
use codex_protocol::ThreadId;
use codex_protocol::openai_models::ModelPreset;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_approval_presets::ApprovalPreset;
use codex_worktree::DirtyPolicy;
use crate::app_command::AppCommand;
use crate::app_server_session::AppServerStartedThread;
@@ -209,13 +211,13 @@ pub(crate) enum AppEvent {
CreateWorktreeAndSwitch {
branch: String,
base_ref: Option<String>,
dirty_policy: Option<DirtyPolicy>,
dirty_policy: Option<WorktreeDirtyPolicy>,
},
/// Result of creating or reusing a managed worktree.
WorktreeCreated {
cwd: PathBuf,
result: Result<codex_worktree::WorktreeResolution, String>,
result: Result<WorktreeCreateResponse, String>,
},
/// Switch the TUI into an existing worktree.
@@ -223,6 +225,11 @@ pub(crate) enum AppEvent {
target: String,
},
/// Switch the TUI into the selected existing worktree.
SwitchToWorktreeInfo {
info: WorktreeInfo,
},
/// A picker row for the current worktree was selected.
CurrentWorktreeSelected {
target: String,
@@ -230,12 +237,12 @@ pub(crate) enum AppEvent {
/// Continue switching into an existing worktree after the loading view has rendered.
SwitchToWorktreeAfterLoading {
target: String,
info: WorktreeInfo,
},
/// Result of starting or forking a session in a worktree.
WorktreeSessionReady {
info: codex_worktree::WorktreeInfo,
info: WorktreeInfo,
config: Config,
forked: bool,
warnings: Vec<String>,
+47 -24
View File
@@ -1,9 +1,10 @@
use std::path::Path;
use std::time::Instant;
use codex_worktree::DirtyPolicy;
use codex_worktree::WorktreeInfo;
use codex_worktree::WorktreeSource;
use codex_app_server_protocol::WorktreeDirtyPolicy as DirtyPolicy;
use codex_app_server_protocol::WorktreeDirtyState;
use codex_app_server_protocol::WorktreeInfo;
use codex_app_server_protocol::WorktreeSource;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Stylize;
@@ -371,7 +372,7 @@ pub(crate) fn picker_params(entries: Vec<WorktreeInfo>, current_cwd: &Path) -> S
items.extend(entries.into_iter().enumerate().map(|(idx, entry)| {
let target = entry.branch.clone().unwrap_or_else(|| entry.name.clone());
let source = source_label(entry.source);
let status = if entry.dirty.is_dirty() {
let status = if dirty_state_is_dirty(&entry.dirty) {
"dirty"
} else {
"clean"
@@ -380,18 +381,15 @@ pub(crate) fn picker_params(entries: Vec<WorktreeInfo>, current_cwd: &Path) -> S
if is_current {
initial_selected_idx = Some(idx + 1);
}
let description = format!("{status} · {source} · {}", entry.workspace_cwd.display());
let description = format!("{status} · {source} · {}", entry.workspace_cwd);
let selected_description = if is_current {
"Already in this worktree".to_string()
} else {
format!("Fork this chat into {}", entry.workspace_cwd.display())
format!("Fork this chat into {}", entry.workspace_cwd)
};
let search_value = Some(format!(
"{} {} {} {}",
target,
entry.name,
source,
entry.workspace_cwd.display()
target, entry.name, source, entry.workspace_cwd
));
let target_for_action = target.clone();
let actions: Vec<SelectionAction> = if is_current {
@@ -401,9 +399,10 @@ pub(crate) fn picker_params(entries: Vec<WorktreeInfo>, current_cwd: &Path) -> S
});
})]
} else {
let info_for_action = entry;
vec![Box::new(move |tx| {
tx.send(AppEvent::SwitchToWorktree {
target: target_for_action.clone(),
tx.send(AppEvent::SwitchToWorktreeInfo {
info: info_for_action.clone(),
});
})]
};
@@ -595,31 +594,34 @@ fn paths_match(a: &Path, b: &Path) -> bool {
}
fn is_current_worktree(current_cwd: &Path, entry: &WorktreeInfo) -> bool {
if paths_match(current_cwd, &entry.workspace_cwd) {
let workspace_cwd = Path::new(&entry.workspace_cwd);
if paths_match(current_cwd, workspace_cwd) {
return true;
}
let current_cwd = current_cwd
.canonicalize()
.unwrap_or_else(|_| current_cwd.to_path_buf());
let worktree_root = entry
.worktree_git_root
let worktree_git_root = Path::new(&entry.worktree_git_root);
let worktree_root = worktree_git_root
.canonicalize()
.unwrap_or_else(|_| entry.worktree_git_root.clone());
.unwrap_or_else(|_| worktree_git_root.to_path_buf());
current_cwd.starts_with(worktree_root)
}
fn dirty_state_is_dirty(dirty: &WorktreeDirtyState) -> bool {
dirty.has_staged_changes || dirty.has_unstaged_changes || dirty.has_untracked_files
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
use crate::app_event_sender::AppEventSender;
use crate::bottom_pane::ListSelectionView;
use crate::keymap::RuntimeKeymap;
use crate::render::renderable::Renderable;
use crate::tui::FrameRequester;
use codex_worktree::DirtyState;
use codex_worktree::WorktreeLocation;
use codex_app_server_protocol::WorktreeLocation;
use pretty_assertions::assert_eq;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
@@ -734,6 +736,27 @@ mod tests {
));
}
#[test]
fn existing_worktree_item_dispatches_selected_worktree_info() {
let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();
let tx = AppEventSender::new(tx_raw);
let params = picker_params(
vec![sample_info(
"fcoury/worktrees",
WorktreeSource::Git,
/*dirty*/ false,
)],
Path::new("/repo/codex"),
);
(params.items[1].actions[0])(&tx);
assert!(matches!(
rx.try_recv(),
Ok(AppEvent::SwitchToWorktreeInfo { info }) if info.branch.as_deref() == Some("fcoury/worktrees")
));
}
#[test]
fn worktree_loading_snapshot() {
insta::assert_snapshot!(
@@ -831,7 +854,7 @@ mod tests {
}
fn sample_info(branch: &str, source: WorktreeSource, dirty: bool) -> WorktreeInfo {
let path = PathBuf::from(format!("/repo/codex.{}", branch.replace('/', "-")));
let path = format!("/repo/codex.{}", branch.replace('/', "-"));
WorktreeInfo {
id: "repo-id".to_string(),
name: branch.to_string(),
@@ -844,15 +867,15 @@ mod tests {
},
repo_name: "codex".to_string(),
repo_root: path.clone(),
common_git_dir: PathBuf::from("/repo/codex/.git"),
common_git_dir: "/repo/codex/.git".to_string(),
worktree_git_root: path.clone(),
workspace_cwd: path,
original_relative_cwd: PathBuf::new(),
original_relative_cwd: String::new(),
branch: Some(branch.to_string()),
head: Some("abcdef".to_string()),
owner_thread_id: None,
metadata_path: PathBuf::from("/repo/codex/.git/codex-worktree.json"),
dirty: DirtyState {
metadata_path: "/repo/codex/.git/codex-worktree.json".to_string(),
dirty: WorktreeDirtyState {
has_staged_changes: false,
has_unstaged_changes: dirty,
has_untracked_files: false,
+1
View File
@@ -14,6 +14,7 @@ pub use dirty::DirtyState;
pub use dirty::dirty_state;
pub use manager::ensure_worktree;
pub use manager::list_worktrees;
pub use manager::prune_stale_managed_worktree_dirs;
pub use manager::remove_worktree;
pub use manager::resolve_worktree;
pub use manager::stale_managed_worktree_dirs;
+41
View File
@@ -346,6 +346,23 @@ pub fn stale_managed_worktree_dirs(codex_home: &Path) -> Result<Vec<PathBuf>> {
Ok(stale)
}
pub fn prune_stale_managed_worktree_dirs(codex_home: &Path, dry_run: bool) -> Result<Vec<PathBuf>> {
let stale = stale_managed_worktree_dirs(codex_home)?;
if dry_run {
return Ok(stale);
}
for path in &stale {
fs::remove_dir_all(path).with_context(|| {
format!(
"failed to remove stale worktree directory {}",
path.display()
)
})?;
}
Ok(stale)
}
fn git_root_is_valid(path: &Path) -> bool {
std::process::Command::new("git")
.args(["rev-parse", "--show-toplevel"])
@@ -689,6 +706,7 @@ fn parse_worktree_list(output: &str) -> Vec<GitWorktreeEntry> {
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
#[test]
fn parse_worktree_list_preserves_branches() {
@@ -709,4 +727,27 @@ mod tests {
]
);
}
#[test]
fn prune_stale_managed_worktree_dirs_respects_dry_run() -> anyhow::Result<()> {
let codex_home = TempDir::new()?;
let stale_path = paths::codex_worktrees_root(codex_home.path())
.join("repo-id")
.join("demo")
.join("codex.demo");
fs::create_dir_all(&stale_path)?;
assert_eq!(
prune_stale_managed_worktree_dirs(codex_home.path(), /*dry_run*/ true)?,
vec![stale_path.clone()]
);
assert!(stale_path.exists());
assert_eq!(
prune_stale_managed_worktree_dirs(codex_home.path(), /*dry_run*/ false)?,
vec![stale_path.clone()]
);
assert!(!stale_path.exists());
Ok(())
}
}