mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
## Why The fork can acknowledge its working directory before startup finishes. MCP startup can also make the composer busy between the test seeing `Ready` and pressing Enter, causing `/cd` to be rejected. ## What changed Wait for the fork's own `Ready` status and a complete terminal update showing the pasted `/cd` command before submitting it. Retry only when a new busy rejection appears and the fork is ready again. Require a complete terminal update showing the directory change before continuing. GitOrigin-RevId: eceb98b3376977dcc60963e3733bf45559b88ae0
287 lines
11 KiB
Rust
287 lines
11 KiB
Rust
//! Exercises stack-sensitive session transitions through the real TUI event loop.
|
|
//!
|
|
//! Uses the CLI binary when available (including Bazel CI) to cover its dispatch frames.
|
|
|
|
use super::focus_palette::PtyCodex;
|
|
use super::focus_palette::write_test_config;
|
|
use anyhow::Result;
|
|
use anyhow::ensure;
|
|
use codex_worktree::ManagedWorktree;
|
|
use codex_worktree::WorktreeManager;
|
|
use codex_worktree::WorktreeSettings;
|
|
use core_test_support::responses;
|
|
use std::fs;
|
|
use std::path::Path;
|
|
use std::process::Command;
|
|
use std::time::Duration;
|
|
use std::time::Instant;
|
|
use wiremock::matchers::body_string_contains;
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
async fn picker_side_worktree_fork_and_cd_run_on_the_production_stack() -> Result<()> {
|
|
let start = if codex_utils_cargo_bin::cargo_bin("codex").is_ok() {
|
|
PtyCodex::start_cli
|
|
} else {
|
|
PtyCodex::start
|
|
};
|
|
let repository = tempfile::tempdir_in("/tmp")?;
|
|
let root = repository.path().canonicalize()?;
|
|
let status = Command::new("git")
|
|
.args(["init", "-q", "-b", "main"])
|
|
.arg(&root)
|
|
.status()?;
|
|
ensure!(status.success(), "initialize test repository");
|
|
fs::write(root.join("README.md"), "stack transition test\n")?;
|
|
ensure!(
|
|
Command::new("git")
|
|
.args(["-C"])
|
|
.arg(&root)
|
|
.args(["add", "README.md"])
|
|
.status()?
|
|
.success(),
|
|
"stage test repository"
|
|
);
|
|
ensure!(
|
|
Command::new("git")
|
|
.args(["-C"])
|
|
.arg(&root)
|
|
.args([
|
|
"-c",
|
|
"user.name=Codex Test",
|
|
"-c",
|
|
"user.email=test@example.invalid"
|
|
])
|
|
.args(["commit", "--no-gpg-sign", "-qm", "initial"])
|
|
.status()?
|
|
.success(),
|
|
"commit test repository"
|
|
);
|
|
|
|
let codex_home = tempfile::tempdir_in("/tmp")?;
|
|
write_test_config(codex_home.path(), &root)?;
|
|
let server = responses::start_mock_server().await;
|
|
let config_path = codex_home.path().join("config.toml");
|
|
let config = fs::read_to_string(&config_path)?
|
|
.replace("model_provider = \"openai\"", "model_provider = \"test\"");
|
|
fs::write(
|
|
&config_path,
|
|
format!(
|
|
"{config}\n[model_providers.test]\nname = \"Mock\"\nbase_url = \"{}/v1\"\nwire_api = \"responses\"\nrequires_openai_auth = false\nsupports_websockets = false\n",
|
|
server.uri()
|
|
),
|
|
)?;
|
|
// Title generation can include the user prompt and race the actual user turn.
|
|
let _title = responses::mount_sse_once_match(
|
|
&server,
|
|
body_string_contains(r#"\"thread_source\":\"thread_title\""#),
|
|
responses::sse(vec![
|
|
responses::ev_assistant_message("title", r#"{"title":"Stack transition test"}"#),
|
|
responses::ev_completed("title-response"),
|
|
]),
|
|
)
|
|
.await;
|
|
let _reply = responses::mount_sse_once_match(
|
|
&server,
|
|
body_string_contains(r#"\"thread_source\":\"user\""#),
|
|
responses::sse(vec![
|
|
responses::ev_assistant_message("saved", "STACK_SAVED_HISTORY"),
|
|
responses::ev_completed("saved-response"),
|
|
]),
|
|
)
|
|
.await;
|
|
|
|
let worktrees = WorktreeManager::new(WorktreeSettings::for_cli(
|
|
codex_home.path(),
|
|
/*desktop*/ None,
|
|
)?);
|
|
// Both launchers give codex-main and Tokio workers explicit 16 MiB stacks.
|
|
let mut terminal = start(
|
|
&root,
|
|
codex_home,
|
|
&[
|
|
"--no-alt-screen",
|
|
"-c",
|
|
"features.worktrees=true",
|
|
"-c",
|
|
"features.shell_snapshot=false",
|
|
"-c",
|
|
"tui.status_line=['thread-id','run-state']",
|
|
"Reply with the marker requested by this test.",
|
|
],
|
|
)?;
|
|
terminal.wait_for_startup()?;
|
|
terminal.wait_for_screen("STACK_SAVED_HISTORY")?;
|
|
terminal.wait_for_screen("Worked for")?;
|
|
terminal.wait_for_screen("Ask Codex to do anything")?;
|
|
|
|
// A second rewind gesture is already buffered when the first is confirmed.
|
|
// A trailing bare Escape must not consume the first character of the fresh edit.
|
|
terminal.write_input(b"\x1b[27u\x1b[27u\r\x1b[27u\x1b[27u\r\x1b")?;
|
|
terminal.wait_for_screen("Conversation reverted to this point")?;
|
|
// Leave the leading space unmarked to exercise Escape, then explicitly
|
|
// end the paste so the next Enter is an unambiguous submit.
|
|
terminal.write_input(b" \x1b[200~Revised.\x1b[201~")?;
|
|
terminal.wait_for_screen("Reply with the marker requested by this test. Revised.")?;
|
|
let _edited_reply = responses::mount_sse_once_match(
|
|
&server,
|
|
body_string_contains("Reply with the marker requested by this test. Revised."),
|
|
responses::sse(vec![
|
|
responses::ev_assistant_message("edited", "STACK_SAVED_HISTORY_EDITED"),
|
|
responses::ev_completed("edited-response"),
|
|
]),
|
|
)
|
|
.await;
|
|
terminal.write_input(b"\r")?;
|
|
terminal.wait_for_screen("STACK_SAVED_HISTORY_EDITED")?;
|
|
terminal.wait_for_screen("Worked for")?;
|
|
|
|
// Starting and closing a side conversation both rebuild the displayed chat widget.
|
|
// Repeat through the real event loop, whose dev-build frames share the production stack.
|
|
for attempt in 1..=3 {
|
|
submit(&mut terminal, "/side")?;
|
|
terminal.wait_for_screen("from main thread")?;
|
|
terminal.ensure_running()?;
|
|
terminal.write_input(b"\x03")?;
|
|
terminal.wait_for_screen("STACK_SAVED_HISTORY")?;
|
|
terminal.wait_for_screen("Ask Codex to do anything")?;
|
|
terminal.ensure_running()?;
|
|
|
|
let draft = format!("SIDE_STACK_DRAFT_{attempt}");
|
|
terminal.write_input(draft.as_bytes())?;
|
|
terminal.wait_for_screen(&draft)?;
|
|
terminal.write_input(b"\x15")?;
|
|
terminal.wait_for_screen("Ask Codex to do anything")?;
|
|
}
|
|
|
|
submit(&mut terminal, "/resume")?;
|
|
terminal.wait_for_screen("Resume a previous session")?;
|
|
terminal.ensure_running()?;
|
|
terminal.write_input(b"\x1b")?;
|
|
terminal.wait_for_screen("Ask Codex to do anything")?;
|
|
|
|
submit(&mut terminal, "/worktree")?;
|
|
terminal.wait_for_screen("Continue current conversation")?;
|
|
terminal.write_input(b"1")?;
|
|
let forked = wait_for_owned_worktrees(&mut terminal, &worktrees, &root, /*count*/ 1)?;
|
|
// The header changes before the queued history replay has finished attaching.
|
|
// Wait for the transition acknowledgement before submitting another command.
|
|
terminal.wait_for_screen(&format!(
|
|
"Working directory changed to: {}",
|
|
forked[0].root.display()
|
|
))?;
|
|
terminal.ensure_running()?;
|
|
|
|
// The directory acknowledgement can precede the end of startup for the fork.
|
|
let owner = worktrees.owner(&forked[0].root)?.expect("bound fork");
|
|
let ready = format!("{owner} · Ready");
|
|
let command = format!("/cd {}", root.display());
|
|
let changed = format!("Working directory changed to: {}", root.display());
|
|
let deadline = Instant::now() + Duration::from_secs(/*secs*/ 30);
|
|
terminal.wait_for_screen(&ready)?;
|
|
paste(&mut terminal, &command)?;
|
|
let mut rejections_at_submit = None;
|
|
loop {
|
|
let screen = terminal.screen_contents();
|
|
// A PTY read can end partway through a path. Decide only after
|
|
// the TUI has finished its synchronized update.
|
|
let begin = b"\x1b[?2026h";
|
|
let end = b"\x1b[?2026l";
|
|
let complete = terminal
|
|
.output
|
|
.windows(begin.len())
|
|
.rev()
|
|
.find(|bytes| *bytes == begin || *bytes == end)
|
|
.is_some_and(|bytes| bytes == end);
|
|
let has_line = |text: &str| screen.lines().any(|line| line.trim_end().ends_with(text));
|
|
if complete && rejections_at_submit.is_some() && has_line(&changed) {
|
|
break;
|
|
}
|
|
ensure!(
|
|
Instant::now() < deadline,
|
|
"missing {changed:?}; screen:\n{screen}"
|
|
);
|
|
|
|
// MCP startup can turn the composer busy between Ready and Enter. A
|
|
// rejection keeps the draft and adds a history entry. Only press Enter
|
|
// again if the count grows, so a redraw cannot replay an old rejection.
|
|
let rejections = screen
|
|
.matches("'/cd' is disabled while a task is in progress.")
|
|
.count();
|
|
if complete
|
|
&& screen.contains(&ready)
|
|
&& has_line(&command)
|
|
&& rejections_at_submit.is_none_or(|previous| rejections > previous)
|
|
{
|
|
terminal.write_input(b"\r")?;
|
|
rejections_at_submit = Some(rejections);
|
|
}
|
|
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
|
terminal.ensure_running()?;
|
|
}
|
|
terminal.ensure_running()?;
|
|
|
|
submit(&mut terminal, "/worktree")?;
|
|
terminal.wait_for_screen("Start new conversation")?;
|
|
terminal.write_input(b"2")?;
|
|
let created = wait_for_owned_worktrees(&mut terminal, &worktrees, &root, /*count*/ 2)?;
|
|
ensure!(
|
|
created
|
|
.iter()
|
|
.any(|checkout| checkout.root == forked[0].root)
|
|
);
|
|
let second = created
|
|
.iter()
|
|
.find(|checkout| checkout.root != forked[0].root)
|
|
.expect("second checkout");
|
|
ensure!(
|
|
worktrees.owner(&forked[0].root)? != worktrees.owner(&second.root)?,
|
|
"new worktree reused the forked thread owner"
|
|
);
|
|
terminal.wait_for_screen(&format!(
|
|
"Working directory changed to: {}",
|
|
second.root.display()
|
|
))?;
|
|
terminal.ensure_running()?;
|
|
Ok(())
|
|
}
|
|
|
|
fn paste(terminal: &mut PtyCodex, input: &str) -> Result<()> {
|
|
// Send one paste event so slashes in arguments cannot accept a completion
|
|
// while earlier characters are still buffered by paste-burst detection.
|
|
terminal.write_input(format!("\x1b[200~{input}\x1b[201~").as_bytes())
|
|
}
|
|
|
|
fn submit(terminal: &mut PtyCodex, input: &str) -> Result<()> {
|
|
paste(terminal, input)?;
|
|
terminal.wait_for_screen(input)?;
|
|
// A worktree switch can acknowledge the new directory while the composer is still busy.
|
|
terminal.wait_for_screen("Ready")?;
|
|
terminal.write_input(b"\r")?;
|
|
Ok(())
|
|
}
|
|
|
|
fn wait_for_owned_worktrees(
|
|
terminal: &mut PtyCodex,
|
|
manager: &WorktreeManager,
|
|
source: &Path,
|
|
count: usize,
|
|
) -> Result<Vec<ManagedWorktree>> {
|
|
let deadline = Instant::now() + Duration::from_secs(/*secs*/ 30);
|
|
while Instant::now() < deadline {
|
|
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
|
let checkouts = manager.list(source).unwrap_or_default();
|
|
if checkouts.len() == count
|
|
&& checkouts
|
|
.iter()
|
|
.all(|checkout| manager.owner(&checkout.root).ok().flatten().is_some())
|
|
{
|
|
return Ok(checkouts);
|
|
}
|
|
terminal.ensure_running()?;
|
|
}
|
|
anyhow::bail!(
|
|
"did not bind {count} managed checkouts; screen:\n{}",
|
|
terminal.screen_contents()
|
|
)
|
|
}
|