diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 8060bca9bc..c2efb3f692 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -1737,8 +1737,8 @@ impl App { self.enqueue_thread_history_entry_response(thread_id, event) .await?; } - AppEvent::DiffResult(cwd, text) => { - if &cwd != self.chat_widget.session_cwd() { + AppEvent::DiffResult { thread_id, cwd, text } => { + if thread_id != self.chat_widget.thread_id() || &cwd != self.chat_widget.session_cwd() { return Ok(AppRunControl::Continue); } // Clear the in-progress state in the bottom pane diff --git a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs index ad87cea99d..5dd23ae217 100644 --- a/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs +++ b/codex-rs/tui/src/app/tests/session_lifecycle_requests.rs @@ -50,7 +50,7 @@ use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::tungstenite::error::ProtocolError; #[tokio::test] -async fn diff_result_matches_the_server_session_cwd() -> Result<()> { +async fn diff_result_matches_the_server_session_thread_and_cwd() -> Result<()> { use codex_utils_path_uri::LegacyAppPathString; use codex_utils_path_uri::PathUri; @@ -67,12 +67,26 @@ async fn diff_result_matches_the_server_session_cwd() -> Result<()> { let cwd = PathUri::try_from(LegacyAppPathString::from_string(foreign_cwd))?; let mut session = test_thread_session(ThreadId::new(), app.config.cwd.to_path_buf()); session.cwd = cwd.clone(); + let thread_id = Some(session.thread_id); app.chat_widget.handle_thread_session(session); - let stale = AppEvent::DiffResult(app.config.cwd.clone().into(), "old diff".into()); - Box::pin(app.handle_event(&mut tui, &mut server, stale)).await?; - assert!(app.overlay.is_none()); + for (thread_id, cwd) in [ + (thread_id, app.config.cwd.clone().into()), + (Some(ThreadId::new()), cwd.clone()), + ] { + let stale = AppEvent::DiffResult { + thread_id, + cwd, + text: "old diff".into(), + }; + Box::pin(app.handle_event(&mut tui, &mut server, stale)).await?; + assert!(app.overlay.is_none()); + } - let current = AppEvent::DiffResult(cwd, "current diff".into()); + let current = AppEvent::DiffResult { + thread_id, + cwd, + text: "current diff".into(), + }; Box::pin(app.handle_event(&mut tui, &mut server, current)).await?; assert!(app.overlay.is_some()); Ok(()) @@ -6464,7 +6478,11 @@ async fn change_directory_scenario() -> Result<()> { let skills = AppEvent::SkillsListLoaded { cwd, result }; let (cwd, plugins) = (current.clone(), Some(vec![])); let plugins = AppEvent::PluginMentionsLoaded { cwd, plugins }; - let diff = AppEvent::DiffResult(current.clone().abs().into(), "stale diff".to_string()); + let diff = AppEvent::DiffResult { + thread_id: Some(original), + cwd: current.clone().abs().into(), + text: "stale diff".to_string(), + }; let branch = AppEvent::SyncThreadGitBranch { thread_id: original, branch: "stale".to_string(), diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 992a0e7173..463d3a1bb3 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -1097,7 +1097,11 @@ pub(crate) enum AppEvent { }, /// Result of computing a `/diff` command. - DiffResult(PathUri, String), + DiffResult { + thread_id: Option, + cwd: PathUri, + text: String, + }, /// Open the app link view in the bottom pane. OpenAppLink { diff --git a/codex-rs/tui/src/chatwidget/slash_dispatch.rs b/codex-rs/tui/src/chatwidget/slash_dispatch.rs index ca85bd5a07..cf89b48fef 100644 --- a/codex-rs/tui/src/chatwidget/slash_dispatch.rs +++ b/codex-rs/tui/src/chatwidget/slash_dispatch.rs @@ -85,6 +85,49 @@ impl ChatWidget { self.bottom_pane.record_pending_slash_command_history(); } + /// Re-anchor the local daemon's sandbox at the session cwd. A profile ID + /// cannot carry extra runtime roots or permissions from a remote executor. + pub(super) fn diff_permission_profile(&self) -> Option { + if !self.remote_connection.as_ref()?.is_local_daemon { + return None; + } + let matches_workspace = match &self.primary_environment_cwd { + // History and inferred sessions can borrow another thread's settings. + Some(primary) => { + self.thread_settings_confirmed + && !self.read_only_history + && primary.is_server_local + && primary.cwd_is_only_root + && primary.path.to_path_buf() == self.session_cwd().to_path_buf() + } + // Before thread creation, the TUI only has the startup workspace. + None => { + self.thread_id().is_none() + && self.session_workspace_roots() == std::slice::from_ref(self.session_cwd()) + } + }; + // command/exec can reload a profile by ID, but cannot replay the + // permission definitions that thread/start received from CLI flags. + if !matches_workspace + || self + .config + .config_layer_stack + .layers_high_to_low() + .any(|layer| { + matches!(layer.name, codex_config::ConfigLayerSource::SessionFlags) + && ["permissions", "sandbox_workspace_write", "network"] + .iter() + .any(|key| layer.config.get(*key).is_some()) + }) + { + return None; + } + self.config + .permissions + .active_permission_profile() + .map(|profile| profile.id) + } + fn apply_plan_slash_command(&mut self) -> bool { if !self.collaboration_modes_enabled() { self.add_info_message( @@ -503,11 +546,19 @@ impl ChatWidget { self.add_diff_in_progress(); let tx = self.app_event_tx.clone(); let runner = self.workspace_command_runner.clone(); + let thread_id = self.thread_id(); let cwd = self.session_cwd().clone(); + let profile = self.diff_permission_profile(); tokio::spawn(async move { let text = match runner { Some(runner) => { - match get_git_diff(runner.as_ref(), &cwd.to_path_buf()).await { + match get_git_diff( + runner.as_ref(), + &cwd.to_path_buf(), + profile.as_deref(), + ) + .await + { Ok((is_git_repo, diff_text)) => { if is_git_repo { diff_text @@ -521,7 +572,11 @@ impl ChatWidget { None => "Failed to compute diff: workspace command runner unavailable" .to_string(), }; - tx.send(AppEvent::DiffResult(cwd, text)); + tx.send(AppEvent::DiffResult { + thread_id, + cwd, + text, + }); }); } SlashCommand::Mention => { diff --git a/codex-rs/tui/src/chatwidget/statusline_reader_tests.rs b/codex-rs/tui/src/chatwidget/statusline_reader_tests.rs index 237b58820e..5e33733737 100644 --- a/codex-rs/tui/src/chatwidget/statusline_reader_tests.rs +++ b/codex-rs/tui/src/chatwidget/statusline_reader_tests.rs @@ -170,6 +170,7 @@ async fn statusline_reader_waits_for_the_displayed_thread_and_keeps_its_result() chat.primary_environment_cwd = Some(crate::session_state::EnvironmentCwd { path: chat.config.cwd.join("executor-checkout").into(), is_server_local: false, + cwd_is_only_root: true, }); chat.refresh_status_line(); assert!(read_events(&mut rx).is_empty()); diff --git a/codex-rs/tui/src/chatwidget/tests/permissions.rs b/codex-rs/tui/src/chatwidget/tests/permissions.rs index 77d22f66ff..26b5812e49 100644 --- a/codex-rs/tui/src/chatwidget/tests/permissions.rs +++ b/codex-rs/tui/src/chatwidget/tests/permissions.rs @@ -37,6 +37,62 @@ async fn remote_windows_agent_permission_uses_server_selection() { )); } +#[tokio::test] +async fn diff_profile_requires_a_matching_local_daemon_workspace() { + let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await; + chat.set_permission_profile_from_session_snapshot(PermissionProfileSnapshot::active( + PermissionProfile::read_only(), + ActivePermissionProfile::new("project"), + )) + .unwrap(); + let cwd = chat.session_cwd().clone(); + let mut environments = [codex_app_server_protocol::ThreadEnvironment { + environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.into(), + cwd: cwd.clone().into(), + runtime_workspace_roots: vec![cwd.clone().into()], + }]; + chat.primary_environment_cwd = crate::session_state::primary_environment_cwd(&environments); + assert_eq!(chat.diff_permission_profile(), None); + + chat.remote_connection = Some(crate::status::remote_connection::RemoteConnectionStatus { + address: "local".into(), + version: None, + is_local_daemon: true, + is_managed_daemon: false, + }); + chat.thread_settings_confirmed = false; + assert_eq!(chat.diff_permission_profile(), None); + chat.thread_settings_confirmed = true; + assert_eq!(chat.diff_permission_profile().as_deref(), Some("project")); + + environments[0] + .runtime_workspace_roots + .push(cwd.join("nested").unwrap().into()); + chat.primary_environment_cwd = crate::session_state::primary_environment_cwd(&environments); + assert_eq!(chat.diff_permission_profile(), None); + + environments[0].runtime_workspace_roots.pop(); + environments[0].environment_id = "remote".into(); + chat.primary_environment_cwd = crate::session_state::primary_environment_cwd(&environments); + assert_eq!(chat.diff_permission_profile(), None); + environments[0].environment_id = codex_exec_server::LOCAL_ENVIRONMENT_ID.into(); + chat.primary_environment_cwd = crate::session_state::primary_environment_cwd(&environments); + chat.config.config_layer_stack = codex_config::ConfigLayerStack::new( + vec![codex_config::ConfigLayerEntry::new( + codex_config::ConfigLayerSource::SessionFlags, + toml::from_str( + r#"[permissions.project.filesystem] +":root" = "read""#, + ) + .unwrap(), + )], + Default::default(), + Default::default(), + ) + .unwrap(); + assert_eq!(chat.diff_permission_profile(), None); +} + #[tokio::test] async fn permission_discovery_uses_server_catalog_for_remote_custom_selection() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; diff --git a/codex-rs/tui/src/get_git_diff.rs b/codex-rs/tui/src/get_git_diff.rs index 11812b3984..a01f85d5f8 100644 --- a/codex-rs/tui/src/get_git_diff.rs +++ b/codex-rs/tui/src/get_git_diff.rs @@ -26,17 +26,34 @@ const EXECUTABLE_FILTER_CONFIG_PATTERN: &str = r"^filter\..*\.(clean|process)$"; // `/diff` may execute Git through a remote workspace, so git-utils owns the // probe policy while this adapter keeps command execution in the TUI layer. // WorkspaceCommand bounds each call; `/diff` has no aggregate command deadline. -struct WorkspaceFsmonitorProbeRunner<'a> { +struct DiffCommands<'a> { runner: &'a dyn WorkspaceCommandExecutor, cwd: &'a Path, + permission_profile: Option<&'a str>, } -impl FsmonitorProbeRunner for WorkspaceFsmonitorProbeRunner<'_> { +impl DiffCommands<'_> { + fn command(&self, argv: impl IntoIterator>) -> WorkspaceCommand { + let mut command = WorkspaceCommand::new(argv, self.cwd.to_path_buf()); + if let Some(profile) = self.permission_profile { + command.permission_profile = Some(profile.to_owned()); + // A thread profile can grant network access outside the application's + // destination policy. Keep Git local even on older versions that + // ignore GIT_NO_LAZY_FETCH by denying all transport protocols. + command = command + .env("GIT_NO_LAZY_FETCH", "1") + .env("GIT_ALLOW_PROTOCOL", ""); + } + command + } +} + +impl FsmonitorProbeRunner for DiffCommands<'_> { async fn run_probe(&mut self, args: &[&str]) -> Option> { let argv = ["git", "-c", codex_git_utils::SAFE_BARE_REPOSITORY_CONFIG] .into_iter() .chain(args.iter().copied()); - let command = WorkspaceCommand::new(argv, self.cwd.to_path_buf()); + let command = self.command(argv); match self.runner.run(command).await { Ok(output) if output.success() => Some(output.stdout.into_bytes()), _ => None, @@ -51,22 +68,36 @@ impl FsmonitorProbeRunner for WorkspaceFsmonitorProbeRunner<'_> { pub(crate) async fn get_git_diff( runner: &dyn WorkspaceCommandExecutor, cwd: &Path, + permission_profile: Option<&str>, ) -> Result<(bool, String), String> { + // A reattached client inherits the ID but not the flags that defined it. + // Check custom IDs once so all Git commands use the same selection. + let permission_profile = match permission_profile { + Some(id) if !id.starts_with(':') => runner + .has_permission_profile(cwd, id) + .await + .map_err(|err| err.to_string())? + .then_some(id), + profile => profile, + }; + let mut commands = DiffCommands { + runner, + cwd, + permission_profile, + }; // First check if we are inside a Git repository. - if !inside_git_repo(runner, cwd).await? { + if !inside_git_repo(&commands).await? { return Ok((false, String::new())); } // Probe once per `/diff` and reuse the result for all subsequent Git commands. - let mut probe_runner = WorkspaceFsmonitorProbeRunner { runner, cwd }; - let fsmonitor = detect_fsmonitor_override(&mut probe_runner).await; + let fsmonitor = detect_fsmonitor_override(&mut commands).await; // Keep `/diff` informational: repository configuration must not select executable diff helpers. - let diff_config_overrides = diff_filter_config_overrides(runner, cwd, fsmonitor).await?; + let diff_config_overrides = diff_filter_config_overrides(&commands, fsmonitor).await?; let (tracked_diff_res, untracked_output_res) = tokio::join!( run_git_capture_diff( - runner, - cwd, + &commands, fsmonitor, &diff_config_overrides, &[ @@ -79,8 +110,7 @@ pub(crate) async fn get_git_diff( ] ), run_git_capture_stdout( - runner, - cwd, + &commands, fsmonitor, &["ls-files", "--others", "--exclude-standard"] ), @@ -114,7 +144,7 @@ pub(crate) async fn get_git_diff( file, ]; let diff = - run_git_capture_diff(runner, cwd, fsmonitor, &diff_config_overrides, &args).await?; + run_git_capture_diff(&commands, fsmonitor, &diff_config_overrides, &args).await?; untracked_diff.push_str(&diff); } @@ -124,12 +154,11 @@ pub(crate) async fn get_git_diff( /// Helper that executes `git` with the given `args` and returns `stdout` as a /// UTF-8 string. Any non-zero exit status is considered an *error*. async fn run_git_capture_stdout( - runner: &dyn WorkspaceCommandExecutor, - cwd: &Path, + commands: &DiffCommands<'_>, fsmonitor: FsmonitorOverride, args: &[&str], ) -> Result { - let output = run_git_command(runner, cwd, fsmonitor, &[], args).await?; + let output = run_git_command(commands, fsmonitor, &[], args).await?; if output.success() { Ok(output.stdout) } else { @@ -143,13 +172,12 @@ async fn run_git_capture_stdout( /// Like [`run_git_capture_stdout`] but treats exit status 1 as success and /// returns stdout. Git returns 1 for diffs when differences are present. async fn run_git_capture_diff( - runner: &dyn WorkspaceCommandExecutor, - cwd: &Path, + commands: &DiffCommands<'_>, fsmonitor: FsmonitorOverride, config_overrides: &[(String, String)], args: &[&str], ) -> Result { - let output = run_git_command(runner, cwd, fsmonitor, config_overrides, args).await?; + let output = run_git_command(commands, fsmonitor, config_overrides, args).await?; if output.success() || output.exit_code == 1 { Ok(output.stdout) } else { @@ -163,8 +191,7 @@ async fn run_git_capture_diff( /// Return Git configuration overrides that prevent configured filter drivers /// from executing while generating diffs. async fn diff_filter_config_overrides( - runner: &dyn WorkspaceCommandExecutor, - cwd: &Path, + commands: &DiffCommands<'_>, fsmonitor: FsmonitorOverride, ) -> Result, String> { let args = [ @@ -174,7 +201,7 @@ async fn diff_filter_config_overrides( "--get-regexp", EXECUTABLE_FILTER_CONFIG_PATTERN, ]; - let output = run_git_command(runner, cwd, fsmonitor, &[], &args).await?; + let output = run_git_command(commands, fsmonitor, &[], &args).await?; if output.exit_code != 0 && output.exit_code != 1 { return Err(format!( "git {:?} failed with status {}", @@ -207,26 +234,34 @@ async fn diff_filter_config_overrides( } /// Determine if the current directory is inside a Git repository. -async fn inside_git_repo( - runner: &dyn WorkspaceCommandExecutor, - cwd: &Path, -) -> Result { +async fn inside_git_repo(commands: &DiffCommands<'_>) -> Result { // `rev-parse` does not inspect the worktree, and probing before this check // would also run extra Git commands outside repositories. let output = run_git_command( - runner, - cwd, + commands, FsmonitorOverride::Disabled, &[], &["rev-parse", "--is-inside-work-tree"], ) .await?; + // Exit 128 also covers inaccessible worktree metadata. Recognize the + // ordinary discovery miss and preserve other (including localized) diagnostics. + let stderr = output.stderr.trim_end(); + if commands.permission_profile.is_some() + && !output.success() + && !(output.exit_code == 128 + && stderr == "fatal: not a git repository (or any of the parent directories): .git") + { + return Err(format!( + "git rev-parse failed under the session permission profile (exit {}).\n{stderr}", + output.exit_code, + )); + } Ok(output.success()) } async fn run_git_command( - runner: &dyn WorkspaceCommandExecutor, - cwd: &Path, + commands: &DiffCommands<'_>, fsmonitor: FsmonitorOverride, config_overrides: &[(String, String)], args: &[&str], @@ -242,7 +277,8 @@ async fn run_git_command( ] .into_iter() .chain(args.iter().copied()); - let mut command = WorkspaceCommand::new(argv, cwd.to_path_buf()) + let mut command = commands + .command(argv) .timeout(DIFF_COMMAND_TIMEOUT) .disable_output_cap(); if !config_overrides.is_empty() { @@ -253,7 +289,11 @@ async fn run_git_command( .env(format!("GIT_CONFIG_VALUE_{index}"), value); } } - runner.run(command).await.map_err(|err| err.to_string()) + commands + .runner + .run(command) + .await + .map_err(|err| err.to_string()) } #[cfg(test)] @@ -272,24 +312,115 @@ mod tests { use std::process::Command as ProcessCommand; use std::sync::Mutex; + #[tokio::test] + async fn diff_profile_after_live_reattachment() -> color_eyre::Result<()> { + use crate::app_server_session::ResumeModelSettings; + use crate::legacy_core::config::ConfigBuilder; + use crate::local_settings::LocalSettings; + use crate::workspace_command::AppServerWorkspaceCommandRunner; + + let home = tempfile::tempdir()?; + let repo = tempfile::tempdir()?; + let cwd = dunce::canonicalize(repo.path())?; + assert!( + std::process::Command::new("git") + .args(["init", "-q"]) + .current_dir(&cwd) + .status()? + .success() + ); + std::fs::write( + home.path().join("config.toml"), + "default_permissions = ':danger-full-access'\n[permissions.disk]\nextends = ':read-only'\n", + )?; + let config = || { + ConfigBuilder::default() + .codex_home(home.path().into()) + .fallback_cwd(Some(cwd.clone())) + }; + let disk_config = config().build().await?; + let mut server = crate::start_embedded_app_server_for_picker(&disk_config).await?; + let first = config() + .cli_overrides(vec![ + ( + "permissions.session-only.extends".into(), + ":read-only".into(), + ), + ("default_permissions".into(), "session-only".into()), + ]) + .build() + .await?; + let thread_id = server.start_thread(&first).await?.session.thread_id; + // Materialize history so the thread can be resumed without unloading it. + server.thread_inject_items(thread_id, vec![serde_json::from_value(serde_json::json!({ + "type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "saved history"}] + }))?]).await?; + + // Rejoin the running thread with a fresh client's settings, without the CLI definition. + let mut second = server.request_view(); + let resumed = second + .resume_thread( + &LocalSettings::from(&disk_config), + disk_config, + thread_id, + ResumeModelSettings::PreserveExistingThread, + ) + .await?; + let profile = resumed.session.active_permission_profile.unwrap(); + assert_eq!(profile.id, "session-only"); + let runner = AppServerWorkspaceCommandRunner::new(second.request_handle()); + let cwd = resumed.session.cwd.to_path_buf(); + assert!(runner.has_permission_profile(&cwd, "disk").await?); + assert_eq!( + get_git_diff(&runner, &cwd, Some(&profile.id)).await, + Ok((true, String::new())) + ); + server.shutdown().await?; + Ok(()) + } + #[tokio::test] async fn get_git_diff_returns_not_git_for_non_git_cwd() { let cwd = PathBuf::from("/workspace"); - let runner = FakeRunner::new(vec![response( + let mut probe = response( git_command( FsmonitorOverride::Disabled, &["rev-parse", "--is-inside-work-tree"], ), /*exit_code*/ 128, "", - )]); - - let result = get_git_diff(&runner, &cwd).await; + ); + probe.output.stderr = + "fatal: not a git repository (or any of the parent directories): .git\n".into(); + let runner = FakeRunner::new(vec![probe]); + let result = get_git_diff(&runner, &cwd, Some(":workspace")).await; assert_eq!(result, Ok((false, String::new()))); assert_command_metadata(&runner.commands(), &cwd); } + #[tokio::test] + async fn get_git_diff_preserves_profiled_worktree_discovery_errors() { + let mut probe = response( + git_command( + FsmonitorOverride::Disabled, + &["rev-parse", "--is-inside-work-tree"], + ), + /*exit_code*/ 128, + "", + ); + probe.output.stderr = + "fatal: gitfile does not point to a valid repository: /linked/.git\n".into(); + let runner = FakeRunner::new(vec![probe]); + let error = get_git_diff(&runner, Path::new("/linked"), Some(":workspace")) + .await + .unwrap_err(); + insta::assert_snapshot!(error, @r" + git rev-parse failed under the session permission profile (exit 128). + fatal: gitfile does not point to a valid repository: /linked/.git + "); + } + #[tokio::test] async fn get_git_diff_disables_helpers_for_tracked_and_untracked_diffs() { let cwd = PathBuf::from("/workspace"); @@ -378,11 +509,16 @@ mod tests { ), ]); - let result = get_git_diff(&runner, &cwd).await; + let result = get_git_diff(&runner, &cwd, Some(":workspace")).await; assert_eq!(result, Ok((true, "tracked\nuntracked\n".to_string()))); let commands = runner.commands(); assert_command_metadata(&commands, &cwd); + assert!( + commands + .iter() + .all(|command| command.permission_profile.as_deref() == Some(":workspace")) + ); assert_eq!(commands[4].env, filter_override_env("filter.evil")); assert_eq!(commands[6].env, filter_override_env("filter.evil")); } @@ -467,7 +603,7 @@ mod tests { ), ]); - let result = get_git_diff(&runner, &cwd).await; + let result = get_git_diff(&runner, &cwd, /*permission_profile*/ None).await; assert_eq!(result, Ok((true, "tracked\nuntracked\n".to_string()))); assert_command_metadata(&runner.commands(), &cwd); @@ -529,7 +665,7 @@ mod tests { ), ]); - let result = get_git_diff(&runner, &cwd).await; + let result = get_git_diff(&runner, &cwd, /*permission_profile*/ None).await; assert_eq!(result, Ok((true, "tracked\n".to_string()))); assert_command_metadata(&runner.commands(), &cwd); @@ -591,7 +727,7 @@ mod tests { ), ]); - let error = get_git_diff(&runner, &cwd) + let error = get_git_diff(&runner, &cwd, /*permission_profile*/ None) .await .expect_err("unexpected git diff status should fail"); @@ -602,6 +738,32 @@ mod tests { assert_command_metadata(&runner.commands(), &cwd); } + #[cfg(unix)] + #[tokio::test] + async fn get_git_diff_with_thread_permissions_does_not_fetch_missing_blobs() { + let tempdir = tempfile::tempdir().unwrap(); + let repo = tempdir.path(); + run_git_setup(repo, &["init", "-q"]); + run_git_setup(repo, &["config", "remote.origin.promisor", "true"]); + run_git_setup(repo, &["config", "remote.origin.url", "ext::touch fetched"]); + run_git_setup(repo, &["config", "protocol.ext.allow", "always"]); + run_git_setup( + repo, + &[ + "update-index", + "--add", + "--cacheinfo", + "100644,1111111111111111111111111111111111111111,missing", + ], + ); + fs::write(repo.join("missing"), "changed").unwrap(); + + get_git_diff(&LocalRunner, repo, Some(":workspace")) + .await + .expect_err("missing blob"); + assert!(!repo.join("fetched").exists()); + } + #[cfg(unix)] #[tokio::test] async fn get_git_diff_does_not_execute_configured_filters_fsmonitor_or_hooks() { @@ -665,7 +827,7 @@ mod tests { fs::write(repo.join("unchanged.txt"), "unchanged\n").expect("refresh unchanged file"); fs::write(repo.join("tracked.txt"), "after\n").expect("modify tracked file"); - let result = get_git_diff(&LocalRunner, &repo) + let result = get_git_diff(&LocalRunner, &repo, /*permission_profile*/ None) .await .expect("generate diff without invoking helpers"); @@ -732,7 +894,7 @@ mod tests { std::thread::sleep(Duration::from_secs(/*secs*/ 1)); fs::write(checkout.join("tracked.txt"), "before\n").expect("refresh child tracked file"); - let result = get_git_diff(&LocalRunner, &repo) + let result = get_git_diff(&LocalRunner, &repo, /*permission_profile*/ None) .await .expect("generate diff without inspecting submodule worktrees"); @@ -768,6 +930,8 @@ mod tests { fn filter_override_env(driver: &str) -> HashMap> { HashMap::from([ + ("GIT_NO_LAZY_FETCH".to_string(), Some("1".to_string())), + ("GIT_ALLOW_PROTOCOL".to_string(), Some(String::new())), ("GIT_CONFIG_COUNT".to_string(), Some("3".to_string())), ( "GIT_CONFIG_KEY_0".to_string(), @@ -834,7 +998,7 @@ mod tests { command.argv.get(3).map(String::as_str), Some("config" | "version") ) { - assert_eq!(command.env, HashMap::new()); + assert!(!command.env.contains_key("GIT_CONFIG_COUNT")); assert_eq!(command.timeout, Duration::from_secs(/*secs*/ 5)); assert_eq!(command.disable_output_cap, false); } else { diff --git a/codex-rs/tui/src/session_state.rs b/codex-rs/tui/src/session_state.rs index 1d0edf8de3..7969db1ab6 100644 --- a/codex-rs/tui/src/session_state.rs +++ b/codex-rs/tui/src/session_state.rs @@ -68,6 +68,7 @@ pub(crate) struct ThreadSessionState { pub(crate) struct EnvironmentCwd { pub(crate) path: LegacyAppPathString, pub(crate) is_server_local: bool, + pub(crate) cwd_is_only_root: bool, } pub(crate) fn primary_environment_cwd( @@ -75,6 +76,7 @@ pub(crate) fn primary_environment_cwd( ) -> Option { environments.first().map(|primary| EnvironmentCwd { path: primary.cwd.clone(), + cwd_is_only_root: primary.runtime_workspace_roots == std::slice::from_ref(&primary.cwd), is_server_local: primary.environment_id == codex_exec_server::LOCAL_ENVIRONMENT_ID, }) } diff --git a/codex-rs/tui/src/workspace_command.rs b/codex-rs/tui/src/workspace_command.rs index 5d0014a388..42caef58eb 100644 --- a/codex-rs/tui/src/workspace_command.rs +++ b/codex-rs/tui/src/workspace_command.rs @@ -12,6 +12,7 @@ use std::collections::HashMap; use std::future::Future; +use std::path::Path; use std::path::PathBuf; use std::pin::Pin; use std::sync::Arc; @@ -21,7 +22,10 @@ use codex_app_server_client::AppServerRequestHandle; use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::CommandExecParams; use codex_app_server_protocol::CommandExecResponse; +use codex_app_server_protocol::PermissionProfileListParams; +use codex_app_server_protocol::PermissionProfileListResponse; use codex_app_server_protocol::RequestId; +use futures::future::BoxFuture; use uuid::Uuid; /// Shared handle for running workspace commands from TUI components. @@ -39,6 +43,8 @@ pub(crate) struct WorkspaceCommand { pub(crate) argv: Vec, /// Explicit working directory on the host that executes the command. pub(crate) cwd: PathBuf, + /// Named permissions to resolve in the command cwd. Omission uses server defaults. + pub(crate) permission_profile: Option, /// Environment overrides where `None` removes a variable. pub(crate) env: HashMap>, /// Maximum wall-clock duration before app-server cancels the command. @@ -56,6 +62,7 @@ impl WorkspaceCommand { Self { argv: argv.into_iter().map(Into::into).collect(), cwd: cwd.into(), + permission_profile: None, env: HashMap::new(), timeout: Duration::from_secs(/*secs*/ 5), disable_output_cap: false, @@ -129,6 +136,15 @@ impl std::error::Error for WorkspaceCommandError {} /// Implementations decide where the workspace lives. Callers provide argv/cwd/env and should not /// branch on local versus remote execution. pub(crate) trait WorkspaceCommandExecutor: Send + Sync { + /// Checks whether a custom profile is defined outside the thread. + fn has_permission_profile<'a>( + &'a self, + _cwd: &'a Path, + _id: &'a str, + ) -> BoxFuture<'a, Result> { + Box::pin(async { Ok(false) }) + } + /// Runs a workspace command and returns captured output or an app-server request error. /// /// Callers should treat errors as infrastructure failures and should treat successful output @@ -156,12 +172,33 @@ impl AppServerWorkspaceCommandRunner { } impl WorkspaceCommandExecutor for AppServerWorkspaceCommandRunner { + fn has_permission_profile<'a>( + &'a self, + cwd: &'a Path, + id: &'a str, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let catalog: PermissionProfileListResponse = self + .request_handle + .request_typed(ClientRequest::PermissionProfileList { + request_id: RequestId::String(format!("workspace-profiles-{}", Uuid::new_v4())), + params: PermissionProfileListParams { + cwd: Some(cwd.to_string_lossy().into_owned()), + cursor: None, + limit: None, // Full catalog. + }, + }) + .await + .map_err(|err| WorkspaceCommandError::new(err.to_string()))?; + // Let command/exec enforce requirements for defined profiles. + Ok(catalog.data.iter().any(|profile| profile.id == id)) + }) + } + /// Sends the command as a one-off app-server `command/exec` request. /// /// The request is non-tty, does not stream stdin/stdout/stderr, and uses the caller's timeout. - /// Bounded commands use app-server's default output cap. It leaves sandbox and permission - /// profile selection to app-server so the same runner follows the active session's embedded or - /// remote execution policy. + /// App-server resolves any named permission profile in the command cwd. fn run( &self, command: WorkspaceCommand, @@ -193,7 +230,7 @@ impl WorkspaceCommandExecutor for AppServerWorkspaceCommandRunner { env, size: None, sandbox_policy: None, - permission_profile: None, + permission_profile: command.permission_profile, }, }) .await