Include linked worktrees in TUI session discovery (#43279)

## Why

Directory-scoped session lookup misses conversations in linked worktrees of the same repository. Managed worktree creation also runs synchronous Git work on the TUI event loop.

## What changed

- With `worktrees` enabled for local sessions, include corresponding directories across linked checkouts in resume and fork pickers and `--last` lookup. Group them together in the agents overview and show checkout paths for picker entries from another worktree.
- Validate shared Git metadata and backlinks, preserve relative working directories and logical path aliases, and reject directory symlink escapes. Keep the expanded directory filter stable across pagination until the listing restarts.
- Fall back to the originally requested directory when an older daemon rejects an array-valued `cwd` filter.
- Create managed worktrees on a blocking worker, check transition blockers before allocation, and revalidate the source session before switching. Report retained checkout paths and cleanup instructions if the transition cannot complete.
- Start the in-session picker server in a separate task to avoid exhausting the TUI event future's stack.

## Testing

Add coverage for linked-checkout discovery, feature gating, picker selection and rendering, project grouping, pagination stability, and legacy daemon fallback. Extend worktree lifecycle tests to cover running-agent blockers and recovery after the source session changes during creation.

GitOrigin-RevId: 4a8a36c0dba3d32d72600f2edf8258a29fb4cb07
This commit is contained in:
Benjamin Carlsson authored and copyberry committed 2026-09-06 20:52:29 +00:00
1 parent ad931a45b2
commit d30f9cc72a
27 files changed
+1511 -144

No files matched your search

+5
View File
@@ -281,6 +281,11 @@ impl App {
rows,
selected_thread_id,
self.primary_thread_id.is_none(),
self.config.features.enabled(Feature::Worktrees)
&& !crate::uses_remote_workspace_or_environment(
&self.app_server_target,
self.environment_manager.as_ref(),
),
self.app_event_tx.clone(),
self.keymap.clone(),
Arc::clone(&self.agents_overview.view_state),
@@ -892,6 +892,72 @@ async fn agents_overview_reasoning_uses_existing_events_and_expires_with_attachm
assert!(!app.agents_overview.activity.contains_key(&thread_id));
}
#[tokio::test]
async fn worktrees_overview_grouping_requires_feature() {
let mut app = make_test_app().await;
let root = tempfile::tempdir().unwrap();
let primary = root.path().join("primary");
let linked = root.path().join("linked");
let linked_subdir = linked.join("subdir/child");
let nested = primary.join("subdir");
let nested_child = nested.join("child");
let admin = primary.join(".git/worktrees/linked");
std::fs::create_dir_all(&admin).unwrap();
std::fs::create_dir_all(&linked_subdir).unwrap();
std::fs::create_dir_all(nested.join(".git")).unwrap();
std::fs::create_dir_all(&nested_child).unwrap();
std::fs::write(primary.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
std::fs::write(nested.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
std::fs::write(admin.join("commondir"), "../..").unwrap();
std::fs::write(
admin.join("gitdir"),
linked.join(".git").display().to_string(),
)
.unwrap();
std::fs::write(linked.join(".git"), format!("gitdir: {}", admin.display())).unwrap();
let primary = dunce::canonicalize(primary).unwrap();
let threads = [primary.clone(), linked, linked_subdir, nested_child]
.into_iter()
.map(|cwd| {
let mut thread = overview_thread(
ThreadId::new(),
/*parent_thread_id*/ None,
"Task",
ThreadStatus::Idle,
);
thread.cwd = AbsolutePathBuf::from_absolute_path(cwd).unwrap();
thread
})
.collect::<Vec<_>>();
let grouped_heading = format!("{} 2", primary.join("").display());
let width = 160;
for enabled in [false, true] {
app.config
.features
.set_enabled(Feature::Worktrees, enabled)
.unwrap();
let view = app.agents_overview_view(threads.clone(), /*selected_thread_id*/ None);
app.chat_widget.show_bottom_pane_view(Box::new(view));
let popup = render_bottom_popup(&app.chat_widget, width);
assert_eq!(popup.contains(&grouped_heading), enabled, "{popup}");
if enabled {
let grouping = popup
.lines()
.map(|line| line.split('│').next().unwrap_or(line).trim_end())
.collect::<Vec<_>>()
.join("\n")
.replace(
&primary.join("").display().to_string(),
"/tmp/worktree-root/primary/",
)
.replace('\\', "/");
insta::with_settings!({snapshot_path => "../snapshots"}, {
insta::assert_snapshot!("agents_overview_worktree_grouping", grouping);
});
}
}
}
#[tokio::test]
async fn shared_overview_shows_only_root_sessions() {
assert_eq!(
@@ -949,6 +1015,7 @@ async fn shared_overview_shows_only_root_sessions() {
view.rows.clone(),
Some(first_root),
/*exit_on_cancel*/ false,
/*worktrees_enabled*/ false,
crate::app_event_sender::AppEventSender::new(event_tx),
app.keymap.clone(),
Arc::clone(&app.agents_overview.view_state),
@@ -1190,6 +1257,7 @@ async fn filtered_dashboard_actions_use_configured_shortcuts() {
.rows,
Some(first),
/*exit_on_cancel*/ false,
/*worktrees_enabled*/ false,
crate::app_event_sender::AppEventSender::new(event_tx),
app.keymap.clone(),
Arc::clone(&app.agents_overview.view_state),
+57 -11
View File
@@ -41,6 +41,7 @@ use ratatui::text::Span;
use ratatui::widgets::Clear;
use ratatui::widgets::Paragraph;
use ratatui::widgets::Widget;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
@@ -96,6 +97,33 @@ fn display_title(thread: &Thread) -> &str {
title.trim().lines().next().unwrap_or("Untitled task")
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct AgentsOverviewProjectGroup {
key: (PathBuf, PathBuf),
heading: PathBuf,
}
impl AgentsOverviewProjectGroup {
fn for_thread(thread: &Thread, worktrees_enabled: bool) -> Self {
if worktrees_enabled
&& let Some(identity) = codex_git_utils::repository_identity(thread.cwd.as_path())
{
Self {
key: (
identity.common_dir.into_path_buf(),
identity.relative_cwd.clone(),
),
heading: identity.primary_root.as_path().join(identity.relative_cwd),
}
} else {
Self {
key: (thread.cwd.to_path_buf(), PathBuf::new()),
heading: thread.cwd.to_path_buf(),
}
}
}
}
#[derive(Default)]
pub(super) struct AgentsOverviewViewState {
// Search and rename never borrow the new-task draft.
@@ -148,6 +176,7 @@ impl AgentsOverviewViewState {
pub(super) struct AgentsOverviewView {
pub(super) rows: Vec<AgentsOverviewRow>,
project_groups: Vec<AgentsOverviewProjectGroup>,
selected: usize,
state: Arc<Mutex<AgentsOverviewViewState>>,
exit_on_cancel: bool,
@@ -163,6 +192,7 @@ impl AgentsOverviewView {
rows: Vec<AgentsOverviewRow>,
selected_thread_id: Option<ThreadId>,
exit_on_cancel: bool,
worktrees_enabled: bool,
app_event_tx: AppEventSender,
keymap: RuntimeKeymap,
state: Arc<Mutex<AgentsOverviewViewState>>,
@@ -183,8 +213,13 @@ impl AgentsOverviewView {
})
.chain([("esc".to_string(), "tasks".to_string())])
.collect();
let project_groups = rows
.iter()
.map(|row| AgentsOverviewProjectGroup::for_thread(&row.thread, worktrees_enabled))
.collect();
let mut view = Self {
rows,
project_groups,
selected,
state,
exit_on_cancel,
@@ -237,7 +272,7 @@ impl AgentsOverviewView {
if !state.status_grouping {
visible.sort_by_key(|index| {
(
&self.rows[*index].thread.cwd,
&self.project_groups[*index].key,
std::cmp::Reverse(self.rows[*index].thread.updated_at),
)
});
@@ -320,7 +355,7 @@ impl AgentsOverviewView {
fn render_rows(&self, area: Rect, buf: &mut Buffer) {
let mut offset = 0;
let mut previous_group: Option<String> = None;
let mut previous_group_index: Option<usize> = None;
let project_grouping = !self
.state
.lock()
@@ -333,10 +368,12 @@ impl AgentsOverviewView {
.unwrap_or_default();
let mut height = 2;
while first > 0 {
let previous = &self.rows[visible[first - 1]];
let current = &self.rows[visible[first]];
let previous_index = visible[first - 1];
let current_index = visible[first];
let previous = &self.rows[previous_index];
let current = &self.rows[current_index];
let group_changed = if project_grouping {
previous.thread.cwd != current.thread.cwd
self.project_groups[previous_index].key != self.project_groups[current_index].key
} else {
previous.group != current.group
};
@@ -353,21 +390,30 @@ impl AgentsOverviewView {
}
let row = &self.rows[index];
let group = if project_grouping {
row.thread.cwd.display().to_string()
self.project_groups[index].heading.display().to_string()
} else {
row.group.label().to_string()
};
if previous_group.as_deref() != Some(group.as_str()) {
offset += u16::from(previous_group.is_some());
let group_changed = previous_group_index.is_none_or(|previous_index| {
if project_grouping {
self.project_groups[previous_index].key != self.project_groups[index].key
} else {
self.rows[previous_index].group != row.group
}
});
if group_changed {
offset += u16::from(previous_group_index.is_some());
if offset >= area.height {
break;
}
let count = self
.rows
.iter()
.filter(|candidate| {
.enumerate()
.filter(|(candidate_index, candidate)| {
if project_grouping {
candidate.thread.cwd == row.thread.cwd
self.project_groups[*candidate_index].key
== self.project_groups[index].key
} else {
candidate.group == row.group
}
@@ -376,7 +422,7 @@ impl AgentsOverviewView {
Line::from(vec![group.clone().bold(), format!(" {count}").dim()])
.render(Rect::new(area.x, area.y + offset, area.width, 1), buf);
offset += 1;
previous_group = Some(group);
previous_group_index = Some(index);
}
if offset >= area.height {
break;
+5 -1
View File
@@ -34,6 +34,7 @@ impl App {
&& !matches!(
&event,
AppEvent::InsertHistoryCell(_)
| AppEvent::ManagedWorktreeCreated(_)
| AppEvent::AppendMessageHistoryEntry { .. }
| AppEvent::BeginInitialHistoryReplayBuffer
| AppEvent::BeginThreadSwitchHistoryReplayBuffer
@@ -91,7 +92,10 @@ impl App {
}
}
AppEvent::StartManagedWorktree { mode, name } => {
self.start_managed_worktree(tui, app_server, mode, name).await;
self.start_managed_worktree(app_server, mode, name).await;
}
AppEvent::ManagedWorktreeCreated(created) => {
self.finish_managed_worktree(tui, app_server, *created).await;
}
AppEvent::ChangeWorkingDirectory {
thread_id,
@@ -0,0 +1,258 @@
//! Managed checkout creation and handoff from blocking Git work to the TUI event loop.
//!
//! Source-only blockers are checked before allocation. The completion event rechecks the
//! original session and reports a recovery path for every retained checkout.
use super::*;
use crate::app_event::ManagedWorktreeCreated;
use crate::history_cell::McpInventoryLoadingCell as LoadingCell;
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,
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 if self.pending_managed_worktree_creation {
self.chat_widget
.add_error_message("A worktree is already being created.".to_string());
} else {
// These source-only checks must precede allocation. The transition repeats them
// after the background task, since the session can change while Git is running.
if self
.transcript_cells
.iter()
.any(|cell| cell.as_any().is::<LoadingCell>())
{
return self.working_directory_error("MCP inventory is still loading.");
}
let Some(thread_id) = self.primary_thread_id else {
return self.working_directory_error(
"Creating a worktree requires an idle primary session without queued input.",
);
};
let agents = self.agent_navigation.ordered_threads();
let closed_agents: HashSet<_> = agents
.iter()
.filter_map(|(id, agent)| agent.is_closed.then_some(*id))
.collect();
let active = self.thread_event_channels.iter().any(|(id, channel)| {
*id != thread_id
&& !closed_agents.contains(id)
&& !channel
.store
.try_lock()
.is_ok_and(|store| store.active_turn_id().is_none())
});
if active
|| agents
.iter()
.any(|(id, agent)| *id != thread_id && agent.is_running)
{
return self.working_directory_error("Cannot change: another agent is running.");
}
let rollout = self.chat_widget.rollout_path();
let has_rollout = rollout.as_deref().is_some_and(rollout_path_is_resumable);
if mode == crate::app_event::ManagedWorktreeMode::Fork
&& !has_rollout
&& (!self.chat_widget.token_usage().is_zero()
|| self
.thread_event_channels
.get(&thread_id)
.is_some_and(|channel| {
channel.store.try_lock().map_or(/*default*/ true, |store| {
!store.turns.is_empty() || store.buffer.iter().any(|event| {
matches!(event, ThreadBufferedEvent::Notification(notification)
if matches!(notification.as_ref(),
ServerNotification::TurnStarted(_)
| ServerNotification::TurnCompleted(_)))
})
})
}))
{
return self.working_directory_error("Conversation history is not saved.");
}
let mut ids: HashSet<_> = self
.thread_event_channels
.keys()
.copied()
.filter(|id| !closed_agents.contains(id))
.collect();
ids.extend(
agents
.iter()
.filter_map(|(id, agent)| (!agent.is_closed).then_some(*id)),
);
for tracked_id in ids {
let request = ClientRequest::ThreadBackgroundTerminalsList {
request_id: app_server.next_request_id(),
params: ThreadBackgroundTerminalsListParams {
thread_id: tracked_id.to_string(),
cursor: None,
limit: Some(1),
},
};
let result = app_server
.request_handle()
.request_typed::<ListResponse>(request)
.await;
if !matches!(result, Ok(response) if response.data.is_empty()) {
return self.working_directory_error("Active background terminals block /cd.");
}
}
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);
anyhow::Ok(manager)
}
.await;
match setup {
Ok(manager) => {
self.pending_managed_worktree_creation = true;
let source_cwd = self.config.cwd.clone();
let sender = self.app_event_tx.clone();
tokio::spawn(async move {
let create_cwd = source_cwd.to_path_buf();
let result = tokio::task::spawn_blocking(move || {
manager
.create(&codex_worktree::CreateWorktree {
source_cwd: create_cwd,
base: None,
})
.map(|checkout| (manager, checkout))
.map_err(|error| error.to_string())
})
.await
.unwrap_or_else(|error| {
Err(format!("Worktree creation task failed: {error}"))
});
sender.send(AppEvent::ManagedWorktreeCreated(Box::new(
ManagedWorktreeCreated {
source_thread_id: thread_id,
source_cwd,
mode,
name,
result,
},
)));
});
}
Err(error) => self.chat_widget.add_error_message(error.to_string()),
}
}
}
pub(super) async fn finish_managed_worktree(
&mut self,
tui: &mut tui::Tui,
app_server: &mut AppServerSession,
created: ManagedWorktreeCreated,
) {
self.pending_managed_worktree_creation = false;
let (manager, checkout) = match created.result {
Ok(created) => created,
Err(error) => return self.working_directory_error(error),
};
let can_continue = !self.reconnect.offline
&& !self.chat_widget.has_misalignment_policy_violation()
&& self.config.features.enabled(Feature::Worktrees)
&& !crate::uses_remote_workspace_or_environment(
&self.app_server_target,
self.environment_manager.as_ref(),
)
&& self.primary_thread_id == Some(created.source_thread_id)
&& !crate::session_resume::cwds_differ(
self.config.cwd.as_path(),
created.source_cwd.as_path(),
)
&& self
.chat_widget
.can_change_working_directory(created.source_thread_id);
if !can_continue {
return self.retained_worktree_error(
&checkout,
"Cannot continue into the new worktree while the source session changed or is unavailable.",
);
}
match self
.rebuild_config_for_cwd(created.source_cwd.to_path_buf())
.await
{
Ok(config) if !config.active_project.is_untrusted() => {}
Ok(_) | Err(_) => {
return self.retained_worktree_error(
&checkout,
"Cannot continue into the new worktree because source configuration changed.",
);
}
}
if let Err(error) = self
.switch_to_managed_worktree(
tui,
app_server,
manager,
checkout.clone(),
created.mode,
created.name,
)
.await
{
self.retained_worktree_error(&checkout, error.to_string());
}
}
fn retained_worktree_error(
&mut self,
checkout: &codex_worktree::ManagedWorktree,
reason: impl std::fmt::Display,
) {
self.working_directory_error(format!(
"{reason} A checkout was retained at {}; remove it with `git worktree remove <checkout-path>` from the source repository if it is no longer needed.",
checkout.root.display()
));
}
}
+25 -8
View File
@@ -9,14 +9,27 @@ impl App {
tui: &mut tui::Tui,
app_server: &mut AppServerSession,
) -> Result<AppRunControl> {
let picker_app_server = match crate::start_app_server_for_picker(
&self.config,
&self.app_server_target,
self.state_db.clone(),
self.environment_manager.clone(),
)
.await
{
// This runs inside the active TUI event future. Starting a second embedded server
// inline can exhaust that thread's stack while initializing its auth manager.
let picker_config = self.config.clone();
let picker_target = self.app_server_target.clone();
let picker_state_db = self.state_db.clone();
let picker_environment_manager = Arc::clone(&self.environment_manager);
let picker_app_server = tokio::spawn(async move {
crate::start_app_server_for_picker(
&picker_config,
&picker_target,
picker_state_db,
picker_environment_manager,
)
.await
})
.await;
let picker_app_server = match picker_app_server {
Ok(result) => result,
Err(err) => Err(err.into()),
};
let picker_app_server = match picker_app_server {
Ok(app_server) => app_server,
Err(err) => {
self.add_session_picker_error(format!("Failed to start TUI session picker: {err}"));
@@ -26,6 +39,10 @@ impl App {
};
let selection =
crate::resume_picker::run_resume_picker_from_existing_session_with_app_server(
crate::uses_remote_workspace_or_environment(
&self.app_server_target,
&self.environment_manager,
),
tui,
&self.config,
&self.local_settings,
+1
View File
@@ -690,6 +690,7 @@ See the Codex keymap documentation for supported actions and examples."
dynamic_tool_status_updates,
dynamic_tool_tasks: HashMap::new(),
pending_startup_thread_start,
pending_managed_worktree_creation: false,
startup_protected_input_boundary: true,
startup_pending_protected_request: false,
rate_limit_hard_stop_generation: 0,
+1
View File
@@ -80,6 +80,7 @@ pub(super) async fn make_test_app() -> App {
dynamic_tool_status_updates: tokio::sync::broadcast::channel(/*capacity*/ 64).0,
dynamic_tool_tasks: HashMap::new(),
pending_startup_thread_start: false,
pending_managed_worktree_creation: false,
startup_protected_input_boundary: false,
startup_pending_protected_request: false,
rate_limit_hard_stop_generation: 0,
+2
View File
@@ -5539,6 +5539,7 @@ async fn make_test_app() -> App {
dynamic_tool_status_updates: tokio::sync::broadcast::channel(/*capacity*/ 64).0,
dynamic_tool_tasks: HashMap::new(),
pending_startup_thread_start: false,
pending_managed_worktree_creation: false,
startup_protected_input_boundary: false,
startup_pending_protected_request: false,
rate_limit_hard_stop_generation: 0,
@@ -5625,6 +5626,7 @@ pub(super) async fn make_test_app_with_channels() -> (
dynamic_tool_status_updates: tokio::sync::broadcast::channel(/*capacity*/ 64).0,
dynamic_tool_tasks: HashMap::new(),
pending_startup_thread_start: false,
pending_managed_worktree_creation: false,
startup_protected_input_boundary: false,
startup_pending_protected_request: false,
rate_limit_hard_stop_generation: 0,
@@ -41,6 +41,23 @@ use tokio_tungstenite::tungstenite::Message;
pub(super) type RecordedRequests = Arc<Mutex<Vec<JSONRPCRequest>>>;
pub(super) type RecordingAppServer = (AppServerSession, RecordedRequests, JoinHandle<Result<()>>);
async fn complete_managed_worktree_creation(
app: &mut App,
tui: &mut crate::tui::Tui,
server: &mut AppServerSession,
events: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
) -> Result<()> {
loop {
let event = tokio::time::timeout(Duration::from_secs(15), events.recv())
.await?
.ok_or_else(|| color_eyre::eyre::eyre!("worktree creation event channel closed"))?;
if matches!(event, AppEvent::ManagedWorktreeCreated(_)) {
app.handle_event(tui, server, event).await?;
return Ok(());
}
}
}
#[tokio::test]
async fn same_thread_retry_keeps_subscription_and_restores_draft() -> Result<()> {
let (mut app, codex_home) = make_history_test_app().await?;
@@ -2947,6 +2964,7 @@ model_reasoning_effort = "low"
},
)
.await?;
complete_managed_worktree_creation(&mut app, &mut tui, &mut server, &mut events).await?;
assert_eq!(app.chat_widget.thread_id(), Some(original));
assert!(recorded_params(&requests, "thread/fork").is_empty());
let unused = manager
@@ -2976,6 +2994,26 @@ model_reasoning_effort = "low"
.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.");
let retained = 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("A checkout was retained at"))
.expect("post-allocation recovery message");
let (_, with_path) = retained
.split_once("A checkout was retained at ")
.expect("retained checkout marker");
let (path, _) = with_path
.split_once("; remove it with")
.expect("retained checkout cleanup marker");
assert_eq!(
dunce::canonicalize(path)?,
dunce::canonicalize(&unused.root)?
);
assert!(retained.contains("git worktree remove <checkout-path>"));
fs::write(
source.join(".codex/config.toml"),
r#"developer_instructions = "committed policy"
@@ -2994,8 +3032,63 @@ terminal_visualization_instructions = true
},
)
.await?;
complete_managed_worktree_creation(&mut app, &mut tui, &mut server, &mut events).await?;
assert_eq!(app.chat_widget.thread_id(), Some(original));
assert!(recorded_params(&requests, "thread/fork").is_empty());
while events.try_recv().is_ok() {}
app.handle_event(
&mut tui,
&mut server,
AppEvent::StartManagedWorktree {
mode: ManagedWorktreeMode::New,
name: None,
},
)
.await?;
assert_eq!(app.chat_widget.thread_id(), Some(original));
assert!(app.pending_managed_worktree_creation);
let created = loop {
let event = tokio::time::timeout(Duration::from_secs(15), events.recv())
.await?
.ok_or_else(|| color_eyre::eyre::eyre!("worktree completion channel closed"))?;
if let AppEvent::ManagedWorktreeCreated(created) = event {
break created;
}
};
let stale_checkout = created
.result
.as_ref()
.expect("created checkout")
.1
.root
.clone();
app.primary_thread_id = Some(ThreadId::new());
app.handle_event(
&mut tui,
&mut server,
AppEvent::ManagedWorktreeCreated(created),
)
.await?;
app.primary_thread_id = Some(original);
assert_eq!(app.chat_widget.thread_id(), Some(original));
assert!(!app.pending_managed_worktree_creation);
let stale_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("A checkout was retained at"))
.expect("stale creation recovery message");
assert!(stale_error.contains(&stale_checkout.display().to_string()));
assert!(stale_error.contains("git worktree remove <checkout-path>"));
assert_eq!(
manager
.owner(&stale_checkout)
.map_err(|error| color_eyre::eyre::eyre!(error.to_string()))?,
None
);
for mode in [ManagedWorktreeMode::New, ManagedWorktreeMode::Fork] {
requests.lock().expect("request recorder lock").clear();
let previous = app.chat_widget.thread_id();
@@ -3009,6 +3102,7 @@ terminal_visualization_instructions = true
},
)
.await?;
complete_managed_worktree_creation(&mut app, &mut tui, &mut server, &mut events).await?;
let replacement = app.chat_widget.thread_id().expect("replacement thread");
assert_ne!(Some(replacement), previous);
assert_eq!(
@@ -3105,6 +3199,10 @@ terminal_visualization_instructions = true
)
.await?;
let is_new = mode == ManagedWorktreeMode::New;
if is_new {
complete_managed_worktree_creation(&mut app, &mut tui, &mut server, &mut events)
.await?;
}
assert_eq!(app.chat_widget.thread_id() != Some(unsaved), is_new);
assert_eq!(recorded_params(&requests, "thread/fork").len(), 0);
}
@@ -89,6 +89,51 @@ async fn worktree_creation_rejects_untrusted_source_before_allocation() -> Resul
Ok(())
}
#[tokio::test]
async fn worktree_creation_rejects_running_agent_before_allocation() -> Result<()> {
let (mut app, mut events, _op_rx) = make_test_app_with_channels().await;
let home = tempfile::tempdir()?;
app.config.codex_home = home.path().to_path_buf().abs();
app.config.features.enable(Feature::Worktrees)?;
app.config.active_project.trust_level = Some(codex_protocol::config_types::TrustLevel::Trusted);
let primary = ThreadId::new();
app.primary_thread_id = Some(primary);
app.chat_widget
.handle_thread_session_quiet(test_thread_session(primary, app.config.cwd.to_path_buf()));
let child = ThreadId::new();
app.agent_navigation.upsert(
child, /*agent_nickname*/ None, /*agent_role*/ None, /*is_closed*/ false,
);
app.agent_navigation.set_running(child, /*is_running*/ true);
let mut tui = crate::tui::test_support::make_test_tui()?;
let mut 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 server,
AppEvent::StartManagedWorktree {
mode: crate::app_event::ManagedWorktreeMode::New,
name: None,
},
)
.await?;
assert!(!app.pending_managed_worktree_creation);
assert!(!home.path().join("worktrees").exists());
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("running agent message");
insta::assert_snapshot!(message, @"■ Cannot change: another agent is running.");
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;
+2 -75
View File
@@ -1,4 +1,4 @@
//! Local directory transitions and managed worktrees with fresh or preserved conversation history.
//! Local directory transitions with fresh or preserved conversation history.
use super::session_lifecycle::ThreadAttachPresentation;
use super::*;
@@ -9,80 +9,7 @@ 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>) {
pub(super) fn working_directory_error(&mut self, message: impl Into<String>) {
self.chat_widget.add_error_message(message.into());
}