From 7038827bf436e0cb2ebb9e7d4489ea66db0d6774 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Thu, 14 Aug 2025 17:08:29 -0400 Subject: [PATCH 01/16] fix bash commands being incorrectly quoted in display (#2313) The "display format" of commands was sometimes producing incorrect quoting like `echo foo '>' bar`, which is importantly different from the actual command that was being run. This refactors ParsedCommand to have a string in `cmd` instead of a vec, as a `vec` can't accurately capture a full command. --- codex-rs/core/src/parse_command.rs | 555 ++++++++++++++------------- codex-rs/tui/src/chatwidget/tests.rs | 4 +- codex-rs/tui/src/history_cell.rs | 20 +- 3 files changed, 289 insertions(+), 290 deletions(-) diff --git a/codex-rs/core/src/parse_command.rs b/codex-rs/core/src/parse_command.rs index 01dc6e3227..6436ce4039 100644 --- a/codex-rs/core/src/parse_command.rs +++ b/codex-rs/core/src/parse_command.rs @@ -3,38 +3,47 @@ use crate::bash::try_parse_word_only_commands_sequence; use serde::Deserialize; use serde::Serialize; use shlex::split as shlex_split; +use shlex::try_join as shlex_try_join; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub enum ParsedCommand { Read { - cmd: Vec, + cmd: String, name: String, }, ListFiles { - cmd: Vec, + cmd: String, path: Option, }, Search { - cmd: Vec, + cmd: String, query: Option, path: Option, }, Format { - cmd: Vec, + cmd: String, tool: Option, targets: Option>, }, Test { - cmd: Vec, + cmd: String, }, Lint { - cmd: Vec, + cmd: String, tool: Option, targets: Option>, }, - Unknown { - cmd: Vec, + Noop { + cmd: String, }, + Unknown { + cmd: String, + }, +} + +fn shlex_join(tokens: &[String]) -> String { + shlex_try_join(tokens.iter().map(|s| s.as_str())) + .unwrap_or_else(|_| "".to_string()) } /// DO NOT REVIEW THIS CODE BY HAND @@ -84,7 +93,29 @@ mod tests { assert_parsed( &vec_str(&["git", "status"]), vec![ParsedCommand::Unknown { - cmd: vec_str(&["git", "status"]), + cmd: "git status".to_string(), + }], + ); + } + + #[test] + fn handles_git_pipe_wc() { + let inner = "git status | wc -l"; + assert_parsed( + &vec_str(&["bash", "-lc", inner]), + vec![ParsedCommand::Unknown { + cmd: "git status | wc -l".to_string(), + }], + ); + } + + #[test] + fn bash_lc_redirect_not_quoted() { + let inner = "echo foo > bar"; + assert_parsed( + &vec_str(&["bash", "-lc", inner]), + vec![ParsedCommand::Unknown { + cmd: "echo foo > bar".to_string(), }], ); } @@ -98,23 +129,23 @@ mod tests { vec![ // Expect commands in left-to-right execution order ParsedCommand::Search { - cmd: vec_str(&["rg", "--version"]), + cmd: "rg --version".to_string(), query: None, path: None, }, ParsedCommand::Unknown { - cmd: vec_str(&["node", "-v"]), + cmd: "node -v".to_string(), }, ParsedCommand::Unknown { - cmd: vec_str(&["pnpm", "-v"]), + cmd: "pnpm -v".to_string(), }, ParsedCommand::Search { - cmd: vec_str(&["rg", "--files"]), + cmd: "rg --files".to_string(), query: None, path: None, }, ParsedCommand::Unknown { - cmd: vec_str(&["head", "-n", "40"]), + cmd: "head -n 40".to_string(), }, ], ); @@ -126,7 +157,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Search { - cmd: shlex_split_safe(inner), + cmd: "rg -n navigate-to-route -S".to_string(), query: Some("navigate-to-route".to_string()), path: None, }], @@ -141,12 +172,12 @@ mod tests { &vec_str(&["bash", "-lc", inner]), vec![ ParsedCommand::Search { - cmd: vec_str(&["rg", "-n", "BUG|FIXME|TODO|XXX|HACK", "-S"]), + cmd: "rg -n 'BUG|FIXME|TODO|XXX|HACK' -S".to_string(), query: Some("BUG|FIXME|TODO|XXX|HACK".to_string()), path: None, }, ParsedCommand::Unknown { - cmd: vec_str(&["head", "-n", "200"]), + cmd: "head -n 200".to_string(), }, ], ); @@ -158,7 +189,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Search { - cmd: vec_str(&["rg", "--files", "webview/src"]), + cmd: "rg --files webview/src".to_string(), query: None, path: Some("webview".to_string()), }], @@ -172,12 +203,12 @@ mod tests { &vec_str(&["bash", "-lc", inner]), vec![ ParsedCommand::Search { - cmd: vec_str(&["rg", "--files"]), + cmd: "rg --files".to_string(), query: None, path: None, }, ParsedCommand::Unknown { - cmd: vec_str(&["head", "-n", "50"]), + cmd: "head -n 50".to_string(), }, ], ); @@ -189,7 +220,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "README.md".to_string(), }], ); @@ -201,7 +232,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::ListFiles { - cmd: vec_str(&["ls", "-la"]), + cmd: "ls -la".to_string(), path: None, }], ); @@ -213,7 +244,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "Cargo.toml".to_string(), }], ); @@ -225,7 +256,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "Cargo.toml".to_string(), }], ); @@ -237,7 +268,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "README.md".to_string(), }], ); @@ -250,7 +281,7 @@ mod tests { assert_eq!( out, vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "README.md".to_string(), }] ); @@ -261,7 +292,7 @@ mod tests { assert_parsed( &vec_str(&["npm", "run", "build"]), vec![ParsedCommand::Unknown { - cmd: vec_str(&["npm", "run", "build"]), + cmd: "npm run build".to_string(), }], ); } @@ -280,16 +311,7 @@ mod tests { "json", ]), vec![ParsedCommand::Lint { - cmd: vec_str(&[ - "npm", - "run", - "lint", - "--", - "--max-warnings", - "0", - "--format", - "json", - ]), + cmd: "npm run lint -- --max-warnings 0 --format json".to_string(), tool: Some("npm-script:lint".to_string()), targets: None, }], @@ -301,7 +323,7 @@ mod tests { assert_parsed( &vec_str(&["grep", "-R", "CODEX_SANDBOX_ENV_VAR", "-n", "."]), vec![ParsedCommand::Search { - cmd: vec_str(&["grep", "-R", "CODEX_SANDBOX_ENV_VAR", "-n", "."]), + cmd: "grep -R CODEX_SANDBOX_ENV_VAR -n .".to_string(), query: Some("CODEX_SANDBOX_ENV_VAR".to_string()), path: Some(".".to_string()), }], @@ -319,13 +341,7 @@ mod tests { "core/src/spawn.rs", ]), vec![ParsedCommand::Search { - cmd: vec_str(&[ - "grep", - "-R", - "CODEX_SANDBOX_ENV_VAR", - "-n", - "core/src/spawn.rs", - ]), + cmd: "grep -R CODEX_SANDBOX_ENV_VAR -n core/src/spawn.rs".to_string(), query: Some("CODEX_SANDBOX_ENV_VAR".to_string()), path: Some("spawn.rs".to_string()), }], @@ -339,7 +355,7 @@ mod tests { assert_parsed( &shlex_split_safe("grep -R src/main.rs -n ."), vec![ParsedCommand::Search { - cmd: vec_str(&["grep", "-R", "src/main.rs", "-n", "."]), + cmd: "grep -R src/main.rs -n .".to_string(), query: Some("src/main.rs".to_string()), path: Some(".".to_string()), }], @@ -351,7 +367,7 @@ mod tests { assert_parsed( &shlex_split_safe("grep -R COD`EX_SANDBOX -n"), vec![ParsedCommand::Search { - cmd: vec_str(&["grep", "-R", "COD`EX_SANDBOX", "-n"]), + cmd: "grep -R 'COD`EX_SANDBOX' -n".to_string(), query: Some("COD`EX_SANDBOX".to_string()), path: None, }], @@ -364,10 +380,10 @@ mod tests { &shlex_split_safe("cd codex-rs && rg --files"), vec![ ParsedCommand::Unknown { - cmd: vec_str(&["cd", "codex-rs"]), + cmd: "cd codex-rs".to_string(), }, ParsedCommand::Search { - cmd: vec_str(&["rg", "--files"]), + cmd: "rg --files".to_string(), query: None, path: None, }, @@ -380,7 +396,7 @@ mod tests { assert_parsed( &shlex_split_safe("echo Running tests... && cargo test --all-features --quiet"), vec![ParsedCommand::Test { - cmd: vec_str(&["cargo", "test", "--all-features", "--quiet"]), + cmd: "cargo test --all-features --quiet".to_string(), }], ); } @@ -393,12 +409,12 @@ mod tests { ), vec![ ParsedCommand::Format { - cmd: shlex_split_safe("cargo fmt -- --config imports_granularity=Item"), + cmd: "cargo fmt -- --config 'imports_granularity=Item'".to_string(), tool: Some("cargo fmt".to_string()), targets: None, }, ParsedCommand::Test { - cmd: vec_str(&["cargo", "test", "-p", "core", "--all-features"]), + cmd: "cargo test -p core --all-features".to_string(), }, ], ); @@ -409,7 +425,7 @@ mod tests { assert_parsed( &shlex_split_safe("rustfmt src/main.rs"), vec![ParsedCommand::Format { - cmd: vec_str(&["rustfmt", "src/main.rs"]), + cmd: "rustfmt src/main.rs".to_string(), tool: Some("rustfmt".to_string()), targets: Some(vec!["src/main.rs".to_string()]), }], @@ -418,16 +434,7 @@ mod tests { assert_parsed( &shlex_split_safe("cargo clippy -p core --all-features -- -D warnings"), vec![ParsedCommand::Lint { - cmd: vec_str(&[ - "cargo", - "clippy", - "-p", - "core", - "--all-features", - "--", - "-D", - "warnings", - ]), + cmd: "cargo clippy -p core --all-features -- -D warnings".to_string(), tool: Some("cargo clippy".to_string()), targets: None, }], @@ -441,19 +448,15 @@ mod tests { "pytest -k 'Login and not slow' tests/test_login.py::TestLogin::test_ok", ), vec![ParsedCommand::Test { - cmd: vec_str(&[ - "pytest", - "-k", - "Login and not slow", - "tests/test_login.py::TestLogin::test_ok", - ]), + cmd: "pytest -k 'Login and not slow' tests/test_login.py::TestLogin::test_ok" + .to_string(), }], ); assert_parsed( &shlex_split_safe("go fmt ./..."), vec![ParsedCommand::Format { - cmd: vec_str(&["go", "fmt", "./..."]), + cmd: "go fmt ./...".to_string(), tool: Some("go fmt".to_string()), targets: Some(vec!["./...".to_string()]), }], @@ -462,14 +465,14 @@ mod tests { assert_parsed( &shlex_split_safe("go test ./pkg -run TestThing"), vec![ParsedCommand::Test { - cmd: vec_str(&["go", "test", "./pkg", "-run", "TestThing"]), + cmd: "go test ./pkg -run TestThing".to_string(), }], ); assert_parsed( &shlex_split_safe("eslint . --max-warnings 0"), vec![ParsedCommand::Lint { - cmd: vec_str(&["eslint", ".", "--max-warnings", "0"]), + cmd: "eslint . --max-warnings 0".to_string(), tool: Some("eslint".to_string()), targets: Some(vec![".".to_string()]), }], @@ -478,7 +481,7 @@ mod tests { assert_parsed( &shlex_split_safe("prettier -w ."), vec![ParsedCommand::Format { - cmd: vec_str(&["prettier", "-w", "."]), + cmd: "prettier -w .".to_string(), tool: Some("prettier".to_string()), targets: Some(vec![".".to_string()]), }], @@ -490,14 +493,14 @@ mod tests { assert_parsed( &shlex_split_safe("jest -t 'should work' src/foo.test.ts"), vec![ParsedCommand::Test { - cmd: vec_str(&["jest", "-t", "should work", "src/foo.test.ts"]), + cmd: "jest -t 'should work' src/foo.test.ts".to_string(), }], ); assert_parsed( &shlex_split_safe("vitest -t 'runs' src/foo.test.tsx"), vec![ParsedCommand::Test { - cmd: vec_str(&["vitest", "-t", "runs", "src/foo.test.tsx"]), + cmd: "vitest -t runs src/foo.test.tsx".to_string(), }], ); } @@ -507,7 +510,7 @@ mod tests { assert_parsed( &shlex_split_safe("npx eslint src"), vec![ParsedCommand::Lint { - cmd: vec_str(&["npx", "eslint", "src"]), + cmd: "npx eslint src".to_string(), tool: Some("eslint".to_string()), targets: Some(vec!["src".to_string()]), }], @@ -516,7 +519,7 @@ mod tests { assert_parsed( &shlex_split_safe("npx prettier -c ."), vec![ParsedCommand::Format { - cmd: vec_str(&["npx", "prettier", "-c", "."]), + cmd: "npx prettier -c .".to_string(), tool: Some("prettier".to_string()), targets: Some(vec![".".to_string()]), }], @@ -525,7 +528,7 @@ mod tests { assert_parsed( &shlex_split_safe("pnpm run lint -- --max-warnings 0"), vec![ParsedCommand::Lint { - cmd: vec_str(&["pnpm", "run", "lint", "--", "--max-warnings", "0"]), + cmd: "pnpm run lint -- --max-warnings 0".to_string(), tool: Some("pnpm-script:lint".to_string()), targets: None, }], @@ -534,14 +537,14 @@ mod tests { assert_parsed( &shlex_split_safe("npm test"), vec![ParsedCommand::Test { - cmd: vec_str(&["npm", "test"]), + cmd: "npm test".to_string(), }], ); assert_parsed( &shlex_split_safe("yarn test"), vec![ParsedCommand::Test { - cmd: vec_str(&["yarn", "test"]), + cmd: "yarn test".to_string(), }], ); } @@ -631,7 +634,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "parse_command.rs".to_string(), }], ); @@ -643,7 +646,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "history_cell.rs".to_string(), }], ); @@ -656,7 +659,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe("cat -- ansi-escape/Cargo.toml"), + cmd: "cat -- ansi-escape/Cargo.toml".to_string(), name: "Cargo.toml".to_string(), }], ); @@ -669,7 +672,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Search { - cmd: vec_str(&["rg", "--files"]), + cmd: "rg --files".to_string(), query: None, path: None, }], @@ -685,9 +688,7 @@ mod tests { assert_parsed( &args, vec![ParsedCommand::Read { - cmd: shlex_split_safe( - "sed -n '260,640p' exec/src/event_processor_with_human_output.rs", - ), + cmd: "sed -n '260,640p' exec/src/event_processor_with_human_output.rs".to_string(), name: "event_processor_with_human_output.rs".to_string(), }], ); @@ -698,7 +699,7 @@ mod tests { assert_parsed( &shlex_split_safe("yes | rg -n 'foo bar' -S"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg -n 'foo bar' -S"), + cmd: "rg -n 'foo bar' -S".to_string(), query: Some("foo bar".to_string()), path: None, }], @@ -710,7 +711,7 @@ mod tests { assert_parsed( &shlex_split_safe("ls -I '*.test.js'"), vec![ParsedCommand::ListFiles { - cmd: shlex_split_safe("ls -I '*.test.js'"), + cmd: "ls -I '*.test.js'".to_string(), path: None, }], ); @@ -722,12 +723,12 @@ mod tests { &shlex_split_safe("rg foo ; echo done"), vec![ ParsedCommand::Search { - cmd: shlex_split_safe("rg foo"), + cmd: "rg foo".to_string(), query: Some("foo".to_string()), path: None, }, ParsedCommand::Unknown { - cmd: shlex_split_safe("echo done"), + cmd: "echo done".to_string(), }, ], ); @@ -740,12 +741,12 @@ mod tests { &shlex_split_safe("rg foo || echo done"), vec![ ParsedCommand::Search { - cmd: shlex_split_safe("rg foo"), + cmd: "rg foo".to_string(), query: Some("foo".to_string()), path: None, }, ParsedCommand::Unknown { - cmd: shlex_split_safe("echo done"), + cmd: "echo done".to_string(), }, ], ); @@ -757,7 +758,7 @@ mod tests { assert_parsed( &shlex_split_safe("true && rg --files"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg --files"), + cmd: "rg --files".to_string(), query: None, path: None, }], @@ -766,7 +767,7 @@ mod tests { assert_parsed( &shlex_split_safe("rg --files && true"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg --files"), + cmd: "rg --files".to_string(), query: None, path: None, }], @@ -779,7 +780,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg --files"), + cmd: "rg --files".to_string(), query: None, path: None, }], @@ -789,7 +790,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner2]), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg --files"), + cmd: "rg --files".to_string(), query: None, path: None, }], @@ -801,7 +802,7 @@ mod tests { assert_parsed( &shlex_split_safe(r#"cat "pkg\src\main.rs""#), vec![ParsedCommand::Read { - cmd: shlex_split_safe(r#"cat "pkg\src\main.rs""#), + cmd: r#"cat "pkg\\src\\main.rs""#.to_string(), name: "main.rs".to_string(), }], ); @@ -812,7 +813,7 @@ mod tests { assert_parsed( &shlex_split_safe("bash -lc 'head -n50 Cargo.toml'"), vec![ParsedCommand::Read { - cmd: shlex_split_safe("head -n50 Cargo.toml"), + cmd: "head -n50 Cargo.toml".to_string(), name: "Cargo.toml".to_string(), }], ); @@ -826,12 +827,12 @@ mod tests { &shlex_split_safe(inner), vec![ ParsedCommand::Search { - cmd: shlex_split_safe("rg --files"), + cmd: "rg --files".to_string(), query: None, path: None, }, ParsedCommand::Unknown { - cmd: shlex_split_safe("head -n 1"), + cmd: "head -n 1".to_string(), }, ], ); @@ -842,7 +843,7 @@ mod tests { assert_parsed( &shlex_split_safe("bash -lc 'tail -n+10 README.md'"), vec![ParsedCommand::Read { - cmd: shlex_split_safe("tail -n+10 README.md"), + cmd: "tail -n+10 README.md".to_string(), name: "README.md".to_string(), }], ); @@ -853,7 +854,7 @@ mod tests { assert_parsed( &shlex_split_safe("pnpm test"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("pnpm test"), + cmd: "pnpm test".to_string(), }], ); } @@ -866,12 +867,10 @@ mod tests { &shlex_split_safe(inner), vec![ ParsedCommand::Unknown { - cmd: shlex_split_safe("cd codex-cli"), + cmd: "cd codex-cli".to_string(), }, ParsedCommand::Unknown { - cmd: shlex_split_safe( - "pnpm exec vitest run tests/file-tag-utils.test.ts --threads=false --passWithNoTests", - ), + cmd: "pnpm exec vitest run tests/file-tag-utils.test.ts '--threads=false' --passWithNoTests".to_string(), }, ], ); @@ -882,7 +881,7 @@ mod tests { assert_parsed( &shlex_split_safe("cargo test -p codex-core parse_command::"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("cargo test -p codex-core parse_command::"), + cmd: "cargo test -p codex-core parse_command::".to_string(), }], ); } @@ -894,9 +893,7 @@ mod tests { "cd core && cargo test -q parse_command::tests::bash_dash_c_pipeline_parsing parse_command::tests::fd_file_finder_variants", ), vec![ParsedCommand::Test { - cmd: shlex_split_safe( - "cargo test -q parse_command::tests::bash_dash_c_pipeline_parsing parse_command::tests::fd_file_finder_variants", - ), + cmd: "cargo test -q parse_command::tests::bash_dash_c_pipeline_parsing parse_command::tests::fd_file_finder_variants".to_string(), }], ); } @@ -906,7 +903,7 @@ mod tests { assert_parsed( &shlex_split_safe("cd core && cargo test -q parse_command::tests"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("cargo test -q parse_command::tests"), + cmd: "cargo test -q parse_command::tests".to_string(), }], ); } @@ -916,7 +913,7 @@ mod tests { assert_parsed( &shlex_split_safe("cd core && cargo test --all-features parse_command -- --nocapture"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("cargo test --all-features parse_command -- --nocapture"), + cmd: "cargo test --all-features parse_command -- --nocapture".to_string(), }], ); } @@ -928,7 +925,7 @@ mod tests { assert_parsed( &shlex_split_safe("black src"), vec![ParsedCommand::Format { - cmd: shlex_split_safe("black src"), + cmd: "black src".to_string(), tool: Some("black".to_string()), targets: Some(vec!["src".to_string()]), }], @@ -938,7 +935,7 @@ mod tests { assert_parsed( &shlex_split_safe("ruff check ."), vec![ParsedCommand::Lint { - cmd: shlex_split_safe("ruff check ."), + cmd: "ruff check .".to_string(), tool: Some("ruff".to_string()), targets: Some(vec![".".to_string()]), }], @@ -948,7 +945,7 @@ mod tests { assert_parsed( &shlex_split_safe("ruff format pkg/"), vec![ParsedCommand::Format { - cmd: shlex_split_safe("ruff format pkg/"), + cmd: "ruff format pkg/".to_string(), tool: Some("ruff".to_string()), targets: Some(vec!["pkg/".to_string()]), }], @@ -961,7 +958,7 @@ mod tests { assert_parsed( &shlex_split_safe("pnpm -r test"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("pnpm -r test"), + cmd: "pnpm -r test".to_string(), }], ); @@ -969,7 +966,7 @@ mod tests { assert_parsed( &shlex_split_safe("npm run format -- -w ."), vec![ParsedCommand::Format { - cmd: shlex_split_safe("npm run format -- -w ."), + cmd: "npm run format -- -w .".to_string(), tool: Some("npm-script:format".to_string()), targets: None, }], @@ -981,7 +978,7 @@ mod tests { assert_parsed( &shlex_split_safe("yarn test"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("yarn test"), + cmd: "yarn test".to_string(), }], ); } @@ -992,7 +989,7 @@ mod tests { assert_parsed( &shlex_split_safe("pytest tests/test_example.py"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("pytest tests/test_example.py"), + cmd: "pytest tests/test_example.py".to_string(), }], ); @@ -1000,7 +997,7 @@ mod tests { assert_parsed( &shlex_split_safe("go test ./... -run '^TestFoo$'"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("go test ./... -run '^TestFoo$'"), + cmd: "go test ./... -run '^TestFoo$'".to_string(), }], ); } @@ -1010,7 +1007,7 @@ mod tests { assert_parsed( &shlex_split_safe("grep -R TODO src"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("grep -R TODO src"), + cmd: "grep -R TODO src".to_string(), query: Some("TODO".to_string()), path: Some("src".to_string()), }], @@ -1022,7 +1019,7 @@ mod tests { assert_parsed( &shlex_split_safe("rg --colors=never -n foo src"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg --colors=never -n foo src"), + cmd: "rg '--colors=never' -n foo src".to_string(), query: Some("foo".to_string()), path: Some("src".to_string()), }], @@ -1035,7 +1032,7 @@ mod tests { assert_parsed( &shlex_split_safe("cat -- ./-strange-file-name"), vec![ParsedCommand::Read { - cmd: shlex_split_safe("cat -- ./-strange-file-name"), + cmd: "cat -- ./-strange-file-name".to_string(), name: "-strange-file-name".to_string(), }], ); @@ -1044,7 +1041,7 @@ mod tests { assert_parsed( &shlex_split_safe("sed -n '12,20p' Cargo.toml"), vec![ParsedCommand::Read { - cmd: shlex_split_safe("sed -n '12,20p' Cargo.toml"), + cmd: "sed -n '12,20p' Cargo.toml".to_string(), name: "Cargo.toml".to_string(), }], ); @@ -1056,7 +1053,7 @@ mod tests { assert_parsed( &shlex_split_safe("rg --files | nl -ba"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg --files"), + cmd: "rg --files".to_string(), query: None, path: None, }], @@ -1068,7 +1065,7 @@ mod tests { assert_parsed( &shlex_split_safe("ls --time-style=long-iso ./dist"), vec![ParsedCommand::ListFiles { - cmd: shlex_split_safe("ls --time-style=long-iso ./dist"), + cmd: "ls '--time-style=long-iso' ./dist".to_string(), // short_display_path drops "dist" and shows "." as the last useful segment path: Some(".".to_string()), }], @@ -1080,7 +1077,7 @@ mod tests { assert_parsed( &shlex_split_safe("eslint -c .eslintrc.json src"), vec![ParsedCommand::Lint { - cmd: shlex_split_safe("eslint -c .eslintrc.json src"), + cmd: "eslint -c .eslintrc.json src".to_string(), tool: Some("eslint".to_string()), targets: Some(vec!["src".to_string()]), }], @@ -1092,7 +1089,7 @@ mod tests { assert_parsed( &shlex_split_safe("npx eslint -c .eslintrc src"), vec![ParsedCommand::Lint { - cmd: shlex_split_safe("npx eslint -c .eslintrc src"), + cmd: "npx eslint -c .eslintrc src".to_string(), tool: Some("eslint".to_string()), targets: Some(vec!["src".to_string()]), }], @@ -1104,7 +1101,7 @@ mod tests { assert_parsed( &shlex_split_safe("fd -t f src/"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("fd -t f src/"), + cmd: "fd -t f src/".to_string(), query: None, path: Some("src".to_string()), }], @@ -1114,7 +1111,7 @@ mod tests { assert_parsed( &shlex_split_safe("fd main src"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("fd main src"), + cmd: "fd main src".to_string(), query: Some("main".to_string()), path: Some("src".to_string()), }], @@ -1126,7 +1123,7 @@ mod tests { assert_parsed( &shlex_split_safe("find . -name '*.rs'"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("find . -name '*.rs'"), + cmd: "find . -name '*.rs'".to_string(), query: Some("*.rs".to_string()), path: Some(".".to_string()), }], @@ -1138,7 +1135,7 @@ mod tests { assert_parsed( &shlex_split_safe("find src -type f"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("find src -type f"), + cmd: "find src -type f".to_string(), query: None, path: Some("src".to_string()), }], @@ -1147,12 +1144,12 @@ mod tests { } pub fn parse_command_impl(command: &[String]) -> Vec { - let normalized = normalize_tokens(command); - - if let Some(commands) = parse_bash_lc_commands(command, &normalized) { + if let Some(commands) = parse_bash_lc_commands(command) { return commands; } + let normalized = normalize_tokens(command); + let parts = if contains_connectors(&normalized) { split_on_connectors(&normalized) } else { @@ -1163,55 +1160,79 @@ pub fn parse_command_impl(command: &[String]) -> Vec { // so summaries reflect the order they will run. // Map each pipeline segment to its parsed summary. - let mut parsed: Vec = parts + let mut commands: Vec = parts .iter() .map(|tokens| summarize_main_tokens(tokens)) .collect(); - // If a pipeline ends with `nl` using only flags (e.g., `| nl -ba`), drop it so the - // main action (e.g., a sed range over a file) is surfaced cleanly. - if parsed.len() >= 2 { - let has_and_and = normalized.iter().any(|t| t == "&&"); - let contains_test = parsed - .iter() - .any(|pc| matches!(pc, ParsedCommand::Test { .. })); - parsed.retain(|pc| match pc { - ParsedCommand::Unknown { cmd } => { - if let Some(first) = cmd.first() { - // Drop cosmetic echo segments in chained commands - if has_and_and && first == "echo" { - return false; - } - // In non-bash chained commands, ignore directory changes like `cd foo` - // when the sequence includes a recognized test command. Preserve `cd` - // for other sequences (e.g., followed by a search command). - if has_and_and && contains_test && first == "cd" { - return false; - } - // Drop no-op commands like `true` - if cmd.len() == 1 && first == "true" { - return false; - } - if first == "nl" { - // Treat `nl` without an explicit file operand as formatting-only. - return cmd.iter().skip(1).any(|a| !a.starts_with('-')); - } - } - true - } - _ => true, - }); + while let Some(next) = simplify_once(&commands) { + commands = next; } - // Also drop standalone `true` commands when not part of a chained `&&` context above - parsed.retain(|pc| match pc { - ParsedCommand::Unknown { cmd } => { - !(cmd.len() == 1 && cmd.first().is_some_and(|s| s == "true")) - } - _ => true, - }); + commands +} - parsed +fn simplify_once(commands: &[ParsedCommand]) -> Option> { + if commands.len() <= 1 { + return None; + } + + // echo ... && ...rest => ...rest + if let ParsedCommand::Unknown { cmd } = &commands[0] { + if shlex_split(cmd).is_some_and(|t| t.first().map(|s| s.as_str()) == Some("echo")) { + return Some(commands[1..].to_vec()); + } + } + + // cd foo && [any Test command] => [any Test command] + if let Some(idx) = commands.iter().position(|pc| match pc { + ParsedCommand::Unknown { cmd } => { + shlex_split(cmd).is_some_and(|t| t.first().map(|s| s.as_str()) == Some("cd")) + } + _ => false, + }) { + if commands + .iter() + .skip(idx + 1) + .any(|pc| matches!(pc, ParsedCommand::Test { .. })) + { + let mut out = Vec::with_capacity(commands.len() - 1); + out.extend_from_slice(&commands[..idx]); + out.extend_from_slice(&commands[idx + 1..]); + return Some(out); + } + } + + // cmd || true => cmd + if let Some(idx) = commands.iter().position(|pc| match pc { + ParsedCommand::Noop { cmd } => cmd == "true", + _ => false, + }) { + let mut out = Vec::with_capacity(commands.len() - 1); + out.extend_from_slice(&commands[..idx]); + out.extend_from_slice(&commands[idx + 1..]); + return Some(out); + } + + // nl -[any_flags] && ...rest => ...rest + if let Some(idx) = commands.iter().position(|pc| match pc { + ParsedCommand::Unknown { cmd } => { + if let Some(tokens) = shlex_split(cmd) { + tokens.first().is_some_and(|s| s.as_str() == "nl") + && tokens.iter().skip(1).all(|t| t.starts_with('-')) + } else { + false + } + } + _ => false, + }) { + let mut out = Vec::with_capacity(commands.len() - 1); + out.extend_from_slice(&commands[..idx]); + out.extend_from_slice(&commands[idx + 1..]); + return Some(out); + } + + None } /// Validates that this is a `sed -n 123,123p` command. @@ -1497,19 +1518,19 @@ fn classify_npm_like(tool: &str, tail: &[String], full_cmd: &[String]) -> Option let lname = name.to_lowercase(); if lname == "test" || lname == "unit" || lname == "jest" || lname == "vitest" { return Some(ParsedCommand::Test { - cmd: full_cmd.to_vec(), + cmd: shlex_join(full_cmd), }); } if lname == "lint" || lname == "eslint" { return Some(ParsedCommand::Lint { - cmd: full_cmd.to_vec(), + cmd: shlex_join(full_cmd), tool: Some(format!("{tool}-script:{name}")), targets: None, }); } if lname == "format" || lname == "fmt" || lname == "prettier" { return Some(ParsedCommand::Format { - cmd: full_cmd.to_vec(), + cmd: shlex_join(full_cmd), tool: Some(format!("{tool}-script:{name}")), targets: None, }); @@ -1518,10 +1539,7 @@ fn classify_npm_like(tool: &str, tail: &[String], full_cmd: &[String]) -> Option None } -fn parse_bash_lc_commands( - original: &[String], - normalized: &[String], -) -> Option> { +fn parse_bash_lc_commands(original: &[String]) -> Option> { let [bash, flag, script] = original else { return None; }; @@ -1543,21 +1561,16 @@ fn parse_bash_lc_commands( filtered_commands.reverse(); if filtered_commands.is_empty() { return Some(vec![ParsedCommand::Unknown { - cmd: normalized.to_vec(), + cmd: script.clone(), }]); } let mut commands: Vec = filtered_commands .into_iter() .map(|tokens| summarize_main_tokens(&tokens)) .collect(); - // Drop no-op `true` commands - commands.retain(|pc| match pc { - ParsedCommand::Unknown { cmd } => { - !(cmd.len() == 1 && cmd.first().is_some_and(|s| s == "true")) - } - _ => true, - }); - commands = maybe_collapse_cat_sed(commands, &script_tokens); + if commands.len() > 1 { + commands.retain(|pc| !matches!(pc, ParsedCommand::Noop { .. })); + } if commands.len() == 1 { // If we reduced to a single command, attribute the full original script // for clearer UX in file-reading and listing scenarios, or when there were @@ -1570,7 +1583,7 @@ fn parse_bash_lc_commands( commands = commands .into_iter() .map(|pc| match pc { - ParsedCommand::Read { name, cmd } => { + ParsedCommand::Read { name, cmd, .. } => { if had_connectors { let has_pipe = script_tokens.iter().any(|t| t == "|"); let has_sed_n = script_tokens.windows(2).any(|w| { @@ -1579,55 +1592,74 @@ fn parse_bash_lc_commands( }); if has_pipe && has_sed_n { ParsedCommand::Read { - cmd: script_tokens.clone(), + cmd: script.clone(), name, } } else { - ParsedCommand::Read { cmd, name } + ParsedCommand::Read { + cmd: cmd.clone(), + name, + } } } else { ParsedCommand::Read { - cmd: script_tokens.clone(), + cmd: shlex_join(&script_tokens), name, } } } - ParsedCommand::ListFiles { path, cmd } => { + ParsedCommand::ListFiles { path, cmd, .. } => { if had_connectors { - ParsedCommand::ListFiles { cmd, path } + ParsedCommand::ListFiles { + cmd: cmd.clone(), + path, + } } else { ParsedCommand::ListFiles { - cmd: script_tokens.clone(), + cmd: shlex_join(&script_tokens), path, } } } - ParsedCommand::Search { cmd, query, path } => { + ParsedCommand::Search { + query, path, cmd, .. + } => { if had_connectors { - ParsedCommand::Search { cmd, query, path } + ParsedCommand::Search { + cmd: cmd.clone(), + query, + path, + } } else { ParsedCommand::Search { - cmd: script_tokens.clone(), + cmd: shlex_join(&script_tokens), query, path, } } } - ParsedCommand::Format { tool, targets, .. } => ParsedCommand::Format { - cmd: script_tokens.clone(), + ParsedCommand::Format { + tool, targets, cmd, .. + } => ParsedCommand::Format { + cmd: cmd.clone(), tool, targets, }, - ParsedCommand::Test { .. } => ParsedCommand::Test { - cmd: script_tokens.clone(), - }, - ParsedCommand::Lint { tool, targets, .. } => ParsedCommand::Lint { - cmd: script_tokens.clone(), + ParsedCommand::Test { cmd, .. } => { + ParsedCommand::Test { cmd: cmd.clone() } + } + ParsedCommand::Lint { + tool, targets, cmd, .. + } => ParsedCommand::Lint { + cmd: cmd.clone(), tool, targets, }, ParsedCommand::Unknown { .. } => ParsedCommand::Unknown { - cmd: script_tokens.clone(), + cmd: script.clone(), + }, + ParsedCommand::Noop { .. } => ParsedCommand::Noop { + cmd: script.clone(), }, }) .collect(); @@ -1637,7 +1669,7 @@ fn parse_bash_lc_commands( } } Some(vec![ParsedCommand::Unknown { - cmd: normalized.to_vec(), + cmd: script.clone(), }]) } @@ -1681,44 +1713,17 @@ fn drop_small_formatting_commands(mut commands: Vec>) -> Vec, - script_tokens: &[String], -) -> Vec { - if commands.len() < 2 { - return commands; - } - let drop_leading_sed = match (&commands[0], &commands[1]) { - (ParsedCommand::Unknown { cmd: sed_cmd }, ParsedCommand::Read { cmd: cat_cmd, .. }) => { - let is_sed_n = sed_cmd.first().map(|s| s.as_str()) == Some("sed") - && sed_cmd.get(1).map(|s| s.as_str()) == Some("-n") - && is_valid_sed_n_arg(sed_cmd.get(2).map(|s| s.as_str())) - && sed_cmd.len() == 3; - let is_cat_file = - cat_cmd.first().map(|s| s.as_str()) == Some("cat") && cat_cmd.len() == 2; - is_sed_n && is_cat_file - } - _ => false, - }; - if drop_leading_sed { - if let ParsedCommand::Read { name, .. } = &commands[1] { - return vec![ParsedCommand::Read { - cmd: script_tokens.to_vec(), - name: name.clone(), - }]; - } - } - commands -} - fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { match main_cmd.split_first() { + Some((head, tail)) if head == "true" && tail.is_empty() => ParsedCommand::Noop { + cmd: shlex_join(main_cmd), + }, // (sed-specific logic handled below in dedicated arm returning Read) Some((head, tail)) if head == "cargo" && tail.first().map(|s| s.as_str()) == Some("fmt") => { ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("cargo fmt".to_string()), targets: collect_non_flag_targets(&tail[1..]), } @@ -1727,7 +1732,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if head == "cargo" && tail.first().map(|s| s.as_str()) == Some("clippy") => { ParsedCommand::Lint { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("cargo clippy".to_string()), targets: collect_non_flag_targets(&tail[1..]), } @@ -1736,45 +1741,45 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if head == "cargo" && tail.first().map(|s| s.as_str()) == Some("test") => { ParsedCommand::Test { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } Some((head, tail)) if head == "rustfmt" => ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("rustfmt".to_string()), targets: collect_non_flag_targets(tail), }, Some((head, tail)) if head == "go" && tail.first().map(|s| s.as_str()) == Some("fmt") => { ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("go fmt".to_string()), targets: collect_non_flag_targets(&tail[1..]), } } Some((head, tail)) if head == "go" && tail.first().map(|s| s.as_str()) == Some("test") => { ParsedCommand::Test { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } Some((head, _)) if head == "pytest" => ParsedCommand::Test { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), }, Some((head, tail)) if head == "eslint" => { // Treat configuration flags with values (e.g. `-c .eslintrc`) as non-targets. let targets = collect_non_flag_targets_with_flags(tail, ESLINT_FLAGS_WITH_VALUES); ParsedCommand::Lint { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("eslint".to_string()), targets, } } Some((head, tail)) if head == "prettier" => ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("prettier".to_string()), targets: collect_non_flag_targets(tail), }, Some((head, tail)) if head == "black" => ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("black".to_string()), targets: collect_non_flag_targets(tail), }, @@ -1782,7 +1787,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if head == "ruff" && tail.first().map(|s| s.as_str()) == Some("check") => { ParsedCommand::Lint { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("ruff".to_string()), targets: collect_non_flag_targets(&tail[1..]), } @@ -1791,20 +1796,20 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if head == "ruff" && tail.first().map(|s| s.as_str()) == Some("format") => { ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("ruff".to_string()), targets: collect_non_flag_targets(&tail[1..]), } } Some((head, _)) if (head == "jest" || head == "vitest") => ParsedCommand::Test { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), }, Some((head, tail)) if head == "npx" && tail.first().map(|s| s.as_str()) == Some("eslint") => { let targets = collect_non_flag_targets_with_flags(&tail[1..], ESLINT_FLAGS_WITH_VALUES); ParsedCommand::Lint { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("eslint".to_string()), targets, } @@ -1813,7 +1818,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if head == "npx" && tail.first().map(|s| s.as_str()) == Some("prettier") => { ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("prettier".to_string()), targets: collect_non_flag_targets(&tail[1..]), } @@ -1824,7 +1829,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { cmd } else { ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } } @@ -1847,7 +1852,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { .find(|p| !p.starts_with('-')) .map(|p| short_display_path(p)); ParsedCommand::ListFiles { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), path, } } @@ -1867,7 +1872,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { ) }; ParsedCommand::Search { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), query, path, } @@ -1875,7 +1880,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { Some((head, tail)) if head == "fd" => { let (query, path) = parse_fd_query_and_path(tail); ParsedCommand::Search { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), query, path, } @@ -1884,7 +1889,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { // Basic find support: capture path and common name filter let (query, path) = parse_find_query_and_path(tail); ParsedCommand::Search { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), query, path, } @@ -1900,7 +1905,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { let query = non_flags.first().cloned().map(|s| s.to_string()); let path = non_flags.get(1).map(|s| short_display_path(s)); ParsedCommand::Search { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), query, path, } @@ -1915,12 +1920,12 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if effective_tail.len() == 1 { let name = short_display_path(&effective_tail[0]); ParsedCommand::Read { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), name, } } else { ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } } @@ -1953,13 +1958,13 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if let Some(p) = candidates.into_iter().find(|p| !p.starts_with('-')) { let name = short_display_path(p); return ParsedCommand::Read { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), name, }; } } ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } Some((head, tail)) if head == "tail" => { @@ -1995,13 +2000,13 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if let Some(p) = candidates.into_iter().find(|p| !p.starts_with('-')) { let name = short_display_path(p); return ParsedCommand::Read { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), name, }; } } ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } Some((head, tail)) if head == "nl" => { @@ -2010,12 +2015,12 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if let Some(p) = candidates.into_iter().find(|p| !p.starts_with('-')) { let name = short_display_path(p); ParsedCommand::Read { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), name, } } else { ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } } @@ -2028,18 +2033,18 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if let Some(path) = tail.get(2) { let name = short_display_path(path); ParsedCommand::Read { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), name, } } else { ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } } // Other commands _ => ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), }, } } diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 143dd4d035..3336024272 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -206,7 +206,7 @@ fn exec_history_cell_shows_working_then_completed() { command: vec!["bash".into(), "-lc".into(), "echo done".into()], cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), parsed_cmd: vec![codex_core::parse_command::ParsedCommand::Unknown { - cmd: vec!["echo".into(), "done".into()], + cmd: "echo done".into(), }], }), }); @@ -248,7 +248,7 @@ fn exec_history_cell_shows_working_then_failed() { command: vec!["bash".into(), "-lc".into(), "false".into()], cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), parsed_cmd: vec![codex_core::parse_command::ParsedCommand::Unknown { - cmd: vec!["false".into()], + cmd: "false".into(), }], }), }); diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index f420065df8..19fdfc4a79 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -248,18 +248,19 @@ fn new_parsed_command( ParsedCommand::Read { name, .. } => format!("πŸ“– {name}"), ParsedCommand::ListFiles { cmd, path } => match path { Some(p) => format!("πŸ“‚ {p}"), - None => format!("πŸ“‚ {}", shlex_join_safe(cmd)), + None => format!("πŸ“‚ {cmd}"), }, ParsedCommand::Search { query, path, cmd } => match (query, path) { (Some(q), Some(p)) => format!("πŸ”Ž {q} in {p}"), (Some(q), None) => format!("πŸ”Ž {q}"), (None, Some(p)) => format!("πŸ”Ž {p}"), - (None, None) => format!("πŸ”Ž {}", shlex_join_safe(cmd)), + (None, None) => format!("πŸ”Ž {cmd}"), }, ParsedCommand::Format { .. } => "✨ Formatting".to_string(), - ParsedCommand::Test { cmd } => format!("πŸ§ͺ {}", shlex_join_safe(cmd)), - ParsedCommand::Lint { cmd, .. } => format!("🧹 {}", shlex_join_safe(cmd)), - ParsedCommand::Unknown { cmd } => format!("⌨️ {}", shlex_join_safe(cmd)), + ParsedCommand::Test { cmd } => format!("πŸ§ͺ {cmd}"), + ParsedCommand::Lint { cmd, .. } => format!("🧹 {cmd}"), + ParsedCommand::Unknown { cmd } => format!("⌨️ {cmd}"), + ParsedCommand::Noop { cmd } => format!("πŸ”„ {cmd}"), }; let first_prefix = if i == 0 { " β”” " } else { " " }; @@ -856,13 +857,6 @@ fn format_mcp_invocation<'a>(invocation: McpInvocation) -> Line<'a> { Line::from(invocation_spans) } -fn shlex_join_safe(command: &[String]) -> String { - match shlex::try_join(command.iter().map(|s| s.as_str())) { - Ok(cmd) => cmd, - Err(_) => command.join(" "), - } -} - #[cfg(test)] mod tests { use super::*; @@ -870,7 +864,7 @@ mod tests { #[test] fn parsed_command_with_newlines_starts_each_line_at_origin() { let parsed = vec![ParsedCommand::Unknown { - cmd: vec!["printf".into(), "foo\nbar".into()], + cmd: "printf 'foo\nbar'".to_string(), }]; let lines = exec_command_lines(&[], &parsed, None); assert!(lines.len() >= 3); From 992e81d9b525446660169ee6e7321ebc13c023fd Mon Sep 17 00:00:00 2001 From: David Z Hao Date: Thu, 14 Aug 2025 14:23:06 -0700 Subject: [PATCH 02/16] test(core): add seatbelt sem lock tests (#1823) ## Summary - add a unit test to ensure the macOS seatbelt policy allows POSIX semaphores - add a macOS-only test that runs a Python multiprocessing Lock under Seatbelt ## Testing - `cargo test -p codex_core seatbelt_base_policy_allows_ipc_posix_sem --no-fail-fast` (failed: failed to download from `https://static.crates.io/crates/tokio-stream/0.1.17/download`) - `cargo test -p codex_core seatbelt_base_policy_allows_ipc_posix_sem --no-fail-fast --offline` (failed: attempting to make an HTTP request, but --offline was specified) - `cargo test --all-features --no-fail-fast --offline` (failed: attempting to make an HTTP request, but --offline was specified) - `just fmt` (failed: command not found: just) - `just fix` (failed: command not found: just) Ran tests locally to confirm it passes on master and failed before my previous change ------ https://chatgpt.com/codex/tasks/task_i_6890f221e0a4833381cfb53e11499bcc --- codex-rs/core/src/seatbelt.rs | 53 +++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/codex-rs/core/src/seatbelt.rs b/codex-rs/core/src/seatbelt.rs index ff9dbaa7f9..893ae8d0da 100644 --- a/codex-rs/core/src/seatbelt.rs +++ b/codex-rs/core/src/seatbelt.rs @@ -301,6 +301,59 @@ mod tests { assert_eq!(expected_args, args); } + #[test] + fn seatbelt_base_policy_allows_ipc_posix_sem() { + assert!( + MACOS_SEATBELT_BASE_POLICY.contains("(allow ipc-posix-sem)"), + "base policy should allow ipc-posix-sem" + ); + } + + #[cfg(target_os = "macos")] + #[tokio::test] + async fn python_multiprocessing_lock_works_under_seatbelt() { + use super::spawn_command_under_seatbelt; + use crate::spawn::StdioPolicy; + use std::collections::HashMap; + + let policy = SandboxPolicy::WorkspaceWrite { + writable_roots: vec![], + network_access: false, + include_default_writable_roots: true, + }; + + let python_code = r#"import multiprocessing +from multiprocessing import Lock, Process + +def f(lock): + with lock: + print("Lock acquired in child process") + +if __name__ == '__main__': + lock = Lock() + p = Process(target=f, args=(lock,)) + p.start() + p.join() +"#; + + let mut child = spawn_command_under_seatbelt( + vec![ + "python3".to_string(), + "-c".to_string(), + python_code.to_string(), + ], + &policy, + std::env::current_dir().expect("should be able to get current dir"), + StdioPolicy::RedirectForShellTool, + HashMap::new(), + ) + .await + .expect("should be able to spawn python under seatbelt"); + + let status = child.wait().await.expect("should wait for child process"); + assert!(status.success(), "python exited with {status:?}"); + } + struct PopulatedTmp { root_with_git: PathBuf, root_without_git: PathBuf, From a8c7f5391c852913dba4b179f0a9125f9de12688 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 14 Aug 2025 14:48:38 -0700 Subject: [PATCH 03/16] fix: move general sandbox tests to codex-rs/core/tests/sandbox.rs (#2317) Previous to this PR, `codex-rs/core/tests/sandbox.rs` contained integration tests that were specific to Seatbelt. This PR moves those tests to `codex-rs/core/src/seatbelt.rs` and designates `codex-rs/core/tests/sandbox.rs` to be used as the home for cross-platform (well, Mac and Linux...) sandbox tests. To start, this migrates `python_multiprocessing_lock_works_under_seatbelt()` from #1823 to the new `sandbox.rs` because this is the type of thing that should work on both Mac _and_ Linux, though I still need to do some work to clean up the test so it works on both platforms. --- codex-rs/core/src/seatbelt.rs | 53 -------- codex-rs/core/tests/sandbox.rs | 212 +++++--------------------------- codex-rs/core/tests/seatbelt.rs | 200 ++++++++++++++++++++++++++++++ 3 files changed, 232 insertions(+), 233 deletions(-) create mode 100644 codex-rs/core/tests/seatbelt.rs diff --git a/codex-rs/core/src/seatbelt.rs b/codex-rs/core/src/seatbelt.rs index 893ae8d0da..ff9dbaa7f9 100644 --- a/codex-rs/core/src/seatbelt.rs +++ b/codex-rs/core/src/seatbelt.rs @@ -301,59 +301,6 @@ mod tests { assert_eq!(expected_args, args); } - #[test] - fn seatbelt_base_policy_allows_ipc_posix_sem() { - assert!( - MACOS_SEATBELT_BASE_POLICY.contains("(allow ipc-posix-sem)"), - "base policy should allow ipc-posix-sem" - ); - } - - #[cfg(target_os = "macos")] - #[tokio::test] - async fn python_multiprocessing_lock_works_under_seatbelt() { - use super::spawn_command_under_seatbelt; - use crate::spawn::StdioPolicy; - use std::collections::HashMap; - - let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], - network_access: false, - include_default_writable_roots: true, - }; - - let python_code = r#"import multiprocessing -from multiprocessing import Lock, Process - -def f(lock): - with lock: - print("Lock acquired in child process") - -if __name__ == '__main__': - lock = Lock() - p = Process(target=f, args=(lock,)) - p.start() - p.join() -"#; - - let mut child = spawn_command_under_seatbelt( - vec![ - "python3".to_string(), - "-c".to_string(), - python_code.to_string(), - ], - &policy, - std::env::current_dir().expect("should be able to get current dir"), - StdioPolicy::RedirectForShellTool, - HashMap::new(), - ) - .await - .expect("should be able to spawn python under seatbelt"); - - let status = child.wait().await.expect("should wait for child process"); - assert!(status.success(), "python exited with {status:?}"); - } - struct PopulatedTmp { root_with_git: PathBuf, root_without_git: PathBuf, diff --git a/codex-rs/core/tests/sandbox.rs b/codex-rs/core/tests/sandbox.rs index ae5bdc44a6..93ffa605f9 100644 --- a/codex-rs/core/tests/sandbox.rs +++ b/codex-rs/core/tests/sandbox.rs @@ -1,197 +1,49 @@ -#![cfg(target_os = "macos")] -#![expect(clippy::expect_used)] - -use std::collections::HashMap; -use std::path::Path; -use std::path::PathBuf; - -use codex_core::protocol::SandboxPolicy; -use codex_core::seatbelt::spawn_command_under_seatbelt; -use codex_core::spawn::CODEX_SANDBOX_ENV_VAR; -use codex_core::spawn::StdioPolicy; -use tempfile::TempDir; - -struct TestScenario { - repo_parent: PathBuf, - file_outside_repo: PathBuf, - repo_root: PathBuf, - file_in_repo_root: PathBuf, - file_in_dot_git_dir: PathBuf, -} - -struct TestExpectations { - file_outside_repo_is_writable: bool, - file_in_repo_root_is_writable: bool, - file_in_dot_git_dir_is_writable: bool, -} - -impl TestScenario { - async fn run_test(&self, policy: &SandboxPolicy, expectations: TestExpectations) { - if std::env::var(CODEX_SANDBOX_ENV_VAR) == Ok("seatbelt".to_string()) { - eprintln!("{CODEX_SANDBOX_ENV_VAR} is set to 'seatbelt', skipping test."); - return; - } - - assert_eq!( - touch(&self.file_outside_repo, policy).await, - expectations.file_outside_repo_is_writable - ); - assert_eq!( - self.file_outside_repo.exists(), - expectations.file_outside_repo_is_writable - ); - - assert_eq!( - touch(&self.file_in_repo_root, policy).await, - expectations.file_in_repo_root_is_writable - ); - assert_eq!( - self.file_in_repo_root.exists(), - expectations.file_in_repo_root_is_writable - ); - - assert_eq!( - touch(&self.file_in_dot_git_dir, policy).await, - expectations.file_in_dot_git_dir_is_writable - ); - assert_eq!( - self.file_in_dot_git_dir.exists(), - expectations.file_in_dot_git_dir_is_writable - ); - } -} - -/// If the user has added a workspace root that is not a Git repo root, then -/// the user has to specify `--skip-git-repo-check` or go through some -/// interstitial that indicates they are taking on some risk because Git -/// cannot be used to backup their work before the agent begins. -/// -/// Because the user has agreed to this risk, we do not try find all .git -/// folders in the workspace and block them (though we could change our -/// position on this in the future). +// TODO(mbolin): Update this test to run on Linux, as well. +// (Should rename the test as part of that work.) +#[cfg(target_os = "macos")] #[tokio::test] -async fn if_parent_of_repo_is_writable_then_dot_git_folder_is_writable() { - let tmp = TempDir::new().expect("should be able to create temp dir"); - let test_scenario = create_test_scenario(&tmp); +async fn python_multiprocessing_lock_works_under_seatbelt() { + #![expect(clippy::expect_used)] + use codex_core::protocol::SandboxPolicy; + use codex_core::seatbelt::spawn_command_under_seatbelt; + use codex_core::spawn::StdioPolicy; + use std::collections::HashMap; + let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![test_scenario.repo_parent.clone()], + writable_roots: vec![], network_access: false, - exclude_tmpdir_env_var: true, - exclude_slash_tmp: true, + exclude_tmpdir_env_var: false, + exclude_slash_tmp: false, }; - test_scenario - .run_test( - &policy, - TestExpectations { - file_outside_repo_is_writable: true, - file_in_repo_root_is_writable: true, - file_in_dot_git_dir_is_writable: true, - }, - ) - .await; -} + let python_code = r#"import multiprocessing +from multiprocessing import Lock, Process -/// When the writable root is the root of a Git repository (as evidenced by the -/// presence of a .git folder), then the .git folder should be read-only if -/// the policy is `WorkspaceWrite`. -#[tokio::test] -async fn if_git_repo_is_writable_root_then_dot_git_folder_is_read_only() { - let tmp = TempDir::new().expect("should be able to create temp dir"); - let test_scenario = create_test_scenario(&tmp); - let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![test_scenario.repo_root.clone()], - network_access: false, - exclude_tmpdir_env_var: true, - exclude_slash_tmp: true, - }; +def f(lock): + with lock: + print("Lock acquired in child process") - test_scenario - .run_test( - &policy, - TestExpectations { - file_outside_repo_is_writable: false, - file_in_repo_root_is_writable: true, - file_in_dot_git_dir_is_writable: false, - }, - ) - .await; -} +if __name__ == '__main__': + lock = Lock() + p = Process(target=f, args=(lock,)) + p.start() + p.join() +"#; -/// Under DangerFullAccess, all writes should be permitted anywhere on disk, -/// including inside the .git folder. -#[tokio::test] -async fn danger_full_access_allows_all_writes() { - let tmp = TempDir::new().expect("should be able to create temp dir"); - let test_scenario = create_test_scenario(&tmp); - let policy = SandboxPolicy::DangerFullAccess; - - test_scenario - .run_test( - &policy, - TestExpectations { - file_outside_repo_is_writable: true, - file_in_repo_root_is_writable: true, - file_in_dot_git_dir_is_writable: true, - }, - ) - .await; -} - -/// Under ReadOnly, writes should not be permitted anywhere on disk. -#[tokio::test] -async fn read_only_forbids_all_writes() { - let tmp = TempDir::new().expect("should be able to create temp dir"); - let test_scenario = create_test_scenario(&tmp); - let policy = SandboxPolicy::ReadOnly; - - test_scenario - .run_test( - &policy, - TestExpectations { - file_outside_repo_is_writable: false, - file_in_repo_root_is_writable: false, - file_in_dot_git_dir_is_writable: false, - }, - ) - .await; -} - -fn create_test_scenario(tmp: &TempDir) -> TestScenario { - let repo_parent = tmp.path().to_path_buf(); - let repo_root = repo_parent.join("repo"); - let dot_git_dir = repo_root.join(".git"); - - std::fs::create_dir(&repo_root).expect("should be able to create repo root"); - std::fs::create_dir(&dot_git_dir).expect("should be able to create .git dir"); - - TestScenario { - file_outside_repo: repo_parent.join("outside.txt"), - repo_parent, - file_in_repo_root: repo_root.join("repo_file.txt"), - repo_root, - file_in_dot_git_dir: dot_git_dir.join("dot_git_file.txt"), - } -} - -/// Note that `path` must be absolute. -async fn touch(path: &Path, policy: &SandboxPolicy) -> bool { - assert!(path.is_absolute(), "Path must be absolute: {path:?}"); let mut child = spawn_command_under_seatbelt( vec![ - "/usr/bin/touch".to_string(), - path.to_string_lossy().to_string(), + "python3".to_string(), + "-c".to_string(), + python_code.to_string(), ], - policy, + &policy, std::env::current_dir().expect("should be able to get current dir"), StdioPolicy::RedirectForShellTool, HashMap::new(), ) .await - .expect("should be able to spawn command under seatbelt"); - child - .wait() - .await - .expect("should be able to wait for child process") - .success() + .expect("should be able to spawn python under seatbelt"); + + let status = child.wait().await.expect("should wait for child process"); + assert!(status.success(), "python exited with {status:?}"); } diff --git a/codex-rs/core/tests/seatbelt.rs b/codex-rs/core/tests/seatbelt.rs new file mode 100644 index 0000000000..fb2e7452f1 --- /dev/null +++ b/codex-rs/core/tests/seatbelt.rs @@ -0,0 +1,200 @@ +#![cfg(target_os = "macos")] +#![expect(clippy::expect_used)] + +//! Tests for the macOS sandboxing that are specific to Seatbelt. +//! Tests that apply to both Mac and Linux sandboxing should go in sandbox.rs. + +use std::collections::HashMap; +use std::path::Path; +use std::path::PathBuf; + +use codex_core::protocol::SandboxPolicy; +use codex_core::seatbelt::spawn_command_under_seatbelt; +use codex_core::spawn::CODEX_SANDBOX_ENV_VAR; +use codex_core::spawn::StdioPolicy; +use tempfile::TempDir; + +struct TestScenario { + repo_parent: PathBuf, + file_outside_repo: PathBuf, + repo_root: PathBuf, + file_in_repo_root: PathBuf, + file_in_dot_git_dir: PathBuf, +} + +struct TestExpectations { + file_outside_repo_is_writable: bool, + file_in_repo_root_is_writable: bool, + file_in_dot_git_dir_is_writable: bool, +} + +impl TestScenario { + async fn run_test(&self, policy: &SandboxPolicy, expectations: TestExpectations) { + if std::env::var(CODEX_SANDBOX_ENV_VAR) == Ok("seatbelt".to_string()) { + eprintln!("{CODEX_SANDBOX_ENV_VAR} is set to 'seatbelt', skipping test."); + return; + } + + assert_eq!( + touch(&self.file_outside_repo, policy).await, + expectations.file_outside_repo_is_writable + ); + assert_eq!( + self.file_outside_repo.exists(), + expectations.file_outside_repo_is_writable + ); + + assert_eq!( + touch(&self.file_in_repo_root, policy).await, + expectations.file_in_repo_root_is_writable + ); + assert_eq!( + self.file_in_repo_root.exists(), + expectations.file_in_repo_root_is_writable + ); + + assert_eq!( + touch(&self.file_in_dot_git_dir, policy).await, + expectations.file_in_dot_git_dir_is_writable + ); + assert_eq!( + self.file_in_dot_git_dir.exists(), + expectations.file_in_dot_git_dir_is_writable + ); + } +} + +/// If the user has added a workspace root that is not a Git repo root, then +/// the user has to specify `--skip-git-repo-check` or go through some +/// interstitial that indicates they are taking on some risk because Git +/// cannot be used to backup their work before the agent begins. +/// +/// Because the user has agreed to this risk, we do not try find all .git +/// folders in the workspace and block them (though we could change our +/// position on this in the future). +#[tokio::test] +async fn if_parent_of_repo_is_writable_then_dot_git_folder_is_writable() { + let tmp = TempDir::new().expect("should be able to create temp dir"); + let test_scenario = create_test_scenario(&tmp); + let policy = SandboxPolicy::WorkspaceWrite { + writable_roots: vec![test_scenario.repo_parent.clone()], + network_access: false, + exclude_tmpdir_env_var: true, + exclude_slash_tmp: true, + }; + + test_scenario + .run_test( + &policy, + TestExpectations { + file_outside_repo_is_writable: true, + file_in_repo_root_is_writable: true, + file_in_dot_git_dir_is_writable: true, + }, + ) + .await; +} + +/// When the writable root is the root of a Git repository (as evidenced by the +/// presence of a .git folder), then the .git folder should be read-only if +/// the policy is `WorkspaceWrite`. +#[tokio::test] +async fn if_git_repo_is_writable_root_then_dot_git_folder_is_read_only() { + let tmp = TempDir::new().expect("should be able to create temp dir"); + let test_scenario = create_test_scenario(&tmp); + let policy = SandboxPolicy::WorkspaceWrite { + writable_roots: vec![test_scenario.repo_root.clone()], + network_access: false, + exclude_tmpdir_env_var: true, + exclude_slash_tmp: true, + }; + + test_scenario + .run_test( + &policy, + TestExpectations { + file_outside_repo_is_writable: false, + file_in_repo_root_is_writable: true, + file_in_dot_git_dir_is_writable: false, + }, + ) + .await; +} + +/// Under DangerFullAccess, all writes should be permitted anywhere on disk, +/// including inside the .git folder. +#[tokio::test] +async fn danger_full_access_allows_all_writes() { + let tmp = TempDir::new().expect("should be able to create temp dir"); + let test_scenario = create_test_scenario(&tmp); + let policy = SandboxPolicy::DangerFullAccess; + + test_scenario + .run_test( + &policy, + TestExpectations { + file_outside_repo_is_writable: true, + file_in_repo_root_is_writable: true, + file_in_dot_git_dir_is_writable: true, + }, + ) + .await; +} + +/// Under ReadOnly, writes should not be permitted anywhere on disk. +#[tokio::test] +async fn read_only_forbids_all_writes() { + let tmp = TempDir::new().expect("should be able to create temp dir"); + let test_scenario = create_test_scenario(&tmp); + let policy = SandboxPolicy::ReadOnly; + + test_scenario + .run_test( + &policy, + TestExpectations { + file_outside_repo_is_writable: false, + file_in_repo_root_is_writable: false, + file_in_dot_git_dir_is_writable: false, + }, + ) + .await; +} + +fn create_test_scenario(tmp: &TempDir) -> TestScenario { + let repo_parent = tmp.path().to_path_buf(); + let repo_root = repo_parent.join("repo"); + let dot_git_dir = repo_root.join(".git"); + + std::fs::create_dir(&repo_root).expect("should be able to create repo root"); + std::fs::create_dir(&dot_git_dir).expect("should be able to create .git dir"); + + TestScenario { + file_outside_repo: repo_parent.join("outside.txt"), + repo_parent, + file_in_repo_root: repo_root.join("repo_file.txt"), + repo_root, + file_in_dot_git_dir: dot_git_dir.join("dot_git_file.txt"), + } +} + +/// Note that `path` must be absolute. +async fn touch(path: &Path, policy: &SandboxPolicy) -> bool { + assert!(path.is_absolute(), "Path must be absolute: {path:?}"); + let mut child = spawn_command_under_seatbelt( + vec![ + "/usr/bin/touch".to_string(), + path.to_string_lossy().to_string(), + ], + policy, + std::env::current_dir().expect("should be able to get current dir"), + StdioPolicy::RedirectForShellTool, + HashMap::new(), + ) + .await + .expect("should be able to spawn command under seatbelt"); + child + .wait() + .await + .expect("should be able to wait for child process") + .success() +} From 2ecca79663849f527f3b75706f416d289269cd55 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 14 Aug 2025 15:47:48 -0700 Subject: [PATCH 04/16] fix: run python_multiprocessing_lock_works integration test on Mac and Linux (#2318) The high-order bit on this PR is that it makes it so `sandbox.rs` tests both Mac and Linux, as we introduce a general `spawn_command_under_sandbox()` function with platform-specific implementations for testing. An important, and interesting, discovery in porting the test to Linux is that (for reasons cited in the code comments), `/dev/shm` has to be added to `writable_roots` on Linux in order for `multiprocessing.Lock` to work there. Granting write access to `/dev/shm` comes with some degree of risk, so we do not make this the default for Codex CLI. Piggybacking on top of #2317, this moves the `python_multiprocessing_lock_works` test yet again, moving `codex-rs/core/tests/sandbox.rs` to `codex-rs/exec/tests/sandbox.rs` because in `codex-rs/exec/tests` we can use `cargo_bin()` like so: ``` let codex_linux_sandbox_exe = assert_cmd::cargo::cargo_bin("codex-exec"); ``` which is necessary so we can use `codex_linux_sandbox_exe` and therefore `spawn_command_under_linux_sandbox` in an integration test. This also moves `spawn_command_under_linux_sandbox()` out of `exec.rs` and into `landlock.rs`, which makes things more consistent with `seatbelt.rs` in `codex-core`. For reference, https://github.com/openai/codex/pull/1808 is the PR that made the change to Seatbelt to get this test to pass on Mac. --- codex-rs/cli/src/debug_sandbox.rs | 2 +- codex-rs/core/src/exec.rs | 61 +------------------- codex-rs/core/src/landlock.rs | 66 ++++++++++++++++++++++ codex-rs/core/src/lib.rs | 1 + codex-rs/core/tests/sandbox.rs | 49 ---------------- codex-rs/exec/tests/sandbox.rs | 92 +++++++++++++++++++++++++++++++ 6 files changed, 161 insertions(+), 110 deletions(-) create mode 100644 codex-rs/core/src/landlock.rs delete mode 100644 codex-rs/core/tests/sandbox.rs create mode 100644 codex-rs/exec/tests/sandbox.rs diff --git a/codex-rs/cli/src/debug_sandbox.rs b/codex-rs/cli/src/debug_sandbox.rs index 7f0983cbc6..30e144ed34 100644 --- a/codex-rs/cli/src/debug_sandbox.rs +++ b/codex-rs/cli/src/debug_sandbox.rs @@ -4,8 +4,8 @@ use codex_common::CliConfigOverrides; use codex_core::config::Config; use codex_core::config::ConfigOverrides; use codex_core::config_types::SandboxMode; -use codex_core::exec::spawn_command_under_linux_sandbox; use codex_core::exec_env::create_env; +use codex_core::landlock::spawn_command_under_linux_sandbox; use codex_core::seatbelt::spawn_command_under_seatbelt; use codex_core::spawn::StdioPolicy; diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index 50bba1b4b7..9430433c11 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -3,7 +3,6 @@ use std::os::unix::process::ExitStatusExt; use std::collections::HashMap; use std::io; -use std::path::Path; use std::path::PathBuf; use std::process::ExitStatus; use std::time::Duration; @@ -18,6 +17,7 @@ use tokio::process::Child; use crate::error::CodexErr; use crate::error::Result; use crate::error::SandboxErr; +use crate::landlock::spawn_command_under_linux_sandbox; use crate::protocol::Event; use crate::protocol::EventMsg; use crate::protocol::ExecCommandOutputDeltaEvent; @@ -163,65 +163,6 @@ pub async fn process_exec_tool_call( } } -/// Spawn a shell tool command under the Linux Landlock+seccomp sandbox helper -/// (codex-linux-sandbox). -/// -/// Unlike macOS Seatbelt where we directly embed the policy text, the Linux -/// helper accepts a list of `--sandbox-permission`/`-s` flags mirroring the -/// public CLI. We convert the internal [`SandboxPolicy`] representation into -/// the equivalent CLI options. -pub async fn spawn_command_under_linux_sandbox

( - codex_linux_sandbox_exe: P, - command: Vec, - sandbox_policy: &SandboxPolicy, - cwd: PathBuf, - stdio_policy: StdioPolicy, - env: HashMap, -) -> std::io::Result -where - P: AsRef, -{ - let args = create_linux_sandbox_command_args(command, sandbox_policy, &cwd); - let arg0 = Some("codex-linux-sandbox"); - spawn_child_async( - codex_linux_sandbox_exe.as_ref().to_path_buf(), - args, - arg0, - cwd, - sandbox_policy, - stdio_policy, - env, - ) - .await -} - -/// Converts the sandbox policy into the CLI invocation for `codex-linux-sandbox`. -fn create_linux_sandbox_command_args( - command: Vec, - sandbox_policy: &SandboxPolicy, - cwd: &Path, -) -> Vec { - #[expect(clippy::expect_used)] - let sandbox_policy_cwd = cwd.to_str().expect("cwd must be valid UTF-8").to_string(); - - #[expect(clippy::expect_used)] - let sandbox_policy_json = - serde_json::to_string(sandbox_policy).expect("Failed to serialize SandboxPolicy to JSON"); - - let mut linux_cmd: Vec = vec![ - sandbox_policy_cwd, - sandbox_policy_json, - // Separator so that command arguments starting with `-` are not parsed as - // options of the helper itself. - "--".to_string(), - ]; - - // Append the original tool command. - linux_cmd.extend(command); - - linux_cmd -} - /// We don't have a fully deterministic way to tell if our command failed /// because of the sandbox - a command in the user's zshrc file might hit an /// error, but the command itself might fail or succeed for other reasons. diff --git a/codex-rs/core/src/landlock.rs b/codex-rs/core/src/landlock.rs new file mode 100644 index 0000000000..8c8840c269 --- /dev/null +++ b/codex-rs/core/src/landlock.rs @@ -0,0 +1,66 @@ +use crate::protocol::SandboxPolicy; +use crate::spawn::StdioPolicy; +use crate::spawn::spawn_child_async; +use std::collections::HashMap; +use std::path::Path; +use std::path::PathBuf; +use tokio::process::Child; + +/// Spawn a shell tool command under the Linux Landlock+seccomp sandbox helper +/// (codex-linux-sandbox). +/// +/// Unlike macOS Seatbelt where we directly embed the policy text, the Linux +/// helper accepts a list of `--sandbox-permission`/`-s` flags mirroring the +/// public CLI. We convert the internal [`SandboxPolicy`] representation into +/// the equivalent CLI options. +pub async fn spawn_command_under_linux_sandbox

( + codex_linux_sandbox_exe: P, + command: Vec, + sandbox_policy: &SandboxPolicy, + cwd: PathBuf, + stdio_policy: StdioPolicy, + env: HashMap, +) -> std::io::Result +where + P: AsRef, +{ + let args = create_linux_sandbox_command_args(command, sandbox_policy, &cwd); + let arg0 = Some("codex-linux-sandbox"); + spawn_child_async( + codex_linux_sandbox_exe.as_ref().to_path_buf(), + args, + arg0, + cwd, + sandbox_policy, + stdio_policy, + env, + ) + .await +} + +/// Converts the sandbox policy into the CLI invocation for `codex-linux-sandbox`. +fn create_linux_sandbox_command_args( + command: Vec, + sandbox_policy: &SandboxPolicy, + cwd: &Path, +) -> Vec { + #[expect(clippy::expect_used)] + let sandbox_policy_cwd = cwd.to_str().expect("cwd must be valid UTF-8").to_string(); + + #[expect(clippy::expect_used)] + let sandbox_policy_json = + serde_json::to_string(sandbox_policy).expect("Failed to serialize SandboxPolicy to JSON"); + + let mut linux_cmd: Vec = vec![ + sandbox_policy_cwd, + sandbox_policy_json, + // Separator so that command arguments starting with `-` are not parsed as + // options of the helper itself. + "--".to_string(), + ]; + + // Append the original tool command. + linux_cmd.extend(command); + + linux_cmd +} diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index d19fbbdb26..e895377b74 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -24,6 +24,7 @@ pub mod exec_env; mod flags; pub mod git_info; mod is_safe_command; +pub mod landlock; mod mcp_connection_manager; mod mcp_tool_call; mod message_history; diff --git a/codex-rs/core/tests/sandbox.rs b/codex-rs/core/tests/sandbox.rs deleted file mode 100644 index 93ffa605f9..0000000000 --- a/codex-rs/core/tests/sandbox.rs +++ /dev/null @@ -1,49 +0,0 @@ -// TODO(mbolin): Update this test to run on Linux, as well. -// (Should rename the test as part of that work.) -#[cfg(target_os = "macos")] -#[tokio::test] -async fn python_multiprocessing_lock_works_under_seatbelt() { - #![expect(clippy::expect_used)] - use codex_core::protocol::SandboxPolicy; - use codex_core::seatbelt::spawn_command_under_seatbelt; - use codex_core::spawn::StdioPolicy; - use std::collections::HashMap; - - let policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], - network_access: false, - exclude_tmpdir_env_var: false, - exclude_slash_tmp: false, - }; - - let python_code = r#"import multiprocessing -from multiprocessing import Lock, Process - -def f(lock): - with lock: - print("Lock acquired in child process") - -if __name__ == '__main__': - lock = Lock() - p = Process(target=f, args=(lock,)) - p.start() - p.join() -"#; - - let mut child = spawn_command_under_seatbelt( - vec![ - "python3".to_string(), - "-c".to_string(), - python_code.to_string(), - ], - &policy, - std::env::current_dir().expect("should be able to get current dir"), - StdioPolicy::RedirectForShellTool, - HashMap::new(), - ) - .await - .expect("should be able to spawn python under seatbelt"); - - let status = child.wait().await.expect("should wait for child process"); - assert!(status.success(), "python exited with {status:?}"); -} diff --git a/codex-rs/exec/tests/sandbox.rs b/codex-rs/exec/tests/sandbox.rs new file mode 100644 index 0000000000..8cc31bba58 --- /dev/null +++ b/codex-rs/exec/tests/sandbox.rs @@ -0,0 +1,92 @@ +#![cfg(unix)] +#![expect(clippy::expect_used)] + +use codex_core::protocol::SandboxPolicy; +use codex_core::spawn::StdioPolicy; +use std::collections::HashMap; +use std::path::PathBuf; +use tokio::process::Child; + +#[cfg(target_os = "macos")] +async fn spawn_command_under_sandbox( + command: Vec, + sandbox_policy: &SandboxPolicy, + cwd: PathBuf, + stdio_policy: StdioPolicy, + env: HashMap, +) -> std::io::Result { + use codex_core::seatbelt::spawn_command_under_seatbelt; + spawn_command_under_seatbelt(command, sandbox_policy, cwd, stdio_policy, env).await +} + +#[cfg(target_os = "linux")] +async fn spawn_command_under_sandbox( + command: Vec, + sandbox_policy: &SandboxPolicy, + cwd: PathBuf, + stdio_policy: StdioPolicy, + env: HashMap, +) -> std::io::Result { + use codex_core::landlock::spawn_command_under_linux_sandbox; + let codex_linux_sandbox_exe = assert_cmd::cargo::cargo_bin("codex-exec"); + spawn_command_under_linux_sandbox( + codex_linux_sandbox_exe, + command, + sandbox_policy, + cwd, + stdio_policy, + env, + ) + .await +} + +#[tokio::test] +async fn python_multiprocessing_lock_works_under_sandbox() { + #[cfg(target_os = "macos")] + let writable_roots = Vec::::new(); + + // From https://man7.org/linux/man-pages/man7/sem_overview.7.html + // + // > On Linux, named semaphores are created in a virtual filesystem, + // > normally mounted under /dev/shm. + #[cfg(target_os = "linux")] + let writable_roots = vec![PathBuf::from("/dev/shm")]; + + let policy = SandboxPolicy::WorkspaceWrite { + writable_roots, + network_access: false, + exclude_tmpdir_env_var: false, + exclude_slash_tmp: false, + }; + + let python_code = r#"import multiprocessing +from multiprocessing import Lock, Process + +def f(lock): + with lock: + print("Lock acquired in child process") + +if __name__ == '__main__': + lock = Lock() + p = Process(target=f, args=(lock,)) + p.start() + p.join() +"#; + + let mut child = spawn_command_under_sandbox( + vec![ + "python3".to_string(), + "-c".to_string(), + python_code.to_string(), + ], + &policy, + std::env::current_dir().expect("should be able to get current dir"), + StdioPolicy::Inherit, + HashMap::new(), + ) + .await + .expect("should be able to spawn python under sandbox"); + + let status = child.wait().await.expect("should wait for child process"); + assert!(status.success(), "python exited with {status:?}"); +} From 6a0f709cff9af480045adc9700c85039fd4c88f0 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 14 Aug 2025 16:09:12 -0700 Subject: [PATCH 05/16] fix: add call_id to ApprovalParams in mcp-server/src/wire_format.rs (#2322) Clients still need this field. --- codex-rs/mcp-server/src/codex_message_processor.rs | 6 ++++-- codex-rs/mcp-server/src/wire_format.rs | 6 ++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/codex-rs/mcp-server/src/codex_message_processor.rs b/codex-rs/mcp-server/src/codex_message_processor.rs index a13f0f2677..2495feb9e0 100644 --- a/codex-rs/mcp-server/src/codex_message_processor.rs +++ b/codex-rs/mcp-server/src/codex_message_processor.rs @@ -306,13 +306,14 @@ async fn apply_bespoke_event_handling( let Event { id: event_id, msg } = event; match msg { EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent { - call_id: _, + call_id, changes, reason, grant_root, }) => { let params = ApplyPatchApprovalParams { conversation_id, + call_id, file_changes: changes, reason, grant_root, @@ -327,13 +328,14 @@ async fn apply_bespoke_event_handling( }); } EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent { - call_id: _, + call_id, command, cwd, reason, }) => { let params = ExecCommandApprovalParams { conversation_id, + call_id, command, cwd, reason, diff --git a/codex-rs/mcp-server/src/wire_format.rs b/codex-rs/mcp-server/src/wire_format.rs index 4a2346cb3f..95d55e8bf5 100644 --- a/codex-rs/mcp-server/src/wire_format.rs +++ b/codex-rs/mcp-server/src/wire_format.rs @@ -187,6 +187,9 @@ pub enum ServerRequest { #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct ApplyPatchApprovalParams { pub conversation_id: ConversationId, + /// Use to correlate this with [codex_core::protocol::PatchApplyBeginEvent] + /// and [codex_core::protocol::PatchApplyEndEvent]. + pub call_id: String, pub file_changes: HashMap, /// Optional explanatory reason (e.g. request for extra write access). #[serde(skip_serializing_if = "Option::is_none")] @@ -200,6 +203,9 @@ pub struct ApplyPatchApprovalParams { #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] pub struct ExecCommandApprovalParams { pub conversation_id: ConversationId, + /// Use to correlate this with [codex_core::protocol::ExecCommandBeginEvent] + /// and [codex_core::protocol::ExecCommandEndEvent]. + pub call_id: String, pub command: Vec, pub cwd: PathBuf, #[serde(skip_serializing_if = "Option::is_none")] From 235987843c3d6647c0819c1071f9b9f064673e9c Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Thu, 14 Aug 2025 19:32:45 -0400 Subject: [PATCH 06/16] add a timer to running exec commands (#2321) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit sometimes i switch back to codex and i don't know how long a command has been running. Screenshot 2025-08-14 at 3 30 07β€―PM --- codex-rs/tui/src/history_cell.rs | 84 ++++++++++++++++++++++---------- 1 file changed, 59 insertions(+), 25 deletions(-) diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 19fdfc4a79..ba645a7e50 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -35,6 +35,7 @@ use std::collections::HashMap; use std::io::Cursor; use std::path::PathBuf; use std::time::Duration; +use std::time::Instant; use tracing::error; #[derive(Clone)] @@ -78,10 +79,16 @@ pub(crate) struct ExecCell { pub(crate) command: Vec, pub(crate) parsed: Vec, pub(crate) output: Option, + start_time: Option, } impl HistoryCell for ExecCell { fn display_lines(&self) -> Vec> { - exec_command_lines(&self.command, &self.parsed, self.output.as_ref()) + exec_command_lines( + &self.command, + &self.parsed, + self.output.as_ref(), + self.start_time, + ) } } @@ -199,49 +206,66 @@ pub(crate) fn new_active_exec_command( command: Vec, parsed: Vec, ) -> ExecCell { - new_exec_cell(command, parsed, None) + ExecCell { + command, + parsed, + output: None, + start_time: Some(Instant::now()), + } } pub(crate) fn new_completed_exec_command( command: Vec, parsed: Vec, output: CommandOutput, -) -> ExecCell { - new_exec_cell(command, parsed, Some(output)) -} - -fn new_exec_cell( - command: Vec, - parsed: Vec, - output: Option, ) -> ExecCell { ExecCell { command, parsed, - output, + output: Some(output), + start_time: None, } } +fn exec_duration(start: Instant) -> String { + format!("{}s", start.elapsed().as_secs()) +} + fn exec_command_lines( command: &[String], parsed: &[ParsedCommand], output: Option<&CommandOutput>, + start_time: Option, ) -> Vec> { match parsed.is_empty() { - true => new_exec_command_generic(command, output), - false => new_parsed_command(parsed, output), + true => new_exec_command_generic(command, output, start_time), + false => new_parsed_command(parsed, output, start_time), } } - fn new_parsed_command( parsed_commands: &[ParsedCommand], output: Option<&CommandOutput>, + start_time: Option, ) -> Vec> { - let mut lines: Vec = vec![match output { - None => Line::from("βš™οΈŽ Working".magenta().bold()), - Some(o) if o.exit_code == 0 => Line::from("βœ“ Completed".green().bold()), - Some(o) => Line::from(format!("βœ— Failed (exit {})", o.exit_code).red().bold()), - }]; + let mut lines: Vec = Vec::new(); + match output { + None => { + let mut spans = vec!["βš™οΈŽ Working".magenta().bold()]; + if let Some(st) = start_time { + let dur = exec_duration(st); + spans.push(format!(" β€’ {dur}").dim()); + } + lines.push(Line::from(spans)); + } + Some(o) if o.exit_code == 0 => { + lines.push(Line::from("βœ“ Completed".green().bold())); + } + Some(o) => { + lines.push(Line::from( + format!("βœ— Failed (exit {})", o.exit_code).red().bold(), + )); + } + }; for (i, parsed) in parsed_commands.iter().enumerate() { let text = match parsed { @@ -282,17 +306,27 @@ fn new_parsed_command( fn new_exec_command_generic( command: &[String], output: Option<&CommandOutput>, + start_time: Option, ) -> Vec> { let mut lines: Vec> = Vec::new(); let command_escaped = strip_bash_lc_and_escape(command); let mut cmd_lines = command_escaped.lines(); if let Some(first) = cmd_lines.next() { - lines.push(Line::from(vec![ - "⚑ Running ".to_string().magenta(), - first.to_string().into(), - ])); + let mut spans: Vec = vec!["⚑ Running".magenta()]; + if let Some(st) = start_time { + let dur = exec_duration(st); + spans.push(format!(" β€’ {dur}").dim()); + } + spans.push(" ".into()); + spans.push(first.to_string().into()); + lines.push(Line::from(spans)); } else { - lines.push(Line::from("⚑ Running".to_string().magenta())); + let mut spans: Vec = vec!["⚑ Running".magenta()]; + if let Some(st) = start_time { + let dur = exec_duration(st); + spans.push(format!(" β€’ {dur}").dim()); + } + lines.push(Line::from(spans)); } for cont in cmd_lines { lines.push(Line::from(cont.to_string())); @@ -866,7 +900,7 @@ mod tests { let parsed = vec![ParsedCommand::Unknown { cmd: "printf 'foo\nbar'".to_string(), }]; - let lines = exec_command_lines(&[], &parsed, None); + let lines = exec_command_lines(&[], &parsed, None, None); assert!(lines.len() >= 3); assert_eq!(lines[1].spans[0].content, " β”” "); assert_eq!(lines[2].spans[0].content, " "); From 333803ed04efe657f9117b5018e8e952dd54fd0d Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 14 Aug 2025 17:00:19 -0700 Subject: [PATCH 07/16] fix: ensure rust-ci always "runs" when a PR is submitted (#2324) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Our existing path filters for `rust-ci.yml`: https://github.com/openai/codex/blob/235987843c3d6647c0819c1071f9b9f064673e9c/.github/workflows/rust-ci.yml#L1-L11 made it so that PRs that touch only `README.md` would not trigger those builds, which is a problem because our branch protection rules are set as follows: Screenshot 2025-08-14 at 4 45
59β€―PM With the existing setup, a change to `README.md` would get stuck in limbo because not all the CI jobs required to merge would get run. It turns out that we need to "run" all the jobs, but make them no-ops when the `codex-rs` and `.github` folders are untouched to get the best of both worlds. I asked chat how to fix this, as we want CI to be fast for documentation-only changes. It had two suggestions: - Use https://github.com/dorny/paths-filter or some other third-party action. - Write an inline Bash script to avoid a third-party dependency. This PR takes the latter approach so that we are clear about what we're running in CI. --- .github/workflows/rust-ci.yml | 63 ++++++++++++++++++++++++++--------- 1 file changed, 48 insertions(+), 15 deletions(-) diff --git a/.github/workflows/rust-ci.yml b/.github/workflows/rust-ci.yml index 735a187a78..1861233abf 100644 --- a/.github/workflows/rust-ci.yml +++ b/.github/workflows/rust-ci.yml @@ -1,29 +1,60 @@ name: rust-ci on: - pull_request: - branches: - - main - paths: - - "codex-rs/**" - - ".github/**" + pull_request: {} push: branches: - main - workflow_dispatch: -# For CI, we build in debug (`--profile dev`) rather than release mode so we -# get signal faster. +# CI builds in debug (dev) for faster signal. jobs: - # CI that don't need specific targets + # --- Detect what changed (always runs) ------------------------------------- + changed: + name: Detect changed areas + runs-on: ubuntu-24.04 + outputs: + codex: ${{ steps.detect.outputs.codex }} + workflows: ${{ steps.detect.outputs.workflows }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Detect changed paths (no external action) + id: detect + shell: bash + run: | + set -euo pipefail + + if [[ "${{ github.event_name }}" == "pull_request" ]]; then + BASE_SHA='${{ github.event.pull_request.base.sha }}' + echo "Base SHA: $BASE_SHA" + # List files changed between base and current HEAD (merge-base aware) + mapfile -t files < <(git diff --name-only --no-renames "$BASE_SHA"...HEAD) + else + # On push / manual runs, default to running everything + files=("codex-rs/force" ".github/force") + fi + + codex=false + workflows=false + for f in "${files[@]}"; do + [[ $f == codex-rs/* ]] && codex=true + [[ $f == .github/* ]] && workflows=true + done + + echo "codex=$codex" >> "$GITHUB_OUTPUT" + echo "workflows=$workflows" >> "$GITHUB_OUTPUT" + + # --- CI that doesn't need specific targets --------------------------------- general: name: Format / etc runs-on: ubuntu-24.04 + needs: changed + if: ${{ needs.changed.outputs.codex == 'true' || needs.changed.outputs.workflows == 'true' || github.event_name == 'push' }} defaults: run: working-directory: codex-rs - steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@1.88 @@ -32,11 +63,13 @@ jobs: - name: cargo fmt run: cargo fmt -- --config imports_granularity=Item --check - # CI to validate on different os/targets + # --- CI to validate on different os/targets -------------------------------- lint_build_test: name: ${{ matrix.runner }} - ${{ matrix.target }}${{ matrix.profile == 'release' && ' (release)' || '' }} runs-on: ${{ matrix.runner }} timeout-minutes: 30 + needs: changed + if: ${{ needs.changed.outputs.codex == 'true' || needs.changed.outputs.workflows == 'true' || github.event_name == 'push' }} defaults: run: working-directory: codex-rs @@ -44,8 +77,6 @@ jobs: strategy: fail-fast: false matrix: - # Note: While Codex CLI does not support Windows today, we include - # Windows in CI to ensure the code at least builds there. include: - runner: macos-14 target: aarch64-apple-darwin @@ -113,7 +144,9 @@ jobs: id: build if: ${{ matrix.target == 'x86_64-unknown-linux-gnu' && matrix.profile != 'release' }} continue-on-error: true - run: find . -name Cargo.toml -mindepth 2 -maxdepth 2 -print0 | xargs -0 -n1 -I{} bash -c 'cd "$(dirname "{}")" && cargo build --profile ${{ matrix.profile }}' + run: | + find . -name Cargo.toml -mindepth 2 -maxdepth 2 -print0 \ + | xargs -0 -n1 -I{} bash -c 'cd "$(dirname "{}")" && cargo build --profile ${{ matrix.profile }}' - name: cargo test id: test From afc377bae545398b0d41f9dcc7e541b191a8960e Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Thu, 14 Aug 2025 20:01:19 -0400 Subject: [PATCH 08/16] clear running commands in various places (#2325) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit we have a very unclear lifecycle for the chatwidgetβ€”this should only have to be added in one place! but this fixes the "hanging commands" issue where the active_exec_cell wasn't correctly cleared when commands finished. To repro w/o this PR: 1. prompt "run sleep 10" 2. once the command starts running, press Esc 3. prompt "run echo hi" Expected: ``` βœ“ Completed β”” ⌨️ echo hi codex hi ``` Actual: ``` βš™οΈŽ Working β”” ⌨️ echo hi β–Œ Ask Codex to do anything ``` i.e. the "Working" never changes to "Completed". The bug is fixed with this PR. --- codex-rs/tui/src/chatwidget.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 3fa78279ec..7cd7e6fad9 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -182,6 +182,7 @@ impl ChatWidget<'_> { } // Mark task stopped and request redraw now that all content is in history. self.bottom_pane.set_task_running(false); + self.running_commands.clear(); self.mark_needs_redraw(); } @@ -198,6 +199,7 @@ impl ChatWidget<'_> { fn on_error(&mut self, message: String) { self.add_to_history(&history_cell::new_error_event(message)); self.bottom_pane.set_task_running(false); + self.running_commands.clear(); self.stream.clear_all(); self.mark_needs_redraw(); } @@ -473,6 +475,7 @@ impl ChatWidget<'_> { fn interrupt_running_task(&mut self) { if self.bottom_pane.is_task_running() { self.active_exec_cell = None; + self.running_commands.clear(); self.bottom_pane.clear_ctrl_c_quit_hint(); self.submit_op(Op::Interrupt); self.bottom_pane.set_task_running(false); From e9b597cfa3c78a239c914ad1ff0ff2c6f5e3310a Mon Sep 17 00:00:00 2001 From: easong-openai Date: Thu, 14 Aug 2025 17:11:26 -0700 Subject: [PATCH 09/16] Port login server to rust (#2294) Port the login server to rust. --------- Co-authored-by: pakrym-oai --- codex-rs/Cargo.lock | 213 +++- codex-rs/cli/src/login.rs | 44 +- codex-rs/login/Cargo.toml | 8 +- codex-rs/login/src/assets/success.html | 198 ++++ codex-rs/login/src/lib.rs | 204 ++-- codex-rs/login/src/login_with_chatgpt.py | 933 ------------------ codex-rs/login/src/pkce.rs | 27 + codex-rs/login/src/server.rs | 443 +++++++++ codex-rs/login/src/token_data.rs | 17 +- codex-rs/login/tests/login_server_e2e.rs | 192 ++++ codex-rs/tui/src/app.rs | 4 + codex-rs/tui/src/onboarding/auth.rs | 30 +- .../tui/src/onboarding/onboarding_screen.rs | 12 + 13 files changed, 1228 insertions(+), 1097 deletions(-) create mode 100644 codex-rs/login/src/assets/success.html delete mode 100644 codex-rs/login/src/login_with_chatgpt.py create mode 100644 codex-rs/login/src/pkce.rs create mode 100644 codex-rs/login/src/server.rs create mode 100644 codex-rs/login/tests/login_server_e2e.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 41392633be..8f077bc0ab 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -203,6 +203,12 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +[[package]] +name = "ascii" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" + [[package]] name = "ascii-canvas" version = "3.0.0" @@ -481,6 +487,12 @@ dependencies = [ "shlex", ] +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + [[package]] name = "cfg-expr" version = "0.15.8" @@ -518,6 +530,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "chunked_transfer" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901" + [[package]] name = "clap" version = "4.5.43" @@ -798,12 +816,18 @@ dependencies = [ "base64 0.22.1", "chrono", "pretty_assertions", + "rand 0.8.5", "reqwest", "serde", "serde_json", + "sha2", "tempfile", "thiserror 2.0.12", + "tiny_http", "tokio", + "url", + "urlencoding", + "webbrowser", ] [[package]] @@ -951,6 +975,16 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "compact_str" version = "0.8.1" @@ -1005,6 +1039,16 @@ dependencies = [ "libc", ] +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -2455,6 +2499,28 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" + [[package]] name = "jobserver" version = "0.1.33" @@ -2791,6 +2857,12 @@ dependencies = [ "tempfile", ] +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + [[package]] name = "new_debug_unreachable" version = "1.0.6" @@ -2944,6 +3016,31 @@ dependencies = [ "libc", ] +[[package]] +name = "objc2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "561f357ba7f3a2a61563a186a163d0a3a5247e1089524a3981d49adb775078bc" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900831247d2fe1a09a683278e5384cfb8c80c79fe6b166f9d14bfdde0ea1b03c" +dependencies = [ + "bitflags 2.9.1", + "objc2", +] + [[package]] name = "object" version = "0.36.7" @@ -3670,6 +3767,7 @@ dependencies = [ "base64 0.22.1", "bytes", "encoding_rs", + "futures-channel", "futures-core", "futures-util", "h2", @@ -3992,7 +4090,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" dependencies = [ "bitflags 2.9.1", - "core-foundation", + "core-foundation 0.9.4", "core-foundation-sys", "libc", "security-framework-sys", @@ -4151,6 +4249,17 @@ dependencies = [ "digest", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -4515,7 +4624,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" dependencies = [ "bitflags 2.9.1", - "core-foundation", + "core-foundation 0.9.4", "system-configuration-sys", ] @@ -4710,6 +4819,18 @@ dependencies = [ "crunchy", ] +[[package]] +name = "tiny_http" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82" +dependencies = [ + "ascii", + "chunked_transfer", + "httpdate", + "log", +] + [[package]] name = "tinystr" version = "0.8.1" @@ -5162,6 +5283,12 @@ dependencies = [ "serde", ] +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -5385,6 +5512,22 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webbrowser" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf4f3c0ba838e82b4e5ccc4157003fb8c324ee24c058470ffb82820becbde98" +dependencies = [ + "core-foundation 0.10.1", + "jni", + "log", + "ndk-context", + "objc2", + "objc2-foundation", + "url", + "web-sys", +] + [[package]] name = "weezl" version = "0.1.10" @@ -5573,6 +5716,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + [[package]] name = "windows-sys" version = "0.52.0" @@ -5600,6 +5752,21 @@ dependencies = [ "windows-targets 0.53.2", ] +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + [[package]] name = "windows-targets" version = "0.52.6" @@ -5632,6 +5799,12 @@ dependencies = [ "windows_x86_64_msvc 0.53.0", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -5644,6 +5817,12 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" @@ -5656,6 +5835,12 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -5680,6 +5865,12 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + [[package]] name = "windows_i686_msvc" version = "0.52.6" @@ -5692,6 +5883,12 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" @@ -5704,6 +5901,12 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" @@ -5716,6 +5919,12 @@ version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" diff --git a/codex-rs/cli/src/login.rs b/codex-rs/cli/src/login.rs index 1a70bd27b6..895eeb1089 100644 --- a/codex-rs/cli/src/login.rs +++ b/codex-rs/cli/src/login.rs @@ -1,20 +1,54 @@ -use std::env; - use codex_common::CliConfigOverrides; use codex_core::config::Config; use codex_core::config::ConfigOverrides; use codex_login::AuthMode; +use codex_login::CLIENT_ID; use codex_login::CodexAuth; +use codex_login::LoginServerInfo; use codex_login::OPENAI_API_KEY_ENV_VAR; +use codex_login::ServerOptions; use codex_login::login_with_api_key; -use codex_login::login_with_chatgpt; use codex_login::logout; +use codex_login::run_server_blocking_with_notify; +use std::env; +use std::path::Path; +use std::sync::mpsc; + +pub async fn login_with_chatgpt(codex_home: &Path) -> std::io::Result<()> { + let (tx, rx) = mpsc::channel::(); + let client_id = CLIENT_ID; + let codex_home = codex_home.to_path_buf(); + tokio::spawn(async move { + match rx.recv() { + Ok(LoginServerInfo { + auth_url, + actual_port, + }) => { + eprintln!( + "Starting local login server on http://localhost:{actual_port}.\nIf your browser did not open, navigate to this URL to authenticate:\n\n{auth_url}", + ); + } + _ => { + tracing::error!("Failed to receive login server info"); + } + } + }); + + tokio::task::spawn_blocking(move || { + let opts = ServerOptions::new(&codex_home, client_id); + run_server_blocking_with_notify(opts, Some(tx), None) + }) + .await + .map_err(std::io::Error::other)??; + + eprintln!("Successfully logged in"); + Ok(()) +} pub async fn run_login_with_chatgpt(cli_config_overrides: CliConfigOverrides) -> ! { let config = load_config_or_exit(cli_config_overrides); - let capture_output = false; - match login_with_chatgpt(&config.codex_home, capture_output).await { + match login_with_chatgpt(&config.codex_home).await { Ok(_) => { eprintln!("Successfully logged in"); std::process::exit(0); diff --git a/codex-rs/login/Cargo.toml b/codex-rs/login/Cargo.toml index 85c11505ec..c1e21ca627 100644 --- a/codex-rs/login/Cargo.toml +++ b/codex-rs/login/Cargo.toml @@ -9,11 +9,14 @@ workspace = true [dependencies] base64 = "0.22" chrono = { version = "0.4", features = ["serde"] } -reqwest = { version = "0.12", features = ["json"] } +rand = "0.8" +reqwest = { version = "0.12", features = ["json", "blocking"] } serde = { version = "1", features = ["derive"] } serde_json = "1" +sha2 = "0.10" tempfile = "3" thiserror = "2.0.12" +tiny_http = "0.12" tokio = { version = "1", features = [ "io-std", "macros", @@ -21,6 +24,9 @@ tokio = { version = "1", features = [ "rt-multi-thread", "signal", ] } +url = "2" +urlencoding = "2.1" +webbrowser = "1.0" [dev-dependencies] pretty_assertions = "1.4.1" diff --git a/codex-rs/login/src/assets/success.html b/codex-rs/login/src/assets/success.html new file mode 100644 index 0000000000..eb2a0ee719 --- /dev/null +++ b/codex-rs/login/src/assets/success.html @@ -0,0 +1,198 @@ + + + + + Sign into Codex CLI + + + + +

+
+
+ +
Signed in to Codex CLI
+
+ + +
+
+ + + + \ No newline at end of file diff --git a/codex-rs/login/src/lib.rs b/codex-rs/login/src/lib.rs index a1dad79e9d..d4358d2735 100644 --- a/codex-rs/login/src/lib.rs +++ b/codex-rs/login/src/lib.rs @@ -1,5 +1,4 @@ use chrono::DateTime; - use chrono::Utc; use serde::Deserialize; use serde::Serialize; @@ -9,27 +8,26 @@ use std::fs::OpenOptions; use std::fs::remove_file; use std::io::Read; use std::io::Write; -use std::io::{self}; #[cfg(unix)] use std::os::unix::fs::OpenOptionsExt; use std::path::Path; use std::path::PathBuf; -use std::process::Child; -use std::process::Stdio; use std::sync::Arc; use std::sync::Mutex; use std::time::Duration; -use tempfile::NamedTempFile; -use tokio::process::Command; +pub use crate::server::LoginServerInfo; +pub use crate::server::ServerOptions; +pub use crate::server::run_server_blocking; +pub use crate::server::run_server_blocking_with_notify; pub use crate::token_data::TokenData; use crate::token_data::parse_id_token; +mod pkce; +mod server; mod token_data; -const SOURCE_FOR_PYTHON_SERVER: &str = include_str!("./login_with_chatgpt.py"); - -const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann"; +pub const CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann"; pub const OPENAI_API_KEY_ENV_VAR: &str = "OPENAI_API_KEY"; #[derive(Clone, Debug, PartialEq, Copy)] @@ -254,139 +252,65 @@ pub fn logout(codex_home: &Path) -> std::io::Result { } } -/// Represents a running login subprocess. The child can be killed by holding -/// the mutex and calling `kill()`. +/// Represents a running login server. The server can be stopped by calling `cancel()` on SpawnedLogin. #[derive(Debug, Clone)] pub struct SpawnedLogin { - pub child: Arc>, - pub stdout: Arc>>, - pub stderr: Arc>>, + url: Arc>>, + done: Arc>>, + shutdown: Arc, } impl SpawnedLogin { - /// Returns the login URL, if one has been emitted by the login subprocess. - /// - /// The Python helper prints the URL to stderr; we capture it and extract - /// the last whitespace-separated token that starts with "http". pub fn get_login_url(&self) -> Option { - self.stderr - .lock() - .ok() - .and_then(|buffer| String::from_utf8(buffer.clone()).ok()) - .and_then(|output| { - output - .split_whitespace() - .filter(|part| part.starts_with("http")) - .next_back() - .map(|s| s.to_string()) - }) + self.url.lock().ok().and_then(|u| u.clone()) + } + + pub fn get_auth_result(&self) -> Option { + self.done.lock().ok().and_then(|d| *d) + } + + pub fn cancel(&self) { + self.shutdown + .store(true, std::sync::atomic::Ordering::SeqCst); } } -// Helpers for streaming child output into shared buffers -struct AppendWriter { - buf: Arc>>, -} - -impl Write for AppendWriter { - fn write(&mut self, data: &[u8]) -> io::Result { - if let Ok(mut b) = self.buf.lock() { - b.extend_from_slice(data); - } - Ok(data.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -fn spawn_pipe_reader(mut reader: R, buf: Arc>>) { - std::thread::spawn(move || { - let _ = io::copy(&mut reader, &mut AppendWriter { buf }); - }); -} - -/// Spawn the ChatGPT login Python server as a child process and return a handle to its process. pub fn spawn_login_with_chatgpt(codex_home: &Path) -> std::io::Result { - let script_path = write_login_script_to_disk()?; - let mut cmd = std::process::Command::new("python3"); - cmd.arg(&script_path) - .env("CODEX_HOME", codex_home) - .env("CODEX_CLIENT_ID", CLIENT_ID) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); + let (tx, rx) = std::sync::mpsc::channel::(); + let shutdown = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let done = Arc::new(Mutex::new(None::)); + let url = Arc::new(Mutex::new(None::)); - let mut child = cmd.spawn()?; + let codex_home_buf = codex_home.to_path_buf(); + let client_id = CLIENT_ID.to_string(); - let stdout_buf = Arc::new(Mutex::new(Vec::new())); - let stderr_buf = Arc::new(Mutex::new(Vec::new())); + let shutdown_clone = shutdown.clone(); + let done_clone = done.clone(); + std::thread::spawn(move || { + let opts = ServerOptions::new(&codex_home_buf, &client_id); + let res = run_server_blocking_with_notify(opts, Some(tx), Some(shutdown_clone)); + let success = res.is_ok(); + if let Ok(mut lock) = done_clone.lock() { + *lock = Some(success); + } + }); - if let Some(out) = child.stdout.take() { - spawn_pipe_reader(out, stdout_buf.clone()); - } - if let Some(err) = child.stderr.take() { - spawn_pipe_reader(err, stderr_buf.clone()); - } + let url_clone = url.clone(); + std::thread::spawn(move || { + if let Ok(u) = rx.recv() { + if let Ok(mut lock) = url_clone.lock() { + *lock = Some(u.auth_url); + } + } + }); Ok(SpawnedLogin { - child: Arc::new(Mutex::new(child)), - stdout: stdout_buf, - stderr: stderr_buf, + url, + done, + shutdown, }) } -/// Run `python3 -c {{SOURCE_FOR_PYTHON_SERVER}}` with the CODEX_HOME -/// environment variable set to the provided `codex_home` path. If the -/// subprocess exits 0, read the OPENAI_API_KEY property out of -/// CODEX_HOME/auth.json and return Ok(OPENAI_API_KEY). Otherwise, return Err -/// with any information from the subprocess. -/// -/// If `capture_output` is true, the subprocess's output will be captured and -/// recorded in memory. Otherwise, the subprocess's output will be sent to the -/// current process's stdout/stderr. -pub async fn login_with_chatgpt(codex_home: &Path, capture_output: bool) -> std::io::Result<()> { - let script_path = write_login_script_to_disk()?; - let child = Command::new("python3") - .arg(&script_path) - .env("CODEX_HOME", codex_home) - .env("CODEX_CLIENT_ID", CLIENT_ID) - .stdin(Stdio::null()) - .stdout(if capture_output { - Stdio::piped() - } else { - Stdio::inherit() - }) - .stderr(if capture_output { - Stdio::piped() - } else { - Stdio::inherit() - }) - .spawn()?; - - let output = child.wait_with_output().await?; - if output.status.success() { - Ok(()) - } else { - let stderr = String::from_utf8_lossy(&output.stderr); - Err(std::io::Error::other(format!( - "login_with_chatgpt subprocess failed: {stderr}" - ))) - } -} - -fn write_login_script_to_disk() -> std::io::Result { - // Write the embedded Python script to a file to avoid very long - // command-line arguments (Windows error 206). - let mut tmp = NamedTempFile::new()?; - tmp.write_all(SOURCE_FOR_PYTHON_SERVER.as_bytes())?; - tmp.flush()?; - - let (_file, path) = tmp.keep()?; - Ok(path) -} - pub fn login_with_api_key(codex_home: &Path, api_key: &str) -> std::io::Result<()> { let auth_dot_json = AuthDotJson { openai_api_key: Some(api_key.to_string()), @@ -538,7 +462,7 @@ mod tests { } #[tokio::test] - async fn pro_account_with_no_api_key_uses_chatgpt_auth() { + async fn roundtrip_auth_dot_json() { let codex_home = tempdir().unwrap(); write_auth_file( AuthFileParams { @@ -549,6 +473,26 @@ mod tests { ) .expect("failed to write auth file"); + let file = get_auth_file(codex_home.path()); + let auth_dot_json = try_read_auth_json(&file).unwrap(); + write_auth_json(&file, &auth_dot_json).unwrap(); + + let same_auth_dot_json = try_read_auth_json(&file).unwrap(); + assert_eq!(auth_dot_json, same_auth_dot_json); + } + + #[tokio::test] + async fn pro_account_with_no_api_key_uses_chatgpt_auth() { + let codex_home = tempdir().unwrap(); + let fake_jwt = write_auth_file( + AuthFileParams { + openai_api_key: None, + chatgpt_plan_type: "pro".to_string(), + }, + codex_home.path(), + ) + .expect("failed to write auth file"); + let CodexAuth { api_key, mode, @@ -567,6 +511,7 @@ mod tests { id_token: IdTokenInfo { email: Some("user@example.com".to_string()), chatgpt_plan_type: Some(PlanType::Known(KnownPlan::Pro)), + raw_jwt: fake_jwt, }, access_token: "test-access-token".to_string(), refresh_token: "test-refresh-token".to_string(), @@ -588,7 +533,7 @@ mod tests { #[tokio::test] async fn pro_account_with_api_key_still_uses_chatgpt_auth() { let codex_home = tempdir().unwrap(); - write_auth_file( + let fake_jwt = write_auth_file( AuthFileParams { openai_api_key: Some("sk-test-key".to_string()), chatgpt_plan_type: "pro".to_string(), @@ -615,6 +560,7 @@ mod tests { id_token: IdTokenInfo { email: Some("user@example.com".to_string()), chatgpt_plan_type: Some(PlanType::Known(KnownPlan::Pro)), + raw_jwt: fake_jwt, }, access_token: "test-access-token".to_string(), refresh_token: "test-refresh-token".to_string(), @@ -662,7 +608,7 @@ mod tests { chatgpt_plan_type: String, } - fn write_auth_file(params: AuthFileParams, codex_home: &Path) -> std::io::Result<()> { + fn write_auth_file(params: AuthFileParams, codex_home: &Path) -> std::io::Result { let auth_file = get_auth_file(codex_home); // Create a minimal valid JWT for the id_token field. #[derive(Serialize)] @@ -700,7 +646,9 @@ mod tests { "last_refresh": LAST_REFRESH, }); let auth_json = serde_json::to_string_pretty(&auth_json_data)?; - std::fs::write(auth_file, auth_json) + std::fs::write(auth_file, auth_json)?; + + Ok(fake_jwt) } #[test] diff --git a/codex-rs/login/src/login_with_chatgpt.py b/codex-rs/login/src/login_with_chatgpt.py deleted file mode 100644 index 252c4e06ae..0000000000 --- a/codex-rs/login/src/login_with_chatgpt.py +++ /dev/null @@ -1,933 +0,0 @@ -"""Script that spawns a local webserver for retrieving an OpenAI API key. - -- Listens on 127.0.0.1:1455 -- Opens http://localhost:1455/auth/callback in the browser -- If the user successfully navigates the auth flow, - $CODEX_HOME/auth.json will be written with the API key. -- User will be redirected to http://localhost:1455/success upon success. - -The script should exit with a non-zero code if the user fails to navigate the -auth flow. - -To test this script locally without overwriting your existing auth.json file: - -``` -rm -rf /tmp/codex_home && mkdir /tmp/codex_home -CODEX_HOME=/tmp/codex_home python3 codex-rs/login/src/login_with_chatgpt.py -``` -""" - -from __future__ import annotations - -import argparse -import base64 -import datetime -import errno -import hashlib -import http.server -import json -import os -import secrets -import sys -import threading -import time -import urllib.parse -import urllib.request -import webbrowser -from dataclasses import dataclass -from typing import Any, Dict # for type hints - -# Required port for OAuth client. -REQUIRED_PORT = 1455 -URL_BASE = f"http://localhost:{REQUIRED_PORT}" -DEFAULT_ISSUER = "https://auth.openai.com" - -EXIT_CODE_WHEN_ADDRESS_ALREADY_IN_USE = 13 - -CA_CONTEXT = None -CODEX_LOGIN_TRACE = os.environ.get("CODEX_LOGIN_TRACE", "false") in ["true", "1"] - -try: - - def trace(msg: str) -> None: - if CODEX_LOGIN_TRACE: - print(msg) - - def attempt_request(method: str) -> bool: - try: - with urllib.request.urlopen( - urllib.request.Request( - f"{DEFAULT_ISSUER}/.well-known/openid-configuration", - method="GET", - ), - context=CA_CONTEXT, - ) as resp: - if resp.status != 200: - trace(f"Request using {method} failed: {resp.status}") - return False - - trace(f"Request using {method} succeeded") - return True - except Exception as e: - trace(f"Request using {method} failed: {e}") - return False - - status = attempt_request("default settings") - if not status: - try: - import truststore - - truststore.inject_into_ssl() - status = attempt_request("truststore") - except Exception as e: - trace(f"Failed to use truststore: {e}") - - if not status: - try: - import ssl - import certifi as _certifi - - CA_CONTEXT = ssl.create_default_context(cafile=_certifi.where()) - status = attempt_request("certify") - except Exception as e: - trace(f"Failed to use certify: {e}") - - -except Exception: - pass - - -@dataclass -class TokenData: - id_token: str - access_token: str - refresh_token: str - account_id: str - - -@dataclass -class AuthBundle: - """Aggregates authentication data produced after successful OAuth flow.""" - - api_key: str | None - token_data: TokenData - last_refresh: str - - -def main() -> None: - parser = argparse.ArgumentParser(description="Retrieve API key via local HTTP flow") - parser.add_argument( - "--no-browser", - action="store_true", - help="Do not automatically open the browser", - ) - parser.add_argument("--verbose", action="store_true", help="Enable request logging") - args = parser.parse_args() - - codex_home = os.environ.get("CODEX_HOME") - if not codex_home: - eprint("ERROR: CODEX_HOME environment variable is not set") - sys.exit(1) - - client_id = os.getenv("CODEX_CLIENT_ID") - if not client_id: - eprint("ERROR: CODEX_CLIENT_ID environment variable is not set") - sys.exit(1) - - # Spawn server. - try: - httpd = _ApiKeyHTTPServer( - ("127.0.0.1", REQUIRED_PORT), - _ApiKeyHTTPHandler, - codex_home=codex_home, - client_id=client_id, - verbose=args.verbose, - ) - except OSError as e: - eprint(f"ERROR: {e}") - if e.errno == errno.EADDRINUSE: - # Caller might want to handle this case specially. - sys.exit(EXIT_CODE_WHEN_ADDRESS_ALREADY_IN_USE) - else: - sys.exit(1) - - auth_url = httpd.auth_url() - - with httpd: - eprint(f"Starting local login server on {URL_BASE}") - if not args.no_browser: - try: - webbrowser.open(auth_url, new=1, autoraise=True) - except Exception as e: - eprint(f"Failed to open browser: {e}") - - eprint( - f". If your browser did not open, navigate to this URL to authenticate: \n\n{auth_url}" - ) - - # Run the server in the main thread until `shutdown()` is called by the - # request handler. - try: - httpd.serve_forever() - except KeyboardInterrupt: - eprint("\nKeyboard interrupt received, exiting.") - - # Server has been shut down by the request handler. Exit with the code - # it set (0 on success, non-zero on failure). - sys.exit(httpd.exit_code) - - -class _ApiKeyHTTPHandler(http.server.BaseHTTPRequestHandler): - """A minimal request handler that captures an *api key* from query/post.""" - - # We store the result in the server instance itself. - server: "_ApiKeyHTTPServer" # type: ignore[override] - helpful annotation - - def do_GET(self) -> None: # noqa: N802 – required by BaseHTTPRequestHandler - path = urllib.parse.urlparse(self.path).path - - if path == "/success": - # Serve confirmation page then gracefully shut down the server so - # the main thread can exit with the previously captured exit code. - self._send_html(LOGIN_SUCCESS_HTML) - - # Ensure the data is flushed to the client before we stop. - try: - self.wfile.flush() - except Exception as e: - eprint(f"Failed to flush response: {e}") - - self.request_shutdown() - elif path == "/auth/callback": - query = urllib.parse.urlparse(self.path).query - params = urllib.parse.parse_qs(query) - - # Validate state ------------------------------------------------- - if params.get("state", [None])[0] != self.server.state: - self.send_error(400, "State parameter mismatch") - return - - # Standard OAuth flow ----------------------------------------- - code = params.get("code", [None])[0] - if not code: - self.send_error(400, "Missing authorization code") - return - - try: - auth_bundle, success_url = self._exchange_code(code) - except Exception as exc: # noqa: BLE001 – propagate to client - self.send_error(500, f"Token exchange failed: {exc}") - return - - # Persist API key along with additional token metadata. - if _write_auth_file( - auth=auth_bundle, - codex_home=self.server.codex_home, - ): - self.server.exit_code = 0 - self._send_redirect(success_url) - else: - self.send_error(500, "Unable to persist auth file") - else: - self.send_error(404, "Endpoint not supported") - - def do_POST(self) -> None: # noqa: N802 – required by BaseHTTPRequestHandler - self.send_error(404, "Endpoint not supported") - - def send_error(self, code, message=None, explain=None) -> None: - """Send an error response and stop the server. - - We avoid calling `sys.exit()` directly from the request-handling thread - so that the response has a chance to be written to the socket. Instead - we shut the server down; the main thread will then exit with the - appropriate status code. - """ - super().send_error(code, message, explain) - try: - self.wfile.flush() - except Exception as e: - eprint(f"Failed to flush response: {e}") - - self.request_shutdown() - - def _send_redirect(self, url: str) -> None: - self.send_response(302) - self.send_header("Location", url) - self.end_headers() - - def _send_html(self, body: str) -> None: - encoded = body.encode() - self.send_response(200) - self.send_header("Content-Type", "text/html; charset=utf-8") - self.send_header("Content-Length", str(len(encoded))) - self.end_headers() - self.wfile.write(encoded) - - # Silence logging for cleanliness unless --verbose flag is used. - def log_message(self, fmt: str, *args): # type: ignore[override] - if getattr(self.server, "verbose", False): # type: ignore[attr-defined] - super().log_message(fmt, *args) - - def _obtain_api_key( - self, - token_claims: Dict[str, Any], - access_claims: Dict[str, Any], - token_data: TokenData, - ) -> tuple[str | None, str | None]: - """Obtain an API key from the auth service. - - Returns (api_key, success_url) if successful, None otherwise. - """ - - org_id = token_claims.get("organization_id") - project_id = token_claims.get("project_id") - - if not org_id or not project_id: - return (None, None) - - random_id = secrets.token_hex(6) - - # 2. Token exchange to obtain API key - today = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d") - exchange_data = urllib.parse.urlencode( - { - "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange", - "client_id": self.server.client_id, - "requested_token": "openai-api-key", - "subject_token": token_data.id_token, - "subject_token_type": "urn:ietf:params:oauth:token-type:id_token", - "name": f"Codex CLI [auto-generated] ({today}) [{random_id}]", - } - ).encode() - - exchanged_access_token: str - with urllib.request.urlopen( - urllib.request.Request( - self.server.token_endpoint, - data=exchange_data, - method="POST", - headers={"Content-Type": "application/x-www-form-urlencoded"}, - ), - context=CA_CONTEXT, - ) as resp: - exchange_payload = json.loads(resp.read().decode()) - exchanged_access_token = exchange_payload["access_token"] - - # Determine whether the organization still requires additional - # setup (e.g., adding a payment method) based on the ID-token - # claim provided by the auth service. - completed_onboarding = token_claims.get("completed_platform_onboarding") == True - chatgpt_plan_type = access_claims.get("chatgpt_plan_type") - is_org_owner = token_claims.get("is_org_owner") == True - needs_setup = not completed_onboarding and is_org_owner - - # Build the success URL on the same host/port as the callback and - # include the required query parameters for the front-end page. - success_url_query = { - "id_token": token_data.id_token, - "needs_setup": "true" if needs_setup else "false", - "org_id": org_id, - "project_id": project_id, - "plan_type": chatgpt_plan_type, - "platform_url": ( - "https://platform.openai.com" - if self.server.issuer == "https://auth.openai.com" - else "https://platform.api.openai.org" - ), - } - success_url = f"{URL_BASE}/success?{urllib.parse.urlencode(success_url_query)}" - - # Attempt to redeem complimentary API credits for eligible ChatGPT - # Plus / Pro subscribers. Any errors are logged but do not interrupt - # the login flow. - - try: - maybe_redeem_credits( - issuer=self.server.issuer, - client_id=self.server.client_id, - id_token=token_data.id_token, - refresh_token=token_data.refresh_token, - codex_home=self.server.codex_home, - ) - except Exception as exc: # pragma: no cover – best-effort only - eprint(f"Unable to redeem ChatGPT subscriber API credits: {exc}") - - return (exchanged_access_token, success_url) - - def _exchange_code(self, code: str) -> tuple[AuthBundle, str]: - """Perform token + token-exchange to obtain an OpenAI API key. - - Returns (AuthBundle, success_url). - """ - - # 1. Authorization-code -> (id_token, access_token, refresh_token) - data = urllib.parse.urlencode( - { - "grant_type": "authorization_code", - "code": code, - "redirect_uri": self.server.redirect_uri, - "client_id": self.server.client_id, - "code_verifier": self.server.pkce.code_verifier, - } - ).encode() - - token_data: TokenData - - with urllib.request.urlopen( - urllib.request.Request( - self.server.token_endpoint, - data=data, - method="POST", - headers={"Content-Type": "application/x-www-form-urlencoded"}, - ), - context=CA_CONTEXT, - ) as resp: - payload = json.loads(resp.read().decode()) - - # Extract chatgpt_account_id from id_token - id_token_parts = payload["id_token"].split(".") - if len(id_token_parts) != 3: - raise ValueError("Invalid ID token") - id_token_claims = _decode_jwt_segment(id_token_parts[1]) - auth_claims = id_token_claims.get("https://api.openai.com/auth", {}) - chatgpt_account_id = auth_claims.get("chatgpt_account_id", "") - - token_data = TokenData( - id_token=payload["id_token"], - access_token=payload["access_token"], - refresh_token=payload["refresh_token"], - account_id=chatgpt_account_id, - ) - - access_token_parts = token_data.access_token.split(".") - if len(access_token_parts) != 3: - raise ValueError("Invalid access token") - - access_token_claims = _decode_jwt_segment(access_token_parts[1]) - - token_claims = id_token_claims.get("https://api.openai.com/auth", {}) - access_claims = access_token_claims.get("https://api.openai.com/auth", {}) - - exchanged_access_token, success_url = self._obtain_api_key( - token_claims, access_claims, token_data - ) - - # Persist refresh_token/id_token for future use (redeem credits etc.) - last_refresh_str = ( - datetime.datetime.now(datetime.timezone.utc) - .isoformat() - .replace("+00:00", "Z") - ) - - auth_bundle = AuthBundle( - api_key=exchanged_access_token, - token_data=token_data, - last_refresh=last_refresh_str, - ) - - return (auth_bundle, success_url or f"{URL_BASE}/success") - - def request_shutdown(self) -> None: - # shutdown() must be invoked from another thread to avoid - # deadlocking the serve_forever() loop, which is running in this - # same thread. A short-lived helper thread does the trick. - threading.Thread(target=self.server.shutdown, daemon=True).start() - - -def _write_auth_file(*, auth: AuthBundle, codex_home: str) -> bool: - """Persist *api_key* to $CODEX_HOME/auth.json. - - Returns True on success, False otherwise. Any error is printed to - *stderr* so that the Rust layer can surface the problem. - """ - if not os.path.isdir(codex_home): - try: - os.makedirs(codex_home, exist_ok=True) - except Exception as exc: # pragma: no cover – unlikely - eprint(f"ERROR: unable to create CODEX_HOME directory: {exc}") - return False - - auth_path = os.path.join(codex_home, "auth.json") - auth_json_contents = { - "OPENAI_API_KEY": auth.api_key, - "tokens": { - "id_token": auth.token_data.id_token, - "access_token": auth.token_data.access_token, - "refresh_token": auth.token_data.refresh_token, - "account_id": auth.token_data.account_id, - }, - "last_refresh": auth.last_refresh, - } - try: - with open(auth_path, "w", encoding="utf-8") as fp: - if hasattr(os, "fchmod"): # POSIX-safe - os.fchmod(fp.fileno(), 0o600) - json.dump(auth_json_contents, fp, indent=2) - except Exception as exc: # pragma: no cover – permissions/filesystem - eprint(f"ERROR: unable to write auth file: {exc}") - return False - - return True - - -@dataclass -class PkceCodes: - code_verifier: str - code_challenge: str - - -class _ApiKeyHTTPServer(http.server.HTTPServer): - """HTTPServer with shutdown helper & self-contained OAuth configuration.""" - - def __init__( - self, - server_address: tuple[str, int], - request_handler_class: type[http.server.BaseHTTPRequestHandler], - *, - codex_home: str, - client_id: str, - verbose: bool = False, - ) -> None: - super().__init__(server_address, request_handler_class, bind_and_activate=True) - - self.exit_code = 1 - self.codex_home = codex_home - self.verbose: bool = verbose - - self.issuer: str = DEFAULT_ISSUER - self.token_endpoint: str = f"{self.issuer}/oauth/token" - self.client_id: str = client_id - port = server_address[1] - self.redirect_uri: str = f"http://localhost:{port}/auth/callback" - self.pkce: PkceCodes = _generate_pkce() - self.state: str = secrets.token_hex(32) - - def auth_url(self) -> str: - """Return fully-formed OpenID authorization URL.""" - params = { - "response_type": "code", - "client_id": self.client_id, - "redirect_uri": self.redirect_uri, - "scope": "openid profile email offline_access", - "code_challenge": self.pkce.code_challenge, - "code_challenge_method": "S256", - "id_token_add_organizations": "true", - "codex_cli_simplified_flow": "true", - "state": self.state, - } - return f"{self.issuer}/oauth/authorize?" + urllib.parse.urlencode(params) - - -def maybe_redeem_credits( - *, - issuer: str, - client_id: str, - id_token: str | None, - refresh_token: str, - codex_home: str, -) -> None: - """Attempt to redeem complimentary API credits for ChatGPT subscribers. - - The operation is best-effort: any error results in a warning being printed - and the function returning early without raising. - """ - id_claims: Dict[str, Any] | None = parse_id_token_claims(id_token or "") - - # Refresh expired ID token, if possible - token_expired = True - if id_claims and isinstance(id_claims.get("exp"), int): - token_expired = _current_timestamp_ms() >= int(id_claims["exp"]) * 1000 - - if token_expired: - eprint("Refreshing credentials...") - new_refresh_token: str | None = None - new_id_token: str | None = None - - try: - payload = json.dumps( - { - "client_id": client_id, - "grant_type": "refresh_token", - "refresh_token": refresh_token, - "scope": "openid profile email", - } - ).encode() - - req = urllib.request.Request( - url="https://auth.openai.com/oauth/token", - data=payload, - method="POST", - headers={"Content-Type": "application/json"}, - ) - - with urllib.request.urlopen(req, context=CA_CONTEXT) as resp: - refresh_data = json.loads(resp.read().decode()) - new_id_token = refresh_data.get("id_token") - new_id_claims = parse_id_token_claims(new_id_token or "") - new_refresh_token = refresh_data.get("refresh_token") - except Exception as err: - eprint("Unable to refresh ID token via token-exchange:", err) - return - - if not new_id_token or not new_refresh_token: - return - - # Update auth.json with new tokens. - try: - auth_dir = codex_home - auth_path = os.path.join(auth_dir, "auth.json") - with open(auth_path, "r", encoding="utf-8") as fp: - existing = json.load(fp) - - tokens = existing.setdefault("tokens", {}) - tokens["id_token"] = new_id_token - # Note this does not touch the access_token? - tokens["refresh_token"] = new_refresh_token - tokens["last_refresh"] = ( - datetime.datetime.now(datetime.timezone.utc) - .isoformat() - .replace("+00:00", "Z") - ) - - with open(auth_path, "w", encoding="utf-8") as fp: - if hasattr(os, "fchmod"): - os.fchmod(fp.fileno(), 0o600) - json.dump(existing, fp, indent=2) - except Exception as err: - eprint("Unable to update refresh token in auth file:", err) - - if not new_id_claims: - # Still couldn't parse claims. - return - - id_token = new_id_token - id_claims = new_id_claims - - # Done refreshing credentials: now try to redeem credits. - if not id_token: - eprint("No ID token available, cannot redeem credits.") - return - - auth_claims = id_claims.get("https://api.openai.com/auth", {}) - - # Subscription eligibility check (Plus or Pro, >7 days active) - sub_start_str = auth_claims.get("chatgpt_subscription_active_start") - if isinstance(sub_start_str, str): - try: - sub_start_ts = datetime.datetime.fromisoformat(sub_start_str.rstrip("Z")) - if datetime.datetime.now( - datetime.timezone.utc - ) - sub_start_ts < datetime.timedelta(days=7): - eprint( - "Sorry, your subscription must be active for more than 7 days to redeem credits." - ) - return - except ValueError: - # Malformed; ignore - pass - - completed_onboarding = bool(auth_claims.get("completed_platform_onboarding")) - is_org_owner = bool(auth_claims.get("is_org_owner")) - needs_setup = not completed_onboarding and is_org_owner - plan_type = auth_claims.get("chatgpt_plan_type") - - if needs_setup or plan_type not in {"plus", "pro"}: - eprint("Only users with Plus or Pro subscriptions can redeem free API credits.") - return - - api_host = ( - "https://api.openai.com" - if issuer == "https://auth.openai.com" - else "https://api.openai.org" - ) - - try: - redeem_payload = json.dumps({"id_token": id_token}).encode() - req = urllib.request.Request( - url=f"{api_host}/v1/billing/redeem_credits", - data=redeem_payload, - method="POST", - headers={"Content-Type": "application/json"}, - ) - - with urllib.request.urlopen(req, context=CA_CONTEXT) as resp: - redeem_data = json.loads(resp.read().decode()) - - granted = redeem_data.get("granted_chatgpt_subscriber_api_credits", 0) - if granted and granted > 0: - eprint( - f"""Thanks for being a ChatGPT {"Plus" if plan_type == "plus" else "Pro"} subscriber! -If you haven't already redeemed, you should receive {"$5" if plan_type == "plus" else "$50"} in API credits. - -Credits: https://platform.openai.com/settings/organization/billing/credit-grants -More info: https://help.openai.com/en/articles/11381614""", - ) - else: - eprint( - f"""It looks like no credits were granted: - -{json.dumps(redeem_data, indent=2)} - -Credits: https://platform.openai.com/settings/organization/billing/credit-grants -More info: https://help.openai.com/en/articles/11381614""" - ) - except Exception as err: - eprint("Credit redemption request failed:", err) - - -def _generate_pkce() -> PkceCodes: - """Generate PKCE *code_verifier* and *code_challenge* (S256).""" - code_verifier = secrets.token_hex(64) - digest = hashlib.sha256(code_verifier.encode()).digest() - code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode() - return PkceCodes(code_verifier, code_challenge) - - -def eprint(*args, **kwargs) -> None: - print(*args, file=sys.stderr, **kwargs) - - -# Parse ID-token claims (if provided) -# -# interface IDTokenClaims { -# "exp": number; // specifically, an int -# "https://api.openai.com/auth": { -# organization_id: string; -# project_id: string; -# completed_platform_onboarding: boolean; -# is_org_owner: boolean; -# chatgpt_subscription_active_start: string; -# chatgpt_subscription_active_until: string; -# chatgpt_plan_type: string; -# }; -# } -def parse_id_token_claims(id_token: str) -> Dict[str, Any] | None: - if id_token: - parts = id_token.split(".") - if len(parts) == 3: - return _decode_jwt_segment(parts[1]) - return None - - -def _decode_jwt_segment(segment: str) -> Dict[str, Any]: - """Return the decoded JSON payload from a JWT segment. - - Adds required padding for urlsafe_b64decode. - """ - padded = segment + "=" * (-len(segment) % 4) - try: - data = base64.urlsafe_b64decode(padded.encode()) - return json.loads(data.decode()) - except Exception: - return {} - - -def _current_timestamp_ms() -> int: - return int(time.time() * 1000) - - -LOGIN_SUCCESS_HTML = """ - - - - Sign into Codex CLI - - - - -
-
-
- -
Signed in to Codex CLI
-
- - -
-
- - -""" - -# Unconditionally call `main()` instead of gating it behind -# `if __name__ == "__main__"` because this script is either: -# -# - invoked as a string passed to `python3 -c` -# - run via `python3 login_with_chatgpt.py` for testing as part of local -# development -main() diff --git a/codex-rs/login/src/pkce.rs b/codex-rs/login/src/pkce.rs new file mode 100644 index 0000000000..3c413b11f1 --- /dev/null +++ b/codex-rs/login/src/pkce.rs @@ -0,0 +1,27 @@ +use base64::Engine; +use rand::RngCore; +use sha2::Digest; +use sha2::Sha256; + +#[derive(Debug, Clone)] +pub struct PkceCodes { + pub code_verifier: String, + pub code_challenge: String, +} + +pub fn generate_pkce() -> PkceCodes { + let mut bytes = [0u8; 64]; + rand::thread_rng().fill_bytes(&mut bytes); + + // Verifier: URL-safe base64 without padding (43..128 chars) + let code_verifier = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes); + + // Challenge (S256): BASE64URL-ENCODE(SHA256(verifier)) without padding + let digest = Sha256::digest(code_verifier.as_bytes()); + let code_challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(digest); + + PkceCodes { + code_verifier, + code_challenge, + } +} diff --git a/codex-rs/login/src/server.rs b/codex-rs/login/src/server.rs new file mode 100644 index 0000000000..550ee703a2 --- /dev/null +++ b/codex-rs/login/src/server.rs @@ -0,0 +1,443 @@ +use std::io::{self}; +use std::path::Path; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; + +use base64::Engine; +use chrono::Utc; +use rand::RngCore; +use tiny_http::Response; +use tiny_http::Server; + +use crate::AuthDotJson; +use crate::get_auth_file; +use crate::pkce::PkceCodes; +use crate::pkce::generate_pkce; + +const DEFAULT_ISSUER: &str = "https://auth.openai.com"; +const DEFAULT_PORT: u16 = 1455; + +#[derive(Debug, Clone)] +pub struct ServerOptions<'a> { + pub codex_home: &'a Path, + pub client_id: &'a str, + pub issuer: &'a str, + pub port: u16, + pub open_browser: bool, + pub force_state: Option, +} + +impl<'a> ServerOptions<'a> { + pub fn new(codex_home: &'a Path, client_id: &'a str) -> Self { + Self { + codex_home, + client_id, + issuer: DEFAULT_ISSUER, + port: DEFAULT_PORT, + open_browser: true, + force_state: None, + } + } +} + +#[allow(dead_code)] +pub fn run_server_blocking(opts: ServerOptions) -> io::Result<()> { + run_server_blocking_with_notify(opts, None, None) +} + +pub struct LoginServerInfo { + pub auth_url: String, + pub actual_port: u16, +} + +pub fn run_server_blocking_with_notify( + opts: ServerOptions, + notify_started: Option>, + shutdown_flag: Option>, +) -> io::Result<()> { + let pkce = generate_pkce(); + let state = opts.force_state.clone().unwrap_or_else(generate_state); + + let server = Server::http(format!("127.0.0.1:{}", opts.port)).map_err(io::Error::other)?; + let actual_port = match server.server_addr().to_ip() { + Some(addr) => addr.port(), + None => { + return Err(io::Error::new( + io::ErrorKind::AddrInUse, + "Unable to determine the server port", + )); + } + }; + + let redirect_uri = format!("http://localhost:{actual_port}/auth/callback"); + let auth_url = build_authorize_url(opts.issuer, opts.client_id, &redirect_uri, &pkce, &state); + + if let Some(tx) = ¬ify_started { + let _ = tx.send(LoginServerInfo { + auth_url: auth_url.clone(), + actual_port, + }); + } + + if opts.open_browser { + let _ = webbrowser::open(&auth_url); + } + + let shutdown_flag = shutdown_flag.unwrap_or_else(|| Arc::new(AtomicBool::new(false))); + while !shutdown_flag.load(Ordering::SeqCst) { + let req = match server.recv() { + Ok(r) => r, + Err(e) => return Err(io::Error::other(e)), + }; + + let url_raw = req.url().to_string(); + let parsed_url = match url::Url::parse(&format!("http://localhost{url_raw}")) { + Ok(u) => u, + Err(e) => { + eprintln!("URL parse error: {e}"); + let _ = req.respond(Response::from_string("Bad Request").with_status_code(400)); + continue; + } + }; + let path = parsed_url.path().to_string(); + + match path.as_str() { + "/auth/callback" => { + let params: std::collections::HashMap = + parsed_url.query_pairs().into_owned().collect(); + if params.get("state").map(String::as_str) != Some(state.as_str()) { + let _ = + req.respond(Response::from_string("State mismatch").with_status_code(400)); + continue; + } + let code = match params.get("code") { + Some(c) if !c.is_empty() => c.clone(), + _ => { + let _ = req.respond( + Response::from_string("Missing authorization code") + .with_status_code(400), + ); + continue; + } + }; + + match exchange_code_for_tokens( + opts.issuer, + opts.client_id, + &redirect_uri, + &pkce, + &code, + ) { + Ok(tokens) => { + // Obtain API key via token-exchange and persist + let api_key = + obtain_api_key(opts.issuer, opts.client_id, &tokens.id_token).ok(); + if let Err(err) = persist_tokens( + opts.codex_home, + api_key.clone(), + tokens.id_token.clone(), + Some(tokens.access_token.clone()), + Some(tokens.refresh_token.clone()), + ) { + eprintln!("Persist error: {err}"); + let _ = req.respond( + Response::from_string(format!( + "Unable to persist auth file: {err}" + )) + .with_status_code(500), + ); + continue; + } + + let success_url = compose_success_url( + actual_port, + opts.issuer, + &tokens.id_token, + &tokens.access_token, + ); + match tiny_http::Header::from_bytes( + &b"Location"[..], + success_url.as_bytes(), + ) { + Ok(h) => { + let response = tiny_http::Response::empty(302).with_header(h); + let _ = req.respond(response); + } + Err(_) => { + let _ = req.respond( + Response::from_string("Internal Server Error") + .with_status_code(500), + ); + } + } + } + Err(err) => { + eprintln!("Token exchange error: {err}"); + let _ = req.respond( + Response::from_string(format!("Token exchange failed: {err}")) + .with_status_code(500), + ); + } + } + } + "/success" => { + let body = include_str!("assets/success.html"); + let mut resp = Response::from_data(body.as_bytes()); + if let Ok(h) = tiny_http::Header::from_bytes( + &b"Content-Type"[..], + &b"text/html; charset=utf-8"[..], + ) { + resp.add_header(h); + } + let _ = req.respond(resp); + shutdown_flag.store(true, Ordering::SeqCst); + } + _ => { + let _ = req.respond(Response::from_string("Not Found").with_status_code(404)); + } + } + } + + Ok(()) +} + +fn build_authorize_url( + issuer: &str, + client_id: &str, + redirect_uri: &str, + pkce: &PkceCodes, + state: &str, +) -> String { + let query = vec![ + ("response_type", "code"), + ("client_id", client_id), + ("redirect_uri", redirect_uri), + ("scope", "openid profile email offline_access"), + ("code_challenge", &pkce.code_challenge), + ("code_challenge_method", "S256"), + ("id_token_add_organizations", "true"), + ("codex_cli_simplified_flow", "true"), + ("state", state), + ]; + let qs = query + .into_iter() + .map(|(k, v)| format!("{}={}", k, urlencoding::encode(v))) + .collect::>() + .join("&"); + format!("{issuer}/oauth/authorize?{qs}") +} + +fn generate_state() -> String { + let mut bytes = [0u8; 32]; + rand::thread_rng().fill_bytes(&mut bytes); + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes) +} + +struct ExchangedTokens { + id_token: String, + access_token: String, + refresh_token: String, +} + +fn exchange_code_for_tokens( + issuer: &str, + client_id: &str, + redirect_uri: &str, + pkce: &PkceCodes, + code: &str, +) -> io::Result { + #[derive(serde::Deserialize)] + struct TokenResponse { + id_token: String, + access_token: String, + refresh_token: String, + } + + let client = reqwest::blocking::Client::new(); + let resp = client + .post(format!("{issuer}/oauth/token")) + .header("Content-Type", "application/x-www-form-urlencoded") + .body(format!( + "grant_type=authorization_code&code={}&redirect_uri={}&client_id={}&code_verifier={}", + urlencoding::encode(code), + urlencoding::encode(redirect_uri), + urlencoding::encode(client_id), + urlencoding::encode(&pkce.code_verifier) + )) + .send() + .map_err(io::Error::other)?; + + if !resp.status().is_success() { + return Err(io::Error::other(format!( + "token endpoint returned status {}", + resp.status() + ))); + } + + let tokens: TokenResponse = resp.json().map_err(io::Error::other)?; + Ok(ExchangedTokens { + id_token: tokens.id_token, + access_token: tokens.access_token, + refresh_token: tokens.refresh_token, + }) +} + +fn persist_tokens( + codex_home: &Path, + api_key: Option, + id_token: String, + access_token: Option, + refresh_token: Option, +) -> io::Result<()> { + let auth_file = get_auth_file(codex_home); + if let Some(parent) = auth_file.parent() { + if !parent.exists() { + std::fs::create_dir_all(parent).map_err(io::Error::other)?; + } + } + + let mut auth = read_or_default(&auth_file); + if let Some(key) = api_key { + auth.openai_api_key = Some(key); + } + let tokens = auth + .tokens + .get_or_insert_with(crate::token_data::TokenData::default); + tokens.id_token = crate::token_data::parse_id_token(&id_token).map_err(io::Error::other)?; + // Persist chatgpt_account_id if present in claims + if let Some(acc) = jwt_auth_claims(&id_token) + .get("chatgpt_account_id") + .and_then(|v| v.as_str()) + { + tokens.account_id = Some(acc.to_string()); + } + if let Some(at) = access_token { + tokens.access_token = at; + } + if let Some(rt) = refresh_token { + tokens.refresh_token = rt; + } + auth.last_refresh = Some(Utc::now()); + super::write_auth_json(&auth_file, &auth) +} + +fn read_or_default(path: &Path) -> AuthDotJson { + match super::try_read_auth_json(path) { + Ok(auth) => auth, + Err(_) => AuthDotJson { + openai_api_key: None, + tokens: None, + last_refresh: None, + }, + } +} + +fn compose_success_url(port: u16, issuer: &str, id_token: &str, access_token: &str) -> String { + let token_claims = jwt_auth_claims(id_token); + let access_claims = jwt_auth_claims(access_token); + + let org_id = token_claims + .get("organization_id") + .and_then(|v| v.as_str()) + .unwrap_or(""); + let project_id = token_claims + .get("project_id") + .and_then(|v| v.as_str()) + .unwrap_or(""); + let completed_onboarding = token_claims + .get("completed_platform_onboarding") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let is_org_owner = token_claims + .get("is_org_owner") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let needs_setup = (!completed_onboarding) && is_org_owner; + let plan_type = access_claims + .get("chatgpt_plan_type") + .and_then(|v| v.as_str()) + .unwrap_or(""); + + let platform_url = if issuer == DEFAULT_ISSUER { + "https://platform.openai.com" + } else { + "https://platform.api.openai.org" + }; + + let mut params = vec![ + ("id_token", id_token.to_string()), + ("needs_setup", needs_setup.to_string()), + ("org_id", org_id.to_string()), + ("project_id", project_id.to_string()), + ("plan_type", plan_type.to_string()), + ("platform_url", platform_url.to_string()), + ]; + let qs = params + .drain(..) + .map(|(k, v)| format!("{}={}", k, urlencoding::encode(&v))) + .collect::>() + .join("&"); + format!("http://localhost:{port}/success?{qs}") +} + +fn jwt_auth_claims(jwt: &str) -> serde_json::Map { + let mut parts = jwt.split('.'); + let (_h, payload_b64, _s) = match (parts.next(), parts.next(), parts.next()) { + (Some(h), Some(p), Some(s)) if !h.is_empty() && !p.is_empty() && !s.is_empty() => (h, p, s), + _ => { + eprintln!("Invalid JWT format while extracting claims"); + return serde_json::Map::new(); + } + }; + match base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload_b64) { + Ok(bytes) => match serde_json::from_slice::(&bytes) { + Ok(mut v) => { + if let Some(obj) = v + .get_mut("https://api.openai.com/auth") + .and_then(|x| x.as_object_mut()) + { + return obj.clone(); + } + eprintln!("JWT payload missing expected 'https://api.openai.com/auth' object"); + } + Err(e) => { + eprintln!("Failed to parse JWT JSON payload: {e}"); + } + }, + Err(e) => { + eprintln!("Failed to base64url-decode JWT payload: {e}"); + } + } + serde_json::Map::new() +} + +fn obtain_api_key(issuer: &str, client_id: &str, id_token: &str) -> io::Result { + // Token exchange for an API key access token + #[derive(serde::Deserialize)] + struct ExchangeResp { + access_token: String, + } + let client = reqwest::blocking::Client::new(); + let resp = client + .post(format!("{issuer}/oauth/token")) + .header("Content-Type", "application/x-www-form-urlencoded") + .body(format!( + "grant_type={}&client_id={}&requested_token={}&subject_token={}&subject_token_type={}", + urlencoding::encode("urn:ietf:params:oauth:grant-type:token-exchange"), + urlencoding::encode(client_id), + urlencoding::encode("openai-api-key"), + urlencoding::encode(id_token), + urlencoding::encode("urn:ietf:params:oauth:token-type:id_token") + )) + .send() + .map_err(io::Error::other)?; + if !resp.status().is_success() { + return Err(io::Error::other(format!( + "api key exchange failed with status {}", + resp.status() + ))); + } + let body: ExchangeResp = resp.json().map_err(io::Error::other)?; + Ok(body.access_token) +} diff --git a/codex-rs/login/src/token_data.rs b/codex-rs/login/src/token_data.rs index fb4d83950f..1cb537fa24 100644 --- a/codex-rs/login/src/token_data.rs +++ b/codex-rs/login/src/token_data.rs @@ -6,7 +6,10 @@ use thiserror::Error; #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Default)] pub struct TokenData { /// Flat info parsed from the JWT in auth.json. - #[serde(deserialize_with = "deserialize_id_token")] + #[serde( + deserialize_with = "deserialize_id_token", + serialize_with = "serialize_id_token" + )] pub id_token: IdTokenInfo, /// This is a JWT. @@ -29,13 +32,14 @@ impl TokenData { } /// Flat subset of useful claims in id_token from auth.json. -#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct IdTokenInfo { pub email: Option, /// The ChatGPT subscription plan type /// (e.g., "free", "plus", "pro", "business", "enterprise", "edu"). /// (Note: ae has not verified that those are the exact values.) pub(crate) chatgpt_plan_type: Option, + pub raw_jwt: String, } impl IdTokenInfo { @@ -126,6 +130,7 @@ pub(crate) fn parse_id_token(id_token: &str) -> Result(id_token: &IdTokenInfo, serializer: S) -> Result +where + S: serde::Serializer, +{ + serializer.serialize_str(&id_token.raw_jwt) +} + #[cfg(test)] mod tests { use super::*; @@ -145,7 +157,6 @@ mod tests { #[test] #[expect(clippy::expect_used, clippy::unwrap_used)] fn id_token_info_parses_email_and_plan() { - // Build a fake JWT with a URL-safe base64 payload containing email and plan. #[derive(Serialize)] struct Header { alg: &'static str, diff --git a/codex-rs/login/tests/login_server_e2e.rs b/codex-rs/login/tests/login_server_e2e.rs new file mode 100644 index 0000000000..3fe0e32041 --- /dev/null +++ b/codex-rs/login/tests/login_server_e2e.rs @@ -0,0 +1,192 @@ +#![allow(clippy::unwrap_used)] +use std::net::SocketAddr; +use std::net::TcpListener; +use std::thread; + +use base64::Engine; +use codex_login::LoginServerInfo; +use codex_login::ServerOptions; +use codex_login::run_server_blocking_with_notify; +use tempfile::tempdir; + +// See spawn.rs for details +pub const CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR: &str = "CODEX_SANDBOX_NETWORK_DISABLED"; + +fn start_mock_issuer() -> (SocketAddr, thread::JoinHandle<()>) { + // Bind to a random available port + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tiny_http::Server::from_listener(listener, None).unwrap(); + + let handle = thread::spawn(move || { + while let Ok(mut req) = server.recv() { + let url = req.url().to_string(); + if url.starts_with("/oauth/token") { + // Read body + let mut body = String::new(); + let _ = req.as_reader().read_to_string(&mut body); + // Build minimal JWT with plan=pro + #[derive(serde::Serialize)] + struct Header { + alg: &'static str, + typ: &'static str, + } + let header = Header { + alg: "none", + typ: "JWT", + }; + let payload = serde_json::json!({ + "email": "user@example.com", + "https://api.openai.com/auth": { + "chatgpt_plan_type": "pro", + "chatgpt_account_id": "acc-123" + } + }); + let b64 = |b: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b); + let header_bytes = serde_json::to_vec(&header).unwrap(); + let payload_bytes = serde_json::to_vec(&payload).unwrap(); + let id_token = format!( + "{}.{}.{}", + b64(&header_bytes), + b64(&payload_bytes), + b64(b"sig") + ); + + let tokens = serde_json::json!({ + "id_token": id_token, + "access_token": "access-123", + "refresh_token": "refresh-123", + }); + let data = serde_json::to_vec(&tokens).unwrap(); + let mut resp = tiny_http::Response::from_data(data); + resp.add_header( + tiny_http::Header::from_bytes(&b"Content-Type"[..], &b"application/json"[..]) + .unwrap_or_else(|_| panic!("header bytes")), + ); + let _ = req.respond(resp); + } else { + let _ = req + .respond(tiny_http::Response::from_string("not found").with_status_code(404)); + } + } + }); + + (addr, handle) +} + +#[test] +fn end_to_end_login_flow_persists_auth_json() { + if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { + println!( + "Skipping test because it cannot execute when network is disabled in a Codex sandbox." + ); + return; + } + + let (issuer_addr, issuer_handle) = start_mock_issuer(); + let issuer = format!("http://{}:{}", issuer_addr.ip(), issuer_addr.port()); + + let tmp = tempdir().unwrap(); + let codex_home = tmp.path().to_path_buf(); + + let state = "test_state_123".to_string(); + + // Run server in background + let server_home = codex_home.clone(); + + let (tx, rx) = std::sync::mpsc::channel::(); + let server_thread = thread::spawn(move || { + let opts = ServerOptions { + codex_home: &server_home, + client_id: codex_login::CLIENT_ID, + issuer: &issuer, + port: 0, + open_browser: false, + force_state: Some(state), + }; + run_server_blocking_with_notify(opts, Some(tx), None).unwrap(); + }); + + let server_info = rx.recv().unwrap(); + let login_port = server_info.actual_port; + + // Simulate browser callback, and follow redirect to /success + let client = reqwest::blocking::Client::builder() + .redirect(reqwest::redirect::Policy::limited(5)) + .build() + .unwrap(); + let url = format!("http://127.0.0.1:{login_port}/auth/callback?code=abc&state=test_state_123"); + let resp = client.get(&url).send().unwrap(); + assert!(resp.status().is_success()); + + // Wait for server shutdown + server_thread + .join() + .unwrap_or_else(|_| panic!("server thread panicked")); + + // Validate auth.json + let auth_path = codex_home.join("auth.json"); + let data = std::fs::read_to_string(&auth_path).unwrap(); + let json: serde_json::Value = serde_json::from_str(&data).unwrap(); + assert!( + !json["OPENAI_API_KEY"].is_null(), + "OPENAI_API_KEY should be set" + ); + assert_eq!(json["tokens"]["access_token"], "access-123"); + assert_eq!(json["tokens"]["refresh_token"], "refresh-123"); + assert_eq!(json["tokens"]["account_id"], "acc-123"); + + // Stop mock issuer + drop(issuer_handle); +} + +#[test] +fn creates_missing_codex_home_dir() { + if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { + println!( + "Skipping test because it cannot execute when network is disabled in a Codex sandbox." + ); + return; + } + + let (issuer_addr, _issuer_handle) = start_mock_issuer(); + let issuer = format!("http://{}:{}", issuer_addr.ip(), issuer_addr.port()); + + let tmp = tempdir().unwrap(); + let codex_home = tmp.path().join("missing-subdir"); // does not exist + + let state = "state2".to_string(); + + // Run server in background + let server_home = codex_home.clone(); + let (tx, rx) = std::sync::mpsc::channel::(); + let server_thread = thread::spawn(move || { + let opts = ServerOptions { + codex_home: &server_home, + client_id: codex_login::CLIENT_ID, + issuer: &issuer, + port: 0, + open_browser: false, + force_state: Some(state), + }; + run_server_blocking_with_notify(opts, Some(tx), None).unwrap() + }); + + let server_info = rx.recv().unwrap(); + let login_port = server_info.actual_port; + + let client = reqwest::blocking::Client::new(); + let url = format!("http://127.0.0.1:{login_port}/auth/callback?code=abc&state=state2"); + let resp = client.get(&url).send().unwrap(); + assert!(resp.status().is_success()); + + server_thread + .join() + .unwrap_or_else(|_| panic!("server thread panicked")); + + let auth_path = codex_home.join("auth.json"); + assert!( + auth_path.exists(), + "auth.json should be created even if parent dir was missing" + ); +} diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 2bef9fb925..256289b21f 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -522,6 +522,10 @@ impl App<'_> { } fn draw_next_frame(&mut self, terminal: &mut tui::Tui) -> Result<()> { + if matches!(self.app_state, AppState::Onboarding { .. }) { + terminal.clear()?; + } + let screen_size = terminal.size()?; let last_known_screen_size = terminal.last_known_screen_size; if screen_size != last_known_screen_size { diff --git a/codex-rs/tui/src/onboarding/auth.rs b/codex-rs/tui/src/onboarding/auth.rs index ed573a4156..a8864e4d57 100644 --- a/codex-rs/tui/src/onboarding/auth.rs +++ b/codex-rs/tui/src/onboarding/auth.rs @@ -44,11 +44,7 @@ pub(crate) struct ContinueInBrowserState { impl Drop for ContinueInBrowserState { fn drop(&mut self) { if let Some(child) = &self.login_child { - if let Ok(mut locked) = child.child.lock() { - // Best-effort terminate and reap the child to avoid zombies. - let _ = locked.kill(); - let _ = locked.wait(); - } + child.cancel(); } } } @@ -321,32 +317,16 @@ impl AuthModeWidget { } fn spawn_completion_poller(&self, child: codex_login::SpawnedLogin) { - let child_arc = child.child.clone(); - let stderr_buf = child.stderr.clone(); let event_tx = self.event_tx.clone(); std::thread::spawn(move || { loop { - let done = { - if let Ok(mut locked) = child_arc.lock() { - match locked.try_wait() { - Ok(Some(status)) => Some(status.success()), - Ok(None) => None, - Err(_) => Some(false), - } - } else { - Some(false) - } - }; - if let Some(success) = done { + if let Some(success) = child.get_auth_result() { if success { event_tx.send(AppEvent::OnboardingAuthComplete(Ok(()))); } else { - let err = stderr_buf - .lock() - .ok() - .and_then(|b| String::from_utf8(b.clone()).ok()) - .unwrap_or_else(|| "login_with_chatgpt subprocess failed".to_string()); - event_tx.send(AppEvent::OnboardingAuthComplete(Err(err))); + event_tx.send(AppEvent::OnboardingAuthComplete(Err( + "login failed".to_string() + ))); } break; } diff --git a/codex-rs/tui/src/onboarding/onboarding_screen.rs b/codex-rs/tui/src/onboarding/onboarding_screen.rs index a104f777c2..a481c8c768 100644 --- a/codex-rs/tui/src/onboarding/onboarding_screen.rs +++ b/codex-rs/tui/src/onboarding/onboarding_screen.rs @@ -2,6 +2,8 @@ use codex_core::util::is_inside_git_repo; use crossterm::event::KeyEvent; use ratatui::buffer::Buffer; use ratatui::layout::Rect; +use ratatui::prelude::Widget; +use ratatui::widgets::Clear; use ratatui::widgets::WidgetRef; use codex_login::AuthMode; @@ -113,6 +115,14 @@ impl OnboardingScreen { Ok(()) => { state.sign_in_state = SignInState::ChatGptSuccessMessage; self.event_tx.send(AppEvent::RequestRedraw); + let tx1 = self.event_tx.clone(); + let tx2 = self.event_tx.clone(); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(150)); + tx1.send(AppEvent::RequestRedraw); + std::thread::sleep(std::time::Duration::from_millis(200)); + tx2.send(AppEvent::RequestRedraw); + }); } Err(e) => { state.sign_in_state = SignInState::PickMode; @@ -171,6 +181,7 @@ impl KeyboardHandler for OnboardingScreen { impl WidgetRef for &OnboardingScreen { fn render_ref(&self, area: Rect, buf: &mut Buffer) { + Clear.render(area, buf); // Render steps top-to-bottom, measuring each step's height dynamically. let mut y = area.y; let bottom = area.y.saturating_add(area.height); @@ -218,6 +229,7 @@ impl WidgetRef for &OnboardingScreen { width, height: h, }; + Clear.render(target, buf); step.render_ref(target, buf); y = y.saturating_add(h); } From c26d42ab69dd17c9ac2732aff8fc84aea8099c34 Mon Sep 17 00:00:00 2001 From: Parker Thompson Date: Thu, 14 Aug 2025 17:12:41 -0700 Subject: [PATCH 10/16] Fix AF_UNIX, sockpair, recvfrom in linux sandbox (#2309) When using codex-tui on a linux system I was unable to run `cargo clippy` inside of codex due to: ``` [pid 3548377] socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, [pid 3548370] close(8 [pid 3548377] <... socketpair resumed>0x7ffb97f4ed60) = -1 EPERM (Operation not permitted) ``` And ``` 3611300 <... recvfrom resumed>0x708b8b5cffe0, 8, 0, NULL, NULL) = -1 EPERM (Operation not permitted) ``` This PR: * Fixes a bug that disallowed AF_UNIX to allow it on `socket()` * Adds recvfrom() to the syscall allow list, this should be fine since we disable opening new sockets. But we should validate there is not a open socket inheritance issue. * Allow socketpair to be called for AF_UNIX * Adds tests for AF_UNIX components * All of which allows running `cargo clippy` within the sandbox on linux, and possibly other tooling using a fork server model + AF_UNIX comms. --- codex-rs/Cargo.lock | 1 + codex-rs/exec/Cargo.toml | 1 + codex-rs/exec/tests/sandbox.rs | 128 +++++++++++++++++++++++++ codex-rs/linux-sandbox/src/landlock.rs | 10 +- 4 files changed, 136 insertions(+), 4 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 8f077bc0ab..ef07a36daf 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -751,6 +751,7 @@ dependencies = [ "codex-common", "codex-core", "codex-ollama", + "libc", "owo-colors", "predicates", "serde_json", diff --git a/codex-rs/exec/Cargo.toml b/codex-rs/exec/Cargo.toml index aee480d7b4..b7c20df321 100644 --- a/codex-rs/exec/Cargo.toml +++ b/codex-rs/exec/Cargo.toml @@ -41,5 +41,6 @@ tracing-subscriber = { version = "0.3.19", features = ["env-filter"] } [dev-dependencies] assert_cmd = "2" +libc = "0.2" predicates = "3" tempfile = "3.13.0" diff --git a/codex-rs/exec/tests/sandbox.rs b/codex-rs/exec/tests/sandbox.rs index 8cc31bba58..22caf8abc6 100644 --- a/codex-rs/exec/tests/sandbox.rs +++ b/codex-rs/exec/tests/sandbox.rs @@ -4,7 +4,10 @@ use codex_core::protocol::SandboxPolicy; use codex_core::spawn::StdioPolicy; use std::collections::HashMap; +use std::future::Future; +use std::io; use std::path::PathBuf; +use std::process::ExitStatus; use tokio::process::Child; #[cfg(target_os = "macos")] @@ -90,3 +93,128 @@ if __name__ == '__main__': let status = child.wait().await.expect("should wait for child process"); assert!(status.success(), "python exited with {status:?}"); } + +fn unix_sock_body() { + unsafe { + let mut fds = [0i32; 2]; + let r = libc::socketpair(libc::AF_UNIX, libc::SOCK_DGRAM, 0, fds.as_mut_ptr()); + assert_eq!( + r, + 0, + "socketpair(AF_UNIX, SOCK_DGRAM) failed: {}", + io::Error::last_os_error() + ); + + let msg = b"hello_unix"; + // write() from one end (generic write is allowed) + let sent = libc::write(fds[0], msg.as_ptr() as *const libc::c_void, msg.len()); + assert!(sent >= 0, "write() failed: {}", io::Error::last_os_error()); + + // recvfrom() on the other end. We don’t need the address for socketpair, + // so we pass null pointers for src address. + let mut buf = [0u8; 64]; + let recvd = libc::recvfrom( + fds[1], + buf.as_mut_ptr() as *mut libc::c_void, + buf.len(), + 0, + std::ptr::null_mut(), + std::ptr::null_mut(), + ); + assert!( + recvd >= 0, + "recvfrom() failed: {}", + io::Error::last_os_error() + ); + + let recvd_slice = &buf[..(recvd as usize)]; + assert_eq!( + recvd_slice, + &msg[..], + "payload mismatch: sent {} bytes, got {} bytes", + msg.len(), + recvd + ); + + // Also exercise AF_UNIX stream socketpair quickly to ensure AF_UNIX in general works. + let mut sfds = [0i32; 2]; + let sr = libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM, 0, sfds.as_mut_ptr()); + assert_eq!( + sr, + 0, + "socketpair(AF_UNIX, SOCK_STREAM) failed: {}", + io::Error::last_os_error() + ); + let snt2 = libc::write(sfds[0], msg.as_ptr() as *const libc::c_void, msg.len()); + assert!( + snt2 >= 0, + "write(stream) failed: {}", + io::Error::last_os_error() + ); + let mut b2 = [0u8; 64]; + let rcv2 = libc::recv(sfds[1], b2.as_mut_ptr() as *mut libc::c_void, b2.len(), 0); + assert!( + rcv2 >= 0, + "recv(stream) failed: {}", + io::Error::last_os_error() + ); + + // Clean up + let _ = libc::close(sfds[0]); + let _ = libc::close(sfds[1]); + let _ = libc::close(fds[0]); + let _ = libc::close(fds[1]); + } +} + +#[tokio::test] +async fn allow_unix_socketpair_recvfrom() { + run_code_under_sandbox( + "allow_unix_socketpair_recvfrom", + &SandboxPolicy::ReadOnly, + || async { unix_sock_body() }, + ) + .await + .expect("should be able to reexec"); +} + +const IN_SANDBOX_ENV_VAR: &str = "IN_SANDBOX"; + +pub async fn run_code_under_sandbox( + test_selector: &str, + policy: &SandboxPolicy, + child_body: F, +) -> io::Result> +where + F: FnOnce() -> Fut + Send + 'static, + Fut: Future + Send + 'static, +{ + if std::env::var(IN_SANDBOX_ENV_VAR).is_err() { + let exe = std::env::current_exe()?; + let mut cmds = vec![exe.to_string_lossy().into_owned(), "--exact".into()]; + let mut stdio_policy = StdioPolicy::RedirectForShellTool; + // Allow for us to pass forward --nocapture / use the right stdio policy. + if std::env::args().any(|a| a == "--nocapture") { + cmds.push("--nocapture".into()); + stdio_policy = StdioPolicy::Inherit; + } + cmds.push(test_selector.into()); + + // Your existing launcher: + let mut child = spawn_command_under_sandbox( + cmds, + policy, + std::env::current_dir().expect("should be able to get current dir"), + stdio_policy, + HashMap::from([("IN_SANDBOX".into(), "1".into())]), + ) + .await?; + + let status = child.wait().await?; + Ok(Some(status)) + } else { + // Child branch: run the provided body. + child_body().await; + Ok(None) + } +} diff --git a/codex-rs/linux-sandbox/src/landlock.rs b/codex-rs/linux-sandbox/src/landlock.rs index e13e3c8b75..5bc96130dd 100644 --- a/codex-rs/linux-sandbox/src/landlock.rs +++ b/codex-rs/linux-sandbox/src/landlock.rs @@ -104,7 +104,9 @@ fn install_network_seccomp_filter_on_current_thread() -> std::result::Result<(), deny_syscall(libc::SYS_sendto); deny_syscall(libc::SYS_sendmsg); deny_syscall(libc::SYS_sendmmsg); - deny_syscall(libc::SYS_recvfrom); + // NOTE: allowing recvfrom allows some tools like: `cargo clippy` to run + // with their socketpair + child processes for sub-proc management + // deny_syscall(libc::SYS_recvfrom); deny_syscall(libc::SYS_recvmsg); deny_syscall(libc::SYS_recvmmsg); deny_syscall(libc::SYS_getsockopt); @@ -115,12 +117,12 @@ fn install_network_seccomp_filter_on_current_thread() -> std::result::Result<(), let unix_only_rule = SeccompRule::new(vec![SeccompCondition::new( 0, // first argument (domain) SeccompCmpArgLen::Dword, - SeccompCmpOp::Eq, + SeccompCmpOp::Ne, libc::AF_UNIX as u64, )?])?; - rules.insert(libc::SYS_socket, vec![unix_only_rule]); - rules.insert(libc::SYS_socketpair, vec![]); // always deny (Unix can use socketpair but fine, keep open?) + rules.insert(libc::SYS_socket, vec![unix_only_rule.clone()]); + rules.insert(libc::SYS_socketpair, vec![unix_only_rule]); // always deny (Unix can use socketpair but fine, keep open?) let filter = SeccompFilter::new( rules, From dd63d61a5927683195fd03f6689dfd1304d4d882 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 14 Aug 2025 17:44:10 -0700 Subject: [PATCH 11/16] fix: trying to simplify rust-ci.yml (#2327) It turns out that https://github.com/openai/codex/pull/2324 did not quite work as intended. Chat's new idea is to have this catch-all "CI results" job and update our branch protection rules to require this instead. --- .github/workflows/rust-ci.yml | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/.github/workflows/rust-ci.yml b/.github/workflows/rust-ci.yml index 1861233abf..fd8340a083 100644 --- a/.github/workflows/rust-ci.yml +++ b/.github/workflows/rust-ci.yml @@ -69,6 +69,7 @@ jobs: runs-on: ${{ matrix.runner }} timeout-minutes: 30 needs: changed + # Keep job-level if to avoid spinning up runners when not needed if: ${{ needs.changed.outputs.codex == 'true' || needs.changed.outputs.workflows == 'true' || github.event_name == 'push' }} defaults: run: @@ -166,3 +167,27 @@ jobs: run: | echo "One or more checks failed (clippy, build, or test). See logs for details." exit 1 + + # --- Gatherer job that you mark as the ONLY required status ----------------- + results: + name: CI results (required) + needs: [changed, general, lint_build_test] + if: always() + runs-on: ubuntu-24.04 + steps: + - name: Summarize + shell: bash + run: | + echo "general: ${{ needs.general.result }}" + echo "matrix : ${{ needs.lint_build_test.result }}" + + # If nothing relevant changed (PR touching only root README, etc.), + # declare success regardless of other jobs. + if [[ '${{ needs.changed.outputs.codex }}' != 'true' && '${{ needs.changed.outputs.workflows }}' != 'true' && '${{ github.event_name }}' != 'push' ]]; then + echo 'No relevant changes -> CI not required.' + exit 0 + fi + + # Otherwise require the jobs to have succeeded + [[ '${{ needs.general.result }}' == 'success' ]] || { echo 'general failed'; exit 1; } + [[ '${{ needs.lint_build_test.result }}' == 'success' ]] || { echo 'matrix failed'; exit 1; } From 8bdb4521c96b386d299052263b0cd7d58b431bf1 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <172423086+nornagon-openai@users.noreply.github.com> Date: Thu, 14 Aug 2025 20:51:32 -0400 Subject: [PATCH 12/16] AGENTS.md more strongly suggests running targeted tests first (#2306) --- AGENTS.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index af25482795..e5520d3266 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,6 @@ In the codex-rs folder where the rust code lives: - You operate in a sandbox where `CODEX_SANDBOX_NETWORK_DISABLED=1` will be set whenever you use the `shell` tool. Any existing code that uses `CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR` was authored with this fact in mind. It is often used to early exit out of tests that the author knew you would not be able to run given your sandbox limitations. - Similarly, when you spawn a process using Seatbelt (`/usr/bin/sandbox-exec`), `CODEX_SANDBOX=seatbelt` will be set on the child process. Integration tests that want to run Seatbelt themselves cannot be run under Seatbelt, so checks for `CODEX_SANDBOX=seatbelt` are also often used to early exit out of tests, as appropriate. -Before creating a pull request with changes to `codex-rs`, run `just fmt` (in `codex-rs` directory) to format the code and `just fix` (in `codex-rs` directory) to fix any linter issues in the code, ensure the test suite passes by running `cargo test --all-features` in the `codex-rs` directory. - -When making individual changes prefer running tests on individual files or projects first. +Before finalizing a change to `codex-rs`, run `just fmt` (in `codex-rs` directory) to format the code and `just fix` (in `codex-rs` directory) to fix any linter issues in the code. Additionally, run the tests: +1. Run the test for the specific project that was changed. For example, if changes were made in `codex-rs/tui`, run `cargo test -p codex-tui`. +2. Once those pass, if any changes were made in common, core, or protocol, run the complete test suite with `cargo test --all-features`. From a0754244379ff337c698e133ad563e098896ca78 Mon Sep 17 00:00:00 2001 From: Parker Thompson Date: Thu, 14 Aug 2025 17:59:01 -0700 Subject: [PATCH 13/16] Added `allow-expect-in-tests` / `allow-unwrap-in-tests` (#2328) This PR: * Added the clippy.toml to configure allowable expect / unwrap usage in tests * Removed as many expect/allow lines as possible from tests * moved a bunch of allows to expects where possible Note: in integration tests, non `#[test]` helper functions are not covered by this so we had to leave a few lingering `expect(expect_used` checks around --- codex-rs/apply-patch/src/lib.rs | 6 ++---- codex-rs/apply-patch/src/parser.rs | 1 - codex-rs/chatgpt/tests/apply_command_e2e.rs | 2 -- codex-rs/clippy.toml | 2 ++ codex-rs/common/src/config_override.rs | 1 - codex-rs/core/src/bash.rs | 1 - codex-rs/core/src/client.rs | 2 -- codex-rs/core/src/client_common.rs | 1 - codex-rs/core/src/codex.rs | 2 +- codex-rs/core/src/config.rs | 1 - codex-rs/core/src/exec_env.rs | 2 -- codex-rs/core/src/git_info.rs | 3 --- codex-rs/core/src/is_safe_command.rs | 1 - codex-rs/core/src/mcp_connection_manager.rs | 1 - codex-rs/core/src/model_provider_info.rs | 1 - codex-rs/core/src/models.rs | 1 - codex-rs/core/src/openai_tools.rs | 1 - codex-rs/core/src/project_doc.rs | 2 -- codex-rs/core/src/protocol.rs | 1 - codex-rs/core/src/safety.rs | 1 - codex-rs/core/src/seatbelt.rs | 1 - codex-rs/core/src/shell.rs | 2 -- codex-rs/core/src/turn_diff_tracker.rs | 1 - codex-rs/core/src/user_agent.rs | 1 - codex-rs/core/src/user_notification.rs | 1 - codex-rs/core/tests/cli_stream.rs | 2 -- codex-rs/core/tests/client.rs | 19 +++---------------- codex-rs/core/tests/common/lib.rs | 2 +- codex-rs/core/tests/exec.rs | 3 +-- codex-rs/core/tests/live_cli.rs | 3 +-- codex-rs/core/tests/prompt_caching.rs | 3 --- codex-rs/core/tests/seatbelt.rs | 3 ++- .../tests/stream_error_allows_next_turn.rs | 1 - codex-rs/core/tests/stream_no_completed.rs | 2 -- .../src/event_processor_with_human_output.rs | 10 +++++----- .../src/event_processor_with_json_output.rs | 2 +- codex-rs/exec/tests/sandbox.rs | 3 +-- codex-rs/execpolicy/src/execv_checker.rs | 1 - codex-rs/execpolicy/tests/bad.rs | 1 - codex-rs/execpolicy/tests/cp.rs | 2 +- codex-rs/execpolicy/tests/good.rs | 1 - codex-rs/execpolicy/tests/head.rs | 2 +- codex-rs/execpolicy/tests/literal.rs | 1 - codex-rs/execpolicy/tests/ls.rs | 2 +- codex-rs/execpolicy/tests/pwd.rs | 2 +- codex-rs/execpolicy/tests/sed.rs | 2 +- codex-rs/linux-sandbox/tests/landlock.rs | 5 ++--- codex-rs/login/src/lib.rs | 1 - codex-rs/login/src/token_data.rs | 1 - codex-rs/login/tests/login_server_e2e.rs | 2 +- codex-rs/mcp-server/src/codex_tool_config.rs | 2 -- codex-rs/mcp-server/src/json_to_toml.rs | 1 - codex-rs/mcp-server/src/mcp_protocol.rs | 2 -- codex-rs/mcp-server/src/outgoing_message.rs | 4 +--- codex-rs/mcp-server/src/wire_format.rs | 1 - .../tests/codex_message_processor_flow.rs | 2 -- codex-rs/mcp-server/tests/codex_tool.rs | 2 +- .../mcp-server/tests/create_conversation.rs | 2 -- codex-rs/mcp-server/tests/send_message.rs | 2 -- codex-rs/mcp-types/tests/initialize.rs | 1 - .../mcp-types/tests/progress_notification.rs | 1 - codex-rs/ollama/src/client.rs | 3 +-- codex-rs/tui/src/app.rs | 2 +- .../src/bottom_pane/chat_composer_history.rs | 1 - codex-rs/tui/src/bottom_pane/textarea.rs | 4 +--- codex-rs/tui/src/chatwidget/tests.rs | 2 -- codex-rs/tui/src/citation_regex.rs | 2 +- codex-rs/tui/src/diff_render.rs | 1 - codex-rs/tui/src/file_search.rs | 11 ++++------- codex-rs/tui/src/insert_history.rs | 1 - codex-rs/tui/src/lib.rs | 1 - codex-rs/tui/src/text_formatting.rs | 1 - 72 files changed, 38 insertions(+), 126 deletions(-) create mode 100644 codex-rs/clippy.toml diff --git a/codex-rs/apply-patch/src/lib.rs b/codex-rs/apply-patch/src/lib.rs index 262d219d6d..87df66dd23 100644 --- a/codex-rs/apply-patch/src/lib.rs +++ b/codex-rs/apply-patch/src/lib.rs @@ -166,7 +166,7 @@ impl ApplyPatchAction { panic!("path must be absolute"); } - #[allow(clippy::expect_used)] + #[expect(clippy::expect_used)] let filename = path .file_name() .expect("path should not be empty") @@ -179,7 +179,7 @@ impl ApplyPatchAction { *** End Patch"#, ); let changes = HashMap::from([(path.to_path_buf(), ApplyPatchFileChange::Add { content })]); - #[allow(clippy::expect_used)] + #[expect(clippy::expect_used)] Self { changes, cwd: path @@ -682,8 +682,6 @@ pub fn print_summary( #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used)] - use super::*; use pretty_assertions::assert_eq; use std::fs; diff --git a/codex-rs/apply-patch/src/parser.rs b/codex-rs/apply-patch/src/parser.rs index 44c5b14619..ff9dfd6f8f 100644 --- a/codex-rs/apply-patch/src/parser.rs +++ b/codex-rs/apply-patch/src/parser.rs @@ -427,7 +427,6 @@ fn parse_update_file_chunk( } #[test] -#[allow(clippy::unwrap_used)] fn test_parse_patch() { assert_eq!( parse_patch_text("bad", ParseMode::Strict), diff --git a/codex-rs/chatgpt/tests/apply_command_e2e.rs b/codex-rs/chatgpt/tests/apply_command_e2e.rs index f1a35e1521..2aa8b809bb 100644 --- a/codex-rs/chatgpt/tests/apply_command_e2e.rs +++ b/codex-rs/chatgpt/tests/apply_command_e2e.rs @@ -1,5 +1,3 @@ -#![expect(clippy::expect_used)] - use codex_chatgpt::apply_command::apply_diff_from_task; use codex_chatgpt::get_task::GetTaskResponse; use std::path::Path; diff --git a/codex-rs/clippy.toml b/codex-rs/clippy.toml new file mode 100644 index 0000000000..9e614bec42 --- /dev/null +++ b/codex-rs/clippy.toml @@ -0,0 +1,2 @@ +allow-expect-in-tests = true +allow-unwrap-in-tests = true \ No newline at end of file diff --git a/codex-rs/common/src/config_override.rs b/codex-rs/common/src/config_override.rs index c9b18edc7c..6b77099524 100644 --- a/codex-rs/common/src/config_override.rs +++ b/codex-rs/common/src/config_override.rs @@ -142,7 +142,6 @@ fn parse_toml_value(raw: &str) -> Result { } #[cfg(all(test, feature = "cli"))] -#[allow(clippy::expect_used, clippy::unwrap_used)] mod tests { use super::*; diff --git a/codex-rs/core/src/bash.rs b/codex-rs/core/src/bash.rs index b9cd444356..5b94daf252 100644 --- a/codex-rs/core/src/bash.rs +++ b/codex-rs/core/src/bash.rs @@ -132,7 +132,6 @@ fn parse_plain_command_from_node(cmd: tree_sitter::Node, src: &str) -> Option Option>> { diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 135782bc31..3d26bd0880 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -609,8 +609,6 @@ fn try_parse_retry_after(err: &Error) -> Option { #[cfg(test)] mod tests { - #![allow(clippy::expect_used, clippy::unwrap_used)] - use super::*; use serde_json::json; use tokio::sync::mpsc; diff --git a/codex-rs/core/src/client_common.rs b/codex-rs/core/src/client_common.rs index d8684648f8..c3489200c9 100644 --- a/codex-rs/core/src/client_common.rs +++ b/codex-rs/core/src/client_common.rs @@ -187,7 +187,6 @@ impl Stream for ResponseStream { #[cfg(test)] mod tests { - #![allow(clippy::expect_used)] use crate::model_family::find_family_for_model; use super::*; diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 098ff115fa..482ac2f1ab 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -1,5 +1,5 @@ // Poisoned mutex should fail the program -#![allow(clippy::unwrap_used)] +#![expect(clippy::unwrap_used)] use std::borrow::Cow; use std::collections::HashMap; diff --git a/codex-rs/core/src/config.rs b/codex-rs/core/src/config.rs index f9c15b9eed..b17bb80815 100644 --- a/codex-rs/core/src/config.rs +++ b/codex-rs/core/src/config.rs @@ -765,7 +765,6 @@ pub fn log_dir(cfg: &Config) -> std::io::Result { #[cfg(test)] mod tests { - #![allow(clippy::expect_used, clippy::unwrap_used)] use crate::config_types::HistoryPersistence; use super::*; diff --git a/codex-rs/core/src/exec_env.rs b/codex-rs/core/src/exec_env.rs index 2957f3da15..88246b063c 100644 --- a/codex-rs/core/src/exec_env.rs +++ b/codex-rs/core/src/exec_env.rs @@ -70,8 +70,6 @@ where #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used, clippy::expect_used)] - use super::*; use crate::config_types::ShellEnvironmentPolicyInherit; use maplit::hashmap; diff --git a/codex-rs/core/src/git_info.rs b/codex-rs/core/src/git_info.rs index 52d029f669..09a59b7b8c 100644 --- a/codex-rs/core/src/git_info.rs +++ b/codex-rs/core/src/git_info.rs @@ -99,9 +99,6 @@ async fn run_git_command_with_timeout(args: &[&str], cwd: &Path) -> Option) -> bool { #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used)] use super::*; fn vec_str(args: &[&str]) -> Vec { diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs index 2e33c8754b..b5813a0462 100644 --- a/codex-rs/core/src/mcp_connection_manager.rs +++ b/codex-rs/core/src/mcp_connection_manager.rs @@ -281,7 +281,6 @@ fn is_valid_mcp_server_name(server_name: &str) -> bool { } #[cfg(test)] -#[allow(clippy::unwrap_used)] mod tests { use super::*; use mcp_types::ToolInputSchema; diff --git a/codex-rs/core/src/model_provider_info.rs b/codex-rs/core/src/model_provider_info.rs index 98f07deb1e..00eabc539c 100644 --- a/codex-rs/core/src/model_provider_info.rs +++ b/codex-rs/core/src/model_provider_info.rs @@ -322,7 +322,6 @@ pub fn create_oss_provider_with_base_url(base_url: &str) -> ModelProviderInfo { #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used)] use super::*; use pretty_assertions::assert_eq; diff --git a/codex-rs/core/src/models.rs b/codex-rs/core/src/models.rs index da1e31b706..5e67fc381a 100644 --- a/codex-rs/core/src/models.rs +++ b/codex-rs/core/src/models.rs @@ -266,7 +266,6 @@ impl std::ops::Deref for FunctionCallOutputPayload { #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used)] use super::*; #[test] diff --git a/codex-rs/core/src/openai_tools.rs b/codex-rs/core/src/openai_tools.rs index ad794c38f1..7c65880433 100644 --- a/codex-rs/core/src/openai_tools.rs +++ b/codex-rs/core/src/openai_tools.rs @@ -470,7 +470,6 @@ pub(crate) fn get_openai_tools( } #[cfg(test)] -#[allow(clippy::expect_used)] mod tests { use crate::model_family::find_family_for_model; use mcp_types::ToolInputSchema; diff --git a/codex-rs/core/src/project_doc.rs b/codex-rs/core/src/project_doc.rs index 9f46159d1d..3591b5b1d8 100644 --- a/codex-rs/core/src/project_doc.rs +++ b/codex-rs/core/src/project_doc.rs @@ -134,8 +134,6 @@ async fn load_first_candidate( #[cfg(test)] mod tests { - #![allow(clippy::expect_used, clippy::unwrap_used)] - use super::*; use crate::config::ConfigOverrides; use crate::config::ConfigToml; diff --git a/codex-rs/core/src/protocol.rs b/codex-rs/core/src/protocol.rs index f32d9ccf53..ac95b6a20a 100644 --- a/codex-rs/core/src/protocol.rs +++ b/codex-rs/core/src/protocol.rs @@ -697,7 +697,6 @@ pub struct Chunk { #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used)] use super::*; /// Serialize Event to verify that its JSON representation has the expected diff --git a/codex-rs/core/src/safety.rs b/codex-rs/core/src/safety.rs index 860a728def..74872ddc4f 100644 --- a/codex-rs/core/src/safety.rs +++ b/codex-rs/core/src/safety.rs @@ -245,7 +245,6 @@ fn is_write_patch_constrained_to_writable_paths( #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used)] use super::*; #[test] diff --git a/codex-rs/core/src/seatbelt.rs b/codex-rs/core/src/seatbelt.rs index ff9dbaa7f9..31aa770d2e 100644 --- a/codex-rs/core/src/seatbelt.rs +++ b/codex-rs/core/src/seatbelt.rs @@ -122,7 +122,6 @@ fn create_seatbelt_command_args( #[cfg(test)] mod tests { - #![expect(clippy::expect_used)] use super::MACOS_SEATBELT_BASE_POLICY; use super::create_seatbelt_command_args; use crate::protocol::SandboxPolicy; diff --git a/codex-rs/core/src/shell.rs b/codex-rs/core/src/shell.rs index 4a4e0146da..0cde3b4a78 100644 --- a/codex-rs/core/src/shell.rs +++ b/codex-rs/core/src/shell.rs @@ -98,7 +98,6 @@ mod tests { use std::process::Command; #[tokio::test] - #[expect(clippy::unwrap_used)] async fn test_current_shell_detects_zsh() { let shell = Command::new("sh") .arg("-c") @@ -129,7 +128,6 @@ mod tests { assert_eq!(actual_cmd, None); } - #[expect(clippy::unwrap_used)] #[tokio::test] async fn test_run_with_profile_escaping_and_execution() { let shell_path = "/bin/zsh"; diff --git a/codex-rs/core/src/turn_diff_tracker.rs b/codex-rs/core/src/turn_diff_tracker.rs index 7026d7bb32..5e73fa0650 100644 --- a/codex-rs/core/src/turn_diff_tracker.rs +++ b/codex-rs/core/src/turn_diff_tracker.rs @@ -466,7 +466,6 @@ fn is_windows_drive_or_unc_root(p: &std::path::Path) -> bool { #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used)] use super::*; use pretty_assertions::assert_eq; use tempfile::tempdir; diff --git a/codex-rs/core/src/user_agent.rs b/codex-rs/core/src/user_agent.rs index a0cf387069..ddcfd4b7f1 100644 --- a/codex-rs/core/src/user_agent.rs +++ b/codex-rs/core/src/user_agent.rs @@ -13,7 +13,6 @@ pub fn get_codex_user_agent(originator: Option<&str>) -> String { } #[cfg(test)] -#[allow(clippy::unwrap_used)] mod tests { use super::*; diff --git a/codex-rs/core/src/user_notification.rs b/codex-rs/core/src/user_notification.rs index e7479f89cd..0a3cb49e78 100644 --- a/codex-rs/core/src/user_notification.rs +++ b/codex-rs/core/src/user_notification.rs @@ -20,7 +20,6 @@ pub(crate) enum UserNotification { #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used)] use super::*; #[test] diff --git a/codex-rs/core/tests/cli_stream.rs b/codex-rs/core/tests/cli_stream.rs index c8570577ce..219e99787d 100644 --- a/codex-rs/core/tests/cli_stream.rs +++ b/codex-rs/core/tests/cli_stream.rs @@ -1,5 +1,3 @@ -#![expect(clippy::unwrap_used)] - use assert_cmd::Command as AssertCommand; use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use std::time::Duration; diff --git a/codex-rs/core/tests/client.rs b/codex-rs/core/tests/client.rs index 10c6c66fb5..2f7977eeb6 100644 --- a/codex-rs/core/tests/client.rs +++ b/codex-rs/core/tests/client.rs @@ -1,5 +1,3 @@ -#![allow(clippy::expect_used, clippy::unwrap_used)] - use codex_core::ConversationManager; use codex_core::ModelProviderInfo; use codex_core::NewConversation; @@ -27,10 +25,12 @@ fn sse_completed(id: &str) -> String { load_sse_fixture_with_id("tests/fixtures/completed_template.json", id) } +#[expect(clippy::unwrap_used)] fn assert_message_role(request_body: &serde_json::Value, role: &str) { assert_eq!(request_body["role"].as_str().unwrap(), role); } +#[expect(clippy::expect_used)] fn assert_message_starts_with(request_body: &serde_json::Value, text: &str) { let content = request_body["content"][0]["text"] .as_str() @@ -42,6 +42,7 @@ fn assert_message_starts_with(request_body: &serde_json::Value, text: &str) { ); } +#[expect(clippy::expect_used)] fn assert_message_ends_with(request_body: &serde_json::Value, text: &str) { let content = request_body["content"][0]["text"] .as_str() @@ -55,8 +56,6 @@ fn assert_message_ends_with(request_body: &serde_json::Value, text: &str) { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn includes_session_id_and_model_headers_in_request() { - #![allow(clippy::unwrap_used)] - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { println!( "Skipping test because it cannot execute when network is disabled in a Codex sandbox." @@ -129,8 +128,6 @@ async fn includes_session_id_and_model_headers_in_request() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn includes_base_instructions_override_in_request() { - #![allow(clippy::unwrap_used)] - // Mock server let server = MockServer::start().await; @@ -187,8 +184,6 @@ async fn includes_base_instructions_override_in_request() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn originator_config_override_is_used() { - #![allow(clippy::unwrap_used)] - // Mock server let server = MockServer::start().await; @@ -238,8 +233,6 @@ async fn originator_config_override_is_used() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn chatgpt_auth_sends_correct_request() { - #![allow(clippy::unwrap_used)] - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { println!( "Skipping test because it cannot execute when network is disabled in a Codex sandbox." @@ -320,8 +313,6 @@ async fn chatgpt_auth_sends_correct_request() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn includes_user_instructions_message_in_request() { - #![allow(clippy::unwrap_used)] - let server = MockServer::start().await; let first = ResponseTemplate::new(200) @@ -382,8 +373,6 @@ async fn includes_user_instructions_message_in_request() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn azure_overrides_assign_properties_used_for_responses_url() { - #![allow(clippy::unwrap_used)] - let existing_env_var_with_random_value = if cfg!(windows) { "USERNAME" } else { "USER" }; // Mock server @@ -460,8 +449,6 @@ async fn azure_overrides_assign_properties_used_for_responses_url() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn env_var_overrides_loaded_auth() { - #![allow(clippy::unwrap_used)] - let existing_env_var_with_random_value = if cfg!(windows) { "USERNAME" } else { "USER" }; // Mock server diff --git a/codex-rs/core/tests/common/lib.rs b/codex-rs/core/tests/common/lib.rs index 04b6dc4b62..0a9c8d5aa8 100644 --- a/codex-rs/core/tests/common/lib.rs +++ b/codex-rs/core/tests/common/lib.rs @@ -1,4 +1,4 @@ -#![allow(clippy::expect_used)] +#![expect(clippy::expect_used)] use tempfile::TempDir; diff --git a/codex-rs/core/tests/exec.rs b/codex-rs/core/tests/exec.rs index ff5d2b7d54..f011aa7a0a 100644 --- a/codex-rs/core/tests/exec.rs +++ b/codex-rs/core/tests/exec.rs @@ -1,5 +1,4 @@ #![cfg(target_os = "macos")] -#![expect(clippy::unwrap_used, clippy::expect_used)] use std::collections::HashMap; @@ -24,6 +23,7 @@ fn skip_test() -> bool { false } +#[expect(clippy::expect_used)] async fn run_test_cmd(tmp: TempDir, cmd: Vec<&str>) -> Result { let sandbox_type = get_platform_sandbox().expect("should be able to get sandbox type"); assert_eq!(sandbox_type, SandboxType::MacosSeatbelt); @@ -68,7 +68,6 @@ async fn truncates_output_lines() { let tmp = TempDir::new().expect("should be able to create temp dir"); let cmd = vec!["seq", "300"]; - #[expect(clippy::unwrap_used)] let output = run_test_cmd(tmp, cmd).await.unwrap(); let expected_output = (1..=256) diff --git a/codex-rs/core/tests/live_cli.rs b/codex-rs/core/tests/live_cli.rs index d79e242c4d..e77fe6998e 100644 --- a/codex-rs/core/tests/live_cli.rs +++ b/codex-rs/core/tests/live_cli.rs @@ -17,7 +17,7 @@ fn require_api_key() -> String { /// Helper that spawns the binary inside a TempDir with minimal flags. Returns (Assert, TempDir). fn run_live(prompt: &str) -> (assert_cmd::assert::Assert, TempDir) { - #![allow(clippy::unwrap_used)] + #![expect(clippy::unwrap_used)] use std::io::Read; use std::io::Write; use std::thread; @@ -113,7 +113,6 @@ fn run_live(prompt: &str) -> (assert_cmd::assert::Assert, TempDir) { #[ignore] #[test] fn live_create_file_hello_txt() { - #![allow(clippy::unwrap_used)] if std::env::var("OPENAI_API_KEY").is_err() { eprintln!("skipping live_create_file_hello_txt – OPENAI_API_KEY not set"); return; diff --git a/codex-rs/core/tests/prompt_caching.rs b/codex-rs/core/tests/prompt_caching.rs index 0c2552ee05..d637eb674e 100644 --- a/codex-rs/core/tests/prompt_caching.rs +++ b/codex-rs/core/tests/prompt_caching.rs @@ -1,5 +1,3 @@ -#![allow(clippy::expect_used, clippy::unwrap_used)] - use codex_core::ConversationManager; use codex_core::ModelProviderInfo; use codex_core::built_in_model_providers; @@ -24,7 +22,6 @@ fn sse_completed(id: &str) -> String { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn prefixes_context_and_instructions_once_and_consistently_across_requests() { - #![allow(clippy::unwrap_used)] use pretty_assertions::assert_eq; let server = MockServer::start().await; diff --git a/codex-rs/core/tests/seatbelt.rs b/codex-rs/core/tests/seatbelt.rs index fb2e7452f1..638ac48bb8 100644 --- a/codex-rs/core/tests/seatbelt.rs +++ b/codex-rs/core/tests/seatbelt.rs @@ -1,5 +1,4 @@ #![cfg(target_os = "macos")] -#![expect(clippy::expect_used)] //! Tests for the macOS sandboxing that are specific to Seatbelt. //! Tests that apply to both Mac and Linux sandboxing should go in sandbox.rs. @@ -160,6 +159,7 @@ async fn read_only_forbids_all_writes() { .await; } +#[expect(clippy::expect_used)] fn create_test_scenario(tmp: &TempDir) -> TestScenario { let repo_parent = tmp.path().to_path_buf(); let repo_root = repo_parent.join("repo"); @@ -177,6 +177,7 @@ fn create_test_scenario(tmp: &TempDir) -> TestScenario { } } +#[expect(clippy::expect_used)] /// Note that `path` must be absolute. async fn touch(path: &Path, policy: &SandboxPolicy) -> bool { assert!(path.is_absolute(), "Path must be absolute: {path:?}"); diff --git a/codex-rs/core/tests/stream_error_allows_next_turn.rs b/codex-rs/core/tests/stream_error_allows_next_turn.rs index d590c43312..415e75a426 100644 --- a/codex-rs/core/tests/stream_error_allows_next_turn.rs +++ b/codex-rs/core/tests/stream_error_allows_next_turn.rs @@ -25,7 +25,6 @@ fn sse_completed(id: &str) -> String { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn continue_after_stream_error() { - #![allow(clippy::unwrap_used)] if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { println!( "Skipping test because it cannot execute when network is disabled in a Codex sandbox." diff --git a/codex-rs/core/tests/stream_no_completed.rs b/codex-rs/core/tests/stream_no_completed.rs index 5fa8ab8ba1..3fb3f642d7 100644 --- a/codex-rs/core/tests/stream_no_completed.rs +++ b/codex-rs/core/tests/stream_no_completed.rs @@ -33,8 +33,6 @@ fn sse_completed(id: &str) -> String { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn retries_on_early_close() { - #![allow(clippy::unwrap_used)] - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { println!( "Skipping test because it cannot execute when network is disabled in a Codex sandbox." diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rs index 22cf130462..5d64fe620b 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -191,7 +191,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { self.answer_started = true; } print!("{delta}"); - #[allow(clippy::expect_used)] + #[expect(clippy::expect_used)] std::io::stdout().flush().expect("could not flush stdout"); } EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent { delta }) => { @@ -207,7 +207,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { self.reasoning_started = true; } print!("{delta}"); - #[allow(clippy::expect_used)] + #[expect(clippy::expect_used)] std::io::stdout().flush().expect("could not flush stdout"); } EventMsg::AgentReasoningSectionBreak(_) => { @@ -215,7 +215,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { return CodexStatus::Running; } println!(); - #[allow(clippy::expect_used)] + #[expect(clippy::expect_used)] std::io::stdout().flush().expect("could not flush stdout"); } EventMsg::AgentReasoningRawContent(AgentReasoningRawContentEvent { text }) => { @@ -224,7 +224,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { } if !self.raw_reasoning_started { print!("{text}"); - #[allow(clippy::expect_used)] + #[expect(clippy::expect_used)] std::io::stdout().flush().expect("could not flush stdout"); } else { println!(); @@ -241,7 +241,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { self.raw_reasoning_started = true; } print!("{delta}"); - #[allow(clippy::expect_used)] + #[expect(clippy::expect_used)] std::io::stdout().flush().expect("could not flush stdout"); } EventMsg::AgentMessage(AgentMessageEvent { message }) => { diff --git a/codex-rs/exec/src/event_processor_with_json_output.rs b/codex-rs/exec/src/event_processor_with_json_output.rs index 76985518e6..11e9732e99 100644 --- a/codex-rs/exec/src/event_processor_with_json_output.rs +++ b/codex-rs/exec/src/event_processor_with_json_output.rs @@ -28,7 +28,7 @@ impl EventProcessor for EventProcessorWithJsonOutput { .into_iter() .map(|(key, value)| (key.to_string(), value)) .collect::>(); - #[allow(clippy::expect_used)] + #[expect(clippy::expect_used)] let config_json = serde_json::to_string(&entries).expect("Failed to serialize config summary to JSON"); println!("{config_json}"); diff --git a/codex-rs/exec/tests/sandbox.rs b/codex-rs/exec/tests/sandbox.rs index 22caf8abc6..a98e0a9760 100644 --- a/codex-rs/exec/tests/sandbox.rs +++ b/codex-rs/exec/tests/sandbox.rs @@ -1,6 +1,4 @@ #![cfg(unix)] -#![expect(clippy::expect_used)] - use codex_core::protocol::SandboxPolicy; use codex_core::spawn::StdioPolicy; use std::collections::HashMap; @@ -180,6 +178,7 @@ async fn allow_unix_socketpair_recvfrom() { const IN_SANDBOX_ENV_VAR: &str = "IN_SANDBOX"; +#[expect(clippy::expect_used)] pub async fn run_code_under_sandbox( test_selector: &str, policy: &SandboxPolicy, diff --git a/codex-rs/execpolicy/src/execv_checker.rs b/codex-rs/execpolicy/src/execv_checker.rs index 3c9084e825..242ea6d177 100644 --- a/codex-rs/execpolicy/src/execv_checker.rs +++ b/codex-rs/execpolicy/src/execv_checker.rs @@ -140,7 +140,6 @@ fn is_executable_file(path: &str) -> bool { #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used)] use tempfile::TempDir; use super::*; diff --git a/codex-rs/execpolicy/tests/bad.rs b/codex-rs/execpolicy/tests/bad.rs index 5c2999a0cb..8b6e195fb0 100644 --- a/codex-rs/execpolicy/tests/bad.rs +++ b/codex-rs/execpolicy/tests/bad.rs @@ -1,4 +1,3 @@ -#![expect(clippy::expect_used)] use codex_execpolicy::NegativeExamplePassedCheck; use codex_execpolicy::get_default_policy; diff --git a/codex-rs/execpolicy/tests/cp.rs b/codex-rs/execpolicy/tests/cp.rs index 14fd24410f..aa19f0b5d5 100644 --- a/codex-rs/execpolicy/tests/cp.rs +++ b/codex-rs/execpolicy/tests/cp.rs @@ -1,4 +1,3 @@ -#![expect(clippy::expect_used)] extern crate codex_execpolicy; use codex_execpolicy::ArgMatcher; @@ -12,6 +11,7 @@ use codex_execpolicy::Result; use codex_execpolicy::ValidExec; use codex_execpolicy::get_default_policy; +#[expect(clippy::expect_used)] fn setup() -> Policy { get_default_policy().expect("failed to load default policy") } diff --git a/codex-rs/execpolicy/tests/good.rs b/codex-rs/execpolicy/tests/good.rs index 645728afbd..3b7313a335 100644 --- a/codex-rs/execpolicy/tests/good.rs +++ b/codex-rs/execpolicy/tests/good.rs @@ -1,4 +1,3 @@ -#![expect(clippy::expect_used)] use codex_execpolicy::PositiveExampleFailedCheck; use codex_execpolicy::get_default_policy; diff --git a/codex-rs/execpolicy/tests/head.rs b/codex-rs/execpolicy/tests/head.rs index 8d7a165cca..3c32ccfbfe 100644 --- a/codex-rs/execpolicy/tests/head.rs +++ b/codex-rs/execpolicy/tests/head.rs @@ -1,4 +1,3 @@ -#![expect(clippy::expect_used)] use codex_execpolicy::ArgMatcher; use codex_execpolicy::ArgType; use codex_execpolicy::Error; @@ -13,6 +12,7 @@ use codex_execpolicy::get_default_policy; extern crate codex_execpolicy; +#[expect(clippy::expect_used)] fn setup() -> Policy { get_default_policy().expect("failed to load default policy") } diff --git a/codex-rs/execpolicy/tests/literal.rs b/codex-rs/execpolicy/tests/literal.rs index 629aeb9cfe..d849371e3b 100644 --- a/codex-rs/execpolicy/tests/literal.rs +++ b/codex-rs/execpolicy/tests/literal.rs @@ -1,4 +1,3 @@ -#![expect(clippy::expect_used)] use codex_execpolicy::ArgType; use codex_execpolicy::Error; use codex_execpolicy::ExecCall; diff --git a/codex-rs/execpolicy/tests/ls.rs b/codex-rs/execpolicy/tests/ls.rs index 854ec3bf58..e52316c06e 100644 --- a/codex-rs/execpolicy/tests/ls.rs +++ b/codex-rs/execpolicy/tests/ls.rs @@ -1,4 +1,3 @@ -#![expect(clippy::expect_used)] extern crate codex_execpolicy; use codex_execpolicy::ArgType; @@ -12,6 +11,7 @@ use codex_execpolicy::Result; use codex_execpolicy::ValidExec; use codex_execpolicy::get_default_policy; +#[expect(clippy::expect_used)] fn setup() -> Policy { get_default_policy().expect("failed to load default policy") } diff --git a/codex-rs/execpolicy/tests/pwd.rs b/codex-rs/execpolicy/tests/pwd.rs index 339908e928..fdf5a4f1a5 100644 --- a/codex-rs/execpolicy/tests/pwd.rs +++ b/codex-rs/execpolicy/tests/pwd.rs @@ -1,4 +1,3 @@ -#![expect(clippy::expect_used)] extern crate codex_execpolicy; use std::vec; @@ -12,6 +11,7 @@ use codex_execpolicy::PositionalArg; use codex_execpolicy::ValidExec; use codex_execpolicy::get_default_policy; +#[expect(clippy::expect_used)] fn setup() -> Policy { get_default_policy().expect("failed to load default policy") } diff --git a/codex-rs/execpolicy/tests/sed.rs b/codex-rs/execpolicy/tests/sed.rs index 064e539305..bf35bf6d46 100644 --- a/codex-rs/execpolicy/tests/sed.rs +++ b/codex-rs/execpolicy/tests/sed.rs @@ -1,4 +1,3 @@ -#![expect(clippy::expect_used)] extern crate codex_execpolicy; use codex_execpolicy::ArgType; @@ -13,6 +12,7 @@ use codex_execpolicy::Result; use codex_execpolicy::ValidExec; use codex_execpolicy::get_default_policy; +#[expect(clippy::expect_used)] fn setup() -> Policy { get_default_policy().expect("failed to load default policy") } diff --git a/codex-rs/linux-sandbox/tests/landlock.rs b/codex-rs/linux-sandbox/tests/landlock.rs index 76de2547a6..8faa02d158 100644 --- a/codex-rs/linux-sandbox/tests/landlock.rs +++ b/codex-rs/linux-sandbox/tests/landlock.rs @@ -1,6 +1,4 @@ #![cfg(target_os = "linux")] -#![expect(clippy::unwrap_used, clippy::expect_used)] - use codex_core::config_types::ShellEnvironmentPolicy; use codex_core::error::CodexErr; use codex_core::error::SandboxErr; @@ -35,7 +33,7 @@ fn create_env_from_core_vars() -> HashMap { create_env(&policy) } -#[allow(clippy::print_stdout)] +#[expect(clippy::print_stdout, clippy::expect_used, clippy::unwrap_used)] async fn run_cmd(cmd: &[&str], writable_roots: &[PathBuf], timeout_ms: u64) { let params = ExecParams { command: cmd.iter().map(|elm| elm.to_string()).collect(), @@ -132,6 +130,7 @@ async fn test_timeout() { /// does NOT succeed (i.e. returns a non‑zero exit code) **unless** the binary /// is missing in which case we silently treat it as an accepted skip so the /// suite remains green on leaner CI images. +#[expect(clippy::expect_used)] async fn assert_network_blocked(cmd: &[&str]) { let cwd = std::env::current_dir().expect("cwd should exist"); let params = ExecParams { diff --git a/codex-rs/login/src/lib.rs b/codex-rs/login/src/lib.rs index d4358d2735..c40c1e6b52 100644 --- a/codex-rs/login/src/lib.rs +++ b/codex-rs/login/src/lib.rs @@ -427,7 +427,6 @@ pub struct AuthDotJson { #[cfg(test)] mod tests { - #![expect(clippy::expect_used, clippy::unwrap_used)] use super::*; use crate::token_data::IdTokenInfo; use crate::token_data::KnownPlan; diff --git a/codex-rs/login/src/token_data.rs b/codex-rs/login/src/token_data.rs index 1cb537fa24..2ac549fda2 100644 --- a/codex-rs/login/src/token_data.rs +++ b/codex-rs/login/src/token_data.rs @@ -155,7 +155,6 @@ mod tests { use serde::Serialize; #[test] - #[expect(clippy::expect_used, clippy::unwrap_used)] fn id_token_info_parses_email_and_plan() { #[derive(Serialize)] struct Header { diff --git a/codex-rs/login/tests/login_server_e2e.rs b/codex-rs/login/tests/login_server_e2e.rs index 3fe0e32041..3d00480051 100644 --- a/codex-rs/login/tests/login_server_e2e.rs +++ b/codex-rs/login/tests/login_server_e2e.rs @@ -1,4 +1,4 @@ -#![allow(clippy::unwrap_used)] +#![expect(clippy::unwrap_used)] use std::net::SocketAddr; use std::net::TcpListener; use std::thread; diff --git a/codex-rs/mcp-server/src/codex_tool_config.rs b/codex-rs/mcp-server/src/codex_tool_config.rs index 1d77eb4b82..548f29334f 100644 --- a/codex-rs/mcp-server/src/codex_tool_config.rs +++ b/codex-rs/mcp-server/src/codex_tool_config.rs @@ -236,7 +236,6 @@ mod tests { #[test] fn verify_codex_tool_json_schema() { let tool = create_tool_for_codex_tool_call_param(); - #[expect(clippy::expect_used)] let tool_json = serde_json::to_value(&tool).expect("tool serializes"); let expected_tool_json = serde_json::json!({ "name": "codex", @@ -305,7 +304,6 @@ mod tests { #[test] fn verify_codex_tool_reply_json_schema() { let tool = create_tool_for_codex_tool_call_reply_param(); - #[expect(clippy::expect_used)] let tool_json = serde_json::to_value(&tool).expect("tool serializes"); let expected_tool_json = serde_json::json!({ "description": "Continue a Codex session by providing the session id and prompt.", diff --git a/codex-rs/mcp-server/src/json_to_toml.rs b/codex-rs/mcp-server/src/json_to_toml.rs index ae33382a1d..04f1f30615 100644 --- a/codex-rs/mcp-server/src/json_to_toml.rs +++ b/codex-rs/mcp-server/src/json_to_toml.rs @@ -28,7 +28,6 @@ pub(crate) fn json_to_toml(v: JsonValue) -> TomlValue { } #[cfg(test)] -#[allow(clippy::unwrap_used)] mod tests { use super::*; use pretty_assertions::assert_eq; diff --git a/codex-rs/mcp-server/src/mcp_protocol.rs b/codex-rs/mcp-server/src/mcp_protocol.rs index 0528e18a39..26c6655f3b 100644 --- a/codex-rs/mcp-server/src/mcp_protocol.rs +++ b/codex-rs/mcp-server/src/mcp_protocol.rs @@ -293,8 +293,6 @@ pub enum ClientNotification { } #[cfg(test)] -#[allow(clippy::expect_used)] -#[allow(clippy::unwrap_used)] mod tests { use std::path::PathBuf; diff --git a/codex-rs/mcp-server/src/outgoing_message.rs b/codex-rs/mcp-server/src/outgoing_message.rs index f13b8b324f..f408ca0a45 100644 --- a/codex-rs/mcp-server/src/outgoing_message.rs +++ b/codex-rs/mcp-server/src/outgoing_message.rs @@ -101,7 +101,7 @@ impl OutgoingMessageSender { event: &Event, meta: Option, ) { - #[allow(clippy::expect_used)] + #[expect(clippy::expect_used)] let event_json = serde_json::to_value(event).expect("Event must serialize"); let params = if let Ok(params) = serde_json::to_value(OutgoingNotificationParams { @@ -244,8 +244,6 @@ pub(crate) struct OutgoingError { #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used)] - use codex_core::protocol::EventMsg; use codex_core::protocol::SessionConfiguredEvent; use pretty_assertions::assert_eq; diff --git a/codex-rs/mcp-server/src/wire_format.rs b/codex-rs/mcp-server/src/wire_format.rs index 95d55e8bf5..034c72a1c2 100644 --- a/codex-rs/mcp-server/src/wire_format.rs +++ b/codex-rs/mcp-server/src/wire_format.rs @@ -222,7 +222,6 @@ pub struct ApplyPatchApprovalResponse { pub decision: ReviewDecision, } -#[allow(clippy::unwrap_used)] #[cfg(test)] mod tests { use super::*; diff --git a/codex-rs/mcp-server/tests/codex_message_processor_flow.rs b/codex-rs/mcp-server/tests/codex_message_processor_flow.rs index 7b7845609e..2cc55c6d62 100644 --- a/codex-rs/mcp-server/tests/codex_message_processor_flow.rs +++ b/codex-rs/mcp-server/tests/codex_message_processor_flow.rs @@ -1,5 +1,3 @@ -#![allow(clippy::expect_used, clippy::unwrap_used)] - use std::path::Path; use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; diff --git a/codex-rs/mcp-server/tests/codex_tool.rs b/codex-rs/mcp-server/tests/codex_tool.rs index fc992a8cd1..92f11eaa4f 100644 --- a/codex-rs/mcp-server/tests/codex_tool.rs +++ b/codex-rs/mcp-server/tests/codex_tool.rs @@ -304,7 +304,7 @@ async fn test_codex_tool_passes_base_instructions() { } async fn codex_tool_passes_base_instructions() -> anyhow::Result<()> { - #![allow(clippy::unwrap_used)] + #![expect(clippy::unwrap_used)] let server = create_mock_chat_completions_server(vec![create_final_assistant_message_sse_response( diff --git a/codex-rs/mcp-server/tests/create_conversation.rs b/codex-rs/mcp-server/tests/create_conversation.rs index 41052ea7b3..2349b0b9e4 100644 --- a/codex-rs/mcp-server/tests/create_conversation.rs +++ b/codex-rs/mcp-server/tests/create_conversation.rs @@ -1,5 +1,3 @@ -#![allow(clippy::expect_used, clippy::unwrap_used)] - use std::path::Path; use mcp_test_support::McpProcess; diff --git a/codex-rs/mcp-server/tests/send_message.rs b/codex-rs/mcp-server/tests/send_message.rs index f06c1587e3..bf2966ef05 100644 --- a/codex-rs/mcp-server/tests/send_message.rs +++ b/codex-rs/mcp-server/tests/send_message.rs @@ -1,5 +1,3 @@ -#![allow(clippy::expect_used)] - use std::path::Path; use std::thread::sleep; use std::time::Duration; diff --git a/codex-rs/mcp-types/tests/initialize.rs b/codex-rs/mcp-types/tests/initialize.rs index c69586f030..04778f2a90 100644 --- a/codex-rs/mcp-types/tests/initialize.rs +++ b/codex-rs/mcp-types/tests/initialize.rs @@ -1,4 +1,3 @@ -#![expect(clippy::expect_used)] use mcp_types::ClientCapabilities; use mcp_types::ClientRequest; use mcp_types::Implementation; diff --git a/codex-rs/mcp-types/tests/progress_notification.rs b/codex-rs/mcp-types/tests/progress_notification.rs index b518e4a91c..396efca2bd 100644 --- a/codex-rs/mcp-types/tests/progress_notification.rs +++ b/codex-rs/mcp-types/tests/progress_notification.rs @@ -1,4 +1,3 @@ -#![expect(clippy::expect_used)] use mcp_types::JSONRPCMessage; use mcp_types::ProgressNotificationParams; use mcp_types::ProgressToken; diff --git a/codex-rs/ollama/src/client.rs b/codex-rs/ollama/src/client.rs index 6f4621135c..55c86e31f8 100644 --- a/codex-rs/ollama/src/client.rs +++ b/codex-rs/ollama/src/client.rs @@ -53,7 +53,7 @@ impl OllamaClient { /// Build a client from a provider definition and verify the server is reachable. async fn try_from_provider(provider: &ModelProviderInfo) -> io::Result { - #![allow(clippy::expect_used)] + #![expect(clippy::expect_used)] let base_url = provider .base_url .as_ref() @@ -235,7 +235,6 @@ impl OllamaClient { #[cfg(test)] mod tests { - #![allow(clippy::expect_used, clippy::unwrap_used)] use super::*; // Happy-path tests using a mock HTTP server; skip if sandbox network is disabled. diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 256289b21f..ee054e037a 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -188,7 +188,7 @@ impl App<'_> { } } - #[allow(clippy::expect_used)] + #[expect(clippy::expect_used)] let deadline = next_deadline.expect("deadline set"); let now = Instant::now(); let timeout = if deadline > now { diff --git a/codex-rs/tui/src/bottom_pane/chat_composer_history.rs b/codex-rs/tui/src/bottom_pane/chat_composer_history.rs index a744a409f3..93accfcd1a 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer_history.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer_history.rs @@ -182,7 +182,6 @@ impl ChatComposerHistory { #[cfg(test)] mod tests { - #![expect(clippy::expect_used)] use super::*; use crate::app_event::AppEvent; use codex_core::protocol::Op; diff --git a/codex-rs/tui/src/bottom_pane/textarea.rs b/codex-rs/tui/src/bottom_pane/textarea.rs index f0cfa614f9..d29698d7df 100644 --- a/codex-rs/tui/src/bottom_pane/textarea.rs +++ b/codex-rs/tui/src/bottom_pane/textarea.rs @@ -801,7 +801,7 @@ impl TextArea { } } - #[allow(clippy::unwrap_used)] + #[expect(clippy::unwrap_used)] fn wrapped_lines(&self, width: u16) -> Ref<'_, Vec>> { // Ensure cache is ready (potentially mutably borrow, then drop) { @@ -926,7 +926,6 @@ impl TextArea { } #[cfg(test)] -#[allow(clippy::unwrap_used)] mod tests { use super::*; // crossterm types are intentionally not imported here to avoid unused warnings @@ -1432,7 +1431,6 @@ mod tests { // Seed the RNG based on the current day in Pacific Time (PST/PDT). This // keeps the fuzz test deterministic within a day while still varying // day-to-day to improve coverage. - #[allow(clippy::unwrap_used)] let pst_today_seed: u64 = (chrono::Utc::now() - chrono::Duration::hours(8)) .date_naive() .and_hms_opt(0, 0, 0) diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 3336024272..95542c06fb 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -1,5 +1,3 @@ -#![allow(clippy::unwrap_used, clippy::expect_used, unnameable_test_items)] - use super::*; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; diff --git a/codex-rs/tui/src/citation_regex.rs b/codex-rs/tui/src/citation_regex.rs index e5355ec2b8..ff5147ca83 100644 --- a/codex-rs/tui/src/citation_regex.rs +++ b/codex-rs/tui/src/citation_regex.rs @@ -1,4 +1,4 @@ -#![allow(clippy::expect_used)] +#![expect(clippy::expect_used)] use regex_lite::Regex; diff --git a/codex-rs/tui/src/diff_render.rs b/codex-rs/tui/src/diff_render.rs index 5a3199c04b..152a8e2862 100644 --- a/codex-rs/tui/src/diff_render.rs +++ b/codex-rs/tui/src/diff_render.rs @@ -357,7 +357,6 @@ fn style_del() -> Style { Style::default().fg(Color::Red) } -#[allow(clippy::expect_used)] #[cfg(test)] mod tests { use super::*; diff --git a/codex-rs/tui/src/file_search.rs b/codex-rs/tui/src/file_search.rs index 9fb010a095..8a05b2c165 100644 --- a/codex-rs/tui/src/file_search.rs +++ b/codex-rs/tui/src/file_search.rs @@ -31,10 +31,7 @@ use std::time::Duration; use crate::app_event::AppEvent; use crate::app_event_sender::AppEventSender; -#[allow(clippy::unwrap_used)] const MAX_FILE_SEARCH_RESULTS: NonZeroUsize = NonZeroUsize::new(8).unwrap(); - -#[allow(clippy::unwrap_used)] const NUM_FILE_SEARCH_THREADS: NonZeroUsize = NonZeroUsize::new(2).unwrap(); /// How long to wait after a keystroke before firing the first search when none @@ -84,7 +81,7 @@ impl FileSearchManager { /// Call whenever the user edits the `@` token. pub fn on_user_query(&self, query: String) { { - #[allow(clippy::unwrap_used)] + #[expect(clippy::unwrap_used)] let mut st = self.state.lock().unwrap(); if query == st.latest_query { // No change, nothing to do. @@ -125,7 +122,7 @@ impl FileSearchManager { // `active_search` is cleared. thread::sleep(FILE_SEARCH_DEBOUNCE); loop { - #[allow(clippy::unwrap_used)] + #[expect(clippy::unwrap_used)] if state.lock().unwrap().active_search.is_none() { break; } @@ -137,7 +134,7 @@ impl FileSearchManager { let cancellation_token = Arc::new(AtomicBool::new(false)); let token = cancellation_token.clone(); let query = { - #[allow(clippy::unwrap_used)] + #[expect(clippy::unwrap_used)] let mut st = state.lock().unwrap(); let query = st.latest_query.clone(); st.is_search_scheduled = false; @@ -188,7 +185,7 @@ impl FileSearchManager { // that we are clearing the ActiveSearch that corresponds to the // cancellation token we were given. { - #[allow(clippy::unwrap_used)] + #[expect(clippy::unwrap_used)] let mut st = search_state.lock().unwrap(); if let Some(active_search) = &st.active_search { if Arc::ptr_eq(&active_search.cancellation_token, &cancellation_token) { diff --git a/codex-rs/tui/src/insert_history.rs b/codex-rs/tui/src/insert_history.rs index 971c376234..ced667af8d 100644 --- a/codex-rs/tui/src/insert_history.rs +++ b/codex-rs/tui/src/insert_history.rs @@ -379,7 +379,6 @@ fn slice_line_spans( #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used)] use super::*; #[test] diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index a661242d3e..f1a7d99b79 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -295,7 +295,6 @@ fn restore() { } } -#[allow(clippy::unwrap_used)] fn should_show_login_screen(config: &Config) -> bool { if config.model_provider.requires_openai_auth { // Reading the OpenAI API key is an async operation because it may need diff --git a/codex-rs/tui/src/text_formatting.rs b/codex-rs/tui/src/text_formatting.rs index 208dc700a8..b77c6e5baa 100644 --- a/codex-rs/tui/src/text_formatting.rs +++ b/codex-rs/tui/src/text_formatting.rs @@ -102,7 +102,6 @@ pub(crate) fn truncate_text(text: &str, max_graphemes: usize) -> String { #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used)] use super::*; use pretty_assertions::assert_eq; From d0b907d3992dd73d40a4ba1f6d78e9c51c0ec324 Mon Sep 17 00:00:00 2001 From: easong-openai Date: Thu, 14 Aug 2025 19:14:46 -0700 Subject: [PATCH 14/16] re-implement session id in status (#2332) Basically the same thing as https://github.com/openai/codex/pull/2297 --- codex-rs/tui/src/chatwidget.rs | 5 +++++ codex-rs/tui/src/chatwidget/tests.rs | 1 + codex-rs/tui/src/history_cell.rs | 14 +++++++++++++- 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 7cd7e6fad9..c10b94b79a 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -59,6 +59,7 @@ use crate::streaming::controller::AppEventHistorySink; use crate::streaming::controller::StreamController; use codex_core::ConversationManager; use codex_file_search::FileMatch; +use uuid::Uuid; // Track information about an in-flight exec command. struct RunningCommand { @@ -86,6 +87,7 @@ pub(crate) struct ChatWidget<'a> { interrupts: InterruptManager, // Whether a redraw is needed after handling the current event needs_redraw: bool, + session_id: Option, } struct UserMessage { @@ -125,6 +127,7 @@ impl ChatWidget<'_> { fn on_session_configured(&mut self, event: codex_core::protocol::SessionConfiguredEvent) { self.bottom_pane .set_history_metadata(event.history_log_id, event.history_entry_count); + self.session_id = Some(event.session_id); self.add_to_history(&history_cell::new_session_info(&self.config, event, true)); if let Some(user_message) = self.initial_user_message.take() { self.submit_user_message(user_message); @@ -528,6 +531,7 @@ impl ChatWidget<'_> { task_complete_pending: false, interrupts: InterruptManager::new(), needs_redraw: false, + session_id: None, } } @@ -675,6 +679,7 @@ impl ChatWidget<'_> { self.add_to_history(&history_cell::new_status_output( &self.config, &self.total_token_usage, + &self.session_id, )); } diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 95542c06fb..bf03a8ed05 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -141,6 +141,7 @@ fn make_chatwidget_manual() -> ( task_complete_pending: false, interrupts: InterruptManager::new(), needs_redraw: false, + session_id: None, }; (widget, rx, op_rx) } diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index ba645a7e50..a4cebe981d 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -37,6 +37,7 @@ use std::path::PathBuf; use std::time::Duration; use std::time::Instant; use tracing::error; +use uuid::Uuid; #[derive(Clone)] pub(crate) struct CommandOutput { @@ -483,7 +484,11 @@ pub(crate) fn new_diff_output(message: String) -> PlainHistoryCell { PlainHistoryCell { lines } } -pub(crate) fn new_status_output(config: &Config, usage: &TokenUsage) -> PlainHistoryCell { +pub(crate) fn new_status_output( + config: &Config, + usage: &TokenUsage, + session_id: &Option, +) -> PlainHistoryCell { let mut lines: Vec> = Vec::new(); lines.push(Line::from("/status".magenta())); @@ -521,6 +526,13 @@ pub(crate) fn new_status_output(config: &Config, usage: &TokenUsage) -> PlainHis sandbox_name.into(), ])); + if let Some(session_id) = session_id { + lines.push(Line::from(vec![ + " β€’ Session ID: ".into(), + session_id.to_string().into(), + ])); + } + lines.push(Line::from("")); // πŸ‘€ Account (only if ChatGPT tokens exist), shown under the first block From 76df07350ac505e2b813e3be88a26c4409760d0a Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 14 Aug 2025 19:42:14 -0700 Subject: [PATCH 15/16] Cleanup rust login server a bit more (#2331) Remove some extra abstractions. --------- Co-authored-by: easong-openai --- codex-rs/cli/src/login.rs | 42 +--- codex-rs/login/src/lib.rs | 64 +----- codex-rs/login/src/server.rs | 266 ++++++++++++----------- codex-rs/login/tests/login_server_e2e.rs | 63 ++---- codex-rs/tui/src/onboarding/auth.rs | 56 ++--- 5 files changed, 208 insertions(+), 283 deletions(-) diff --git a/codex-rs/cli/src/login.rs b/codex-rs/cli/src/login.rs index 895eeb1089..a5ee7fa430 100644 --- a/codex-rs/cli/src/login.rs +++ b/codex-rs/cli/src/login.rs @@ -4,42 +4,24 @@ use codex_core::config::ConfigOverrides; use codex_login::AuthMode; use codex_login::CLIENT_ID; use codex_login::CodexAuth; -use codex_login::LoginServerInfo; use codex_login::OPENAI_API_KEY_ENV_VAR; use codex_login::ServerOptions; use codex_login::login_with_api_key; use codex_login::logout; -use codex_login::run_server_blocking_with_notify; +use codex_login::run_login_server; use std::env; -use std::path::Path; -use std::sync::mpsc; +use std::path::PathBuf; -pub async fn login_with_chatgpt(codex_home: &Path) -> std::io::Result<()> { - let (tx, rx) = mpsc::channel::(); - let client_id = CLIENT_ID; - let codex_home = codex_home.to_path_buf(); - tokio::spawn(async move { - match rx.recv() { - Ok(LoginServerInfo { - auth_url, - actual_port, - }) => { - eprintln!( - "Starting local login server on http://localhost:{actual_port}.\nIf your browser did not open, navigate to this URL to authenticate:\n\n{auth_url}", - ); - } - _ => { - tracing::error!("Failed to receive login server info"); - } - } - }); +pub async fn login_with_chatgpt(codex_home: PathBuf) -> std::io::Result<()> { + let opts = ServerOptions::new(codex_home, CLIENT_ID.to_string()); + let server = run_login_server(opts, None)?; - tokio::task::spawn_blocking(move || { - let opts = ServerOptions::new(&codex_home, client_id); - run_server_blocking_with_notify(opts, Some(tx), None) - }) - .await - .map_err(std::io::Error::other)??; + eprintln!( + "Starting local login server on http://localhost:{}.\nIf your browser did not open, navigate to this URL to authenticate:\n\n{}", + server.actual_port, server.auth_url, + ); + + server.block_until_done()?; eprintln!("Successfully logged in"); Ok(()) @@ -48,7 +30,7 @@ pub async fn login_with_chatgpt(codex_home: &Path) -> std::io::Result<()> { pub async fn run_login_with_chatgpt(cli_config_overrides: CliConfigOverrides) -> ! { let config = load_config_or_exit(cli_config_overrides); - match login_with_chatgpt(&config.codex_home).await { + match login_with_chatgpt(config.codex_home).await { Ok(_) => { eprintln!("Successfully logged in"); std::process::exit(0); diff --git a/codex-rs/login/src/lib.rs b/codex-rs/login/src/lib.rs index c40c1e6b52..7a5f0277e9 100644 --- a/codex-rs/login/src/lib.rs +++ b/codex-rs/login/src/lib.rs @@ -16,10 +16,9 @@ use std::sync::Arc; use std::sync::Mutex; use std::time::Duration; -pub use crate::server::LoginServerInfo; +pub use crate::server::LoginServer; pub use crate::server::ServerOptions; -pub use crate::server::run_server_blocking; -pub use crate::server::run_server_blocking_with_notify; +pub use crate::server::run_login_server; pub use crate::token_data::TokenData; use crate::token_data::parse_id_token; @@ -252,65 +251,6 @@ pub fn logout(codex_home: &Path) -> std::io::Result { } } -/// Represents a running login server. The server can be stopped by calling `cancel()` on SpawnedLogin. -#[derive(Debug, Clone)] -pub struct SpawnedLogin { - url: Arc>>, - done: Arc>>, - shutdown: Arc, -} - -impl SpawnedLogin { - pub fn get_login_url(&self) -> Option { - self.url.lock().ok().and_then(|u| u.clone()) - } - - pub fn get_auth_result(&self) -> Option { - self.done.lock().ok().and_then(|d| *d) - } - - pub fn cancel(&self) { - self.shutdown - .store(true, std::sync::atomic::Ordering::SeqCst); - } -} - -pub fn spawn_login_with_chatgpt(codex_home: &Path) -> std::io::Result { - let (tx, rx) = std::sync::mpsc::channel::(); - let shutdown = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let done = Arc::new(Mutex::new(None::)); - let url = Arc::new(Mutex::new(None::)); - - let codex_home_buf = codex_home.to_path_buf(); - let client_id = CLIENT_ID.to_string(); - - let shutdown_clone = shutdown.clone(); - let done_clone = done.clone(); - std::thread::spawn(move || { - let opts = ServerOptions::new(&codex_home_buf, &client_id); - let res = run_server_blocking_with_notify(opts, Some(tx), Some(shutdown_clone)); - let success = res.is_ok(); - if let Ok(mut lock) = done_clone.lock() { - *lock = Some(success); - } - }); - - let url_clone = url.clone(); - std::thread::spawn(move || { - if let Ok(u) = rx.recv() { - if let Ok(mut lock) = url_clone.lock() { - *lock = Some(u.auth_url); - } - } - }); - - Ok(SpawnedLogin { - url, - done, - shutdown, - }) -} - pub fn login_with_api_key(codex_home: &Path, api_key: &str) -> std::io::Result<()> { let auth_dot_json = AuthDotJson { openai_api_key: Some(api_key.to_string()), diff --git a/codex-rs/login/src/server.rs b/codex-rs/login/src/server.rs index 550ee703a2..9365905f46 100644 --- a/codex-rs/login/src/server.rs +++ b/codex-rs/login/src/server.rs @@ -1,39 +1,40 @@ use std::io::{self}; use std::path::Path; +use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; +use std::thread; +use crate::AuthDotJson; +use crate::get_auth_file; +use crate::pkce::PkceCodes; +use crate::pkce::generate_pkce; use base64::Engine; use chrono::Utc; use rand::RngCore; use tiny_http::Response; use tiny_http::Server; -use crate::AuthDotJson; -use crate::get_auth_file; -use crate::pkce::PkceCodes; -use crate::pkce::generate_pkce; - const DEFAULT_ISSUER: &str = "https://auth.openai.com"; const DEFAULT_PORT: u16 = 1455; #[derive(Debug, Clone)] -pub struct ServerOptions<'a> { - pub codex_home: &'a Path, - pub client_id: &'a str, - pub issuer: &'a str, +pub struct ServerOptions { + pub codex_home: PathBuf, + pub client_id: String, + pub issuer: String, pub port: u16, pub open_browser: bool, pub force_state: Option, } -impl<'a> ServerOptions<'a> { - pub fn new(codex_home: &'a Path, client_id: &'a str) -> Self { +impl ServerOptions { + pub fn new(codex_home: PathBuf, client_id: String) -> Self { Self { codex_home, - client_id, - issuer: DEFAULT_ISSUER, + client_id: client_id.to_string(), + issuer: DEFAULT_ISSUER.to_string(), port: DEFAULT_PORT, open_browser: true, force_state: None, @@ -41,21 +42,31 @@ impl<'a> ServerOptions<'a> { } } -#[allow(dead_code)] -pub fn run_server_blocking(opts: ServerOptions) -> io::Result<()> { - run_server_blocking_with_notify(opts, None, None) -} - -pub struct LoginServerInfo { +#[derive(Debug)] +pub struct LoginServer { pub auth_url: String, pub actual_port: u16, + pub server_handle: thread::JoinHandle>, + pub shutdown_flag: Arc, } -pub fn run_server_blocking_with_notify( +impl LoginServer { + pub fn block_until_done(self) -> io::Result<()> { + #[expect(clippy::expect_used)] + self.server_handle + .join() + .expect("can't join on the server thread") + } + + pub fn cancel(&self) { + self.shutdown_flag.store(true, Ordering::SeqCst); + } +} + +pub fn run_login_server( opts: ServerOptions, - notify_started: Option>, shutdown_flag: Option>, -) -> io::Result<()> { +) -> io::Result { let pkce = generate_pkce(); let state = opts.force_state.clone().unwrap_or_else(generate_state); @@ -71,135 +82,138 @@ pub fn run_server_blocking_with_notify( }; let redirect_uri = format!("http://localhost:{actual_port}/auth/callback"); - let auth_url = build_authorize_url(opts.issuer, opts.client_id, &redirect_uri, &pkce, &state); - - if let Some(tx) = ¬ify_started { - let _ = tx.send(LoginServerInfo { - auth_url: auth_url.clone(), - actual_port, - }); - } + let auth_url = build_authorize_url(&opts.issuer, &opts.client_id, &redirect_uri, &pkce, &state); if opts.open_browser { let _ = webbrowser::open(&auth_url); } - let shutdown_flag = shutdown_flag.unwrap_or_else(|| Arc::new(AtomicBool::new(false))); - while !shutdown_flag.load(Ordering::SeqCst) { - let req = match server.recv() { - Ok(r) => r, - Err(e) => return Err(io::Error::other(e)), - }; + let shutdown_flag_clone = shutdown_flag.clone(); + let server_handle = thread::spawn(move || { + while !shutdown_flag.load(Ordering::SeqCst) { + let req = match server.recv() { + Ok(r) => r, + Err(e) => return Err(io::Error::other(e)), + }; - let url_raw = req.url().to_string(); - let parsed_url = match url::Url::parse(&format!("http://localhost{url_raw}")) { - Ok(u) => u, - Err(e) => { - eprintln!("URL parse error: {e}"); - let _ = req.respond(Response::from_string("Bad Request").with_status_code(400)); - continue; - } - }; - let path = parsed_url.path().to_string(); - - match path.as_str() { - "/auth/callback" => { - let params: std::collections::HashMap = - parsed_url.query_pairs().into_owned().collect(); - if params.get("state").map(String::as_str) != Some(state.as_str()) { - let _ = - req.respond(Response::from_string("State mismatch").with_status_code(400)); + let url_raw = req.url().to_string(); + let parsed_url = match url::Url::parse(&format!("http://localhost{url_raw}")) { + Ok(u) => u, + Err(e) => { + eprintln!("URL parse error: {e}"); + let _ = req.respond(Response::from_string("Bad Request").with_status_code(400)); continue; } - let code = match params.get("code") { - Some(c) if !c.is_empty() => c.clone(), - _ => { - let _ = req.respond( - Response::from_string("Missing authorization code") - .with_status_code(400), - ); + }; + let path = parsed_url.path().to_string(); + + match path.as_str() { + "/auth/callback" => { + let params: std::collections::HashMap = + parsed_url.query_pairs().into_owned().collect(); + if params.get("state").map(String::as_str) != Some(state.as_str()) { + let _ = req + .respond(Response::from_string("State mismatch").with_status_code(400)); continue; } - }; - - match exchange_code_for_tokens( - opts.issuer, - opts.client_id, - &redirect_uri, - &pkce, - &code, - ) { - Ok(tokens) => { - // Obtain API key via token-exchange and persist - let api_key = - obtain_api_key(opts.issuer, opts.client_id, &tokens.id_token).ok(); - if let Err(err) = persist_tokens( - opts.codex_home, - api_key.clone(), - tokens.id_token.clone(), - Some(tokens.access_token.clone()), - Some(tokens.refresh_token.clone()), - ) { - eprintln!("Persist error: {err}"); + let code = match params.get("code") { + Some(c) if !c.is_empty() => c.clone(), + _ => { let _ = req.respond( - Response::from_string(format!( - "Unable to persist auth file: {err}" - )) - .with_status_code(500), + Response::from_string("Missing authorization code") + .with_status_code(400), ); continue; } + }; - let success_url = compose_success_url( - actual_port, - opts.issuer, - &tokens.id_token, - &tokens.access_token, - ); - match tiny_http::Header::from_bytes( - &b"Location"[..], - success_url.as_bytes(), - ) { - Ok(h) => { - let response = tiny_http::Response::empty(302).with_header(h); - let _ = req.respond(response); - } - Err(_) => { + match exchange_code_for_tokens( + &opts.issuer, + &opts.client_id, + &redirect_uri, + &pkce, + &code, + ) { + Ok(tokens) => { + // Obtain API key via token-exchange and persist + let api_key = + obtain_api_key(&opts.issuer, &opts.client_id, &tokens.id_token) + .ok(); + if let Err(err) = persist_tokens( + &opts.codex_home, + api_key.clone(), + tokens.id_token.clone(), + Some(tokens.access_token.clone()), + Some(tokens.refresh_token.clone()), + ) { + eprintln!("Persist error: {err}"); let _ = req.respond( - Response::from_string("Internal Server Error") - .with_status_code(500), + Response::from_string(format!( + "Unable to persist auth file: {err}" + )) + .with_status_code(500), ); + continue; + } + + let success_url = compose_success_url( + actual_port, + &opts.issuer, + &tokens.id_token, + &tokens.access_token, + ); + match tiny_http::Header::from_bytes( + &b"Location"[..], + success_url.as_bytes(), + ) { + Ok(h) => { + let response = tiny_http::Response::empty(302).with_header(h); + let _ = req.respond(response); + } + Err(_) => { + let _ = req.respond( + Response::from_string("Internal Server Error") + .with_status_code(500), + ); + } } } - } - Err(err) => { - eprintln!("Token exchange error: {err}"); - let _ = req.respond( - Response::from_string(format!("Token exchange failed: {err}")) - .with_status_code(500), - ); + Err(err) => { + eprintln!("Token exchange error: {err}"); + let _ = req.respond( + Response::from_string(format!("Token exchange failed: {err}")) + .with_status_code(500), + ); + } } } - } - "/success" => { - let body = include_str!("assets/success.html"); - let mut resp = Response::from_data(body.as_bytes()); - if let Ok(h) = tiny_http::Header::from_bytes( - &b"Content-Type"[..], - &b"text/html; charset=utf-8"[..], - ) { - resp.add_header(h); + "/success" => { + let body = include_str!("assets/success.html"); + let mut resp = Response::from_data(body.as_bytes()); + if let Ok(h) = tiny_http::Header::from_bytes( + &b"Content-Type"[..], + &b"text/html; charset=utf-8"[..], + ) { + resp.add_header(h); + } + let _ = req.respond(resp); + shutdown_flag.store(true, Ordering::SeqCst); + return Ok(()); + } + _ => { + let _ = req.respond(Response::from_string("Not Found").with_status_code(404)); } - let _ = req.respond(resp); - shutdown_flag.store(true, Ordering::SeqCst); - } - _ => { - let _ = req.respond(Response::from_string("Not Found").with_status_code(404)); } } - } + Err(io::Error::other("Login flow was not completed")) + }); - Ok(()) + Ok(LoginServer { + auth_url: auth_url.clone(), + actual_port, + server_handle, + shutdown_flag: shutdown_flag_clone, + }) } fn build_authorize_url( diff --git a/codex-rs/login/tests/login_server_e2e.rs b/codex-rs/login/tests/login_server_e2e.rs index 3d00480051..b3e124682c 100644 --- a/codex-rs/login/tests/login_server_e2e.rs +++ b/codex-rs/login/tests/login_server_e2e.rs @@ -1,12 +1,11 @@ -#![expect(clippy::unwrap_used)] +#![allow(clippy::unwrap_used)] use std::net::SocketAddr; use std::net::TcpListener; use std::thread; use base64::Engine; -use codex_login::LoginServerInfo; use codex_login::ServerOptions; -use codex_login::run_server_blocking_with_notify; +use codex_login::run_login_server; use tempfile::tempdir; // See spawn.rs for details @@ -94,21 +93,16 @@ fn end_to_end_login_flow_persists_auth_json() { // Run server in background let server_home = codex_home.clone(); - let (tx, rx) = std::sync::mpsc::channel::(); - let server_thread = thread::spawn(move || { - let opts = ServerOptions { - codex_home: &server_home, - client_id: codex_login::CLIENT_ID, - issuer: &issuer, - port: 0, - open_browser: false, - force_state: Some(state), - }; - run_server_blocking_with_notify(opts, Some(tx), None).unwrap(); - }); - - let server_info = rx.recv().unwrap(); - let login_port = server_info.actual_port; + let opts = ServerOptions { + codex_home: server_home, + client_id: codex_login::CLIENT_ID.to_string(), + issuer, + port: 0, + open_browser: false, + force_state: Some(state), + }; + let server = run_login_server(opts, None).unwrap(); + let login_port = server.actual_port; // Simulate browser callback, and follow redirect to /success let client = reqwest::blocking::Client::builder() @@ -120,9 +114,7 @@ fn end_to_end_login_flow_persists_auth_json() { assert!(resp.status().is_success()); // Wait for server shutdown - server_thread - .join() - .unwrap_or_else(|_| panic!("server thread panicked")); + server.block_until_done().unwrap(); // Validate auth.json let auth_path = codex_home.join("auth.json"); @@ -159,30 +151,23 @@ fn creates_missing_codex_home_dir() { // Run server in background let server_home = codex_home.clone(); - let (tx, rx) = std::sync::mpsc::channel::(); - let server_thread = thread::spawn(move || { - let opts = ServerOptions { - codex_home: &server_home, - client_id: codex_login::CLIENT_ID, - issuer: &issuer, - port: 0, - open_browser: false, - force_state: Some(state), - }; - run_server_blocking_with_notify(opts, Some(tx), None).unwrap() - }); - - let server_info = rx.recv().unwrap(); - let login_port = server_info.actual_port; + let opts = ServerOptions { + codex_home: server_home, + client_id: codex_login::CLIENT_ID.to_string(), + issuer, + port: 0, + open_browser: false, + force_state: Some(state), + }; + let server = run_login_server(opts, None).unwrap(); + let login_port = server.actual_port; let client = reqwest::blocking::Client::new(); let url = format!("http://127.0.0.1:{login_port}/auth/callback?code=abc&state=state2"); let resp = client.get(&url).send().unwrap(); assert!(resp.status().is_success()); - server_thread - .join() - .unwrap_or_else(|_| panic!("server thread panicked")); + server.block_until_done().unwrap(); let auth_path = codex_home.join("auth.json"); assert!( diff --git a/codex-rs/tui/src/onboarding/auth.rs b/codex-rs/tui/src/onboarding/auth.rs index a8864e4d57..de98678623 100644 --- a/codex-rs/tui/src/onboarding/auth.rs +++ b/codex-rs/tui/src/onboarding/auth.rs @@ -1,3 +1,6 @@ +use codex_login::CLIENT_ID; +use codex_login::ServerOptions; +use codex_login::run_login_server; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use ratatui::buffer::Buffer; @@ -22,6 +25,10 @@ use crate::onboarding::onboarding_screen::KeyboardHandler; use crate::onboarding::onboarding_screen::StepStateProvider; use crate::shimmer::shimmer_spans; use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::thread::JoinHandle; use super::onboarding_screen::StepState; // no additional imports @@ -39,12 +46,14 @@ pub(crate) enum SignInState { #[derive(Debug)] /// Used to manage the lifecycle of SpawnedLogin and ensure it gets cleaned up. pub(crate) struct ContinueInBrowserState { - login_child: Option, + auth_url: String, + shutdown_flag: Option>, + _login_wait_handle: Option>, } impl Drop for ContinueInBrowserState { fn drop(&mut self) { - if let Some(child) = &self.login_child { - child.cancel(); + if let Some(flag) = &self.shutdown_flag { + flag.store(true, Ordering::SeqCst); } } } @@ -184,16 +193,12 @@ impl AuthModeWidget { let mut lines = vec![Line::from(spans), Line::from("")]; if let SignInState::ChatGptContinueInBrowser(state) = &self.sign_in_state { - if let Some(url) = state - .login_child - .as_ref() - .and_then(|child| child.get_login_url()) - { + if !state.auth_url.is_empty() { lines.push(Line::from(" If the link doesn't open automatically, open the following link to authenticate:")); lines.push(Line::from(vec![ Span::raw(" "), Span::styled( - url, + state.auth_url.as_str(), Style::default() .fg(LIGHT_BLUE) .add_modifier(Modifier::UNDERLINED), @@ -289,12 +294,17 @@ impl AuthModeWidget { fn start_chatgpt_login(&mut self) { self.error = None; - match codex_login::spawn_login_with_chatgpt(&self.codex_home) { + let opts = ServerOptions::new(self.codex_home.clone(), CLIENT_ID.to_string()); + let server = run_login_server(opts, None); + match server { Ok(child) => { - self.spawn_completion_poller(child.clone()); + let auth_url = child.auth_url.clone(); + let shutdown_flag = child.shutdown_flag.clone(); self.sign_in_state = SignInState::ChatGptContinueInBrowser(ContinueInBrowserState { - login_child: Some(child), + auth_url, + shutdown_flag: Some(shutdown_flag), + _login_wait_handle: Some(self.spawn_completion_poller(child)), }); self.event_tx.send(AppEvent::RequestRedraw); } @@ -316,23 +326,17 @@ impl AuthModeWidget { self.event_tx.send(AppEvent::RequestRedraw); } - fn spawn_completion_poller(&self, child: codex_login::SpawnedLogin) { + fn spawn_completion_poller(&self, child: codex_login::LoginServer) -> JoinHandle<()> { let event_tx = self.event_tx.clone(); std::thread::spawn(move || { - loop { - if let Some(success) = child.get_auth_result() { - if success { - event_tx.send(AppEvent::OnboardingAuthComplete(Ok(()))); - } else { - event_tx.send(AppEvent::OnboardingAuthComplete(Err( - "login failed".to_string() - ))); - } - break; - } - std::thread::sleep(std::time::Duration::from_millis(250)); + if let Ok(()) = child.block_until_done() { + event_tx.send(AppEvent::OnboardingAuthComplete(Ok(()))); + } else { + event_tx.send(AppEvent::OnboardingAuthComplete(Err( + "login failed".to_string() + ))); } - }); + }) } } From 5552688621340c7042a9240a9bedc864242c5ee7 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 14 Aug 2025 19:49:42 -0700 Subject: [PATCH 16/16] Format multiline commands (#2333) image image --- codex-rs/tui/src/chatwidget.rs | 12 --- codex-rs/tui/src/history_cell.rs | 8 -- codex-rs/tui/src/user_approval_widget.rs | 118 ++++++++++++++--------- 3 files changed, 75 insertions(+), 63 deletions(-) diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index c10b94b79a..c39edb8229 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -43,7 +43,6 @@ use crate::bottom_pane::BottomPane; use crate::bottom_pane::BottomPaneParams; use crate::bottom_pane::CancellationEvent; use crate::bottom_pane::InputResult; -use crate::exec_command::strip_bash_lc_and_escape; use crate::history_cell; use crate::history_cell::CommandOutput; use crate::history_cell::ExecCell; @@ -391,17 +390,6 @@ impl ChatWidget<'_> { pub(crate) fn handle_exec_approval_now(&mut self, id: String, ev: ExecApprovalRequestEvent) { self.flush_answer_stream_with_separator(); - // Log a background summary immediately so the history is chronological. - let cmdline = strip_bash_lc_and_escape(&ev.command); - let text = format!( - "command requires approval:\n$ {cmdline}{reason}", - reason = ev - .reason - .as_ref() - .map(|r| format!("\n{r}")) - .unwrap_or_default() - ); - self.add_to_history(&history_cell::new_background_event(text)); let request = ApprovalRequest::Exec { id, diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index a4cebe981d..2a17ff1644 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -136,14 +136,6 @@ fn pretty_provider_name(id: &str) -> String { } } -pub(crate) fn new_background_event(message: String) -> PlainHistoryCell { - let mut lines: Vec> = Vec::new(); - lines.push(Line::from("event".dim())); - lines.extend(message.lines().map(|line| ansi_escape_line(line).dim())); - lines.push(Line::from("")); - PlainHistoryCell { lines } -} - pub(crate) fn new_session_info( config: &Config, event: SessionConfiguredEvent, diff --git a/codex-rs/tui/src/user_approval_widget.rs b/codex-rs/tui/src/user_approval_widget.rs index 78ece561ab..7a4e3d9008 100644 --- a/codex-rs/tui/src/user_approval_widget.rs +++ b/codex-rs/tui/src/user_approval_widget.rs @@ -109,6 +109,34 @@ pub(crate) struct UserApprovalWidget<'a> { done: bool, } +fn to_command_display<'a>( + first_line: Vec>, + cmd: String, + last_line: Vec>, +) -> Vec> { + let command_lines: Vec = cmd + .lines() + .map(|line| Span::from(line.to_string()).style(Style::new().add_modifier(Modifier::DIM))) + .collect(); + + let mut lines: Vec> = vec![]; + + let mut first_line = first_line.clone(); + if command_lines.len() == 1 { + first_line.push(command_lines[0].clone()); + first_line.extend(last_line); + } else { + for line in command_lines { + lines.push(Line::from(vec![Span::from(" "), line])); + } + let last_line = last_line.clone(); + lines.push(Line::from(last_line)); + } + lines.insert(0, Line::from(first_line)); + + lines +} + impl UserApprovalWidget<'_> { pub(crate) fn new(approval_request: ApprovalRequest, app_event_tx: AppEventSender) -> Self { let confirmation_prompt = match &approval_request { @@ -116,17 +144,13 @@ impl UserApprovalWidget<'_> { command, reason, .. } => { let cmd = strip_bash_lc_and_escape(command); - // Present a single-line summary without cwd: "codex wants to run: " - let mut cmd_span: Span = cmd.clone().into(); - cmd_span.style = cmd_span.style.add_modifier(Modifier::DIM); - let mut contents: Vec = vec![ - Line::from(vec![ - "? ".fg(Color::Blue), - "Codex wants to run ".bold(), - cmd_span, - ]), - Line::from(""), - ]; + let mut contents: Vec = to_command_display( + vec!["? ".fg(Color::Blue), "Codex wants to run ".bold()], + cmd, + vec![], + ); + + contents.push(Line::from("")); if let Some(reason) = reason { contents.push(Line::from(reason.clone().italic())); contents.push(Line::from("")); @@ -244,44 +268,52 @@ impl UserApprovalWidget<'_> { // Result line based on decision. match decision { ReviewDecision::Approved => { - lines.push(Line::from(vec![ - "βœ” ".fg(Color::Green), - "You ".into(), - "approved".bold(), - " codex to run ".into(), - cmd_span, - " ".into(), - "this time".bold(), - ])); + lines.extend(to_command_display( + vec![ + "βœ” ".fg(Color::Green), + "You ".into(), + "approved".bold(), + " codex to run ".into(), + ], + cmd, + vec![" this time".bold()], + )); } ReviewDecision::ApprovedForSession => { - lines.push(Line::from(vec![ - "βœ” ".fg(Color::Green), - "You ".into(), - "approved".bold(), - " codex to run ".into(), - cmd_span, - " ".into(), - "every time this session".bold(), - ])); + lines.extend(to_command_display( + vec![ + "βœ” ".fg(Color::Green), + "You ".into(), + "approved".bold(), + "codex to run ".into(), + ], + cmd, + vec![" every time this session".bold()], + )); } ReviewDecision::Denied => { - lines.push(Line::from(vec![ - "βœ— ".fg(Color::Red), - "You ".into(), - "did not approve".bold(), - " codex to run ".into(), - cmd_span, - ])); + lines.extend(to_command_display( + vec![ + "βœ— ".fg(Color::Red), + "You ".into(), + "did not approve".bold(), + " codex to run ".into(), + ], + cmd, + vec![], + )); } ReviewDecision::Abort => { - lines.push(Line::from(vec![ - "βœ— ".fg(Color::Red), - "You ".into(), - "canceled".bold(), - " the request to run ".into(), - cmd_span, - ])); + lines.extend(to_command_display( + vec![ + "βœ— ".fg(Color::Red), + "You ".into(), + "canceled".bold(), + " the request to run ".into(), + ], + cmd, + vec![], + )); } } }