Fix hook env file lifecycle

This commit is contained in:
Abhinav Vedmala
2026-05-26 13:15:24 -07:00
parent 28dff23b2f
commit 9ecd72ff13
3 changed files with 121 additions and 40 deletions
+114 -40
View File
@@ -31,6 +31,23 @@ impl HookEnvFile {
&self.path
}
/// Clears any env updates from an earlier SessionStart boundary.
///
/// Each SessionStart event gets a fresh file. Hooks that append updates rebuild the overlay
/// for the current boundary, while removed hooks leave no stale file behind.
pub(crate) fn reset(&self) {
match fs::remove_file(self.path.as_path()) {
Ok(()) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => {
warn!(
path = %self.path.display(),
"failed to reset hook env file: {err}"
);
}
}
}
/// Applies persisted hook env updates to later local tool environments.
///
/// The returned names are the variables touched by the file. Shell-like tools use that list
@@ -97,15 +114,15 @@ fn parse_env_value(value: &str, env: &HashMap<String, String>) -> String {
.strip_prefix('"')
.and_then(|value| value.strip_suffix('"'))
{
return expand_env_vars(&unescape_double_quoted(value), env);
return expand_double_quoted_env_value(value, env);
}
expand_env_vars(value.trim_end(), env)
}
/// Handles the small set of backslash escapes expected inside double-quoted env values.
fn unescape_double_quoted(value: &str) -> String {
/// Parses double-quoted values, expanding unescaped env vars while preserving escaped dollars.
fn expand_double_quoted_env_value(value: &str, env: &HashMap<String, String>) -> String {
let mut out = String::with_capacity(value.len());
let mut chars = value.chars();
let mut chars = value.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '\\'
&& let Some(next) = chars.next()
@@ -119,6 +136,10 @@ fn unescape_double_quoted(value: &str) -> String {
}
continue;
}
if ch == '$' {
push_expanded_env_var_or_literal(&mut chars, env, &mut out);
continue;
}
out.push(ch);
}
out
@@ -134,46 +155,55 @@ fn expand_env_vars(value: &str, env: &HashMap<String, String>) -> String {
continue;
}
if chars.peek() == Some(&'{') {
chars.next();
let mut name = String::new();
while let Some(&next) = chars.peek() {
chars.next();
if next == '}' {
break;
}
name.push(next);
}
if is_env_name(&name) {
out.push_str(env.get(&name).map_or("", String::as_str));
} else {
out.push_str("${");
out.push_str(&name);
out.push('}');
}
continue;
}
let mut name = String::new();
while let Some(&next) = chars.peek() {
if !is_env_name_char(next) {
break;
}
chars.next();
name.push(next);
}
if name.is_empty() {
out.push('$');
} else if is_env_name(&name) {
out.push_str(env.get(&name).map_or("", String::as_str));
} else {
out.push('$');
out.push_str(&name);
}
push_expanded_env_var_or_literal(&mut chars, env, &mut out);
}
out
}
/// Appends the expansion for a `$` already consumed from `chars`.
fn push_expanded_env_var_or_literal(
chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
env: &HashMap<String, String>,
out: &mut String,
) {
if chars.peek() == Some(&'{') {
chars.next();
let mut name = String::new();
while let Some(&next) = chars.peek() {
chars.next();
if next == '}' {
break;
}
name.push(next);
}
if is_env_name(&name) {
out.push_str(env.get(&name).map_or("", String::as_str));
} else {
out.push_str("${");
out.push_str(&name);
out.push('}');
}
return;
}
let mut name = String::new();
while let Some(&next) = chars.peek() {
if !is_env_name_char(next) {
break;
}
chars.next();
name.push(next);
}
if name.is_empty() {
out.push('$');
} else if is_env_name(&name) {
out.push_str(env.get(&name).map_or("", String::as_str));
} else {
out.push('$');
out.push_str(&name);
}
}
/// Returns whether a string is a valid shell environment variable name.
fn is_env_name(name: &str) -> bool {
let mut chars = name.chars();
@@ -256,4 +286,48 @@ export FROM_BRACES=${FROM_DECLARE}/braces
vec!["FROM_DECLARE".to_string(), "FROM_BRACES".to_string()]
);
}
#[test]
fn env_file_preserves_escaped_dollars_in_double_quotes() {
let mut env = HashMap::from([
("HOME".to_string(), "/home/codex".to_string()),
("PATH".to_string(), "/usr/bin".to_string()),
]);
apply_env_file_lines(
&mut env,
r#"
export TEMPLATE="\$HOME/bin"
export MIXED="\$HOME:$PATH"
"#,
);
assert_eq!(
env,
HashMap::from([
("HOME".to_string(), "/home/codex".to_string()),
("MIXED".to_string(), "$HOME:/usr/bin".to_string()),
("PATH".to_string(), "/usr/bin".to_string()),
("TEMPLATE".to_string(), "$HOME/bin".to_string()),
])
);
}
#[test]
fn reset_removes_existing_env_file_and_ignores_missing_file() {
let dir = tempfile::tempdir().expect("create temp dir");
let path =
AbsolutePathBuf::try_from(dir.path().join("env.sh")).expect("absolute env file path");
let env_file = HookEnvFile { path };
fs::write(
env_file.path().as_path(),
"export PATH=\"/old/bin:$PATH\"\n",
)
.expect("write env file");
env_file.reset();
assert!(!env_file.path().as_path().exists());
env_file.reset();
}
}
+3
View File
@@ -124,6 +124,9 @@ pub(crate) async fn run_pending_session_start_hooks(
source: session_start_source,
},
};
if matches!(target, StartHookTarget::SessionStart { .. }) {
sess.reset_hook_env_file();
}
let request = codex_hooks::SessionStartRequest {
session_id: sess.session_id().into(),
#[allow(deprecated)]
+4
View File
@@ -3248,6 +3248,10 @@ impl Session {
self.services.hook_env_file.apply_to_env(env)
}
pub(crate) fn reset_hook_env_file(&self) {
self.services.hook_env_file.reset();
}
pub(crate) fn user_shell(&self) -> Arc<shell::Shell> {
Arc::clone(&self.services.user_shell)
}