Base: codex-main originale (prima del fork aKode)
This commit is contained in:
97
codex-rs/tui/tests/suite/daemon_compatibility.rs
Normal file
97
codex-rs/tui/tests/suite/daemon_compatibility.rs
Normal file
@@ -0,0 +1,97 @@
|
||||
//! Exercises daemon compatibility recovery through real TUI startup.
|
||||
|
||||
use super::focus_palette::PtyCodex;
|
||||
use super::focus_palette::write_test_config;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use codex_app_server_protocol::JSONRPCMessage;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use serde_json::json;
|
||||
use tokio::net::UnixListener;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn incompatible_daemon_can_run_embedded_for_explicit_features() -> Result<()> {
|
||||
for scenario in ["explicit enable", "explicit disable"] {
|
||||
let cwd = codex_utils_cargo_bin::repo_root()?;
|
||||
let home = tempfile::tempdir_in("/tmp")?;
|
||||
write_test_config(home.path(), &cwd)?;
|
||||
let socket = codex_app_server_client::app_server_control_socket_path(home.path())?;
|
||||
std::fs::create_dir_all(socket.parent().unwrap())?;
|
||||
let listener = UnixListener::bind(socket.as_path())?;
|
||||
let server = tokio::spawn(async move {
|
||||
let mut socket = loop {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
if let Ok(socket) = tokio_tungstenite::accept_async(stream).await {
|
||||
break socket;
|
||||
}
|
||||
};
|
||||
while let Some(Ok(Message::Text(text))) = socket.next().await {
|
||||
let JSONRPCMessage::Request(request) = serde_json::from_str(&text)? else {
|
||||
continue;
|
||||
};
|
||||
let response = match request.method.as_str() {
|
||||
"initialize" => {
|
||||
json!({"id": request.id, "result": {"userAgent": "daemon-test/0.0.0"}})
|
||||
}
|
||||
"config/read" => {
|
||||
json!({"id": request.id, "result": {"config": {}, "layers": []}})
|
||||
}
|
||||
"configRequirements/read" => {
|
||||
json!({"id": request.id, "result": {"requirements": null}})
|
||||
}
|
||||
"experimentalFeature/list" => json!({"id": request.id, "result": {"data": [{
|
||||
"name": "api_key_model_discovery", "stage": "stable",
|
||||
"displayName": null, "description": null, "announcement": null,
|
||||
"enabled": scenario == "explicit disable", "defaultEnabled": true,
|
||||
}], "nextCursor": null}}),
|
||||
_ => panic!("unexpected request: {}", request.method),
|
||||
};
|
||||
socket
|
||||
.send(Message::Text(response.to_string().into()))
|
||||
.await?;
|
||||
}
|
||||
Ok::<_, anyhow::Error>(())
|
||||
});
|
||||
let args = if scenario == "explicit disable" {
|
||||
vec!["-c", "features.api_key_model_discovery=false"]
|
||||
} else {
|
||||
vec!["-c", "features.api_key_model_discovery=true"]
|
||||
};
|
||||
let mut terminal = PtyCodex::start(&cwd, home, &args)?;
|
||||
terminal.wait_for_screen("Background server has incompatible feature settings")?;
|
||||
terminal.write_input(b"1")?;
|
||||
terminal.wait_for_startup()?;
|
||||
terminal.wait_for_screen("warning")?;
|
||||
terminal.write_input(b"\x14")?;
|
||||
let (snapshot, warning_end) = match scenario {
|
||||
"explicit enable" => (
|
||||
"daemon_feature_mismatch",
|
||||
"api_key_model_discovery to be enabled.",
|
||||
),
|
||||
"explicit disable" => (
|
||||
"daemon_override_mismatch",
|
||||
"api_key_model_discovery to be disabled.",
|
||||
),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
terminal.wait_for_screen(warning_end)?;
|
||||
let screen = terminal.screen_contents();
|
||||
let warning = screen
|
||||
.lines()
|
||||
.find(|line| line.contains("Running without the shared background server"))
|
||||
.context("missing warning line")?;
|
||||
insta::assert_snapshot!(snapshot, warning);
|
||||
terminal.write_input(b"\x14")?;
|
||||
terminal.write_input(b"/status")?;
|
||||
terminal.wait_for_screen("show current session configuration")?;
|
||||
terminal.read_output(std::time::Duration::from_millis(/*millis*/ 200))?;
|
||||
terminal.write_input(b"\r")?;
|
||||
terminal.wait_for_screen("Model:")?;
|
||||
ensure!(!terminal.screen_contains("unix://"));
|
||||
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 5), server).await???;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
257
codex-rs/tui/tests/suite/directory_trust.rs
Normal file
257
codex-rs/tui/tests/suite/directory_trust.rs
Normal file
@@ -0,0 +1,257 @@
|
||||
//! Exercises folder consent against a connected server through the real terminal event loop.
|
||||
|
||||
use super::focus_palette::PtyCodex;
|
||||
use super::focus_palette::write_test_config;
|
||||
use anyhow::Result;
|
||||
use codex_app_server_protocol::JSONRPCMessage;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use tokio::net::UnixListener;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn connected_trust_cancellation_and_acceptance_control_task_creation() -> Result<()> {
|
||||
for trust_level in [None, Some("untrusted")] {
|
||||
let workspace = tempfile::tempdir()?;
|
||||
let repo_root = workspace.path().canonicalize()?;
|
||||
std::fs::create_dir(repo_root.join(".git"))?;
|
||||
std::fs::write(repo_root.join(".git/HEAD"), "ref: refs/heads/main\n")?;
|
||||
let codex_home = tempfile::tempdir_in("/tmp")?;
|
||||
// The server's trust decision must win over the client's trusted-folder setting.
|
||||
write_test_config(codex_home.path(), &repo_root)?;
|
||||
let config_path = codex_home.path().join("config.toml");
|
||||
let config = std::fs::read_to_string(&config_path)?;
|
||||
std::fs::write(
|
||||
config_path,
|
||||
format!("{config}\n[tui]\nresume_cwd = \"current\"\n"),
|
||||
)?;
|
||||
let socket = codex_app_server_client::app_server_control_socket_path(codex_home.path())?;
|
||||
std::fs::create_dir_all(socket.parent().unwrap())?;
|
||||
let listener = UnixListener::bind(socket.as_path())?;
|
||||
let cwd = repo_root.clone();
|
||||
let methods = Arc::new(Mutex::new(Vec::new()));
|
||||
let requests = Arc::clone(&methods);
|
||||
let server = tokio::spawn(async move {
|
||||
let mut clients = tokio::task::JoinSet::new();
|
||||
let trust_reads = Arc::new(AtomicUsize::new(0));
|
||||
loop {
|
||||
let (stream, _) = listener
|
||||
.accept()
|
||||
.await
|
||||
.expect("accept fake app-server client");
|
||||
let cwd = cwd.clone();
|
||||
let methods = Arc::clone(&requests);
|
||||
let trust_reads = Arc::clone(&trust_reads);
|
||||
clients.spawn(async move {
|
||||
let Ok(mut socket) = tokio_tungstenite::accept_async(stream).await else {
|
||||
return Ok::<_, anyhow::Error>(());
|
||||
};
|
||||
let other_cwd = cwd.join("other-folder");
|
||||
let id = "00000000-0000-0000-0000-000000000001";
|
||||
let thread = json!({
|
||||
"id": id, "sessionId": id, "preview": "Untrusted saved task", "ephemeral": false,
|
||||
"modelProvider": "openai", "createdAt": 1, "updatedAt": 2,
|
||||
"status": if trust_level.is_some() { json!({"type": "active", "activeFlags": []}) } else { json!({"type": "notLoaded"}) }, "cwd": other_cwd,
|
||||
"cliVersion": "0.0.0", "source": "cli", "turns": []
|
||||
});
|
||||
let mut launch_thread = thread.clone();
|
||||
launch_thread["id"] = json!("00000000-0000-0000-0000-000000000002");
|
||||
launch_thread["sessionId"] = launch_thread["id"].clone();
|
||||
launch_thread["cwd"] = json!(cwd);
|
||||
launch_thread["preview"] = json!("Launch-folder task");
|
||||
launch_thread["updatedAt"] = json!(1);
|
||||
let mut pending_hooks = None;
|
||||
let mut saw_model_list = false;
|
||||
while let Some(Ok(Message::Text(text))) = socket.next().await {
|
||||
let JSONRPCMessage::Request(request) = serde_json::from_str(&text)? else {
|
||||
continue;
|
||||
};
|
||||
methods.lock().unwrap().push(request.method.clone());
|
||||
let result = match request.method.as_str() {
|
||||
"initialize" => json!({"userAgent": "trust-pty"}),
|
||||
"experimentalFeature/list" => json!({"data": (["api_key_model_discovery", "code_mode_host", "auth_elicitation"].map(|name| json!({
|
||||
"name": name, "stage": "stable", "displayName": null,
|
||||
"description": null, "announcement": null,
|
||||
"enabled": true, "defaultEnabled": true,
|
||||
}))), "nextCursor": null}),
|
||||
"account/read" => {
|
||||
json!({"account": {"type": "apiKey"}, "requiresOpenaiAuth": false})
|
||||
}
|
||||
"config/read" => {
|
||||
if matches!(&request.id, RequestId::String(id) if id.starts_with("tui-project-trust-read-")) {
|
||||
trust_reads.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
json!({"config": {"model": "gpt-5.6-terra", "projects": {
|
||||
cwd.to_string_lossy(): {"trust_level": if trust_reads.load(Ordering::SeqCst) == 4 { Some("trusted") } else { trust_level }},
|
||||
other_cwd.to_string_lossy(): {"trust_level": "untrusted"},
|
||||
cwd.join("moved-folder").to_string_lossy(): {"trust_level": "untrusted"}
|
||||
}}, "origins": {}, "layers": []})
|
||||
}
|
||||
"config/batchWrite" => json!({"status": "ok", "version": "1", "filePath": cwd.join("config.toml"), "overriddenMetadata": null}),
|
||||
"hooks/list" => json!({"data": if trust_level.is_none() && methods.lock().unwrap().iter().any(|method| method == "config/batchWrite") {
|
||||
vec![json!({"cwd": request.params.as_ref().unwrap()["cwds"][0], "hooks": [{
|
||||
"key": "project:test", "eventName": "sessionStart", "handlerType": "command",
|
||||
"command": "echo hook", "async": false, "matcher": null, "timeoutSec": 30,
|
||||
"statusMessage": null, "additionalContextLimit": null,
|
||||
"sourcePath": cwd.join(".codex/hooks.json"), "source": "project", "pluginId": null,
|
||||
"displayOrder": 0, "enabled": false, "isManaged": false,
|
||||
"currentHash": "sha256:test", "trustStatus": "untrusted"
|
||||
}], "warnings": [], "errors": []})]
|
||||
} else { vec![] }}),
|
||||
"configRequirements/read" => json!({"requirements": null}),
|
||||
"model/list" => json!({"data": [], "nextCursor": null}),
|
||||
"thread/list" => {
|
||||
json!({"data": vec![thread.clone(), launch_thread.clone()], "nextCursor": null})
|
||||
}
|
||||
"thread/read" => {
|
||||
let mut thread = if request.params.as_ref().unwrap()["threadId"] == launch_thread["id"] {
|
||||
launch_thread.clone()
|
||||
} else {
|
||||
thread.clone()
|
||||
};
|
||||
if thread["id"] == id && trust_reads.load(Ordering::SeqCst) >= 5 {
|
||||
thread["cwd"] = json!(cwd.join("moved-folder"));
|
||||
}
|
||||
json!({"thread": thread})
|
||||
} ,
|
||||
"skills/list" | "thread/loaded/list" => json!({"data": []}),
|
||||
_ => {
|
||||
socket
|
||||
.send(Message::Text(
|
||||
json!({"id": request.id, "error": {
|
||||
"code": if request.method == "thread/start" { -32000 } else { -32601 }, "message": if request.method == "thread/start" { "Consent accepted" } else { "method not found" }
|
||||
}})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await?;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let response = Message::Text(
|
||||
json!({"id": request.id, "result": result}).to_string().into(),
|
||||
);
|
||||
// Startup must request the catalog even while hooks/list is outstanding.
|
||||
if request.method == "hooks/list" && !saw_model_list {
|
||||
pending_hooks = Some(response);
|
||||
continue;
|
||||
}
|
||||
socket.send(response).await?;
|
||||
if request.method == "model/list" {
|
||||
saw_model_list = true;
|
||||
if let Some(hooks) = pending_hooks.take() {
|
||||
socket.send(hooks).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
});
|
||||
let mut terminal = PtyCodex::start(
|
||||
&repo_root,
|
||||
codex_home,
|
||||
&["--no-alt-screen", "do not submit this launch prompt"],
|
||||
)?;
|
||||
let prompt = if trust_level.is_some() {
|
||||
"Open restricted"
|
||||
} else {
|
||||
"Trust and continue"
|
||||
};
|
||||
for (expected, input) in [
|
||||
(prompt, b"\x1b".as_slice()),
|
||||
("Launch-folder task", b"\x1b"),
|
||||
("Launch-folder task", b"\x1b[Bn"),
|
||||
(prompt, b"\x1b"),
|
||||
("n new", b"n"),
|
||||
("Folder access", b"\x1b"),
|
||||
("Agent command center", b"o"),
|
||||
("Resume a previous session", b"\x1b[C"),
|
||||
("Untrusted saved task", b"\r"),
|
||||
("Open existing task", b"\r"),
|
||||
("moved-folder", b"\x1b"),
|
||||
("Agent command center", b"n"),
|
||||
(prompt, b"\r"),
|
||||
] {
|
||||
let is_consent = expected == prompt
|
||||
|| matches!(
|
||||
expected,
|
||||
"Open existing task" | "moved-folder" | "Folder access"
|
||||
);
|
||||
terminal.wait_for_screen(expected)?;
|
||||
if expected == "Folder access" {
|
||||
assert_eq!(
|
||||
terminal
|
||||
.screen_contents()
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.skip_while(|line| *line != "Folder access")
|
||||
.skip(/*n*/ 1)
|
||||
.find(|line| !line.is_empty()),
|
||||
Some(repo_root.to_string_lossy().as_ref())
|
||||
);
|
||||
}
|
||||
if is_consent {
|
||||
terminal.wait_for_screen("Back to Agent Command Center")?;
|
||||
}
|
||||
// Confirmations must be fresh input after the protected-screen transition.
|
||||
tokio::time::sleep(Duration::from_millis(/*millis*/ 200)).await;
|
||||
terminal.write_input(input)?;
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 100))?;
|
||||
}
|
||||
if trust_level.is_none() {
|
||||
terminal.wait_for_screen("Hooks need review")?;
|
||||
assert!(
|
||||
!methods
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|method| method == "thread/start")
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(/*millis*/ 200)).await;
|
||||
terminal.write_input(b"3")?;
|
||||
}
|
||||
terminal.wait_for_screen("Consent accepted")?;
|
||||
drop(terminal);
|
||||
server.abort();
|
||||
let methods = methods.lock().unwrap();
|
||||
assert_eq!(
|
||||
methods
|
||||
.iter()
|
||||
.filter(|method| *method == "model/list")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
let mutations: Vec<_> = methods
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.filter(|method| {
|
||||
matches!(
|
||||
*method,
|
||||
"thread/start"
|
||||
| "thread/resume"
|
||||
| "thread/fork"
|
||||
| "turn/start"
|
||||
| "config/batchWrite"
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
mutations,
|
||||
if trust_level.is_some() {
|
||||
vec!["thread/start"]
|
||||
} else {
|
||||
vec!["config/batchWrite", "thread/start"]
|
||||
}
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
105
codex-rs/tui/tests/suite/external_editor_tests.rs
Normal file
105
codex-rs/tui/tests/suite/external_editor_tests.rs
Normal file
@@ -0,0 +1,105 @@
|
||||
//! Exercise editor handoff through a terminal, including editors that switch screens.
|
||||
|
||||
use super::PtyCodex;
|
||||
use super::write_test_config;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
#[test]
|
||||
fn external_editors_keep_the_screen_and_return_the_draft() -> Result<()> {
|
||||
let repo_root = codex_utils_cargo_bin::repo_root()?;
|
||||
for (editor_output, fullscreen) in [
|
||||
("", true),
|
||||
("printf '\\033[?1049h\\033[2J\\033[Hterminal editor'", true),
|
||||
("printf '\\033[2J\\033[Hterminal editor'", true),
|
||||
("printf '\\033[?1049l\\033[2J\\033[Hterminal editor'", true),
|
||||
("", false),
|
||||
] {
|
||||
let home = tempfile::tempdir()?;
|
||||
write_test_config(home.path(), &repo_root)?;
|
||||
let editor = home.path().join("editor.sh");
|
||||
codex_utils_cargo_bin::write_executable(
|
||||
&editor,
|
||||
&format!(
|
||||
"#!/bin/sh\n{editor_output}\n: > \"$0.ready\"\nIFS= read -r ignored\n\
|
||||
{exit_screen}\nprintf 'edited draft' > \"$1\"\n",
|
||||
exit_screen = if editor_output.contains("1049h") {
|
||||
"printf '\\033[?1049l'"
|
||||
} else {
|
||||
""
|
||||
},
|
||||
),
|
||||
)?;
|
||||
// Give each editor its own app server and wait for the thread before sending Ctrl+G.
|
||||
let args = if fullscreen {
|
||||
vec!["--no-daemon", "-c", "sandbox_mode=\"read-only\""]
|
||||
} else {
|
||||
vec![
|
||||
"--no-daemon",
|
||||
"-c",
|
||||
"sandbox_mode=\"read-only\"",
|
||||
"-c",
|
||||
"tui.fullscreen_transcript=false",
|
||||
]
|
||||
};
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex-tui")
|
||||
.or_else(|_| codex_utils_cargo_bin::cargo_bin("codex"))?;
|
||||
let mut terminal = PtyCodex::start_binary(&codex, &repo_root, home, &args, Some(&editor))?;
|
||||
terminal.wait_for_startup()?;
|
||||
terminal.wait_for_screen("GPT-5.6-Terra")?;
|
||||
terminal.write_input(b"initial draft")?;
|
||||
terminal.wait_for_screen("initial draft")?;
|
||||
terminal.write_input(b"\x07")?;
|
||||
|
||||
let deadline = Instant::now() + Duration::from_secs(/*secs*/ 10);
|
||||
while !editor.with_extension("sh.ready").exists() && Instant::now() < deadline {
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
terminal.ensure_running()?;
|
||||
}
|
||||
ensure!(
|
||||
editor.with_extension("sh.ready").exists(),
|
||||
"editor did not start (fullscreen={fullscreen}, output={editor_output:?}); screen:\n{}",
|
||||
terminal.screen_contents()
|
||||
);
|
||||
|
||||
let mut visible = None;
|
||||
if editor_output.is_empty() {
|
||||
terminal.wait_for_screen("Save and close external editor to continue.")?;
|
||||
ensure!(terminal.screen_contains("initial draft"));
|
||||
if fullscreen {
|
||||
ensure!(terminal.screen_contains("OpenAI Codex"));
|
||||
ensure!(terminal.screen_contains("GPT-5.6-Terra"));
|
||||
}
|
||||
ensure!(
|
||||
terminal.parser.screen().mouse_protocol_mode() == vt100::MouseProtocolMode::None
|
||||
);
|
||||
if fullscreen {
|
||||
visible = Some(
|
||||
terminal
|
||||
.screen_contents()
|
||||
.lines()
|
||||
.filter(|line| {
|
||||
line.contains("initial draft")
|
||||
|| line.contains("Save and close external editor to continue.")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
terminal.wait_for_screen("terminal editor")?;
|
||||
}
|
||||
|
||||
terminal.write_input(b"\n")?;
|
||||
terminal.wait_for_screen("edited draft")?;
|
||||
ensure!(terminal.parser.screen().alternate_screen() == fullscreen);
|
||||
terminal.write_input(b"!")?;
|
||||
terminal.wait_for_screen("edited draft!")?;
|
||||
if let Some(visible) = visible {
|
||||
insta::assert_snapshot!("external_editor_visible_handoff", visible);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
690
codex-rs/tui/tests/suite/focus_palette.rs
Normal file
690
codex-rs/tui/tests/suite/focus_palette.rs
Normal file
@@ -0,0 +1,690 @@
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::fd::FromRawFd;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::path::Path;
|
||||
use std::process::Child;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::bail;
|
||||
use anyhow::ensure;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
// Full startup continues after the composer first appears and can be slower under Rosetta in CI.
|
||||
const STARTUP_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30);
|
||||
const FOCUS_INPUT_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 5);
|
||||
const FOCUS_PROBE_INPUT: &str = "focus-palette-24527";
|
||||
|
||||
#[path = "external_editor_tests.rs"]
|
||||
mod external_editor;
|
||||
#[path = "gov_cloud_guidance_tests.rs"]
|
||||
mod gov_cloud_guidance;
|
||||
#[path = "tui_mode_picker_tests.rs"]
|
||||
mod tui_mode_picker;
|
||||
|
||||
#[test]
|
||||
fn focus_gained_with_unanswered_palette_queries_preserves_immediate_input() -> Result<()> {
|
||||
let repo_root = codex_utils_cargo_bin::repo_root()?;
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
write_test_config(codex_home.path(), &repo_root)?;
|
||||
|
||||
let mut terminal = PtyCodex::start(&repo_root, codex_home, &["--no-alt-screen"])?;
|
||||
terminal.wait_for_startup()?;
|
||||
|
||||
let startup_output_len = terminal.output.len();
|
||||
let focus_started = Instant::now();
|
||||
terminal.write_input(format!("\u{1b}[I{FOCUS_PROBE_INPUT}").as_bytes())?;
|
||||
terminal.wait_for_focus_input(FOCUS_PROBE_INPUT, focus_started, startup_output_len)?;
|
||||
|
||||
let delayed_input = format!("{FOCUS_PROBE_INPUT}-delayed");
|
||||
let delayed_focus_started = Instant::now();
|
||||
terminal.write_input(b"\x1b[I")?;
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 20))?;
|
||||
terminal.write_input(delayed_input.as_bytes())?;
|
||||
terminal.wait_for_focus_input(&delayed_input, delayed_focus_started, startup_output_len)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn interactive_startup_honors_codex_home_symlink_opt_out() -> Result<()> {
|
||||
use core_test_support::responses;
|
||||
use wiremock::matchers::body_string_contains;
|
||||
|
||||
core_test_support::skip_if_sandbox!(Ok(()));
|
||||
let workspace = tempfile::tempdir()?;
|
||||
let workspace_path = workspace.path().canonicalize()?;
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let target = tempfile::tempdir()?;
|
||||
let visualizations = codex_home.path().join("visualizations");
|
||||
std::os::unix::fs::symlink(target.path(), &visualizations)?;
|
||||
write_test_config(codex_home.path(), &workspace_path)?;
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
// Automatic thread-title requests must not consume the tool responses.
|
||||
let _title_mock = responses::mount_sse_once_match(
|
||||
&server,
|
||||
body_string_contains(r#"\"thread_source\":\"system\""#),
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("title", r#"{"title":"Symlink probe"}"#),
|
||||
responses::ev_completed("title"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let _write_mock = responses::mount_sse_once_match(
|
||||
&server,
|
||||
body_string_contains(r#"\"thread_source\":\"user\""#),
|
||||
responses::sse(vec![
|
||||
responses::ev_exec_command_call_with_args(
|
||||
"write",
|
||||
&serde_json::json!({
|
||||
"cmd": "printf ready > ready.txt",
|
||||
"workdir": visualizations,
|
||||
"shell": "/bin/sh",
|
||||
"login": false,
|
||||
}),
|
||||
),
|
||||
responses::ev_completed("startup"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let completion_mock = responses::mount_sse_once_match(
|
||||
&server,
|
||||
body_string_contains(r#"\"thread_source\":\"user\""#),
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("ready", "symlink-opt-out-ready"),
|
||||
responses::ev_completed("complete"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let base_url = server.uri();
|
||||
let visualizations = toml::Value::String(visualizations.display().to_string());
|
||||
let config_path = codex_home.path().join("config.toml");
|
||||
let config = std::fs::read_to_string(&config_path)?;
|
||||
std::fs::write(
|
||||
config_path,
|
||||
format!(
|
||||
"allow_symlinked_codex_home = true\n\
|
||||
sandbox_mode = \"workspace-write\"\n\
|
||||
approval_policy = \"never\"\n\
|
||||
{config}\n\
|
||||
[sandbox_workspace_write]\nwritable_roots = [{visualizations}]\n\
|
||||
[model_providers.test]\nname = \"Mock\"\n\
|
||||
base_url = \"{base_url}/v1\"\nwire_api = \"responses\"\n\
|
||||
requires_openai_auth = false\nsupports_websockets = false\n"
|
||||
),
|
||||
)?;
|
||||
|
||||
// A fresh home has no daemon. Writing through the link exercises the embedded server's
|
||||
// local executor and its sandbox policy.
|
||||
let mut terminal = PtyCodex::start(
|
||||
&workspace_path,
|
||||
codex_home,
|
||||
&[
|
||||
"--no-alt-screen",
|
||||
"-c",
|
||||
"model_provider=\"test\"",
|
||||
"Write ready.txt",
|
||||
],
|
||||
)?;
|
||||
terminal.wait_for_startup()?;
|
||||
let deadline = Instant::now() + STARTUP_TIMEOUT;
|
||||
while Instant::now() < deadline {
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
if terminal.screen_contains("symlink-opt-out-ready") {
|
||||
let tool_output = completion_mock
|
||||
.function_call_output_text("write")
|
||||
.context("missing symlink write tool output")?;
|
||||
ensure!(
|
||||
tool_output.contains("Process exited with code 0"),
|
||||
"{tool_output}"
|
||||
);
|
||||
assert_eq!(std::fs::read(target.path().join("ready.txt"))?, b"ready");
|
||||
return Ok(());
|
||||
}
|
||||
if terminal.child.try_wait()?.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
bail!(
|
||||
"interactive startup did not honor the symlink opt-out; screen:\n{}",
|
||||
terminal.screen_contents(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_owned_screen_entry_paints_before_sync_ends_and_exit_clears_inline_draft() -> Result<()> {
|
||||
let repo_root = codex_utils_cargo_bin::repo_root()?;
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
write_test_config(codex_home.path(), &repo_root)?;
|
||||
let mut terminal = PtyCodex::start(&repo_root, codex_home, &[])?;
|
||||
terminal.wait_for_startup()?;
|
||||
let deadline = Instant::now() + STARTUP_TIMEOUT;
|
||||
while !terminal.parser.screen().alternate_screen() && Instant::now() < deadline {
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
terminal.answer_startup_queries()?;
|
||||
terminal.ensure_running()?;
|
||||
}
|
||||
ensure!(
|
||||
terminal.parser.screen().alternate_screen(),
|
||||
"owned screen did not open"
|
||||
);
|
||||
terminal.wait_for_screen("GPT-5.6-Terra")?;
|
||||
ensure!(
|
||||
terminal.parser.screen().alternate_screen(),
|
||||
"fullscreen did not survive application startup"
|
||||
);
|
||||
let enter_alt = b"\x1b[?1049h";
|
||||
let begin_sync = b"\x1b[?2026h";
|
||||
let end_sync = b"\x1b[?2026l";
|
||||
let entry = terminal
|
||||
.output
|
||||
.windows(enter_alt.len())
|
||||
.position(|bytes| bytes == enter_alt)
|
||||
.context("missing owned-screen entry")?;
|
||||
let begin = terminal.output[..entry]
|
||||
.windows(begin_sync.len())
|
||||
.rposition(|bytes| bytes == begin_sync)
|
||||
.context("missing synchronized update before owned-screen entry")?;
|
||||
ensure!(
|
||||
!terminal.output[begin..entry]
|
||||
.windows(end_sync.len())
|
||||
.any(|bytes| bytes == end_sync),
|
||||
"owned-screen entry happened outside a synchronized update"
|
||||
);
|
||||
let end = entry
|
||||
+ terminal.output[entry..]
|
||||
.windows(end_sync.len())
|
||||
.position(|bytes| bytes == end_sync)
|
||||
.context("missing synchronized update end after owned-screen entry")?;
|
||||
let (rows, cols) = terminal.parser.screen().size();
|
||||
let mut first_frame = vt100::Parser::new(rows, cols, /*scrollback_len*/ 0);
|
||||
first_frame.process(&terminal.output[..end]);
|
||||
let first_contents = first_frame.screen().contents();
|
||||
ensure!(
|
||||
first_contents.contains("OpenAI Codex")
|
||||
&& first_contents.contains("Ask Codex to do anything"),
|
||||
"owned-screen synchronization ended before its first complete loading frame:\n{first_contents}"
|
||||
);
|
||||
let composer_row = first_contents
|
||||
.lines()
|
||||
.position(|line| line.contains("Ask Codex to do anything"))
|
||||
.context("missing composer in first owned-screen frame")?;
|
||||
assert_eq!(
|
||||
(
|
||||
first_contents.matches("Ask Codex to do anything").count(),
|
||||
first_frame.screen().cursor_position(),
|
||||
first_frame.screen().hide_cursor(),
|
||||
),
|
||||
(1, (u16::try_from(composer_row)?, 2), false),
|
||||
"first owned-screen frame must contain one composer with its visible cursor"
|
||||
);
|
||||
let exit_start = terminal.output.len();
|
||||
terminal.write_input(b"\x1b[99;5u")?;
|
||||
let deadline = Instant::now() + STARTUP_TIMEOUT;
|
||||
while !contains_bytes(&terminal.output[exit_start..], b"\x1b[c") {
|
||||
terminal.ensure_running()?;
|
||||
ensure!(Instant::now() < deadline, "missing exit DA1 query");
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
}
|
||||
assert_eq!(
|
||||
terminal.parser.screen().mouse_protocol_mode(),
|
||||
vt100::MouseProtocolMode::None
|
||||
);
|
||||
// The DA1 reply straddles the first 1 KiB of in-flight mouse reports.
|
||||
let mut reports = b"\x1b[<51;23;56M".repeat(85);
|
||||
reports.extend_from_slice(b"\x1b[?1;2c");
|
||||
terminal.write_input(&reports)?;
|
||||
loop {
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
if let Some(status) = terminal.child.try_wait()? {
|
||||
ensure!(status.success(), "owned screen exited with {status}");
|
||||
break;
|
||||
}
|
||||
ensure!(
|
||||
Instant::now() < deadline,
|
||||
"owned screen did not exit; screen:\n{}",
|
||||
terminal.screen_contents()
|
||||
);
|
||||
}
|
||||
terminal.write_input(b"shell\n")?;
|
||||
let mut shell_input = [0; 6];
|
||||
terminal.slave.read_exact(&mut shell_input)?;
|
||||
assert_eq!(&shell_input, b"shell\n");
|
||||
ensure!(
|
||||
!terminal.parser.screen().alternate_screen(),
|
||||
"alternate screen was not restored"
|
||||
);
|
||||
ensure!(
|
||||
!terminal
|
||||
.screen_contents()
|
||||
.contains("Ask Codex to do anything"),
|
||||
"owned-screen exit left the inline composer visible"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fullscreen_transcript_can_opt_out_to_terminal_scrollback() -> Result<()> {
|
||||
let repo_root = codex_utils_cargo_bin::repo_root()?;
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
write_test_config(codex_home.path(), &repo_root)?;
|
||||
let mut terminal = PtyCodex::start(
|
||||
&repo_root,
|
||||
codex_home,
|
||||
&["-c", "tui.fullscreen_transcript=false"],
|
||||
)?;
|
||||
terminal.wait_for_startup()?;
|
||||
terminal.wait_for_screen("GPT-5.6-Terra")?;
|
||||
ensure!(
|
||||
!terminal
|
||||
.output
|
||||
.windows(b"\x1b[?1049h".len())
|
||||
.any(|bytes| bytes == b"\x1b[?1049h"),
|
||||
"fullscreen opt-out entered the alternate screen"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) struct PtyCodex {
|
||||
master: File,
|
||||
slave: File,
|
||||
child: Child,
|
||||
parser: vt100::Parser,
|
||||
output: Vec<u8>,
|
||||
cursor_answered: bool,
|
||||
palette_answered: bool,
|
||||
keyboard_answered: bool,
|
||||
_codex_home: TempDir,
|
||||
}
|
||||
|
||||
impl PtyCodex {
|
||||
pub(super) fn start(
|
||||
repo_root: &Path,
|
||||
codex_home: TempDir,
|
||||
extra_args: &[&str],
|
||||
) -> Result<Self> {
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex-tui")
|
||||
.or_else(|_| codex_utils_cargo_bin::cargo_bin("codex"))?;
|
||||
Self::start_binary(
|
||||
&codex, repo_root, codex_home, extra_args, /*editor*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
/// Include the CLI dispatch futures when testing production stack headroom.
|
||||
pub(super) fn start_cli(
|
||||
repo_root: &Path,
|
||||
codex_home: TempDir,
|
||||
extra_args: &[&str],
|
||||
) -> Result<Self> {
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")
|
||||
.context("build codex-cli and set CARGO_BIN_EXE_codex to its executable")?;
|
||||
Self::start_binary(
|
||||
&codex, repo_root, codex_home, extra_args, /*editor*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
fn start_binary(
|
||||
codex: &Path,
|
||||
repo_root: &Path,
|
||||
codex_home: TempDir,
|
||||
extra_args: &[&str],
|
||||
editor: Option<&Path>,
|
||||
) -> Result<Self> {
|
||||
let mut master_fd = -1;
|
||||
let mut slave_fd = -1;
|
||||
let mut window_size = libc::winsize {
|
||||
ws_row: 32,
|
||||
ws_col: 120,
|
||||
ws_xpixel: 0,
|
||||
ws_ypixel: 0,
|
||||
};
|
||||
|
||||
// SAFETY: `openpty` initializes both file descriptors on success, and the supplied window
|
||||
// size remains valid for the duration of the call.
|
||||
let result = unsafe {
|
||||
libc::openpty(
|
||||
&mut master_fd,
|
||||
&mut slave_fd,
|
||||
/*name*/ std::ptr::null_mut(),
|
||||
/*termp*/ std::ptr::null_mut(),
|
||||
&raw mut window_size,
|
||||
)
|
||||
};
|
||||
if result == -1 {
|
||||
return Err(std::io::Error::last_os_error()).context("open focus-test pseudo-terminal");
|
||||
}
|
||||
|
||||
// SAFETY: a successful `openpty` transfers ownership of both unique file descriptors.
|
||||
let master = File::from(unsafe { OwnedFd::from_raw_fd(master_fd) });
|
||||
// SAFETY: `slave_fd` is the second unique descriptor initialized by `openpty`.
|
||||
let slave = File::from(unsafe { OwnedFd::from_raw_fd(slave_fd) });
|
||||
let stdin = slave.try_clone().context("clone pseudo-terminal stdin")?;
|
||||
let stdout = slave.try_clone().context("clone pseudo-terminal stdout")?;
|
||||
|
||||
let mut command = Command::new(codex);
|
||||
if let Some(editor) = editor {
|
||||
command.env("VISUAL", editor);
|
||||
}
|
||||
let child = command
|
||||
.args(extra_args)
|
||||
.arg("-C")
|
||||
.arg(repo_root)
|
||||
.env("TERM", "xterm-256color")
|
||||
// This PTY answers its own capability probes; it is not inside the caller's mux.
|
||||
.env_remove("TMUX")
|
||||
.env_remove("TMUX_PANE")
|
||||
.env_remove("STY")
|
||||
.env("TERM_PROGRAM", "kitty")
|
||||
.env_remove("TERM_PROGRAM_VERSION")
|
||||
// Exercise the fixture's login state even on hosts configured with workload identity.
|
||||
.env_remove(codex_protocol::shell_environment::OPENAI_FEDERATION_RULE_ID_ENV_VAR)
|
||||
.env_remove(codex_protocol::shell_environment::OPENAI_IDENTITY_TOKEN_FILE_ENV_VAR)
|
||||
.env("OPENAI_API_KEY", "focus-palette-test")
|
||||
.env("CODEX_HOME", codex_home.path())
|
||||
.stdin(stdin)
|
||||
.stdout(stdout)
|
||||
.stderr(slave.try_clone()?)
|
||||
.spawn()
|
||||
.context("start Codex in focus-test pseudo-terminal")?;
|
||||
|
||||
Ok(Self {
|
||||
master,
|
||||
slave,
|
||||
child,
|
||||
parser: vt100::Parser::new(
|
||||
/*rows*/ 32, /*cols*/ 120, /*scrollback_len*/ 0,
|
||||
),
|
||||
output: Vec::new(),
|
||||
cursor_answered: false,
|
||||
palette_answered: false,
|
||||
keyboard_answered: false,
|
||||
_codex_home: codex_home,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn wait_for_startup(&mut self) -> Result<()> {
|
||||
let deadline = Instant::now() + STARTUP_TIMEOUT;
|
||||
while Instant::now() < deadline {
|
||||
self.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
self.answer_startup_queries()?;
|
||||
|
||||
if self.palette_answered && self.screen_contains("OpenAI Codex") {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Some(status) = self.child.try_wait()? {
|
||||
bail!(
|
||||
"Codex exited before the focus test started ({status}); screen:\n{}",
|
||||
self.screen_contents(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
bail!(
|
||||
"Codex did not initialize within {:?}; screen:\n{}",
|
||||
STARTUP_TIMEOUT,
|
||||
self.screen_contents(),
|
||||
);
|
||||
}
|
||||
|
||||
fn wait_for_focus_input(
|
||||
&mut self,
|
||||
input: &str,
|
||||
focus_started: Instant,
|
||||
startup_output_len: usize,
|
||||
) -> Result<()> {
|
||||
while focus_started.elapsed() < FOCUS_INPUT_TIMEOUT {
|
||||
self.read_output(Duration::from_millis(/*millis*/ 20))?;
|
||||
let focus_output = &self.output[startup_output_len..];
|
||||
ensure!(
|
||||
!contains_bytes(focus_output, b"\x1b]10;?")
|
||||
&& !contains_bytes(focus_output, b"\x1b]11;?"),
|
||||
"focus regain queried terminal colors after the startup palette was cached",
|
||||
);
|
||||
if self.screen_contains(input) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
bail!(
|
||||
"focus-time palette refresh blocked or discarded {input:?} for more than {:?}; \
|
||||
screen:\n{}",
|
||||
FOCUS_INPUT_TIMEOUT,
|
||||
self.screen_contents(),
|
||||
);
|
||||
}
|
||||
|
||||
fn answer_startup_queries(&mut self) -> Result<()> {
|
||||
if !self.cursor_answered && contains_bytes(&self.output, b"\x1b[6n") {
|
||||
self.write_input(b"\x1b[1;1R")?;
|
||||
self.cursor_answered = true;
|
||||
}
|
||||
|
||||
if !self.keyboard_answered && contains_bytes(&self.output, b"\x1b[c") {
|
||||
if contains_bytes(&self.output, b"\x1b[?u") {
|
||||
self.write_input(b"\x1b[?7u")?;
|
||||
}
|
||||
self.write_input(b"\x1b[?1;2c")?;
|
||||
self.keyboard_answered = true;
|
||||
}
|
||||
|
||||
if !self.palette_answered
|
||||
&& contains_bytes(&self.output, b"\x1b]10;?")
|
||||
&& contains_bytes(&self.output, b"\x1b]11;?")
|
||||
{
|
||||
self.write_input(b"\x1b]10;rgb:ffff/ffff/ffff\x1b\\\x1b]11;rgb:0000/0000/0000\x1b\\")?;
|
||||
self.palette_answered = true;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn read_output(&mut self, timeout: Duration) -> Result<()> {
|
||||
let timeout_ms = timeout.as_millis().min(libc::c_int::MAX as u128) as libc::c_int;
|
||||
let mut descriptor = libc::pollfd {
|
||||
fd: self.master.as_raw_fd(),
|
||||
events: libc::POLLIN,
|
||||
revents: 0,
|
||||
};
|
||||
|
||||
// SAFETY: `descriptor` points to one initialized poll descriptor.
|
||||
let ready = unsafe {
|
||||
libc::poll(&mut descriptor, /*nfds*/ 1, timeout_ms)
|
||||
};
|
||||
if ready == -1 {
|
||||
let error = std::io::Error::last_os_error();
|
||||
if error.kind() == std::io::ErrorKind::Interrupted {
|
||||
return Ok(());
|
||||
}
|
||||
return Err(error).context("poll focus-test pseudo-terminal");
|
||||
}
|
||||
if ready == 0 || descriptor.revents & libc::POLLIN == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut chunk = [0_u8; 8192];
|
||||
let count = self.master.read(&mut chunk)?;
|
||||
self.output.extend_from_slice(&chunk[..count]);
|
||||
self.parser.process(&chunk[..count]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn write_input(&mut self, bytes: &[u8]) -> Result<()> {
|
||||
self.master.write_all(bytes)?;
|
||||
self.master.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn screen_contains(&self, text: &str) -> bool {
|
||||
self.parser.screen().contents().contains(text)
|
||||
}
|
||||
|
||||
pub(super) fn screen_contents(&self) -> String {
|
||||
self.parser.screen().contents()
|
||||
}
|
||||
|
||||
pub(super) fn wait_for_screen(&mut self, text: &str) -> Result<()> {
|
||||
let deadline = Instant::now() + STARTUP_TIMEOUT;
|
||||
while Instant::now() < deadline {
|
||||
self.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
self.answer_startup_queries()?;
|
||||
if self.screen_contains(text) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(status) = self.child.try_wait()? {
|
||||
bail!("Codex exited while waiting for {text:?} ({status})");
|
||||
}
|
||||
}
|
||||
bail!("missing {text:?}; screen:\n{}", self.screen_contents())
|
||||
}
|
||||
|
||||
pub(super) fn ensure_running(&mut self) -> Result<()> {
|
||||
ensure!(
|
||||
self.child.try_wait()?.is_none(),
|
||||
"Codex exited unexpectedly; screen:\n{}",
|
||||
self.screen_contents()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PtyCodex {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn contains_bytes(buffer: &[u8], needle: &[u8]) -> bool {
|
||||
buffer.windows(needle.len()).any(|window| window == needle)
|
||||
}
|
||||
|
||||
pub(super) fn write_test_config(codex_home: &Path, repo_root: &Path) -> Result<()> {
|
||||
let repo_root = repo_root.display();
|
||||
let config = format!(
|
||||
"model = \"gpt-5.6-terra\"\nmodel_provider = \"openai\"\n\
|
||||
suppress_unstable_features_warning = true\nanalytics.enabled = false\n\
|
||||
features.daemon_auto_start = false\n\
|
||||
notice.model_migrations.\"gpt-5.6-terra\" = \"gpt-6-sol\"\n\n\
|
||||
[projects.\"{repo_root}\"]\ntrust_level = \"trusted\"\n"
|
||||
);
|
||||
std::fs::write(codex_home.join("config.toml"), config)
|
||||
.context("write focus-test Codex configuration")?;
|
||||
std::fs::write(
|
||||
codex_home.join("auth.json"),
|
||||
r#"{"OPENAI_API_KEY":"focus-palette-test","tokens":null,"last_refresh":null}"#,
|
||||
)
|
||||
.context("write focus-test API-key authentication")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_daemon_skips_startup_and_discovery() -> Result<()> {
|
||||
for running in [false, true] {
|
||||
let workspace = tempfile::tempdir()?;
|
||||
let home = tempfile::tempdir()?;
|
||||
write_test_config(home.path(), workspace.path())?;
|
||||
let config = home.path().join("config.toml");
|
||||
let contents = std::fs::read_to_string(&config)?;
|
||||
std::fs::write(
|
||||
config,
|
||||
contents.replace("features.daemon_auto_start = false\n", ""),
|
||||
)?;
|
||||
let socket_path = codex_app_server_client::app_server_control_socket_path(home.path())?;
|
||||
std::fs::create_dir_all(socket_path.as_path().parent().unwrap())?;
|
||||
let listener = if running {
|
||||
let listener = std::os::unix::net::UnixListener::bind(socket_path.as_path())?;
|
||||
listener.set_nonblocking(true)?;
|
||||
Some(listener)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut terminal = PtyCodex::start(workspace.path(), home, &["--no-daemon"])?;
|
||||
terminal.wait_for_startup()?;
|
||||
terminal.write_input(b"/status")?;
|
||||
terminal.wait_for_screen("show current session configuration")?;
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 200))?;
|
||||
terminal.write_input(b"\r")?;
|
||||
terminal.wait_for_screen("Model:")?;
|
||||
ensure!(
|
||||
!terminal
|
||||
._codex_home
|
||||
.path()
|
||||
.join("app-server-daemon")
|
||||
.exists()
|
||||
);
|
||||
if let Some(listener) = listener {
|
||||
assert_eq!(
|
||||
listener.accept().unwrap_err().kind(),
|
||||
std::io::ErrorKind::WouldBlock
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
!String::from_utf8_lossy(&terminal.output)
|
||||
.contains("Running without the shared background server")
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_daemon_start_failure_exits_with_manual_fallback_hint() -> Result<()> {
|
||||
let workspace = tempfile::tempdir()?;
|
||||
let home = tempfile::tempdir()?;
|
||||
write_test_config(home.path(), workspace.path())?;
|
||||
let config = home.path().join("config.toml");
|
||||
let contents = std::fs::read_to_string(&config)?;
|
||||
std::fs::write(
|
||||
config,
|
||||
contents.replace("features.daemon_auto_start = false\n", ""),
|
||||
)?;
|
||||
// An incomplete selected package must fail without installing a replacement.
|
||||
std::fs::create_dir_all(home.path().join("packages/app-server-daemon/current"))?;
|
||||
let mut terminal = PtyCodex::start(
|
||||
workspace.path(),
|
||||
home,
|
||||
&[
|
||||
"-c",
|
||||
"features.api_key_model_discovery=true",
|
||||
"-c",
|
||||
"suppress_unstable_features_warning=true",
|
||||
],
|
||||
)?;
|
||||
let deadline = Instant::now() + STARTUP_TIMEOUT;
|
||||
while Instant::now() < deadline {
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
terminal.answer_startup_queries()?;
|
||||
if let Some(status) = terminal.child.try_wait()? {
|
||||
ensure!(!status.success());
|
||||
let output = String::from_utf8_lossy(&terminal.output);
|
||||
let failure = &output[output.find("Error:").context("missing fatal error")?..];
|
||||
let failure = codex_ansi_escape::ansi_escape(failure)
|
||||
.to_string()
|
||||
.replace(
|
||||
terminal
|
||||
._codex_home
|
||||
.path()
|
||||
.canonicalize()?
|
||||
.to_string_lossy()
|
||||
.as_ref(),
|
||||
"[CODEX_HOME]",
|
||||
)
|
||||
.replace(
|
||||
terminal._codex_home.path().to_string_lossy().as_ref(),
|
||||
"[CODEX_HOME]",
|
||||
)
|
||||
.replace('\r', "");
|
||||
insta::assert_snapshot!("daemon_auto_start_failure", failure.trim());
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
bail!("auto-start did not fail: {}", terminal.screen_contents())
|
||||
}
|
||||
62
codex-rs/tui/tests/suite/gov_cloud_guidance_tests.rs
Normal file
62
codex-rs/tui/tests/suite/gov_cloud_guidance_tests.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
//! Verify startup acknowledgment, quit without saving, and restart suppression.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn gov_cloud_startup_persists_only_acknowledgment() -> Result<()> {
|
||||
let cwd = codex_utils_cargo_bin::repo_root()?;
|
||||
let args = [
|
||||
"--no-daemon",
|
||||
"-c",
|
||||
"features.api_key_model_discovery=false",
|
||||
];
|
||||
for action in ["quit", "acknowledge"] {
|
||||
let home = tempfile::tempdir()?;
|
||||
write_test_config(home.path(), &cwd)?;
|
||||
let path = home.path().join("config.toml");
|
||||
let config = std::fs::read_to_string(&path)?.replace(
|
||||
"model_provider = \"openai\"",
|
||||
"model_provider = \"amazon-bedrock\"",
|
||||
);
|
||||
let config = format!(
|
||||
"{config}\n[model_providers.amazon-bedrock]\nbase_url = 'https://bedrock-mantle.us-gov-west-1.api.aws/openai/v1'\n"
|
||||
);
|
||||
std::fs::write(&path, &config)?;
|
||||
let mut terminal = PtyCodex::start(&cwd, home, &args)?;
|
||||
terminal.wait_for_screen("Using Codex with AWS GovCloud")?;
|
||||
let original = std::fs::read_to_string(&path)?;
|
||||
let deadline = Instant::now() + STARTUP_TIMEOUT;
|
||||
loop {
|
||||
// Startup drains pending keys after drawing the guidance; retry until it handles one.
|
||||
terminal.write_input(if action == "quit" { b"q" } else { b"\r" })?;
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
if action == "quit" {
|
||||
if let Some(status) = terminal.child.try_wait()? {
|
||||
ensure!(status.success(), "quit exited with {status}");
|
||||
break;
|
||||
}
|
||||
} else if terminal.screen_contains("OpenAI Codex") {
|
||||
break;
|
||||
}
|
||||
ensure!(Instant::now() < deadline, "{action} did not complete");
|
||||
}
|
||||
let saved = std::fs::read_to_string(&path)?;
|
||||
if action == "acknowledge" {
|
||||
let config: toml::Value = toml::from_str(&saved)?;
|
||||
assert_eq!(
|
||||
config["notice"]["hide_gov_cloud_guidance"].as_bool(),
|
||||
Some(true)
|
||||
);
|
||||
let home = std::mem::replace(&mut terminal._codex_home, tempfile::tempdir()?);
|
||||
drop(terminal);
|
||||
let mut restarted = PtyCodex::start(&cwd, home, &args)?;
|
||||
// The startup draft says "loading"; the actual model appears after guidance.
|
||||
restarted.wait_for_screen("gpt-5.6-terra")?;
|
||||
assert!(!restarted.screen_contains("Using Codex with AWS GovCloud"));
|
||||
} else {
|
||||
assert_eq!(saved, original);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
19
codex-rs/tui/tests/suite/mod.rs
Normal file
19
codex-rs/tui/tests/suite/mod.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
// Aggregates all former standalone integration tests as modules.
|
||||
#[cfg(unix)]
|
||||
mod daemon_compatibility;
|
||||
#[cfg(unix)]
|
||||
mod directory_trust;
|
||||
#[cfg(unix)]
|
||||
mod focus_palette;
|
||||
#[cfg(unix)]
|
||||
mod provider_defaults;
|
||||
#[cfg(unix)]
|
||||
mod reconnect;
|
||||
mod resize_reflow;
|
||||
#[cfg(unix)]
|
||||
mod screen_reader;
|
||||
mod status_indicator;
|
||||
mod vt100_history;
|
||||
mod vt100_live_commit;
|
||||
#[cfg(unix)]
|
||||
mod worktree_stack;
|
||||
232
codex-rs/tui/tests/suite/provider_defaults.rs
Normal file
232
codex-rs/tui/tests/suite/provider_defaults.rs
Normal file
@@ -0,0 +1,232 @@
|
||||
//! Resume and fork picker and --last provider defaults through the real CLI and app server.
|
||||
|
||||
use super::focus_palette::PtyCodex;
|
||||
use super::focus_palette::write_test_config;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use app_test_support::create_fake_rollout;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn resume_lists_all_providers_and_fork_keeps_provider_filter() -> Result<()> {
|
||||
let codex = codex_utils_cargo_bin::cargo_bin("codex")?;
|
||||
let cwd = codex_utils_cargo_bin::repo_root()?;
|
||||
for action in ["resume", "fork"] {
|
||||
for (embedded, last, explicit) in [
|
||||
(false, false, false),
|
||||
(true, false, false),
|
||||
(false, true, false),
|
||||
(true, true, false),
|
||||
(false, true, true),
|
||||
(false, false, true),
|
||||
] {
|
||||
let home = tempfile::tempdir_in("/tmp")?;
|
||||
write_test_config(home.path(), &cwd)?;
|
||||
let config_path = home.path().join("config.toml");
|
||||
let config = std::fs::read_to_string(&config_path)?;
|
||||
std::fs::write(
|
||||
config_path,
|
||||
format!(
|
||||
"{config}\n[model_providers.server-provider]\nname = 'Server provider'\nbase_url = 'http://127.0.0.1:9/v1'\nwire_api = 'responses'\nrequires_openai_auth = false\n[projects.'/']\ntrust_level = 'trusted'\n"
|
||||
),
|
||||
)?;
|
||||
for (hour, provider, preview) in [
|
||||
("10", "openai", "Client provider history"),
|
||||
("11", "server-provider", "Server provider history"),
|
||||
] {
|
||||
create_fake_rollout(
|
||||
home.path(),
|
||||
&format!("2025-01-02T{hour}-00-00"),
|
||||
&format!("2025-01-02T{hour}:00:00Z"),
|
||||
preview,
|
||||
Some(provider),
|
||||
/*git_info*/ None,
|
||||
)?;
|
||||
}
|
||||
let mut daemon = tokio::process::Command::new(&codex)
|
||||
.args([
|
||||
"app-server",
|
||||
"--listen",
|
||||
"unix://",
|
||||
"-c",
|
||||
"model_provider=\"server-provider\"",
|
||||
])
|
||||
.env("CODEX_HOME", home.path())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true)
|
||||
.spawn()?;
|
||||
let socket = codex_app_server_client::app_server_control_socket_path(home.path())?;
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 30), async {
|
||||
loop {
|
||||
if tokio::net::UnixStream::connect(socket.as_path())
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
return Ok::<(), anyhow::Error>(());
|
||||
}
|
||||
ensure!(
|
||||
daemon.try_wait()?.is_none(),
|
||||
"app server exited before opening its socket"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(/*millis*/ 20)).await;
|
||||
}
|
||||
})
|
||||
.await??;
|
||||
let remote_endpoint = format!("unix://{}", socket.as_path().display());
|
||||
let mut args = vec![action, "--all"];
|
||||
if embedded {
|
||||
args.push("--no-daemon");
|
||||
}
|
||||
if last {
|
||||
args.push("--last");
|
||||
}
|
||||
if explicit {
|
||||
args.extend([
|
||||
"--remote",
|
||||
remote_endpoint.as_str(),
|
||||
"-c",
|
||||
"model_provider=\"openai\"",
|
||||
]);
|
||||
}
|
||||
let case = format!("{action}: embedded={embedded}, last={last}, explicit={explicit}");
|
||||
let mut terminal = PtyCodex::start_cli(&cwd, home, &args)?;
|
||||
if action == "resume" && last && explicit {
|
||||
// --last finds the newest thread across providers. An explicit override
|
||||
// cannot switch that thread from server-provider to openai.
|
||||
terminal
|
||||
.wait_for_screen("Cannot change this thread's model provider")
|
||||
.with_context(|| format!("{case}; screen:\n{}", terminal.screen_contents()))?;
|
||||
} else if action == "resume" {
|
||||
terminal
|
||||
.wait_for_screen("Server provider history")
|
||||
.with_context(|| format!("{case}; screen:\n{}", terminal.screen_contents()))?;
|
||||
if !last {
|
||||
terminal
|
||||
.wait_for_screen("Client provider history")
|
||||
.with_context(|| {
|
||||
format!("{case}; screen:\n{}", terminal.screen_contents())
|
||||
})?;
|
||||
}
|
||||
} else {
|
||||
let (expected, excluded) = if embedded || explicit {
|
||||
("Client provider history", "Server provider history")
|
||||
} else {
|
||||
("Server provider history", "Client provider history")
|
||||
};
|
||||
terminal
|
||||
.wait_for_screen(expected)
|
||||
.with_context(|| format!("{case}; screen:\n{}", terminal.screen_contents()))?;
|
||||
ensure!(
|
||||
!terminal.screen_contains(excluded),
|
||||
"{case}: unexpected provider history"
|
||||
);
|
||||
}
|
||||
drop(terminal);
|
||||
daemon.kill().await?;
|
||||
daemon.wait().await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn selected_gateway_authenticates_before_its_first_chat() -> Result<()> {
|
||||
use core_test_support::responses;
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let reply = responses::mount_sse_once_match(
|
||||
&server,
|
||||
wiremock::matchers::body_string_contains(r#"\"thread_source\":\"user\""#),
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("msg", "gateway handoff verified"),
|
||||
responses::ev_completed("resp"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let workspace = tempfile::tempdir()?;
|
||||
let home = tempfile::tempdir()?;
|
||||
let cwd = workspace.path().canonicalize()?;
|
||||
let profile = home.path().join("work.config.toml");
|
||||
let auth = home.path().join("auth.json");
|
||||
let url = server.uri();
|
||||
let trusted = toml::Value::String(cwd.display().to_string());
|
||||
std::fs::write(
|
||||
&profile,
|
||||
format!(
|
||||
r#"
|
||||
model_provider = "openai"
|
||||
model = "gpt-5.1"
|
||||
forced_login_method = "api"
|
||||
cli_auth_credentials_store = "file"
|
||||
suppress_unstable_features_warning = true
|
||||
[features]
|
||||
gateway_setup_wizard = true
|
||||
bedrock_setup_wizard = false
|
||||
gcp_setup_wizard = false
|
||||
api_key_model_discovery = false
|
||||
[projects.{trusted}]
|
||||
trust_level = "trusted"
|
||||
[model_providers.office]
|
||||
name = "Office gateway"
|
||||
base_url = "{url}/v1"
|
||||
wire_api = "responses"
|
||||
supports_websockets = false
|
||||
requires_openai_auth = true
|
||||
"#
|
||||
),
|
||||
)?;
|
||||
let mut terminal = PtyCodex::start(
|
||||
&cwd,
|
||||
home,
|
||||
&["--profile", "work", "--no-daemon", "verify the gateway"],
|
||||
)?;
|
||||
terminal
|
||||
.wait_for_screen("Sign in another way")
|
||||
.with_context(|| terminal.screen_contents())?;
|
||||
// Startup drains input after its first draw. Retry the menu shortcut until it is accepted.
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(/*secs*/ 30);
|
||||
while !terminal.screen_contains("Use a custom provider or gateway") {
|
||||
ensure!(
|
||||
std::time::Instant::now() < deadline,
|
||||
"gateway option missing: {}",
|
||||
terminal.screen_contents()
|
||||
);
|
||||
terminal.write_input(b"2")?;
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
}
|
||||
// Arrow navigation avoids carrying the menu shortcut across two screens.
|
||||
terminal.write_input(b"\x1b[B\r")?;
|
||||
terminal.wait_for_screen("Office gateway")?;
|
||||
terminal.write_input(b"\x1b[H\r")?;
|
||||
terminal.wait_for_screen("Paste or type your API key")?;
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(/*secs*/ 30);
|
||||
while !auth.is_file() && terminal.screen_contains("Paste or type your API key") {
|
||||
ensure!(
|
||||
std::time::Instant::now() < deadline,
|
||||
"API key was not saved: {}",
|
||||
terminal.screen_contents()
|
||||
);
|
||||
terminal.write_input(b"\r")?;
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
}
|
||||
terminal.wait_for_screen("gateway handoff verified")?;
|
||||
let first_chat = reply
|
||||
.requests()
|
||||
.into_iter()
|
||||
.find(|request| {
|
||||
request
|
||||
.message_input_texts("user")
|
||||
.iter()
|
||||
.any(|text| text == "verify the gateway")
|
||||
})
|
||||
.context("the selected gateway received the first chat")?;
|
||||
assert_eq!(
|
||||
first_chat.header("authorization").as_deref(),
|
||||
Some("Bearer focus-palette-test")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
284
codex-rs/tui/tests/suite/reconnect.rs
Normal file
284
codex-rs/tui/tests/suite/reconnect.rs
Normal file
@@ -0,0 +1,284 @@
|
||||
//! Drives automatic reconnect through the real binary and terminal event loop.
|
||||
|
||||
use super::focus_palette::PtyCodex;
|
||||
use super::focus_palette::write_test_config;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use codex_app_server_protocol::JSONRPCMessage;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use tokio::net::UnixListener;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn automatic_reconnect_restores_draft_and_routes_new_notifications() -> Result<()> {
|
||||
core_test_support::skip_if_sandbox!(Ok(()));
|
||||
// Use a workspace without project-specific permission requirements.
|
||||
let workspace = tempfile::tempdir()?;
|
||||
let workspace_path = workspace.path().canonicalize()?;
|
||||
// macOS's default temporary directory leaves too little room for the control socket path.
|
||||
let codex_home = tempfile::tempdir_in("/tmp")?;
|
||||
write_test_config(codex_home.path(), &workspace_path)?;
|
||||
let config_path = codex_home.path().join("config.toml");
|
||||
let config = std::fs::read_to_string(&config_path)?.replace(
|
||||
"model = \"gpt-5.6-terra\"",
|
||||
"model = \"stale-client-model\"",
|
||||
);
|
||||
std::fs::write(
|
||||
config_path,
|
||||
format!("{config}\n[tui]\nstatus_line = [\"thread-id\"]\n"),
|
||||
)?;
|
||||
let socket = codex_app_server_client::app_server_control_socket_path(codex_home.path())?;
|
||||
std::fs::create_dir_all(socket.parent().unwrap())?;
|
||||
let listener = UnixListener::bind(socket.as_path())?;
|
||||
let (disconnect_tx, mut disconnect_rx) = tokio::sync::oneshot::channel();
|
||||
let (restore_tx, restore_rx) = tokio::sync::oneshot::channel();
|
||||
let (complete_tx, mut complete_rx) = tokio::sync::oneshot::channel();
|
||||
let (submitted_tx, submitted_rx) = tokio::sync::oneshot::channel();
|
||||
let server_cwd = workspace_path.clone();
|
||||
let id = "00000000-0000-0000-0000-000000000001";
|
||||
let server = tokio::spawn(async move {
|
||||
let mut methods = Vec::new();
|
||||
let mut restore_rx = Some(restore_rx);
|
||||
let mut recovered_completed = false;
|
||||
let mut submitted_tx = Some(submitted_tx);
|
||||
let thread = json!({
|
||||
"id": id, "sessionId": id, "preview": "", "ephemeral": false,
|
||||
"modelProvider": "openai", "createdAt": 1, "updatedAt": 2,
|
||||
"status": {"type": "active", "activeFlags": []}, "cwd": server_cwd,
|
||||
"cliVersion": "0.0.0", "source": "cli", "turns": [{"id": "running", "items": [], "status": "inProgress", "error": null}]
|
||||
});
|
||||
// The first connection checks daemon compatibility before TUI startup.
|
||||
for connection in -1..7 {
|
||||
let mut socket = loop {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
// Startup probes the default daemon socket before opening its WebSocket.
|
||||
if let Ok(socket) = tokio_tungstenite::accept_async(stream).await {
|
||||
break socket;
|
||||
}
|
||||
};
|
||||
loop {
|
||||
let frame = tokio::select! {
|
||||
_ = &mut complete_rx, if connection == 6 && !recovered_completed => {
|
||||
recovered_completed = true;
|
||||
socket.send(Message::Text(json!({
|
||||
"method": "turn/completed", "params": {
|
||||
"threadId": id, "turn": {"id": "running", "status": "completed", "error": null,
|
||||
"items": [{"type": "agentMessage", "id": "completed-item", "text": "Recovered turn completed."}]}
|
||||
}
|
||||
}).to_string().into())).await?;
|
||||
continue;
|
||||
}
|
||||
_ = &mut disconnect_rx, if connection == 0 => {
|
||||
socket.close(/*msg*/ None).await?;
|
||||
break;
|
||||
}
|
||||
frame = socket.next() => frame,
|
||||
};
|
||||
let Some(Ok(Message::Text(text))) = frame else {
|
||||
break;
|
||||
};
|
||||
let JSONRPCMessage::Request(request) = serde_json::from_str(&text)? else {
|
||||
continue;
|
||||
};
|
||||
methods.push(request.method.clone());
|
||||
if connection == 1 && request.method == "initialize" {
|
||||
restore_rx.take().unwrap().await?;
|
||||
}
|
||||
// Keep failing past the original five-attempt limit.
|
||||
if (1..=5).contains(&connection) && request.method == "thread/resume" {
|
||||
socket
|
||||
.send(Message::Text(
|
||||
json!({"id": request.id, "error": {
|
||||
"code": -32600,
|
||||
"message": "Server is draining; retry after reconnecting",
|
||||
"data": {"reason": "serverShuttingDown"}
|
||||
}})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await?;
|
||||
continue;
|
||||
}
|
||||
let result = match request.method.as_str() {
|
||||
"initialize" => json!({"userAgent": "reconnect-pty"}),
|
||||
// An older daemon can omit the client's default-disabled features.
|
||||
"experimentalFeature/list" => {
|
||||
json!({"data": (["api_key_model_discovery", "code_mode_host", "auth_elicitation"].map(|name| json!({
|
||||
"name": name, "stage": "stable", "displayName": null,
|
||||
"description": null, "announcement": null,
|
||||
"enabled": true, "defaultEnabled": true,
|
||||
}))), "nextCursor": null})
|
||||
}
|
||||
"account/read" => {
|
||||
json!({"account": {"type": "apiKey"}, "requiresOpenaiAuth": false})
|
||||
}
|
||||
"model/list" => json!({"data": [], "nextCursor": null}),
|
||||
"config/read" => {
|
||||
let params = request.params.as_ref().unwrap();
|
||||
assert_eq!(params["cwd"], server_cwd.to_string_lossy().as_ref());
|
||||
json!({"config": {"model": "gpt-5.6-terra", "model_provider": "openai",
|
||||
"tui": {"status_line": ["thread-id"]}, "projects": {
|
||||
server_cwd.to_string_lossy(): {"trust_level": "trusted"}
|
||||
}}, "origins": {}, "layers": []})
|
||||
}
|
||||
"configRequirements/read" => json!({"requirements": null}),
|
||||
"thread/start" | "thread/resume" => {
|
||||
let starting = request.method == "thread/start";
|
||||
if !starting {
|
||||
let params = request.params.as_ref().unwrap();
|
||||
assert_eq!(
|
||||
json!([
|
||||
params["approvalPolicy"],
|
||||
params["sandbox"],
|
||||
params["permissions"]
|
||||
]),
|
||||
json!([null, null, null])
|
||||
);
|
||||
}
|
||||
json!({"thread": thread, "model": "gpt-5.6-terra", "modelProvider": "openai",
|
||||
"cwd": server_cwd, "approvalPolicy": if starting { "on-request" } else { "never" }, "approvalsReviewer": "user",
|
||||
"sandbox": {"type": if starting { "readOnly" } else { "workspaceWrite" }}, "reasoningEffort": null})
|
||||
}
|
||||
"turn/start" => {
|
||||
let params = request.params.as_ref().unwrap();
|
||||
assert_eq!(params["input"][0]["text"], "preserved-draft!");
|
||||
assert_eq!(
|
||||
json!([
|
||||
params["approvalPolicy"],
|
||||
params["sandboxPolicy"],
|
||||
params["permissions"]
|
||||
]),
|
||||
json!(["on-request", {"type": "readOnly", "networkAccess": false}, null])
|
||||
);
|
||||
json!({"turn": {"id": "fresh", "items": [], "status": "inProgress", "error": null}})
|
||||
}
|
||||
"thread/read" => json!({"thread": thread}),
|
||||
"thread/goal/get" => json!({"goal": null}),
|
||||
"skills/list" => json!({"data": []}),
|
||||
_ => {
|
||||
socket
|
||||
.send(Message::Text(
|
||||
json!({"id": request.id, "error": {
|
||||
"code": -32601, "message": "method not found"
|
||||
}})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await?;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
socket
|
||||
.send(Message::Text(
|
||||
json!({"id": request.id, "result": result})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await?;
|
||||
if request.method == "turn/start" {
|
||||
submitted_tx.take().unwrap().send(()).unwrap();
|
||||
}
|
||||
if connection == 6 && request.method == "thread/resume" {
|
||||
// Keep the recovered turn running: its output must appear without waiting
|
||||
// for turn/completed or rebuilding the transcript.
|
||||
socket
|
||||
.send(Message::Text(
|
||||
json!({
|
||||
"method": "item/agentMessage/delta", "params": {
|
||||
"threadId": id, "turnId": "running", "itemId": "live-item",
|
||||
"delta": "fresh-notification-after-reconnect\n"
|
||||
}
|
||||
})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok::<_, anyhow::Error>(methods)
|
||||
});
|
||||
let mut terminal = PtyCodex::start(
|
||||
&workspace_path,
|
||||
codex_home,
|
||||
&[
|
||||
"--sandbox",
|
||||
"read-only",
|
||||
"--ask-for-approval",
|
||||
"on-request",
|
||||
"--no-alt-screen",
|
||||
],
|
||||
)?;
|
||||
terminal.wait_for_startup()?;
|
||||
let mut disconnect_tx = Some(disconnect_tx);
|
||||
let mut restore_tx = Some(restore_tx);
|
||||
for expected in [
|
||||
id, // The model label does not establish that the client has attached a thread.
|
||||
"preserved-draft",
|
||||
"Reconnecting",
|
||||
"preserved-draft!",
|
||||
"fresh-notification-after-reconnect",
|
||||
] {
|
||||
let deadline = Instant::now() + Duration::from_secs(/*secs*/ 60);
|
||||
while !terminal.screen_contains(expected) && Instant::now() < deadline {
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 20))?;
|
||||
}
|
||||
ensure!(
|
||||
terminal.screen_contains(expected),
|
||||
"missing {expected}; screen:\n{}",
|
||||
terminal.screen_contents()
|
||||
);
|
||||
match expected {
|
||||
ready if ready == id => terminal.write_input(b"preserved-draft")?,
|
||||
"preserved-draft" => {
|
||||
disconnect_tx.take().unwrap().send(()).unwrap();
|
||||
}
|
||||
"Reconnecting" => terminal.write_input(b"!")?,
|
||||
"preserved-draft!" => {
|
||||
restore_tx.take().unwrap().send(()).unwrap();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// A PTY read can expose the history write before the same terminal update redraws the
|
||||
// composer. Wait for both pieces in the same parsed screen before checking recovery.
|
||||
let deadline = Instant::now() + Duration::from_secs(/*secs*/ 30);
|
||||
while !(terminal.screen_contains("preserved-draft!")
|
||||
&& terminal.screen_contains("fresh-notification-after-reconnect"))
|
||||
&& Instant::now() < deadline
|
||||
{
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 20))?;
|
||||
}
|
||||
ensure!(
|
||||
terminal.screen_contains("preserved-draft!")
|
||||
&& terminal.screen_contains("fresh-notification-after-reconnect"),
|
||||
"draft and notification did not remain visible after recovery; screen:\n{}",
|
||||
terminal.screen_contents()
|
||||
);
|
||||
complete_tx.send(()).unwrap();
|
||||
terminal.wait_for_screen("Recovered turn completed.")?;
|
||||
terminal.write_input(b"\r")?;
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 10), submitted_rx).await??;
|
||||
drop(terminal);
|
||||
let methods = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), server).await???;
|
||||
assert_eq!(
|
||||
methods
|
||||
.iter()
|
||||
.filter(|method| *method == "thread/resume")
|
||||
.count(),
|
||||
6
|
||||
);
|
||||
assert_eq!(
|
||||
methods
|
||||
.iter()
|
||||
.filter(|method| *method == "turn/start")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
726
codex-rs/tui/tests/suite/resize_reflow.rs
Normal file
726
codex-rs/tui/tests/suite/resize_reflow.rs
Normal file
@@ -0,0 +1,726 @@
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::process::Output;
|
||||
use std::thread::sleep;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use tempfile::tempdir;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::matchers::body_string_contains;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "requires tmux and a locally built codex binary; run with --ignored for manual resize smoke"]
|
||||
async fn tmux_split_preserves_fresh_session_composer_row_after_resize_reflow() -> Result<()> {
|
||||
if cfg!(windows) {
|
||||
return Ok(());
|
||||
}
|
||||
skip_if_no_network!(Ok(()));
|
||||
if Command::new("tmux").arg("-V").output().is_err() {
|
||||
eprintln!("skipping resize smoke because tmux is unavailable");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let repo_root = codex_utils_cargo_bin::repo_root()?;
|
||||
let codex = codex_binary(&repo_root)?;
|
||||
let codex_home = tempdir()?;
|
||||
let server = MockServer::start().await;
|
||||
let _response_mock = mount_resize_response(&server).await;
|
||||
write_config(codex_home.path(), &repo_root, &server.uri())?;
|
||||
write_auth(codex_home.path())?;
|
||||
|
||||
let session_name = format!("codex-resize-reflow-smoke-{}", std::process::id());
|
||||
let _session = TmuxSession {
|
||||
name: session_name.clone(),
|
||||
};
|
||||
|
||||
let prompt = "Say hi.";
|
||||
let start_output = checked_output(
|
||||
Command::new("tmux")
|
||||
.arg("new-session")
|
||||
.arg("-d")
|
||||
.arg("-P")
|
||||
.arg("-F")
|
||||
.arg("#{pane_id}")
|
||||
.arg("-x")
|
||||
.arg("120")
|
||||
.arg("-y")
|
||||
.arg("40")
|
||||
.arg("-s")
|
||||
.arg(&session_name)
|
||||
.arg("--")
|
||||
.arg("env")
|
||||
.arg(format!("CODEX_HOME={}", codex_home.path().display()))
|
||||
.arg("OPENAI_API_KEY=dummy")
|
||||
.arg(codex)
|
||||
.arg("-c")
|
||||
.arg("analytics.enabled=false")
|
||||
.arg("--no-alt-screen")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg(prompt),
|
||||
)?;
|
||||
let codex_pane = stdout_text(&start_output).trim().to_string();
|
||||
anyhow::ensure!(!codex_pane.is_empty(), "tmux did not report a pane id");
|
||||
|
||||
wait_for_capture_contains(
|
||||
&codex_pane,
|
||||
"resize reflow sentinel",
|
||||
Duration::from_secs(/*secs*/ 15),
|
||||
)?;
|
||||
wait_for_capture_contains(
|
||||
&codex_pane,
|
||||
"gpt-5.4 default",
|
||||
Duration::from_secs(/*secs*/ 15),
|
||||
)?;
|
||||
let draft = "Notice where we are here in terms of y location.";
|
||||
check(
|
||||
Command::new("tmux")
|
||||
.arg("send-keys")
|
||||
.arg("-t")
|
||||
.arg(&codex_pane)
|
||||
.arg("-l")
|
||||
.arg(draft),
|
||||
)?;
|
||||
let baseline_capture =
|
||||
wait_for_capture_contains(&codex_pane, draft, Duration::from_secs(/*secs*/ 15))?;
|
||||
let baseline_row = last_composer_row(&baseline_capture).context("composer row before split")?;
|
||||
let baseline_history_row = first_row_containing(&baseline_capture, "resize reflow sentinel")
|
||||
.context("history row before split")?;
|
||||
|
||||
let split_output = checked_output(
|
||||
Command::new("tmux")
|
||||
.arg("split-window")
|
||||
.arg("-d")
|
||||
.arg("-P")
|
||||
.arg("-F")
|
||||
.arg("#{pane_id}")
|
||||
.arg("-v")
|
||||
.arg("-l")
|
||||
.arg("12")
|
||||
.arg("-t")
|
||||
.arg(&codex_pane)
|
||||
.arg("sleep")
|
||||
.arg("30"),
|
||||
)?;
|
||||
let split_pane = stdout_text(&split_output).trim().to_string();
|
||||
|
||||
sleep(Duration::from_millis(/*millis*/ 250));
|
||||
let first_capture = capture_pane(&codex_pane)?;
|
||||
let first_row = last_composer_row(&first_capture).context("composer row after split")?;
|
||||
|
||||
sleep(Duration::from_millis(/*millis*/ 1_000));
|
||||
let second_capture = capture_pane(&codex_pane)?;
|
||||
let second_row =
|
||||
last_composer_row(&second_capture).context("composer row after reflow wait")?;
|
||||
|
||||
anyhow::ensure!(
|
||||
first_row == second_row,
|
||||
"composer row drifted after split: before={first_row}, after={second_row}\n\
|
||||
before:\n{first_capture}\n\
|
||||
after:\n{second_capture}"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
second_row <= baseline_row + 1,
|
||||
"composer row snapped downward after split: baseline={baseline_row}, after={second_row}\n\
|
||||
baseline:\n{baseline_capture}\n\
|
||||
after:\n{second_capture}"
|
||||
);
|
||||
|
||||
check(
|
||||
Command::new("tmux")
|
||||
.arg("kill-pane")
|
||||
.arg("-t")
|
||||
.arg(&split_pane),
|
||||
)?;
|
||||
|
||||
sleep(Duration::from_millis(/*millis*/ 500));
|
||||
let final_capture = capture_pane(&codex_pane)?;
|
||||
let final_row =
|
||||
last_composer_row(&final_capture).context("composer row after closing split")?;
|
||||
anyhow::ensure!(
|
||||
final_row == baseline_row,
|
||||
"composer row drifted after closing split: baseline={baseline_row}, after={final_row}\n\
|
||||
capture:\n{final_capture}"
|
||||
);
|
||||
let final_history_row = first_row_containing(&final_capture, "resize reflow sentinel")
|
||||
.context("history row after closing split")?;
|
||||
anyhow::ensure!(
|
||||
final_history_row == baseline_history_row,
|
||||
"history row drifted after closing split: baseline={baseline_history_row}, \
|
||||
after={final_history_row}\n\
|
||||
baseline:\n{baseline_capture}\n\
|
||||
after:\n{final_capture}"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "requires tmux and a locally built codex binary; run with --ignored for manual resize smoke"]
|
||||
async fn tmux_repeated_resizes_do_not_push_composer_down() -> Result<()> {
|
||||
if cfg!(windows) {
|
||||
return Ok(());
|
||||
}
|
||||
skip_if_no_network!(Ok(()));
|
||||
if Command::new("tmux").arg("-V").output().is_err() {
|
||||
eprintln!("skipping resize smoke because tmux is unavailable");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
run_repeated_resize_smoke().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "requires tmux and a locally built codex binary; run with --ignored for manual resize smoke"]
|
||||
async fn tmux_width_resize_restore_keeps_visible_content_anchored() -> Result<()> {
|
||||
if cfg!(windows) {
|
||||
return Ok(());
|
||||
}
|
||||
skip_if_no_network!(Ok(()));
|
||||
if Command::new("tmux").arg("-V").output().is_err() {
|
||||
eprintln!("skipping resize smoke because tmux is unavailable");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let repo_root = codex_utils_cargo_bin::repo_root()?;
|
||||
let codex = codex_binary(&repo_root)?;
|
||||
let codex_home = tempdir()?;
|
||||
let server = MockServer::start().await;
|
||||
let _response_mock = mount_resize_response(&server).await;
|
||||
write_config(codex_home.path(), &repo_root, &server.uri())?;
|
||||
write_auth(codex_home.path())?;
|
||||
|
||||
let session_name = format!("codex-resize-width-{}", std::process::id());
|
||||
let _session = TmuxSession {
|
||||
name: session_name.clone(),
|
||||
};
|
||||
|
||||
let prompt = "Send me a large paragraph of text for testing.";
|
||||
let start_output = checked_output(
|
||||
Command::new("tmux")
|
||||
.arg("new-session")
|
||||
.arg("-d")
|
||||
.arg("-P")
|
||||
.arg("-F")
|
||||
.arg("#{pane_id}")
|
||||
.arg("-x")
|
||||
.arg("120")
|
||||
.arg("-y")
|
||||
.arg("40")
|
||||
.arg("-s")
|
||||
.arg(&session_name)
|
||||
.arg("--")
|
||||
.arg("env")
|
||||
.arg(format!("CODEX_HOME={}", codex_home.path().display()))
|
||||
.arg("OPENAI_API_KEY=dummy")
|
||||
.arg(codex)
|
||||
.arg("-c")
|
||||
.arg("analytics.enabled=false")
|
||||
.arg("--no-alt-screen")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg(prompt),
|
||||
)?;
|
||||
let codex_pane = stdout_text(&start_output).trim().to_string();
|
||||
anyhow::ensure!(!codex_pane.is_empty(), "tmux did not report a pane id");
|
||||
|
||||
wait_for_capture_contains(
|
||||
&codex_pane,
|
||||
"resize reflow sentinel",
|
||||
Duration::from_secs(/*secs*/ 15),
|
||||
)?;
|
||||
wait_for_capture_contains(
|
||||
&codex_pane,
|
||||
"gpt-5.4 default",
|
||||
Duration::from_secs(/*secs*/ 15),
|
||||
)?;
|
||||
let draft = "Notice where we are here in terms of y location.";
|
||||
check(
|
||||
Command::new("tmux")
|
||||
.arg("send-keys")
|
||||
.arg("-t")
|
||||
.arg(&codex_pane)
|
||||
.arg("-l")
|
||||
.arg(draft),
|
||||
)?;
|
||||
let baseline_capture =
|
||||
wait_for_capture_contains(&codex_pane, draft, Duration::from_secs(/*secs*/ 15))?;
|
||||
let baseline_row = last_composer_row(&baseline_capture).context("composer row before split")?;
|
||||
let baseline_history_row = first_row_containing(&baseline_capture, "resize reflow sentinel")
|
||||
.context("history row before split")?;
|
||||
|
||||
let split_output = checked_output(
|
||||
Command::new("tmux")
|
||||
.arg("split-window")
|
||||
.arg("-d")
|
||||
.arg("-P")
|
||||
.arg("-F")
|
||||
.arg("#{pane_id}")
|
||||
.arg("-h")
|
||||
.arg("-l")
|
||||
.arg("40")
|
||||
.arg("-t")
|
||||
.arg(&codex_pane)
|
||||
.arg("sleep")
|
||||
.arg("30"),
|
||||
)?;
|
||||
let split_pane = stdout_text(&split_output).trim().to_string();
|
||||
|
||||
sleep(Duration::from_millis(/*millis*/ 750));
|
||||
check(
|
||||
Command::new("tmux")
|
||||
.arg("kill-pane")
|
||||
.arg("-t")
|
||||
.arg(&split_pane),
|
||||
)?;
|
||||
|
||||
sleep(Duration::from_millis(/*millis*/ 1_000));
|
||||
let restored_capture = capture_pane(&codex_pane)?;
|
||||
let restored_row =
|
||||
last_composer_row(&restored_capture).context("composer row after width restore")?;
|
||||
let restored_history_row = first_row_containing(&restored_capture, "resize reflow sentinel")
|
||||
.context("history row after width restore")?;
|
||||
anyhow::ensure!(
|
||||
restored_row == baseline_row,
|
||||
"composer row drifted after width restore: baseline={baseline_row}, \
|
||||
restored={restored_row}\n\
|
||||
baseline:\n{baseline_capture}\n\
|
||||
restored:\n{restored_capture}"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
restored_history_row == baseline_history_row,
|
||||
"history row drifted after width restore: baseline={baseline_history_row}, \
|
||||
restored={restored_history_row}\n\
|
||||
baseline:\n{baseline_capture}\n\
|
||||
restored:\n{restored_capture}"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "requires tmux and a locally built codex binary; run with --ignored for manual resize smoke"]
|
||||
async fn tmux_scrolled_composer_resize_preserves_visible_draft_text() -> Result<()> {
|
||||
if cfg!(windows) {
|
||||
return Ok(());
|
||||
}
|
||||
skip_if_no_network!(Ok(()));
|
||||
if Command::new("tmux").arg("-V").output().is_err() {
|
||||
eprintln!("skipping resize smoke because tmux is unavailable");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let repo_root = codex_utils_cargo_bin::repo_root()?;
|
||||
let codex = codex_binary(&repo_root)?;
|
||||
let codex_home = tempdir()?;
|
||||
let server = MockServer::start().await;
|
||||
write_config(codex_home.path(), &repo_root, &server.uri())?;
|
||||
write_auth(codex_home.path())?;
|
||||
|
||||
let session_name = format!("codex-resize-scrolled-composer-{}", std::process::id());
|
||||
let _session = TmuxSession {
|
||||
name: session_name.clone(),
|
||||
};
|
||||
|
||||
let start_output = checked_output(
|
||||
Command::new("tmux")
|
||||
.arg("new-session")
|
||||
.arg("-d")
|
||||
.arg("-P")
|
||||
.arg("-F")
|
||||
.arg("#{pane_id}")
|
||||
.arg("-x")
|
||||
.arg("44")
|
||||
.arg("-y")
|
||||
.arg("14")
|
||||
.arg("-s")
|
||||
.arg(&session_name)
|
||||
.arg("--")
|
||||
.arg("env")
|
||||
.arg(format!("CODEX_HOME={}", codex_home.path().display()))
|
||||
.arg("OPENAI_API_KEY=dummy")
|
||||
.arg(codex)
|
||||
.arg("--model")
|
||||
.arg("gpt-5.6-terra")
|
||||
.arg("-c")
|
||||
.arg("analytics.enabled=false")
|
||||
.arg("--no-alt-screen")
|
||||
.arg("-C")
|
||||
.arg(&repo_root),
|
||||
)?;
|
||||
let codex_pane = stdout_text(&start_output).trim().to_string();
|
||||
anyhow::ensure!(!codex_pane.is_empty(), "tmux did not report a pane id");
|
||||
wait_for_capture_contains(
|
||||
&codex_pane,
|
||||
"gpt-5.6-terra",
|
||||
Duration::from_secs(/*secs*/ 15),
|
||||
)?;
|
||||
|
||||
for index in 1..=9 {
|
||||
let line = format!("probe-{index:02} clean words");
|
||||
check(
|
||||
Command::new("tmux")
|
||||
.arg("send-keys")
|
||||
.arg("-t")
|
||||
.arg(&codex_pane)
|
||||
.arg("-l")
|
||||
.arg(line),
|
||||
)?;
|
||||
check(
|
||||
Command::new("tmux")
|
||||
.arg("send-keys")
|
||||
.arg("-t")
|
||||
.arg(&codex_pane)
|
||||
.arg("C-j"),
|
||||
)?;
|
||||
}
|
||||
|
||||
let final_line = "q".repeat(/*n*/ 41);
|
||||
check(
|
||||
Command::new("tmux")
|
||||
.arg("send-keys")
|
||||
.arg("-t")
|
||||
.arg(&codex_pane)
|
||||
.arg("-l")
|
||||
.arg(&final_line),
|
||||
)?;
|
||||
let baseline =
|
||||
wait_for_capture_contains(&codex_pane, &final_line, Duration::from_secs(/*secs*/ 15))?;
|
||||
|
||||
for (phase, width, height, minimum_visible_rows) in
|
||||
[("narrowed", "28", "9", 2), ("restored", "44", "14", 6)]
|
||||
{
|
||||
check(
|
||||
Command::new("tmux")
|
||||
.arg("resize-window")
|
||||
.arg("-t")
|
||||
.arg(&session_name)
|
||||
.arg("-x")
|
||||
.arg(width)
|
||||
.arg("-y")
|
||||
.arg(height),
|
||||
)?;
|
||||
sleep(Duration::from_millis(/*millis*/ 350));
|
||||
let capture = capture_pane(&codex_pane)?;
|
||||
let visible_rows = capture
|
||||
.lines()
|
||||
.filter_map(|line| line.find("probe-").map(|start| (line, start)))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
anyhow::ensure!(
|
||||
visible_rows.len() >= minimum_visible_rows,
|
||||
"{phase} composer exposes too few draft rows: expected at least \
|
||||
{minimum_visible_rows}, found {}\nbaseline:\n{baseline}\ncapture:\n{capture}",
|
||||
visible_rows.len()
|
||||
);
|
||||
|
||||
for (line, start) in visible_rows {
|
||||
let draft = &line[start..];
|
||||
let row_number = draft
|
||||
.get(6..8)
|
||||
.with_context(|| format!("malformed draft row after {phase}: {draft}"))?;
|
||||
let expected = format!("probe-{row_number} clean words");
|
||||
let prefix = line[..start].trim();
|
||||
anyhow::ensure!(
|
||||
draft.starts_with(&expected) && (prefix.is_empty() || prefix == "›"),
|
||||
"{phase} resize left stale terminal content in the composer: \
|
||||
expected {expected:?}, found {line:?}\nbaseline:\n{baseline}\ncapture:\n{capture}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_repeated_resize_smoke() -> Result<()> {
|
||||
let repo_root = codex_utils_cargo_bin::repo_root()?;
|
||||
let codex = codex_binary(&repo_root)?;
|
||||
let codex_home = tempdir()?;
|
||||
let server = MockServer::start().await;
|
||||
let _response_mock = mount_resize_response(&server).await;
|
||||
write_config(codex_home.path(), &repo_root, &server.uri())?;
|
||||
write_auth(codex_home.path())?;
|
||||
|
||||
let session_name = format!("codex-resize-repeat-{}", std::process::id());
|
||||
let _session = TmuxSession {
|
||||
name: session_name.clone(),
|
||||
};
|
||||
|
||||
let prompt = "Send me a large paragraph of text for testing.";
|
||||
let start_output = checked_output(
|
||||
Command::new("tmux")
|
||||
.arg("new-session")
|
||||
.arg("-d")
|
||||
.arg("-P")
|
||||
.arg("-F")
|
||||
.arg("#{pane_id}")
|
||||
.arg("-x")
|
||||
.arg("120")
|
||||
.arg("-y")
|
||||
.arg("40")
|
||||
.arg("-s")
|
||||
.arg(&session_name)
|
||||
.arg("--")
|
||||
.arg("env")
|
||||
.arg(format!("CODEX_HOME={}", codex_home.path().display()))
|
||||
.arg("OPENAI_API_KEY=dummy")
|
||||
.arg(codex)
|
||||
.arg("-c")
|
||||
.arg("analytics.enabled=false")
|
||||
.arg("--no-alt-screen")
|
||||
.arg("-C")
|
||||
.arg(&repo_root)
|
||||
.arg(prompt),
|
||||
)?;
|
||||
let codex_pane = stdout_text(&start_output).trim().to_string();
|
||||
anyhow::ensure!(!codex_pane.is_empty(), "tmux did not report a pane id");
|
||||
|
||||
wait_for_capture_contains(
|
||||
&codex_pane,
|
||||
"resize reflow sentinel",
|
||||
Duration::from_secs(/*secs*/ 15),
|
||||
)?;
|
||||
wait_for_capture_contains(
|
||||
&codex_pane,
|
||||
"gpt-5.4 default",
|
||||
Duration::from_secs(/*secs*/ 15),
|
||||
)?;
|
||||
let draft = "Notice where we are here in terms of y location.";
|
||||
check(
|
||||
Command::new("tmux")
|
||||
.arg("send-keys")
|
||||
.arg("-t")
|
||||
.arg(&codex_pane)
|
||||
.arg("-l")
|
||||
.arg(draft),
|
||||
)?;
|
||||
let baseline_capture =
|
||||
wait_for_capture_contains(&codex_pane, draft, Duration::from_secs(/*secs*/ 15))?;
|
||||
let baseline_row = last_composer_row(&baseline_capture).context("composer row before split")?;
|
||||
let baseline_history_row = first_row_containing(&baseline_capture, "resize reflow sentinel")
|
||||
.context("history row before split")?;
|
||||
|
||||
for cycle in 1..=3 {
|
||||
let split_output = checked_output(
|
||||
Command::new("tmux")
|
||||
.arg("split-window")
|
||||
.arg("-d")
|
||||
.arg("-P")
|
||||
.arg("-F")
|
||||
.arg("#{pane_id}")
|
||||
.arg("-v")
|
||||
.arg("-l")
|
||||
.arg("12")
|
||||
.arg("-t")
|
||||
.arg(&codex_pane)
|
||||
.arg("sleep")
|
||||
.arg("30"),
|
||||
)?;
|
||||
let split_pane = stdout_text(&split_output).trim().to_string();
|
||||
|
||||
sleep(Duration::from_millis(/*millis*/ 250));
|
||||
check(
|
||||
Command::new("tmux")
|
||||
.arg("kill-pane")
|
||||
.arg("-t")
|
||||
.arg(&split_pane),
|
||||
)?;
|
||||
|
||||
sleep(Duration::from_millis(/*millis*/ 500));
|
||||
let restored_capture = capture_pane(&codex_pane)?;
|
||||
let restored_row = last_composer_row(&restored_capture)
|
||||
.with_context(|| format!("composer row after resize cycle {cycle}"))?;
|
||||
let restored_history_row =
|
||||
first_row_containing(&restored_capture, "resize reflow sentinel")
|
||||
.with_context(|| format!("history row after resize cycle {cycle}"))?;
|
||||
anyhow::ensure!(
|
||||
restored_row == baseline_row,
|
||||
"composer row drifted after resize cycle {cycle}: baseline={baseline_row}, \
|
||||
restored={restored_row}\n\
|
||||
baseline:\n{baseline_capture}\n\
|
||||
restored:\n{restored_capture}"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
restored_history_row == baseline_history_row,
|
||||
"history row drifted after resize cycle {cycle}: baseline={baseline_history_row}, \
|
||||
restored={restored_history_row}\n\
|
||||
baseline:\n{baseline_capture}\n\
|
||||
restored:\n{restored_capture}"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct TmuxSession {
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl Drop for TmuxSession {
|
||||
fn drop(&mut self) {
|
||||
let _ = Command::new("tmux")
|
||||
.arg("kill-session")
|
||||
.arg("-t")
|
||||
.arg(&self.name)
|
||||
.output();
|
||||
}
|
||||
}
|
||||
|
||||
fn codex_binary(repo_root: &Path) -> Result<PathBuf> {
|
||||
if let Ok(path) = codex_utils_cargo_bin::cargo_bin("codex") {
|
||||
return Ok(path);
|
||||
}
|
||||
|
||||
let fallback = repo_root.join("codex-rs/target/debug/codex");
|
||||
anyhow::ensure!(
|
||||
fallback.is_file(),
|
||||
"codex binary is unavailable; run `cargo build -p codex-cli` first"
|
||||
);
|
||||
Ok(fallback)
|
||||
}
|
||||
|
||||
fn write_config(codex_home: &Path, repo_root: &Path, server_url: &str) -> Result<()> {
|
||||
let repo_root_display = repo_root.display();
|
||||
let config = format!(
|
||||
r#"model = "gpt-5.4"
|
||||
model_provider = "resize_mock"
|
||||
suppress_unstable_features_warning = true
|
||||
|
||||
# The resize fixture serves HTTP SSE only, not WebSocket upgrades.
|
||||
[model_providers.resize_mock]
|
||||
name = "Resize mock"
|
||||
base_url = "{server_url}/v1"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = false
|
||||
supports_websockets = false
|
||||
|
||||
[notice.model_migrations]
|
||||
"gpt-5.4" = "gpt-6-sol"
|
||||
|
||||
[projects."{repo_root_display}"]
|
||||
trust_level = "trusted"
|
||||
"#
|
||||
);
|
||||
std::fs::write(codex_home.join("config.toml"), config)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_auth(codex_home: &Path) -> Result<()> {
|
||||
std::fs::write(
|
||||
codex_home.join("auth.json"),
|
||||
r#"{"OPENAI_API_KEY":"dummy","tokens":null,"last_refresh":null}"#,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Title generation and the visible turn race; neither may consume the other's response.
|
||||
async fn mount_resize_response(server: &MockServer) -> responses::ResponseMock {
|
||||
let _title = responses::mount_sse_once_match(
|
||||
server,
|
||||
body_string_contains(r#"\"thread_source\":\"system\""#),
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message(
|
||||
"resize-title",
|
||||
r#"{"title":"Test terminal resizing"}"#,
|
||||
),
|
||||
responses::ev_completed("resize-title"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
responses::mount_sse_once_match(
|
||||
server,
|
||||
body_string_contains(r#"\"thread_source\":\"user\""#),
|
||||
resize_reflow_sse(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
fn resize_reflow_sse() -> String {
|
||||
let text = "resize reflow sentinel says hi. This paragraph is intentionally long enough to exercise terminal wrapping, scrollback redraw, and pane resize behavior without requiring a live model response. It includes enough ordinary prose to wrap across several rows in a narrow tmux pane, then keep going so repeated split and restore cycles have visible history above the composer. If a resize path accidentally inserts blank rows or anchors the viewport lower on each pass, the composer row will drift after the pane returns to its original height.";
|
||||
responses::sse(vec![
|
||||
responses::ev_response_created("resp-resize-smoke"),
|
||||
responses::ev_assistant_message("msg-resize-smoke", text),
|
||||
responses::ev_completed("resp-resize-smoke"),
|
||||
])
|
||||
}
|
||||
|
||||
fn wait_for_capture_contains(pane: &str, needle: &str, timeout: Duration) -> Result<String> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut last_capture = String::new();
|
||||
while Instant::now() < deadline {
|
||||
last_capture = capture_pane(pane)?;
|
||||
if last_capture.contains(needle) {
|
||||
return Ok(last_capture);
|
||||
}
|
||||
sleep(Duration::from_millis(/*millis*/ 100));
|
||||
}
|
||||
|
||||
anyhow::bail!("timed out waiting for {needle:?}; last capture:\n{last_capture}");
|
||||
}
|
||||
|
||||
fn capture_pane(pane: &str) -> Result<String> {
|
||||
let output = output(
|
||||
Command::new("tmux")
|
||||
.arg("capture-pane")
|
||||
.arg("-p")
|
||||
.arg("-t")
|
||||
.arg(pane),
|
||||
)?;
|
||||
Ok(String::from_utf8_lossy(&output.stdout).to_string())
|
||||
}
|
||||
|
||||
fn last_composer_row(capture: &str) -> Option<usize> {
|
||||
capture
|
||||
.lines()
|
||||
.enumerate()
|
||||
.filter_map(|(index, line)| {
|
||||
if line.trim_start().starts_with('\u{203a}') {
|
||||
Some(index)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.last()
|
||||
}
|
||||
|
||||
fn first_row_containing(capture: &str, needle: &str) -> Option<usize> {
|
||||
capture
|
||||
.lines()
|
||||
.enumerate()
|
||||
.find_map(|(index, line)| line.contains(needle).then_some(index))
|
||||
}
|
||||
|
||||
fn check(command: &mut Command) -> Result<()> {
|
||||
checked_output(command)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn checked_output(command: &mut Command) -> Result<Output> {
|
||||
let output = output(command)?;
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"command failed with status {:?}\nstdout:\n{}\nstderr:\n{}",
|
||||
output.status.code(),
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn output(command: &mut Command) -> Result<Output> {
|
||||
command
|
||||
.output()
|
||||
.with_context(|| format!("failed to run {command:?}"))
|
||||
}
|
||||
|
||||
fn stdout_text(output: &Output) -> String {
|
||||
String::from_utf8_lossy(&output.stdout).to_string()
|
||||
}
|
||||
39
codex-rs/tui/tests/suite/screen_reader.rs
Normal file
39
codex-rs/tui/tests/suite/screen_reader.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
//! Checks that interactive startup persists detection without replacing a user preference.
|
||||
|
||||
use super::focus_palette::PtyCodex;
|
||||
use super::focus_palette::write_test_config;
|
||||
use anyhow::Result;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
#[test]
|
||||
fn startup_records_screen_reader_detection() -> Result<()> {
|
||||
let repo_root = codex_utils_cargo_bin::repo_root()?;
|
||||
let home = tempfile::tempdir()?;
|
||||
write_test_config(home.path(), &repo_root)?;
|
||||
let path = home.path().join("config.toml");
|
||||
let contents = std::fs::read_to_string(&path)?;
|
||||
std::fs::write(&path, format!("{contents}\n[tui]\nanimations = true\n"))?;
|
||||
let mut terminal = PtyCodex::start(&repo_root, home, &[])?;
|
||||
terminal.wait_for_startup()?;
|
||||
let deadline = Instant::now() + Duration::from_secs(/*secs*/ 30);
|
||||
loop {
|
||||
let config: toml::Value = toml::from_str(&std::fs::read_to_string(&path)?)?;
|
||||
if config["tui"].get("screen_reader_detection_done").is_some() {
|
||||
assert_eq!(
|
||||
config["tui"],
|
||||
toml::Value::Table(toml::toml! {
|
||||
animations = true
|
||||
screen_reader_detection_done = true
|
||||
})
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
anyhow::ensure!(
|
||||
Instant::now() < deadline,
|
||||
"startup did not record detection"
|
||||
);
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
source: tui/tests/suite/daemon_compatibility.rs
|
||||
expression: warning
|
||||
---
|
||||
⚠ Running without the shared background server: This session requires api_key_model_discovery to be enabled.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
source: tui/tests/suite/daemon_compatibility.rs
|
||||
expression: warning
|
||||
---
|
||||
⚠ Running without the shared background server: code-mode host fallback policy requires embedded mode.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
source: tui/tests/suite/daemon_compatibility.rs
|
||||
expression: warning
|
||||
---
|
||||
⚠ Running without the shared background server: This session requires api_key_model_discovery to be disabled.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/tests/suite/focus_palette.rs
|
||||
assertion_line: 484
|
||||
expression: failure.trim()
|
||||
---
|
||||
Error: daemon executable not found at [CODEX_HOME]/packages/app-server-daemon/current/bin/codex; repair the existing installation, or run `codex app-server daemon start` to install a missing daemon
|
||||
To work without the background server, rerun the same command with --no-daemon (including resume or fork and its arguments).
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/tests/suite/external_editor_tests.rs
|
||||
assertion_line: 89
|
||||
expression: visible
|
||||
---
|
||||
› initial draft
|
||||
Save and close external editor to continue.
|
||||
24
codex-rs/tui/tests/suite/status_indicator.rs
Normal file
24
codex-rs/tui/tests/suite/status_indicator.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
//! Regression test: ensure that `StatusIndicatorWidget` sanitises ANSI escape
|
||||
//! sequences so that no raw `\x1b` bytes are written into the backing
|
||||
//! buffer. Rendering logic is tricky to unit‑test end‑to‑end, therefore we
|
||||
//! verify the *public* contract of `ansi_escape_line()` which the widget now
|
||||
//! relies on.
|
||||
|
||||
use codex_ansi_escape::ansi_escape_line;
|
||||
|
||||
#[test]
|
||||
fn ansi_escape_line_strips_escape_sequences() {
|
||||
let text_in_ansi_red = "\x1b[31mRED\x1b[0m";
|
||||
|
||||
// The returned line must contain three printable glyphs and **no** raw
|
||||
// escape bytes.
|
||||
let line = ansi_escape_line(text_in_ansi_red);
|
||||
|
||||
let combined: String = line
|
||||
.spans
|
||||
.iter()
|
||||
.map(|span| span.content.to_string())
|
||||
.collect();
|
||||
|
||||
assert_eq!(combined, "RED");
|
||||
}
|
||||
66
codex-rs/tui/tests/suite/tui_mode_picker_tests.rs
Normal file
66
codex-rs/tui/tests/suite/tui_mode_picker_tests.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
//! The picker persists a preference, but only a new process adopts the renderer.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn tui_mode_picker_applies_only_after_restart() -> Result<()> {
|
||||
let root = codex_utils_cargo_bin::repo_root()?;
|
||||
let mut home = tempfile::tempdir()?;
|
||||
write_test_config(home.path(), &root)?;
|
||||
let path = home.path().join("config.toml");
|
||||
let config = std::fs::read_to_string(&path)?;
|
||||
std::fs::write(
|
||||
&path,
|
||||
format!(
|
||||
"tui.fullscreen_transcript = false\ntui.alternate_screen = \"always\"\ntui.disable_paste_burst = true\ntui.status_line = [\"thread-id\"]\n{config}"
|
||||
),
|
||||
)?;
|
||||
for (launch, current) in [false, true, false].into_iter().enumerate() {
|
||||
let mut terminal = PtyCodex::start(&root, home, &[])?;
|
||||
terminal.wait_for_startup()?;
|
||||
// The header precedes session setup; wait for the thread ID before sending commands.
|
||||
let deadline = Instant::now() + STARTUP_TIMEOUT;
|
||||
loop {
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
terminal.answer_startup_queries()?;
|
||||
if terminal
|
||||
.screen_contents()
|
||||
.split_whitespace()
|
||||
.any(|word| uuid::Uuid::parse_str(word).is_ok())
|
||||
{
|
||||
break;
|
||||
}
|
||||
ensure!(
|
||||
Instant::now() < deadline,
|
||||
"thread did not become ready: {}",
|
||||
terminal.screen_contents()
|
||||
);
|
||||
terminal.ensure_running()?;
|
||||
}
|
||||
assert_eq!(terminal.parser.screen().alternate_screen(), current);
|
||||
if launch == 2 {
|
||||
break;
|
||||
}
|
||||
terminal.write_input(b"/tui")?;
|
||||
terminal.wait_for_screen("/tui")?;
|
||||
terminal.write_input(b"\r")?;
|
||||
terminal.wait_for_screen("TUI mode for next launch")?;
|
||||
terminal.write_input(if current { b"\x1b[A" } else { b"\x1b[B" })?;
|
||||
terminal.write_input(b"\r")?;
|
||||
terminal.wait_for_screen(if current {
|
||||
"Saved TUI mode: Scrollback"
|
||||
} else {
|
||||
"Saved TUI mode: Fullscreen"
|
||||
})?;
|
||||
assert_eq!(terminal.parser.screen().alternate_screen(), current);
|
||||
let saved: toml::Value = toml::from_str(&std::fs::read_to_string(&path)?)?;
|
||||
assert_eq!(
|
||||
saved["tui"]["fullscreen_transcript"].as_bool(),
|
||||
Some(!current)
|
||||
);
|
||||
home = std::mem::replace(&mut terminal._codex_home, tempfile::tempdir()?);
|
||||
drop(terminal);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
164
codex-rs/tui/tests/suite/vt100_history.rs
Normal file
164
codex-rs/tui/tests/suite/vt100_history.rs
Normal file
@@ -0,0 +1,164 @@
|
||||
use crate::test_backend::VT100Backend;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::text::Line;
|
||||
|
||||
// Small helper macro to assert a collection contains an item with a clearer
|
||||
// failure message.
|
||||
macro_rules! assert_contains {
|
||||
($collection:expr, $item:expr $(,)?) => {
|
||||
assert!(
|
||||
$collection.contains(&$item),
|
||||
"Expected {:?} to contain {:?}",
|
||||
$collection,
|
||||
$item
|
||||
);
|
||||
};
|
||||
($collection:expr, $item:expr, $($arg:tt)+) => {
|
||||
assert!($collection.contains(&$item), $($arg)+);
|
||||
};
|
||||
}
|
||||
|
||||
struct TestScenario {
|
||||
term: codex_tui::Terminal<VT100Backend>,
|
||||
}
|
||||
|
||||
impl TestScenario {
|
||||
fn new(width: u16, height: u16, viewport: Rect) -> Self {
|
||||
let backend = VT100Backend::new(width, height);
|
||||
let mut term =
|
||||
codex_tui::Terminal::with_options(backend).expect("failed to construct terminal");
|
||||
term.set_viewport_area(viewport);
|
||||
Self { term }
|
||||
}
|
||||
|
||||
fn run_insert(&mut self, lines: Vec<Line<'static>>) {
|
||||
codex_tui::insert_history_lines(&mut self.term, lines)
|
||||
.expect("Failed to insert history lines in test");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_insertion_no_wrap() {
|
||||
// Screen of 20x6; viewport is the last row (height=1 at y=5)
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 5, /*width*/ 20, /*height*/ 1,
|
||||
);
|
||||
let mut scenario = TestScenario::new(/*width*/ 20, /*height*/ 6, area);
|
||||
|
||||
let lines = vec!["first".into(), "second".into()];
|
||||
scenario.run_insert(lines);
|
||||
let rows = scenario.term.backend().vt100().screen().contents();
|
||||
assert_contains!(rows, String::from("first"));
|
||||
assert_contains!(rows, String::from("second"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_token_wraps() {
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 5, /*width*/ 20, /*height*/ 1,
|
||||
);
|
||||
let mut scenario = TestScenario::new(/*width*/ 20, /*height*/ 6, area);
|
||||
|
||||
let long = "A".repeat(45); // > 2 lines at width 20
|
||||
let lines = vec![long.clone().into()];
|
||||
scenario.run_insert(lines);
|
||||
let screen = scenario.term.backend().vt100().screen();
|
||||
|
||||
// Count total A's on the screen
|
||||
let mut count_a = 0usize;
|
||||
for row in 0..6 {
|
||||
for col in 0..20 {
|
||||
if let Some(cell) = screen.cell(row, col)
|
||||
&& let Some(ch) = cell.contents().chars().next()
|
||||
&& ch == 'A'
|
||||
{
|
||||
count_a += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
count_a,
|
||||
long.len(),
|
||||
"wrapped content did not preserve all characters"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emoji_and_cjk() {
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 5, /*width*/ 20, /*height*/ 1,
|
||||
);
|
||||
let mut scenario = TestScenario::new(/*width*/ 20, /*height*/ 6, area);
|
||||
|
||||
let text = String::from("😀😀😀😀😀 你好世界");
|
||||
let lines = vec![text.clone().into()];
|
||||
scenario.run_insert(lines);
|
||||
let rows = scenario.term.backend().vt100().screen().contents();
|
||||
for ch in text.chars().filter(|c| !c.is_whitespace()) {
|
||||
assert!(
|
||||
rows.contains(ch),
|
||||
"missing character {ch:?} in reconstructed screen"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_ansi_spans() {
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 5, /*width*/ 20, /*height*/ 1,
|
||||
);
|
||||
let mut scenario = TestScenario::new(/*width*/ 20, /*height*/ 6, area);
|
||||
|
||||
let line = vec!["red".red(), "+plain".into()].into();
|
||||
scenario.run_insert(vec![line]);
|
||||
let rows = scenario.term.backend().vt100().screen().contents();
|
||||
assert_contains!(rows, String::from("red+plain"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_restoration() {
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 5, /*width*/ 20, /*height*/ 1,
|
||||
);
|
||||
let mut scenario = TestScenario::new(/*width*/ 20, /*height*/ 6, area);
|
||||
|
||||
let lines = vec!["x".into()];
|
||||
scenario.run_insert(lines);
|
||||
assert_eq!(scenario.term.last_known_cursor_pos, (0, 0).into());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_wrap_no_mid_word_split() {
|
||||
// Screen of 40x10; viewport is the last row
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 9, /*width*/ 40, /*height*/ 1,
|
||||
);
|
||||
let mut scenario = TestScenario::new(/*width*/ 40, /*height*/ 10, area);
|
||||
|
||||
let sample = "Years passed, and Willowmere thrived in peace and friendship. Mira’s herb garden flourished with both ordinary and enchanted plants, and travelers spoke of the kindness of the woman who tended them.";
|
||||
scenario.run_insert(vec![sample.into()]);
|
||||
let joined = scenario.term.backend().vt100().screen().contents();
|
||||
assert!(
|
||||
!joined.contains("bo\nth"),
|
||||
"word 'both' should not be split across lines:\n{joined}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn em_dash_and_space_word_wrap() {
|
||||
// Repro from report: ensure we break before "inside", not mid-word.
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 9, /*width*/ 40, /*height*/ 1,
|
||||
);
|
||||
let mut scenario = TestScenario::new(/*width*/ 40, /*height*/ 10, area);
|
||||
|
||||
let sample = "Mara found an old key on the shore. Curious, she opened a tarnished box half-buried in sand—and inside lay a single, glowing seed.";
|
||||
scenario.run_insert(vec![sample.into()]);
|
||||
let joined = scenario.term.backend().vt100().screen().contents();
|
||||
assert!(
|
||||
!joined.contains("insi\nde"),
|
||||
"word 'inside' should not be split across lines:\n{joined}"
|
||||
);
|
||||
}
|
||||
43
codex-rs/tui/tests/suite/vt100_live_commit.rs
Normal file
43
codex-rs/tui/tests/suite/vt100_live_commit.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
use crate::test_backend::VT100Backend;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::text::Line;
|
||||
|
||||
#[test]
|
||||
fn live_001_commit_on_overflow() {
|
||||
let backend = VT100Backend::new(/*width*/ 20, /*height*/ 6);
|
||||
let mut term =
|
||||
codex_tui::Terminal::with_options(backend).expect("terminal should be constructed");
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 5, /*width*/ 20, /*height*/ 1,
|
||||
);
|
||||
term.set_viewport_area(area);
|
||||
|
||||
// Build 5 explicit rows at width 20.
|
||||
let mut rb = codex_tui::RowBuilder::new(/*target_width*/ 20);
|
||||
rb.push_fragment("one\n");
|
||||
rb.push_fragment("two\n");
|
||||
rb.push_fragment("three\n");
|
||||
rb.push_fragment("four\n");
|
||||
rb.push_fragment("five\n");
|
||||
|
||||
// Keep the last 3 in the live ring; commit the first 2.
|
||||
let commit_rows = rb.drain_commit_ready(/*max_keep*/ 3);
|
||||
let lines: Vec<Line<'static>> = commit_rows.into_iter().map(|r| r.text.into()).collect();
|
||||
|
||||
codex_tui::insert_history_lines(&mut term, lines)
|
||||
.expect("Failed to insert history lines in test");
|
||||
|
||||
let screen = term.backend().vt100().screen();
|
||||
|
||||
// The words "one" and "two" should appear above the viewport.
|
||||
let joined = screen.contents();
|
||||
assert!(
|
||||
joined.contains("one"),
|
||||
"expected committed 'one' to be visible\n{joined}"
|
||||
);
|
||||
assert!(
|
||||
joined.contains("two"),
|
||||
"expected committed 'two' to be visible\n{joined}"
|
||||
);
|
||||
// The last three (three,four,five) remain in the live ring, not committed here.
|
||||
}
|
||||
222
codex-rs/tui/tests/suite/worktree_stack.rs
Normal file
222
codex-rs/tui/tests/suite/worktree_stack.rs
Normal file
@@ -0,0 +1,222 @@
|
||||
//! 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",
|
||||
"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")?;
|
||||
|
||||
// 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("Side 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()?;
|
||||
|
||||
submit(&mut terminal, &format!("/cd {}", root.display()))?;
|
||||
terminal.wait_for_screen(&format!("Working directory changed to: {}", root.display()))?;
|
||||
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 submit(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())?;
|
||||
terminal.wait_for_screen(input)?;
|
||||
// Thread startup can keep the composer in queue mode after the history is visible.
|
||||
let deadline = Instant::now() + Duration::from_secs(/*secs*/ 30);
|
||||
while terminal.screen_contains("tab to queue message") {
|
||||
ensure!(
|
||||
Instant::now() < deadline,
|
||||
"composer remained busy before {input:?}"
|
||||
);
|
||||
terminal.read_output(Duration::from_millis(/*millis*/ 50))?;
|
||||
terminal.ensure_running()?;
|
||||
}
|
||||
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()
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user