mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Add managed worktree creation to TUI session commands (#43120)
## What changed - Add `/worktree` to start a fresh conversation or fork the current conversation into a new managed checkout. - Offer current-checkout and new-worktree choices for `/new` and `/fork`, preserving optional conversation names. Enable these choices for local Git repositories when the `worktrees` feature is enabled. - Load destination configuration, bind the checkout to the replacement thread, and inherit conversation history only when forking. - Reject creation from explicitly untrusted sources and require an idle primary session without queued input. Refuse forks when developer instructions differ, with guidance for removing the unused checkout. ## Testing Add picker snapshots and tests for command availability, named selections, fresh versus forked history, destination configuration, worktree ownership, and feature and trust checks. GitOrigin-RevId: d6c83e00217660aacf2a6d92acad50b506607e0b
This commit is contained in:
1 parent
f5a71ff40a
commit
f6976ab036
28 files changed
+980
-30
No files matched your search
@@ -50,6 +50,10 @@ impl App {
|
||||
| AppEvent::SelectAgentThread(_)
|
||||
| AppEvent::StartSide { .. }
|
||||
| AppEvent::ForkCurrentSession { .. }
|
||||
| AppEvent::StartManagedWorktree {
|
||||
mode: crate::app_event::ManagedWorktreeMode::Fork,
|
||||
..
|
||||
}
|
||||
| AppEvent::ForkSessionForPromptEdit { .. }
|
||||
| AppEvent::SetThreadGoalDraft { .. }
|
||||
| AppEvent::SetThreadGoalStatus {
|
||||
@@ -86,6 +90,9 @@ impl App {
|
||||
self.chat_widget.show_misalignment_policy_precaution();
|
||||
}
|
||||
}
|
||||
AppEvent::StartManagedWorktree { mode, name } => {
|
||||
self.start_managed_worktree(tui, app_server, mode, name).await;
|
||||
}
|
||||
AppEvent::ChangeWorkingDirectory {
|
||||
thread_id,
|
||||
requested_cwd,
|
||||
|
||||
@@ -244,6 +244,12 @@ impl App {
|
||||
self.rate_limit_refresh_state.invalidate_recovery();
|
||||
session.inherit_task_tool_capabilities(app_server);
|
||||
*app_server = session;
|
||||
self.chat_widget.set_local_worktree_operations(
|
||||
!crate::uses_remote_workspace_or_environment(
|
||||
&self.app_server_target,
|
||||
self.environment_manager.as_ref(),
|
||||
),
|
||||
);
|
||||
self.chat_widget.cyber_policy_notice = Default::default();
|
||||
self.chat_widget.requires_openai_auth = bootstrap.requires_openai_auth;
|
||||
self.chat_widget.remote_connection =
|
||||
|
||||
@@ -486,6 +486,7 @@ impl App {
|
||||
chat_widget.last_terminal_title = previous_terminal_title;
|
||||
}
|
||||
chat_widget.remote_connection = self.chat_widget.remote_connection.clone();
|
||||
chat_widget.set_local_worktree_operations(self.chat_widget.local_worktree_operations);
|
||||
chat_widget.set_agents_navigation_enabled(matches!(
|
||||
self.app_server_target,
|
||||
AppServerTarget::LocalDaemon { .. }
|
||||
|
||||
@@ -505,6 +505,10 @@ impl App {
|
||||
};
|
||||
chat_widget.note_rendered_width(tui.terminal.last_known_screen_size.width);
|
||||
chat_widget.remote_connection = remote_connection;
|
||||
chat_widget.set_local_worktree_operations(!crate::uses_remote_workspace_or_environment(
|
||||
&app_server_target,
|
||||
environment_manager.as_ref(),
|
||||
));
|
||||
chat_widget.set_agents_navigation_enabled(matches!(
|
||||
app_server_target,
|
||||
AppServerTarget::LocalDaemon { .. }
|
||||
|
||||
@@ -2762,6 +2762,287 @@ async fn cold_paginated_subagent_transcript_excludes_inherited_parent_history()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_worktree_transitions_bind_owner_and_preserve_only_fork_history() -> Result<()> {
|
||||
use crate::app_event::ManagedWorktreeMode;
|
||||
use std::fs;
|
||||
use std::process::Command;
|
||||
|
||||
let (mut app, mut events, _op_rx) = make_test_app_with_channels().await;
|
||||
let root = tempdir()?;
|
||||
let home = dunce::canonicalize(root.path())?.join("home");
|
||||
let source = dunce::canonicalize(root.path())?.join("source");
|
||||
let project_pool = dunce::canonicalize(root.path())?.join("project-pool");
|
||||
fs::create_dir_all(&home)?;
|
||||
fs::create_dir_all(source.join(".codex"))?;
|
||||
fs::write(home.join("config.toml"), "[features]\nworktrees = true\n")?;
|
||||
crate::legacy_core::config::set_project_trust_level(
|
||||
&home,
|
||||
&source,
|
||||
codex_protocol::config_types::TrustLevel::Trusted,
|
||||
)
|
||||
.map_err(|error| color_eyre::eyre::eyre!(error.to_string()))?;
|
||||
let destination = format!(
|
||||
r#"developer_instructions = "committed policy"
|
||||
model = "gpt-5.2"
|
||||
model_reasoning_effort = "high"
|
||||
[desktop]
|
||||
git-worktree-root = {}
|
||||
"#,
|
||||
toml::Value::String(project_pool.display().to_string()),
|
||||
);
|
||||
fs::write(source.join(".codex/config.toml"), destination)?;
|
||||
fs::write(source.join("AGENTS.md"), "committed worktree instructions")?;
|
||||
for args in [
|
||||
vec!["init", "--quiet"],
|
||||
vec!["add", "."],
|
||||
vec!["commit", "--quiet", "--no-gpg-sign", "-m", "initial"],
|
||||
] {
|
||||
let result = Command::new("git")
|
||||
.current_dir(&source)
|
||||
.args([
|
||||
"-c",
|
||||
"user.name=Worktree Test",
|
||||
"-c",
|
||||
"user.email=test@example.invalid",
|
||||
])
|
||||
.args(args)
|
||||
.output()?;
|
||||
assert!(
|
||||
result.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
}
|
||||
fs::write(
|
||||
source.join(".codex/config.toml"),
|
||||
r#"developer_instructions = "dirty policy"
|
||||
model = "gpt-5.4"
|
||||
model_reasoning_effort = "low"
|
||||
"#,
|
||||
)?;
|
||||
fs::write(source.join("AGENTS.md"), "dirty source instructions")?;
|
||||
app.config.codex_home = home.clone().abs();
|
||||
app.config.sqlite = SqliteConfig::new_for_testing(home.clone().abs());
|
||||
app.config.cwd = source.clone().abs();
|
||||
app.harness_overrides.permission_profile = Some(PermissionProfile::workspace_write());
|
||||
app.config = app.rebuild_config_for_cwd(source.clone()).await?;
|
||||
app.chat_widget
|
||||
.handle_thread_session_quiet(test_thread_session(ThreadId::new(), source.clone()));
|
||||
let (mut server, requests, proxy) = start_recording_app_server(
|
||||
&app.config,
|
||||
/*blocked_thread_list*/ None,
|
||||
/*failed_thread_name*/ None,
|
||||
)
|
||||
.await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
app.start_fresh_session_with_summary_hint(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
/*session_start_source*/ None,
|
||||
/*initial_user_message*/ None,
|
||||
/*new_thread_name*/ None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
(
|
||||
app.chat_widget.current_model(),
|
||||
app.config.model_provider_id.as_str(),
|
||||
app.chat_widget.current_reasoning_effort()
|
||||
),
|
||||
("gpt-5.4", "openai", Some(ReasoningEffortConfig::Low))
|
||||
);
|
||||
// Provider selection belongs to host config, not project config.
|
||||
let host_config = home.join("config.toml");
|
||||
let contents = fs::read_to_string(&host_config)?;
|
||||
fs::write(
|
||||
host_config,
|
||||
format!("model_provider = \"ollama\"\n{contents}"),
|
||||
)?;
|
||||
let original = app.chat_widget.thread_id().expect("original thread");
|
||||
server.thread_inject_items(original, vec![serde_json::from_value(serde_json::json!({
|
||||
"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "managed fork history"}]
|
||||
}))?]).await?;
|
||||
let manager = codex_worktree::WorktreeManager::new(
|
||||
codex_worktree::WorktreeSettings::for_cli(&home, /*desktop*/ None)
|
||||
.map_err(|error| color_eyre::eyre::eyre!(error.to_string()))?,
|
||||
);
|
||||
requests.lock().expect("request recorder lock").clear();
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
AppEvent::StartManagedWorktree {
|
||||
mode: ManagedWorktreeMode::Fork,
|
||||
name: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(app.chat_widget.thread_id(), Some(original));
|
||||
assert!(recorded_params(&requests, "thread/fork").is_empty());
|
||||
let unused = manager
|
||||
.list(&source)
|
||||
.map_err(|error| color_eyre::eyre::eyre!(error.to_string()))?
|
||||
.pop()
|
||||
.expect("unused checkout");
|
||||
assert_eq!(
|
||||
manager
|
||||
.owner(&unused.root)
|
||||
.map_err(|error| color_eyre::eyre::eyre!(error.to_string()))?,
|
||||
None
|
||||
);
|
||||
let error = std::iter::from_fn(|| events.try_recv().ok())
|
||||
.filter_map(|event| match event {
|
||||
AppEvent::InsertHistoryCell(cell) => {
|
||||
Some(lines_to_single_string(&cell.display_lines(/*width*/ 500)))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.find(|message| message.contains("Cannot fork into this worktree"))
|
||||
.expect("fork refusal");
|
||||
let (_, with_path) = error
|
||||
.split_once("An unused checkout was created at ")
|
||||
.expect("checkout marker");
|
||||
let (path, _) = with_path
|
||||
.split_once("; remove it with")
|
||||
.expect("cleanup marker");
|
||||
insta::assert_snapshot!(error.replace(path, "<CHECKOUT>"), @"■ Cannot fork into this worktree because developer instructions differ. Start a new conversation instead. An unused checkout was created at <CHECKOUT>; remove it with `git worktree remove <checkout-path>` from the source repository.");
|
||||
fs::write(
|
||||
source.join(".codex/config.toml"),
|
||||
r#"developer_instructions = "committed policy"
|
||||
[features]
|
||||
terminal_visualization_instructions = true
|
||||
"#,
|
||||
)?;
|
||||
app.config = app.rebuild_config_for_cwd(source.clone()).await?;
|
||||
requests.lock().expect("request recorder lock").clear();
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
AppEvent::StartManagedWorktree {
|
||||
mode: ManagedWorktreeMode::Fork,
|
||||
name: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(app.chat_widget.thread_id(), Some(original));
|
||||
assert!(recorded_params(&requests, "thread/fork").is_empty());
|
||||
for mode in [ManagedWorktreeMode::New, ManagedWorktreeMode::Fork] {
|
||||
requests.lock().expect("request recorder lock").clear();
|
||||
let previous = app.chat_widget.thread_id();
|
||||
let previous_rollout = app.chat_widget.rollout_path().expect("previous rollout");
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
AppEvent::StartManagedWorktree {
|
||||
mode,
|
||||
name: Some(format!("{mode:?} worktree")),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let replacement = app.chat_widget.thread_id().expect("replacement thread");
|
||||
assert_ne!(Some(replacement), previous);
|
||||
assert_eq!(
|
||||
app.chat_widget.thread_name(),
|
||||
Some(format!("{mode:?} worktree"))
|
||||
);
|
||||
let cwd = app.config.cwd.as_path().canonicalize()?;
|
||||
let checkouts = manager
|
||||
.list(&source)
|
||||
.map_err(|error| color_eyre::eyre::eyre!(error.to_string()))?;
|
||||
let checkout = checkouts
|
||||
.iter()
|
||||
.find(|checkout| checkout.cwd.canonicalize().ok().as_ref() == Some(&cwd))
|
||||
.expect("managed checkout");
|
||||
assert!(checkout.root.starts_with(home.join("worktrees")));
|
||||
assert!(!project_pool.exists());
|
||||
assert_eq!(
|
||||
manager
|
||||
.owner(&checkout.root)
|
||||
.map_err(|error| color_eyre::eyre::eyre!(error.to_string()))?,
|
||||
Some(replacement.to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
app.config.developer_instructions.as_deref(),
|
||||
Some("committed policy")
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(checkout.cwd.join("AGENTS.md"))?,
|
||||
"committed worktree instructions"
|
||||
);
|
||||
let fork = matches!(mode, ManagedWorktreeMode::Fork);
|
||||
let method = if fork { "thread/fork" } else { "thread/start" };
|
||||
let params = recorded_params(&requests, method);
|
||||
assert_eq!(params.len(), 1);
|
||||
assert_eq!(
|
||||
[
|
||||
params[0]["model"].as_str(),
|
||||
params[0]["modelProvider"].as_str(),
|
||||
params[0]["config"]["model_reasoning_effort"].as_str(),
|
||||
],
|
||||
[Some("gpt-5.2"), Some("ollama"), Some("high")]
|
||||
);
|
||||
// Injection flushes and materializes a new thread's otherwise lazy rollout.
|
||||
server.thread_inject_items(replacement, vec![serde_json::from_value(serde_json::json!({
|
||||
"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": format!("replacement persistence probe {mode:?}")}]
|
||||
}))?]).await?;
|
||||
let rollout = app.chat_widget.rollout_path().expect("replacement rollout");
|
||||
let mut history = fs::read(&rollout)?;
|
||||
let metadata = codex_rollout::read_session_meta_line(&rollout).await?;
|
||||
assert_eq!(metadata.meta.history_base.is_some(), fork);
|
||||
if let Some(base) = metadata.meta.history_base {
|
||||
assert!(fork, "New must not inherit history");
|
||||
assert_eq!(Some(base.thread_id), previous);
|
||||
let parent = fs::read(&previous_rollout)?;
|
||||
history.extend_from_slice(
|
||||
parent
|
||||
.get(..usize::try_from(base.end_byte_offset)?)
|
||||
.expect("valid inherited prefix"),
|
||||
);
|
||||
}
|
||||
let history = String::from_utf8(history)?;
|
||||
assert!(!history.contains("managed fork history"));
|
||||
if fork {
|
||||
assert!(history.contains("replacement persistence probe New"));
|
||||
}
|
||||
let attached = server
|
||||
.thread_read(replacement, /*include_turns*/ false)
|
||||
.await?;
|
||||
assert_eq!(attached.cwd.as_path().canonicalize()?, cwd);
|
||||
}
|
||||
app.start_fresh_session_with_summary_hint(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
/*session_start_source*/ None,
|
||||
/*initial_user_message*/ None,
|
||||
/*new_thread_name*/ None,
|
||||
)
|
||||
.await;
|
||||
let unsaved = app.chat_widget.thread_id().expect("unsaved thread");
|
||||
let path = app.chat_widget.rollout_path();
|
||||
assert!(path.is_none_or(|path| !rollout_path_is_resumable(&path)));
|
||||
let completed = test_turn("completed-unsaved-turn", TurnStatus::Completed, Vec::new());
|
||||
app.thread_event_channels[&unsaved]
|
||||
.store
|
||||
.lock()
|
||||
.await
|
||||
.set_turns(vec![completed]);
|
||||
for mode in [ManagedWorktreeMode::Fork, ManagedWorktreeMode::New] {
|
||||
requests.lock().expect("request recorder lock").clear();
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
AppEvent::StartManagedWorktree { mode, name: None },
|
||||
)
|
||||
.await?;
|
||||
let is_new = mode == ManagedWorktreeMode::New;
|
||||
assert_eq!(app.chat_widget.thread_id() != Some(unsaved), is_new);
|
||||
assert_eq!(recorded_params(&requests, "thread/fork").len(), 0);
|
||||
}
|
||||
server.shutdown().await?;
|
||||
proxy.await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn changing_directory_preserves_project_trust_permissions_history_and_hooks() -> Result<()> {
|
||||
use codex_protocol::config_types::TrustLevel as T;
|
||||
|
||||
@@ -11,6 +11,84 @@ use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn worktree_creation_event_requires_feature() -> Result<()> {
|
||||
let (mut app, mut events, _op_rx) = make_test_app_with_channels().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
while events.try_recv().is_ok() {}
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
AppEvent::StartManagedWorktree {
|
||||
mode: crate::app_event::ManagedWorktreeMode::New,
|
||||
name: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let message = std::iter::from_fn(|| events.try_recv().ok())
|
||||
.find_map(|event| match event {
|
||||
AppEvent::InsertHistoryCell(cell) => {
|
||||
Some(lines_to_single_string(&cell.display_lines(/*width*/ 100)))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.expect("disabled feature message");
|
||||
insta::assert_snapshot!(message, @"■ Enable worktrees in /experimental to create a worktree.");
|
||||
assert!(!app.config.codex_home.join("worktrees").exists());
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn worktree_creation_rejects_untrusted_source_before_allocation() -> Result<()> {
|
||||
use crate::app_event::ManagedWorktreeMode;
|
||||
|
||||
let (mut app, mut events, _op_rx) = make_test_app_with_channels().await;
|
||||
app.config.features.enable(Feature::Worktrees)?;
|
||||
app.config.active_project.trust_level =
|
||||
Some(codex_protocol::config_types::TrustLevel::Untrusted);
|
||||
let thread_id = ThreadId::new();
|
||||
app.primary_thread_id = Some(thread_id);
|
||||
app.chat_widget
|
||||
.handle_thread_session_quiet(test_thread_session(thread_id, app.config.cwd.to_path_buf()));
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
for mode in [ManagedWorktreeMode::New, ManagedWorktreeMode::Fork] {
|
||||
if mode == ManagedWorktreeMode::Fork {
|
||||
app.config.active_project.trust_level =
|
||||
Some(codex_protocol::config_types::TrustLevel::Trusted);
|
||||
crate::legacy_core::config::set_project_trust_level(
|
||||
&app.config.codex_home,
|
||||
app.config.cwd.as_path(),
|
||||
codex_protocol::config_types::TrustLevel::Untrusted,
|
||||
)
|
||||
.map_err(|error| color_eyre::eyre::eyre!(error.to_string()))?;
|
||||
}
|
||||
while events.try_recv().is_ok() {}
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
AppEvent::StartManagedWorktree { mode, name: None },
|
||||
)
|
||||
.await?;
|
||||
let message = std::iter::from_fn(|| events.try_recv().ok())
|
||||
.find_map(|event| match event {
|
||||
AppEvent::InsertHistoryCell(cell) => {
|
||||
Some(lines_to_single_string(&cell.display_lines(/*width*/ 100)))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.expect("source trust error");
|
||||
insta::allow_duplicates! {
|
||||
insta::assert_snapshot!(message, @"■ Cannot create a worktree from an explicitly untrusted source.");
|
||||
}
|
||||
assert!(!app.config.codex_home.join("worktrees").exists());
|
||||
}
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn turn_start_failure_is_shown_without_exiting() -> Result<()> {
|
||||
let (mut app, mut app_event_rx, mut op_rx) = make_test_app_with_channels().await;
|
||||
@@ -64,6 +142,32 @@ async fn turn_start_failure_is_shown_without_exiting() -> Result<()> {
|
||||
#[tokio::test]
|
||||
async fn misalignment_policy_blocks_queued_turns_and_goal_resumption() -> Result<()> {
|
||||
let (mut app, _app_event_rx, mut op_rx) = make_test_app_with_channels().await;
|
||||
let checkout = tempfile::tempdir()?;
|
||||
app.config.cwd = AbsolutePathBuf::from_absolute_path(checkout.path())?;
|
||||
for args in [
|
||||
vec!["init", "--quiet"],
|
||||
vec![
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"--quiet",
|
||||
"--allow-empty",
|
||||
"-m",
|
||||
"initial",
|
||||
],
|
||||
] {
|
||||
assert!(
|
||||
std::process::Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(checkout.path())
|
||||
.status()?
|
||||
.success()
|
||||
);
|
||||
}
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
||||
let started = app_server.start_thread(&app.config).await?;
|
||||
@@ -126,12 +230,17 @@ async fn misalignment_policy_blocks_queued_turns_and_goal_resumption() -> Result
|
||||
user_message: Some("Do not fork this stopped thread".into()),
|
||||
},
|
||||
AppEvent::ForkCurrentSession { name: None },
|
||||
AppEvent::StartManagedWorktree {
|
||||
mode: crate::app_event::ManagedWorktreeMode::Fork,
|
||||
name: None,
|
||||
},
|
||||
AppEvent::OpenAgentPicker,
|
||||
AppEvent::SelectAgentThread(thread_id),
|
||||
] {
|
||||
app.handle_event(&mut tui, &mut app_server, event).await?;
|
||||
}
|
||||
|
||||
assert!(!app.config.codex_home.join("worktrees").exists());
|
||||
assert_eq!(
|
||||
app_server.next_request_id(),
|
||||
AppServerRequestId::Integer(next_request_id + 1)
|
||||
|
||||
@@ -1,22 +1,141 @@
|
||||
//! Local working-directory changes that preserve conversation history.
|
||||
//! Local directory transitions and managed worktrees with fresh or preserved conversation history.
|
||||
|
||||
use super::session_lifecycle::ThreadAttachPresentation;
|
||||
use super::*;
|
||||
use crate::app_server_session::ForkGoalContinuation::DeferUntilNextTurn;
|
||||
use crate::history_cell::McpInventoryLoadingCell as LoadingCell;
|
||||
use crate::terminal_visualization_instructions::with_terminal_visualization_instructions;
|
||||
use codex_app_server_protocol::ThreadBackgroundTerminalsListParams;
|
||||
use codex_app_server_protocol::ThreadBackgroundTerminalsListResponse as ListResponse;
|
||||
|
||||
impl App {
|
||||
pub(super) async fn start_managed_worktree(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
mode: crate::app_event::ManagedWorktreeMode,
|
||||
name: Option<String>,
|
||||
) {
|
||||
if !self.config.features.enabled(Feature::Worktrees) {
|
||||
self.chat_widget.add_error_message(
|
||||
"Enable worktrees in /experimental to create a worktree.".to_string(),
|
||||
);
|
||||
} else if self.config.active_project.is_untrusted() {
|
||||
self.chat_widget.add_error_message(
|
||||
"Cannot create a worktree from an explicitly untrusted source.".to_string(),
|
||||
);
|
||||
} else if crate::uses_remote_workspace_or_environment(
|
||||
&self.app_server_target,
|
||||
self.environment_manager.as_ref(),
|
||||
) {
|
||||
self.chat_widget.add_error_message(
|
||||
"Managed worktrees are only supported for local sessions.".to_string(),
|
||||
);
|
||||
} else if self
|
||||
.primary_thread_id
|
||||
.is_none_or(|thread_id| !self.chat_widget.can_change_working_directory(thread_id))
|
||||
{
|
||||
self.chat_widget.add_error_message(
|
||||
"Creating a worktree requires an idle primary session without queued input."
|
||||
.to_string(),
|
||||
);
|
||||
} else {
|
||||
let setup = async {
|
||||
let source = self
|
||||
.rebuild_config_for_cwd(self.config.cwd.to_path_buf())
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
|
||||
anyhow::ensure!(
|
||||
!source.active_project.is_untrusted(),
|
||||
"Cannot create a worktree from an explicitly untrusted source."
|
||||
);
|
||||
let host = crate::legacy_core::config::load_config_toml_with_layer_stack(
|
||||
&self.config.codex_home,
|
||||
/*cwd*/ None,
|
||||
Vec::new(),
|
||||
codex_config::ConfigLoadOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
let settings = codex_worktree::WorktreeSettings::for_cli(
|
||||
&self.config.codex_home,
|
||||
host.config_toml.desktop.as_ref(),
|
||||
)?;
|
||||
let manager = codex_worktree::WorktreeManager::new(settings);
|
||||
let checkout = manager.create(&codex_worktree::CreateWorktree {
|
||||
source_cwd: self.config.cwd.to_path_buf(),
|
||||
base: None,
|
||||
})?;
|
||||
anyhow::Ok((manager, checkout))
|
||||
}
|
||||
.await;
|
||||
match setup {
|
||||
Ok((manager, checkout)) => {
|
||||
if let Err(error) = self
|
||||
.switch_to_managed_worktree(tui, app_server, manager, checkout, mode, name)
|
||||
.await
|
||||
{
|
||||
self.chat_widget.add_error_message(error.to_string());
|
||||
}
|
||||
}
|
||||
Err(error) => self.chat_widget.add_error_message(error.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn working_directory_error(&mut self, message: impl Into<String>) {
|
||||
self.chat_widget.add_error_message(message.into());
|
||||
}
|
||||
|
||||
pub(super) async fn switch_to_managed_worktree(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
manager: codex_worktree::WorktreeManager,
|
||||
checkout: codex_worktree::ManagedWorktree,
|
||||
mode: crate::app_event::ManagedWorktreeMode,
|
||||
name: Option<String>,
|
||||
) -> Result<()> {
|
||||
let previous_thread_id = self.chat_widget.thread_id();
|
||||
let cwd = AbsolutePathBuf::from_absolute_path(checkout.cwd.clone())
|
||||
.map_err(|error| color_eyre::eyre::eyre!(error.to_string()))?;
|
||||
self.change_working_directory_with_managed(
|
||||
tui,
|
||||
app_server,
|
||||
cwd,
|
||||
Some((manager, checkout, mode, name)),
|
||||
)
|
||||
.await;
|
||||
if self.chat_widget.thread_id() == previous_thread_id {
|
||||
return Err(color_eyre::eyre::eyre!(
|
||||
"Could not start a session in the managed worktree"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn change_working_directory(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
cwd: AbsolutePathBuf,
|
||||
) {
|
||||
self.change_working_directory_with_managed(
|
||||
tui, app_server, cwd, /*managed_worktree*/ None,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn change_working_directory_with_managed(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
cwd: AbsolutePathBuf,
|
||||
managed_worktree: Option<(
|
||||
codex_worktree::WorktreeManager,
|
||||
codex_worktree::ManagedWorktree,
|
||||
crate::app_event::ManagedWorktreeMode,
|
||||
Option<String>,
|
||||
)>,
|
||||
) {
|
||||
if self.config.ephemeral || !cwd.as_path().is_dir() {
|
||||
return self.working_directory_error("This task cannot be safely replaced.");
|
||||
@@ -55,6 +174,21 @@ impl App {
|
||||
if config.active_project.trust_level.is_none() {
|
||||
return self.working_directory_error("This directory is not trusted; run Codex there.");
|
||||
}
|
||||
if let Some((_, checkout, crate::app_event::ManagedWorktreeMode::Fork, _)) =
|
||||
managed_worktree.as_ref()
|
||||
&& with_terminal_visualization_instructions(
|
||||
&self.config,
|
||||
self.config.developer_instructions.clone(),
|
||||
) != with_terminal_visualization_instructions(
|
||||
&config,
|
||||
config.developer_instructions.clone(),
|
||||
)
|
||||
{
|
||||
return self.working_directory_error(format!(
|
||||
"Cannot fork into this worktree because developer instructions differ. Start a new conversation instead. An unused checkout was created at {}; remove it with `git worktree remove <checkout-path>` from the source repository.",
|
||||
checkout.root.display()
|
||||
));
|
||||
}
|
||||
if let Some(profile) = self.runtime_permission_profile_override.as_ref()
|
||||
&& profile.active_permission_profile.is_some()
|
||||
&& (!profile.matches_config(&config)
|
||||
@@ -98,10 +232,15 @@ impl App {
|
||||
Err(error) => return self.chat_widget.add_error_message(error),
|
||||
};
|
||||
config.service_tier = self.chat_widget.configured_service_tier();
|
||||
let is_new_worktree = matches!(
|
||||
managed_worktree.as_ref().map(|(_, _, mode, _)| mode),
|
||||
Some(crate::app_event::ManagedWorktreeMode::New)
|
||||
);
|
||||
let rollout = self.chat_widget.rollout_path();
|
||||
let has_rollout = rollout.as_deref().is_some_and(rollout_path_is_resumable);
|
||||
let channels = &self.thread_event_channels;
|
||||
if !has_rollout
|
||||
&& !is_new_worktree
|
||||
&& (!self.chat_widget.token_usage().is_zero()
|
||||
|| channels.get(&thread_id).is_some_and(|channel| {
|
||||
channel.store.try_lock().map_or(/*default*/ true, |store| {
|
||||
@@ -142,7 +281,16 @@ impl App {
|
||||
return self.working_directory_error("Active background terminals block /cd.");
|
||||
}
|
||||
}
|
||||
let transitioned = if has_rollout {
|
||||
if is_new_worktree {
|
||||
apply_managed_new_thread_defaults(
|
||||
&mut config,
|
||||
app_server.managed_new_thread_defaults(),
|
||||
&self.cli_kv_overrides,
|
||||
&self.harness_overrides,
|
||||
);
|
||||
}
|
||||
let preserve_history = has_rollout && !is_new_worktree;
|
||||
let transitioned = if preserve_history {
|
||||
app_server
|
||||
.fork_thread_at(
|
||||
&local_settings,
|
||||
@@ -163,7 +311,7 @@ impl App {
|
||||
)
|
||||
.await
|
||||
};
|
||||
let transitioned = match transitioned {
|
||||
let mut transitioned = match transitioned {
|
||||
Ok(value) => value,
|
||||
Err(e) => return self.working_directory_error(format!("Failed to change: {e}")),
|
||||
};
|
||||
@@ -177,16 +325,46 @@ impl App {
|
||||
{
|
||||
if session.thread_id != thread_id {
|
||||
let _ = app_server.thread_unsubscribe(session.thread_id).await;
|
||||
if has_rollout {
|
||||
if preserve_history {
|
||||
let _ = app_server.thread_archive(session.thread_id).await;
|
||||
}
|
||||
}
|
||||
return self.working_directory_error("Requested directory or permissions not applied.");
|
||||
}
|
||||
if let Some((manager, checkout, _, _)) = managed_worktree.as_ref()
|
||||
&& let Err(error) =
|
||||
manager.bind_thread(&checkout.root, &transitioned.session.thread_id.to_string())
|
||||
{
|
||||
let replacement_id = transitioned.session.thread_id;
|
||||
let _ = app_server.thread_unsubscribe(replacement_id).await;
|
||||
if preserve_history {
|
||||
let _ = app_server.thread_archive(replacement_id).await;
|
||||
}
|
||||
return self.working_directory_error(format!(
|
||||
"Cannot register managed worktree ownership: {error}"
|
||||
));
|
||||
}
|
||||
let name_error = if let Some(name) = managed_worktree
|
||||
.as_ref()
|
||||
.and_then(|(_, _, _, name)| name.as_ref())
|
||||
{
|
||||
match app_server
|
||||
.thread_set_name(transitioned.session.thread_id, name.clone())
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
transitioned.session.thread_name = Some(name.clone());
|
||||
None
|
||||
}
|
||||
Err(error) => Some(format!("Failed to name the worktree session: {error}")),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Err(error) = app_server.thread_unsubscribe(thread_id).await {
|
||||
let replacement_id = transitioned.session.thread_id;
|
||||
let _ = app_server.thread_unsubscribe(replacement_id).await;
|
||||
if has_rollout {
|
||||
if preserve_history {
|
||||
let _ = app_server.thread_archive(replacement_id).await;
|
||||
}
|
||||
return self.working_directory_error(format!("Cannot change directories: {error}"));
|
||||
@@ -210,6 +388,9 @@ impl App {
|
||||
if let Err(error) = attach(self, tui, transitioned, lineage, message).await {
|
||||
return self.working_directory_error(format!("Could not restore session: {error}"));
|
||||
}
|
||||
if let Some(error) = name_error {
|
||||
self.chat_widget.add_error_message(error);
|
||||
}
|
||||
self.cancel_pending_key_chord();
|
||||
self.keymap = keymap;
|
||||
self.merge_startup_warnings(tui, &history_cell::StartupWarningsCell::default());
|
||||
|
||||
Reference in new issue
Block a user