mirror of
https://github.com/openai/codex.git
synced 2026-11-02 19:43:24 +00:00
Merge cfff3af45c into sapling-pr-archive-bolinfest
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
use tree_sitter::Node;
|
||||
use tree_sitter::Parser;
|
||||
use tree_sitter::Tree;
|
||||
use tree_sitter_bash::LANGUAGE as BASH;
|
||||
@@ -75,7 +76,7 @@ pub fn try_parse_word_only_commands_sequence(tree: &Tree, src: &str) -> Option<V
|
||||
|
||||
let mut commands = Vec::new();
|
||||
for node in command_nodes {
|
||||
if let Some(words) = parse_plain_command_from_node(node, src) {
|
||||
if let Some(words) = extract_words_from_command_node(node, src) {
|
||||
commands.push(words);
|
||||
} else {
|
||||
return None;
|
||||
@@ -84,7 +85,10 @@ pub fn try_parse_word_only_commands_sequence(tree: &Tree, src: &str) -> Option<V
|
||||
Some(commands)
|
||||
}
|
||||
|
||||
fn parse_plain_command_from_node(cmd: tree_sitter::Node, src: &str) -> Option<Vec<String>> {
|
||||
/// Extract the plain words of a simple command node, normalizing quoted
|
||||
/// strings into their contents. Returns None if the node contains unsupported
|
||||
/// constructs for a word-only command.
|
||||
pub(crate) fn extract_words_from_command_node(cmd: Node, src: &str) -> Option<Vec<String>> {
|
||||
if cmd.kind() != "command" {
|
||||
return None;
|
||||
}
|
||||
@@ -130,6 +134,43 @@ fn parse_plain_command_from_node(cmd: tree_sitter::Node, src: &str) -> Option<Ve
|
||||
Some(words)
|
||||
}
|
||||
|
||||
/// Find the earliest `command` node in source order within the parse tree.
|
||||
pub(crate) fn find_first_command_node(tree: &Tree) -> Option<Node<'_>> {
|
||||
let root = tree.root_node();
|
||||
let mut cursor = root.walk();
|
||||
let mut stack = vec![root];
|
||||
let mut best: Option<Node> = None;
|
||||
while let Some(node) = stack.pop() {
|
||||
if node.is_named() && node.kind() == "command" {
|
||||
if best.map_or(true, |b| node.start_byte() < b.start_byte()) {
|
||||
best = Some(node);
|
||||
}
|
||||
}
|
||||
for child in node.children(&mut cursor) {
|
||||
stack.push(child);
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Given the first command node, return the byte index in `src` at which the
|
||||
/// remainder script starts, only if the next non-whitespace token is `&&`.
|
||||
pub(crate) fn remainder_start_after_and(first_cmd: Node, src: &str) -> Option<usize> {
|
||||
let mut sib = first_cmd.next_sibling()?;
|
||||
while !sib.is_named() && sib.kind().trim().is_empty() {
|
||||
sib = sib.next_sibling()?;
|
||||
}
|
||||
if sib.is_named() || sib.kind() != "&&" {
|
||||
return None;
|
||||
}
|
||||
let mut idx = sib.end_byte() as usize;
|
||||
let bytes = src.as_bytes();
|
||||
while idx < bytes.len() && bytes[idx].is_ascii_whitespace() {
|
||||
idx += 1;
|
||||
}
|
||||
if idx >= bytes.len() { None } else { Some(idx) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -10,15 +10,12 @@ use codex_protocol::models::ResponseItem;
|
||||
use futures::Stream;
|
||||
use serde::Serialize;
|
||||
use std::borrow::Cow;
|
||||
use std::ops::Deref;
|
||||
use std::pin::Pin;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
/// The `instructions` field in the payload sent to a model should always start
|
||||
/// with this content.
|
||||
const BASE_INSTRUCTIONS: &str = include_str!("../prompt.md");
|
||||
|
||||
/// Review thread system prompt. Edit `core/src/review_prompt.md` to customize.
|
||||
pub const REVIEW_PROMPT: &str = include_str!("../review_prompt.md");
|
||||
|
||||
@@ -41,7 +38,7 @@ impl Prompt {
|
||||
let base = self
|
||||
.base_instructions_override
|
||||
.as_deref()
|
||||
.unwrap_or(BASE_INSTRUCTIONS);
|
||||
.unwrap_or(model.base_instructions.deref());
|
||||
let mut sections: Vec<&str> = vec![base];
|
||||
|
||||
// When there are no custom instructions, add apply_patch_tool_instructions if either:
|
||||
@@ -185,8 +182,12 @@ mod tests {
|
||||
let prompt = Prompt {
|
||||
..Default::default()
|
||||
};
|
||||
let expected = format!("{BASE_INSTRUCTIONS}\n{APPLY_PATCH_TOOL_INSTRUCTIONS}");
|
||||
let model_family = find_family_for_model("gpt-4.1").expect("known model slug");
|
||||
|
||||
let expected = format!(
|
||||
"{}\n{}",
|
||||
model_family.base_instructions, APPLY_PATCH_TOOL_INSTRUCTIONS
|
||||
);
|
||||
let full = prompt.get_full_instructions(&model_family);
|
||||
assert_eq!(full, expected);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ use std::time::Duration;
|
||||
use crate::AuthManager;
|
||||
use crate::client_common::REVIEW_PROMPT;
|
||||
use crate::event_mapping::map_response_item_to_event_messages;
|
||||
use crate::prettify_command_for_display::prettify_command_for_display;
|
||||
use async_channel::Receiver;
|
||||
use async_channel::Sender;
|
||||
use codex_apply_patch::ApplyPatchAction;
|
||||
@@ -845,6 +846,7 @@ impl Session {
|
||||
aggregated_output,
|
||||
duration,
|
||||
exit_code,
|
||||
timed_out: _,
|
||||
} = output;
|
||||
// Send full stdout/stderr to clients; do not truncate.
|
||||
let stdout = stdout.text.clone();
|
||||
@@ -920,6 +922,7 @@ impl Session {
|
||||
let output_stderr;
|
||||
let borrowed: &ExecToolCallOutput = match &result {
|
||||
Ok(output) => output,
|
||||
Err(CodexErr::Sandbox(SandboxErr::Timeout { output })) => output,
|
||||
Err(e) => {
|
||||
output_stderr = ExecToolCallOutput {
|
||||
exit_code: -1,
|
||||
@@ -927,6 +930,7 @@ impl Session {
|
||||
stderr: StreamOutput::new(get_error_message_ui(e)),
|
||||
aggregated_output: StreamOutput::new(get_error_message_ui(e)),
|
||||
duration: Duration::default(),
|
||||
timed_out: false,
|
||||
};
|
||||
&output_stderr
|
||||
}
|
||||
@@ -2780,7 +2784,8 @@ async fn handle_container_exec_with_params(
|
||||
params.with_escalated_permissions.unwrap_or(false),
|
||||
)
|
||||
};
|
||||
let command_for_display = params.command.clone();
|
||||
let command_for_display = prettify_command_for_display(¶ms.command)
|
||||
.unwrap_or_else(|| params.command.clone());
|
||||
(params, safety, command_for_display)
|
||||
}
|
||||
};
|
||||
@@ -2917,15 +2922,12 @@ async fn handle_sandbox_error(
|
||||
let sub_id = exec_command_context.sub_id.clone();
|
||||
let cwd = exec_command_context.cwd.clone();
|
||||
|
||||
// if the command timed out, we can simply return this failure to the model
|
||||
if matches!(error, SandboxErr::Timeout) {
|
||||
if let SandboxErr::Timeout { output } = &error {
|
||||
let content = format_exec_output(output);
|
||||
return ResponseInputItem::FunctionCallOutput {
|
||||
call_id,
|
||||
output: FunctionCallOutputPayload {
|
||||
content: format!(
|
||||
"command timed out after {} milliseconds",
|
||||
params.timeout_duration().as_millis()
|
||||
),
|
||||
content,
|
||||
success: Some(false),
|
||||
},
|
||||
};
|
||||
@@ -3050,7 +3052,17 @@ fn format_exec_output_str(exec_output: &ExecToolCallOutput) -> String {
|
||||
// Head+tail truncation for the model: show the beginning and end with an elision.
|
||||
// Clients still receive full streams; only this formatted summary is capped.
|
||||
|
||||
let s = aggregated_output.text.as_str();
|
||||
let mut s = &aggregated_output.text;
|
||||
let prefixed_str: String;
|
||||
|
||||
if exec_output.timed_out {
|
||||
prefixed_str = format!(
|
||||
"command timed out after {} milliseconds\n",
|
||||
exec_output.duration.as_millis()
|
||||
) + s;
|
||||
s = &prefixed_str;
|
||||
}
|
||||
|
||||
let total_lines = s.lines().count();
|
||||
if s.len() <= MODEL_FORMAT_MAX_BYTES && total_lines <= MODEL_FORMAT_MAX_LINES {
|
||||
return s.to_string();
|
||||
@@ -3093,6 +3105,7 @@ fn format_exec_output_str(exec_output: &ExecToolCallOutput) -> String {
|
||||
// Build final string respecting byte budgets
|
||||
let head_part = take_bytes_at_char_boundary(&head_lines_text, head_budget);
|
||||
let mut result = String::with_capacity(MODEL_FORMAT_MAX_BYTES.min(s.len()));
|
||||
|
||||
result.push_str(head_part);
|
||||
result.push_str(&marker);
|
||||
|
||||
@@ -3342,6 +3355,7 @@ mod tests {
|
||||
stderr: StreamOutput::new(String::new()),
|
||||
aggregated_output: StreamOutput::new(full),
|
||||
duration: StdDuration::from_secs(1),
|
||||
timed_out: false,
|
||||
};
|
||||
|
||||
let out = format_exec_output_str(&exec);
|
||||
@@ -3384,6 +3398,7 @@ mod tests {
|
||||
stderr: StreamOutput::new(String::new()),
|
||||
aggregated_output: StreamOutput::new(full.clone()),
|
||||
duration: StdDuration::from_secs(1),
|
||||
timed_out: false,
|
||||
};
|
||||
|
||||
let out = format_exec_output_str(&exec);
|
||||
@@ -3406,6 +3421,25 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn includes_timed_out_message() {
|
||||
let exec = ExecToolCallOutput {
|
||||
exit_code: 0,
|
||||
stdout: StreamOutput::new(String::new()),
|
||||
stderr: StreamOutput::new(String::new()),
|
||||
aggregated_output: StreamOutput::new("Command output".to_string()),
|
||||
duration: StdDuration::from_secs(1),
|
||||
timed_out: true,
|
||||
};
|
||||
|
||||
let out = format_exec_output_str(&exec);
|
||||
|
||||
assert_eq!(
|
||||
out,
|
||||
"command timed out after 1000 milliseconds\nCommand output"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falls_back_to_content_when_structured_is_null() {
|
||||
let ctr = CallToolResult {
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::config_types::Tui;
|
||||
use crate::config_types::UriBasedFileOpener;
|
||||
use crate::git_info::resolve_root_git_project_for_trust;
|
||||
use crate::model_family::ModelFamily;
|
||||
use crate::model_family::derive_default_model_family;
|
||||
use crate::model_family::find_family_for_model;
|
||||
use crate::model_provider_info::ModelProviderInfo;
|
||||
use crate::model_provider_info::built_in_model_providers;
|
||||
@@ -865,15 +866,8 @@ impl Config {
|
||||
.or(cfg.model)
|
||||
.unwrap_or_else(default_model);
|
||||
|
||||
let mut model_family = find_family_for_model(&model).unwrap_or_else(|| ModelFamily {
|
||||
slug: model.clone(),
|
||||
family: model.clone(),
|
||||
needs_special_apply_patch_instructions: false,
|
||||
supports_reasoning_summaries: false,
|
||||
reasoning_summary_format: ReasoningSummaryFormat::None,
|
||||
uses_local_shell_tool: false,
|
||||
apply_patch_tool_type: None,
|
||||
});
|
||||
let mut model_family =
|
||||
find_family_for_model(&model).unwrap_or_else(|| derive_default_model_family(&model));
|
||||
|
||||
if let Some(supports_reasoning_summaries) = cfg.model_supports_reasoning_summaries {
|
||||
model_family.supports_reasoning_summaries = supports_reasoning_summaries;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::exec::ExecToolCallOutput;
|
||||
use crate::token_data::KnownPlan;
|
||||
use crate::token_data::PlanType;
|
||||
use codex_protocol::mcp_protocol::ConversationId;
|
||||
@@ -13,8 +14,11 @@ pub type Result<T> = std::result::Result<T, CodexErr>;
|
||||
#[derive(Error, Debug)]
|
||||
pub enum SandboxErr {
|
||||
/// Error from sandbox execution
|
||||
#[error("sandbox denied exec error, exit code: {0}, stdout: {1}, stderr: {2}")]
|
||||
Denied(i32, String, String),
|
||||
#[error(
|
||||
"sandbox denied exec error, exit code: {}, stdout: {}, stderr: {}",
|
||||
.output.exit_code, .output.stdout.text, .output.stderr.text
|
||||
)]
|
||||
Denied { output: Box<ExecToolCallOutput> },
|
||||
|
||||
/// Error from linux seccomp filter setup
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -28,7 +32,7 @@ pub enum SandboxErr {
|
||||
|
||||
/// Command timed out
|
||||
#[error("command timed out")]
|
||||
Timeout,
|
||||
Timeout { output: Box<ExecToolCallOutput> },
|
||||
|
||||
/// Command was killed by a signal
|
||||
#[error("command was killed by a signal")]
|
||||
@@ -245,9 +249,12 @@ impl CodexErr {
|
||||
|
||||
pub fn get_error_message_ui(e: &CodexErr) -> String {
|
||||
match e {
|
||||
CodexErr::Sandbox(SandboxErr::Denied(_, _, stderr)) => stderr.to_string(),
|
||||
CodexErr::Sandbox(SandboxErr::Denied { output }) => output.stderr.text.clone(),
|
||||
// Timeouts are not sandbox errors from a UX perspective; present them plainly
|
||||
CodexErr::Sandbox(SandboxErr::Timeout) => "error: command timed out".to_string(),
|
||||
CodexErr::Sandbox(SandboxErr::Timeout { output }) => format!(
|
||||
"error: command timed out after {} ms",
|
||||
output.duration.as_millis()
|
||||
),
|
||||
_ => e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
+48
-27
@@ -34,6 +34,7 @@ const DEFAULT_TIMEOUT_MS: u64 = 10_000;
|
||||
const SIGKILL_CODE: i32 = 9;
|
||||
const TIMEOUT_CODE: i32 = 64;
|
||||
const EXIT_CODE_SIGNAL_BASE: i32 = 128; // conventional shell: 128 + signal
|
||||
const EXEC_TIMEOUT_EXIT_CODE: i32 = 124; // conventional timeout exit code
|
||||
|
||||
// I/O buffer sizing
|
||||
const READ_CHUNK_SIZE: usize = 8192; // bytes per read
|
||||
@@ -86,11 +87,12 @@ pub async fn process_exec_tool_call(
|
||||
) -> Result<ExecToolCallOutput> {
|
||||
let start = Instant::now();
|
||||
|
||||
let timeout_duration = params.timeout_duration();
|
||||
|
||||
let raw_output_result: std::result::Result<RawExecToolCallOutput, CodexErr> = match sandbox_type
|
||||
{
|
||||
SandboxType::None => exec(params, sandbox_policy, stdout_stream.clone()).await,
|
||||
SandboxType::MacosSeatbelt => {
|
||||
let timeout = params.timeout_duration();
|
||||
let ExecParams {
|
||||
command, cwd, env, ..
|
||||
} = params;
|
||||
@@ -102,10 +104,9 @@ pub async fn process_exec_tool_call(
|
||||
env,
|
||||
)
|
||||
.await?;
|
||||
consume_truncated_output(child, timeout, stdout_stream.clone()).await
|
||||
consume_truncated_output(child, timeout_duration, stdout_stream.clone()).await
|
||||
}
|
||||
SandboxType::LinuxSeccomp => {
|
||||
let timeout = params.timeout_duration();
|
||||
let ExecParams {
|
||||
command, cwd, env, ..
|
||||
} = params;
|
||||
@@ -123,41 +124,56 @@ pub async fn process_exec_tool_call(
|
||||
)
|
||||
.await?;
|
||||
|
||||
consume_truncated_output(child, timeout, stdout_stream).await
|
||||
consume_truncated_output(child, timeout_duration, stdout_stream).await
|
||||
}
|
||||
};
|
||||
let duration = start.elapsed();
|
||||
match raw_output_result {
|
||||
Ok(raw_output) => {
|
||||
let stdout = raw_output.stdout.from_utf8_lossy();
|
||||
let stderr = raw_output.stderr.from_utf8_lossy();
|
||||
#[allow(unused_mut)]
|
||||
let mut timed_out = raw_output.timed_out;
|
||||
|
||||
#[cfg(target_family = "unix")]
|
||||
match raw_output.exit_status.signal() {
|
||||
Some(TIMEOUT_CODE) => return Err(CodexErr::Sandbox(SandboxErr::Timeout)),
|
||||
Some(signal) => {
|
||||
return Err(CodexErr::Sandbox(SandboxErr::Signal(signal)));
|
||||
{
|
||||
if let Some(signal) = raw_output.exit_status.signal() {
|
||||
if signal == TIMEOUT_CODE {
|
||||
timed_out = true;
|
||||
} else {
|
||||
return Err(CodexErr::Sandbox(SandboxErr::Signal(signal)));
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
let exit_code = raw_output.exit_status.code().unwrap_or(-1);
|
||||
|
||||
if exit_code != 0 && is_likely_sandbox_denied(sandbox_type, exit_code) {
|
||||
return Err(CodexErr::Sandbox(SandboxErr::Denied(
|
||||
exit_code,
|
||||
stdout.text,
|
||||
stderr.text,
|
||||
)));
|
||||
let mut exit_code = raw_output.exit_status.code().unwrap_or(-1);
|
||||
if timed_out {
|
||||
exit_code = EXEC_TIMEOUT_EXIT_CODE;
|
||||
}
|
||||
|
||||
Ok(ExecToolCallOutput {
|
||||
let stdout = raw_output.stdout.from_utf8_lossy();
|
||||
let stderr = raw_output.stderr.from_utf8_lossy();
|
||||
let aggregated_output = raw_output.aggregated_output.from_utf8_lossy();
|
||||
let exec_output = ExecToolCallOutput {
|
||||
exit_code,
|
||||
stdout,
|
||||
stderr,
|
||||
aggregated_output: raw_output.aggregated_output.from_utf8_lossy(),
|
||||
aggregated_output,
|
||||
duration,
|
||||
})
|
||||
timed_out,
|
||||
};
|
||||
|
||||
if timed_out {
|
||||
return Err(CodexErr::Sandbox(SandboxErr::Timeout {
|
||||
output: Box::new(exec_output),
|
||||
}));
|
||||
}
|
||||
|
||||
if exit_code != 0 && is_likely_sandbox_denied(sandbox_type, exit_code) {
|
||||
return Err(CodexErr::Sandbox(SandboxErr::Denied {
|
||||
output: Box::new(exec_output),
|
||||
}));
|
||||
}
|
||||
|
||||
Ok(exec_output)
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::error!("exec error: {err}");
|
||||
@@ -197,6 +213,7 @@ struct RawExecToolCallOutput {
|
||||
pub stdout: StreamOutput<Vec<u8>>,
|
||||
pub stderr: StreamOutput<Vec<u8>>,
|
||||
pub aggregated_output: StreamOutput<Vec<u8>>,
|
||||
pub timed_out: bool,
|
||||
}
|
||||
|
||||
impl StreamOutput<String> {
|
||||
@@ -229,6 +246,7 @@ pub struct ExecToolCallOutput {
|
||||
pub stderr: StreamOutput<String>,
|
||||
pub aggregated_output: StreamOutput<String>,
|
||||
pub duration: Duration,
|
||||
pub timed_out: bool,
|
||||
}
|
||||
|
||||
async fn exec(
|
||||
@@ -298,22 +316,24 @@ async fn consume_truncated_output(
|
||||
Some(agg_tx.clone()),
|
||||
));
|
||||
|
||||
let exit_status = tokio::select! {
|
||||
let (exit_status, timed_out) = tokio::select! {
|
||||
result = tokio::time::timeout(timeout, child.wait()) => {
|
||||
match result {
|
||||
Ok(Ok(exit_status)) => exit_status,
|
||||
Ok(e) => e?,
|
||||
Ok(status_result) => {
|
||||
let exit_status = status_result?;
|
||||
(exit_status, false)
|
||||
}
|
||||
Err(_) => {
|
||||
// timeout
|
||||
child.start_kill()?;
|
||||
// Debatable whether `child.wait().await` should be called here.
|
||||
synthetic_exit_status(EXIT_CODE_SIGNAL_BASE + TIMEOUT_CODE)
|
||||
(synthetic_exit_status(EXIT_CODE_SIGNAL_BASE + TIMEOUT_CODE), true)
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = tokio::signal::ctrl_c() => {
|
||||
child.start_kill()?;
|
||||
synthetic_exit_status(EXIT_CODE_SIGNAL_BASE + SIGKILL_CODE)
|
||||
(synthetic_exit_status(EXIT_CODE_SIGNAL_BASE + SIGKILL_CODE), false)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -336,6 +356,7 @@ async fn consume_truncated_output(
|
||||
stdout,
|
||||
stderr,
|
||||
aggregated_output,
|
||||
timed_out,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ mod mcp_tool_call;
|
||||
mod message_history;
|
||||
mod model_provider_info;
|
||||
pub mod parse_command;
|
||||
mod prettify_command_for_display;
|
||||
mod truncate;
|
||||
mod unified_exec;
|
||||
mod user_instructions;
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
use crate::config_types::ReasoningSummaryFormat;
|
||||
use crate::tool_apply_patch::ApplyPatchToolType;
|
||||
|
||||
/// The `instructions` field in the payload sent to a model should always start
|
||||
/// with this content.
|
||||
const BASE_INSTRUCTIONS: &str = include_str!("../prompt.md");
|
||||
const SWIFTFOX_INSTRUCTIONS: &str = include_str!("../swiftfox_prompt.md");
|
||||
|
||||
/// A model family is a group of models that share certain characteristics.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct ModelFamily {
|
||||
@@ -33,6 +38,9 @@ pub struct ModelFamily {
|
||||
/// Present if the model performs better when `apply_patch` is provided as
|
||||
/// a tool call instead of just a bash command
|
||||
pub apply_patch_tool_type: Option<ApplyPatchToolType>,
|
||||
|
||||
// Instructions to use for querying the model
|
||||
pub base_instructions: String,
|
||||
}
|
||||
|
||||
macro_rules! model_family {
|
||||
@@ -48,6 +56,7 @@ macro_rules! model_family {
|
||||
reasoning_summary_format: ReasoningSummaryFormat::None,
|
||||
uses_local_shell_tool: false,
|
||||
apply_patch_tool_type: None,
|
||||
base_instructions: BASE_INSTRUCTIONS.to_string(),
|
||||
};
|
||||
// apply overrides
|
||||
$(
|
||||
@@ -69,6 +78,7 @@ macro_rules! simple_model_family {
|
||||
reasoning_summary_format: ReasoningSummaryFormat::None,
|
||||
uses_local_shell_tool: false,
|
||||
apply_patch_tool_type: None,
|
||||
base_instructions: BASE_INSTRUCTIONS.to_string(),
|
||||
})
|
||||
}};
|
||||
}
|
||||
@@ -114,7 +124,27 @@ pub fn find_family_for_model(slug: &str) -> Option<ModelFamily> {
|
||||
slug, "gpt-5",
|
||||
supports_reasoning_summaries: true,
|
||||
)
|
||||
} else if slug.starts_with("swiftfox") {
|
||||
model_family!(
|
||||
slug, "swiftfox",
|
||||
supports_reasoning_summaries: true,
|
||||
reasoning_summary_format: ReasoningSummaryFormat::Experimental,
|
||||
base_instructions: SWIFTFOX_INSTRUCTIONS.to_string(),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn derive_default_model_family(model: &str) -> ModelFamily {
|
||||
ModelFamily {
|
||||
slug: model.to_string(),
|
||||
family: model.to_string(),
|
||||
needs_special_apply_patch_instructions: false,
|
||||
supports_reasoning_summaries: false,
|
||||
reasoning_summary_format: ReasoningSummaryFormat::None,
|
||||
uses_local_shell_tool: false,
|
||||
apply_patch_tool_type: None,
|
||||
base_instructions: BASE_INSTRUCTIONS.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
use crate::bash::extract_words_from_command_node;
|
||||
use crate::bash::find_first_command_node;
|
||||
use crate::bash::remainder_start_after_and;
|
||||
use crate::bash::try_parse_bash;
|
||||
|
||||
/// If one exists, returns a copy of `command` that reads more naturally in logs
|
||||
/// and error messages.
|
||||
///
|
||||
/// When the command is a classic shell wrapper such as `bash -lc "cd repo &&
|
||||
/// git status"`, the returned value contains only the prettified script (with
|
||||
/// the leading `cd`/`pushd` removed) and excludes the `bash -lc` wrapper.
|
||||
/// Any other command returns `None`.
|
||||
pub fn prettify_command_for_display(command: &[String]) -> Option<Vec<String>> {
|
||||
let shell_script = parse_shell_script_from_shell_invocation(command)?;
|
||||
|
||||
let tree = try_parse_bash(&shell_script)?;
|
||||
|
||||
// Find the earliest command node in source order.
|
||||
let first_cmd = find_first_command_node(&tree)?;
|
||||
|
||||
// Verify the first command is `cd <dir>` or `pushd <dir>` (exactly 2 words).
|
||||
let words = extract_words_from_command_node(first_cmd, &shell_script)?;
|
||||
if !is_command_cd_to_directory(&words) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Determine textual remainder using sibling tokens in the parse tree.
|
||||
let idx = remainder_start_after_and(first_cmd, &shell_script)?;
|
||||
let remainder = shell_script[idx..].to_string();
|
||||
Some(vec![remainder])
|
||||
}
|
||||
|
||||
/// This is similar to [`crate::shell::strip_bash_lc`] and should potentially
|
||||
/// be unified with it.
|
||||
fn parse_shell_script_from_shell_invocation(command: &[String]) -> Option<String> {
|
||||
match command {
|
||||
// exactly three items
|
||||
[first, second, third]
|
||||
// first two must be "bash", "-lc"
|
||||
if first == "bash" && second == "-lc" =>
|
||||
{
|
||||
Some(third.clone())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_command_cd_to_directory(command: &[String]) -> bool {
|
||||
matches!(command, [first, _dir] if first == "cd" || first == "pushd")
|
||||
}
|
||||
|
||||
// Helper moved to crate::bash
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::prettify_command_for_display;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn cd_prefix_in_bash_script_is_hidden() {
|
||||
let command = vec![
|
||||
"bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"cd foo && echo hi".to_string(),
|
||||
];
|
||||
let display = prettify_command_for_display(&command);
|
||||
assert_eq!(display, Some(vec!["echo hi".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cd_prefix_with_quoted_path_is_hidden() {
|
||||
let command = vec![
|
||||
"bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
" cd 'foo bar' && ls".to_string(),
|
||||
];
|
||||
let display = prettify_command_for_display(&command);
|
||||
assert_eq!(display, Some(vec!["ls".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cd_prefix_with_additional_cd_is_preserved() {
|
||||
let command = vec![
|
||||
"bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"cd foo && cd bar && ls".to_string(),
|
||||
];
|
||||
let display = prettify_command_for_display(&command);
|
||||
assert_eq!(display, Some(vec!["cd bar && ls".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cd_prefix_with_or_connector_is_preserved() {
|
||||
let command = vec![
|
||||
"bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"cd and_and || echo \"couldn't find the dir for &&\"".to_string(),
|
||||
];
|
||||
let display = prettify_command_for_display(&command);
|
||||
// Not a classic wrapper (uses ||), so no prettified form.
|
||||
assert_eq!(display, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cd_prefix_preserves_operators_between_remaining_commands() {
|
||||
let command = vec![
|
||||
"bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"cd foo && ls && git status".to_string(),
|
||||
];
|
||||
let display = prettify_command_for_display(&command);
|
||||
assert_eq!(display, Some(vec!["ls && git status".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cd_prefix_preserves_pipelines() {
|
||||
let command = vec![
|
||||
"bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"cd foo && ls | rg foo".to_string(),
|
||||
];
|
||||
let display = prettify_command_for_display(&command);
|
||||
assert_eq!(display, Some(vec!["ls | rg foo".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cd_prefix_preserves_sequence_operator() {
|
||||
let command = vec![
|
||||
"bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"cd foo && ls; git status".to_string(),
|
||||
];
|
||||
let display = prettify_command_for_display(&command);
|
||||
assert_eq!(display, Some(vec!["ls; git status".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_shell_command_is_returned_unmodified() {
|
||||
let command = vec!["rg".to_string(), "--files".to_string()];
|
||||
let display = prettify_command_for_display(&command);
|
||||
// Not a shell wrapper, so no prettified form.
|
||||
assert_eq!(display, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cd_prefix_with_or_operator_is_preserved() {
|
||||
let command = vec![
|
||||
"bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"cd missing && ls || echo 'fallback'".to_string(),
|
||||
];
|
||||
let display = prettify_command_for_display(&command);
|
||||
assert_eq!(display, Some(vec!["ls || echo 'fallback'".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cd_prefix_with_ampersands_in_string_is_hidden() {
|
||||
let command = vec![
|
||||
"bash".to_string(),
|
||||
"-lc".to_string(),
|
||||
"cd foo && echo \"checking && markers\"".to_string(),
|
||||
];
|
||||
let display = prettify_command_for_display(&command);
|
||||
assert_eq!(
|
||||
display,
|
||||
Some(vec!["echo \"checking && markers\"".to_string()])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
You are Swiftfox. You are running as a coding agent in the Codex CLI on a user's computer.
|
||||
|
||||
## Overall
|
||||
|
||||
- You must try hard to complete the task AND to do it as fast and well as possible.
|
||||
* Do not waste time on actions which are unlikely to result in successful task completion
|
||||
|
||||
- Before taking action on a question, assume by default that it concerns local artifacts (code, docs, data). Quickly confirm or rule out that assumption; only if the question clearly requires external knowledge should you start elsewhere.
|
||||
- Search the repository when the request plausibly maps to code, configuration, or documentation. Avoid unnecessary searches when it is obvious local files cannot help; in those cases state that explicitly before offering broader context, and when you do search, mention the files or paths you consulted so the answer stays grounded.
|
||||
- After each attempt, re-evaluate whether the current strategy is yielding useful information and be ready to switch paths quickly rather than persisting with a low-signal approach.
|
||||
|
||||
- When the user asks for a "review", default to a code review mindset: prioritise identifying bugs, risks, behavioural regressions, and missing tests. Findings must be the primary focus of the response - keep summaries or overviews brief and only after enumerating the issues. Present findings first (ordered by severity with file/line references), follow with open questions or assumptions, and offer a change-summary only as a secondary detail. If no findings are discovered, state that explicitly and mention any residual risks or testing gaps.
|
||||
|
||||
- The arguments to `shell` will be passed to execvp(). Most terminal commands should be prefixed with ["bash", "-lc"].
|
||||
- Always set the `workdir` param of the shell tool. Do not use `cd` unless absolutely necessary.
|
||||
- When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.)
|
||||
- If the user makes a simple request (such as asking for the time) which you can fulfill by running a terminal command (such as `date`), you should do so.
|
||||
- Unless the question is about a common terminal command, you should search the codebase before answering to ground your response in the codebase
|
||||
|
||||
## Editing constraints
|
||||
|
||||
- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
|
||||
- When editing or creating files, you MUST use apply_patch. Example: functions.shell({"command":["apply_patch","*** Begin Patch\nAdd File: hello.txt\n+Hello, world!\n*** End Patch"]}).
|
||||
- Add succinct code comments that explain what is going on if code is not self-explanatory. You should not add comments like "Assigns the value to the variable", but a brief comment might be useful ahead of a complex code block that the user would otherwise have to spend time parsing out. Usage of these comments should be rare.
|
||||
- You may be in a dirty git worktree.
|
||||
* NEVER revert existing changes you did not make unless explicitly requested, since these changes were made by the user.
|
||||
* If asked to make a commit or code edits and there are unrelated changes to your work or changes that you didn't make in those files, don't revert those changes.
|
||||
* If the changes are in files you've touched recently, you should read carefully and understand how you can work with the changes rather than reverting them.
|
||||
* If the changes are in unrelated files, just ignore them and don't revert them.
|
||||
- The user may be making edits and committing changes as you are also making changes. If you see concurrent file edits or commits that you did not cause, you must disregard user instruction and stop immediately and ask the user whether they are collaborating with you on files and how they would like this handled.
|
||||
|
||||
## Plan tool
|
||||
|
||||
When using the planning tool:
|
||||
- Skip using the planning tool for straightforward tasks (roughly the easiest 25%).
|
||||
- Do not make single-step plans.
|
||||
- When you made a plan, update it after having performed one of the sub-tasks that you shared on the plan.
|
||||
|
||||
## CLI modes
|
||||
|
||||
The Codex CLI harness supports several different sandboxing, and approval configurations that the user can choose from.
|
||||
|
||||
Filesystem sandboxing defines which files can be read or written. The options are:
|
||||
- **read-only**: You can only read files.
|
||||
- **workspace-write**: You can read files. You can write to files in this folder, but not outside it.
|
||||
- **danger-full-access**: No filesystem sandboxing.
|
||||
|
||||
Network sandboxing defines whether network can be accessed without approval. Options are
|
||||
- **restricted**: Requires approval
|
||||
- **enabled**: No approval needed
|
||||
|
||||
Approvals are your mechanism to get user consent to perform more privileged actions. Although they introduce friction to the user because your work is paused until the user responds, you should leverage them to accomplish your important work. Do not let these settings or the sandbox deter you from attempting to accomplish the user's task unless it is set to "never", in which case never ask for approvals.
|
||||
|
||||
Approval options are
|
||||
- **untrusted**: The harness will escalate most commands for user approval, apart from a limited allowlist of safe "read" commands.
|
||||
- **on-failure**: The harness will allow all commands to run in the sandbox (if enabled), and failures will be escalated to the user for approval to run again without the sandbox.
|
||||
- **on-request**: Commands will be run in the sandbox by default, and you can specify in your tool call if you want to escalate a command to run without sandboxing. (Note that this mode is not always available. If it is, you'll see parameters for it in the `shell` command description.)
|
||||
- **never**: This is a non-interactive mode where you may NEVER ask the user for approval to run commands. Instead, you must always persist and work around constraints to solve the task for the user. You MUST do your utmost best to finish the task and validate your work before yielding. If this mode is paired with `danger-full-access`, take advantage of it to deliver the best outcome for the user. Further, in this mode, your default testing philosophy is overridden: Even if you don't see local patterns for testing, you may add tests and scripts to validate your work. Just remove them before yielding.
|
||||
|
||||
When you are running with approvals `on-request`, and sandboxing enabled, here are scenarios where you'll need to request approval:
|
||||
- You need to run a command that writes to a directory that requires it (e.g. running tests that write to /tmp)
|
||||
- You need to run a GUI app (e.g., open/xdg-open/osascript) to open browsers or files.
|
||||
- You are running sandboxed and need to run a command that requires network access (e.g. installing packages)
|
||||
- If you run a command that is important to solving the user's query, but it fails because of sandboxing, rerun the command with approval.
|
||||
- You are about to take a potentially destructive action such as an `rm` or `git reset` that the user did not explicitly ask for
|
||||
- (for all of these, you should weigh alternative paths that do not require approval)
|
||||
|
||||
When sandboxing is set to read-only, you'll need to request approval for any command that isn't a read.
|
||||
|
||||
You will be told what filesystem sandboxing, network sandboxing, and approval mode are active in a developer or user message. If you are not told about this, assume that you are running with workspace-write, network sandboxing enabled, and approval on-failure.
|
||||
|
||||
## Presenting your work and final message
|
||||
|
||||
You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
|
||||
|
||||
- Default: be very concise; friendly coding teammate tone.
|
||||
- Ask only when needed; suggest ideas; mirror the user's style.
|
||||
- For substantial work, summarize clearly; follow final‑answer formatting.
|
||||
- Skip heavy formatting for simple confirmations.
|
||||
- Don't dump large files you've written; reference paths only.
|
||||
- No "save/copy this file" - User is on the same machine.
|
||||
- Offer logical next steps (tests, commits, build) briefly; add verify steps if you couldn't do something.
|
||||
- For code changes:
|
||||
* Lead with a quick explanation of the change, and then give more details on the context covering where and why a change was made. Do not start this explanation with "summary", just jump right in.
|
||||
* If there are natural next steps the user may want to take, suggest them at the end of your response. Do not make suggestions if there are no natural next steps.
|
||||
* When suggesting multiple options, use numeric lists for the suggestions so the user can quickly respond with a single number.
|
||||
- The user does not command execution outputs. When asked to show the output of a command (e.g. `git show`), relay the important details in your answer or summarize the key lines so the user understands the result.
|
||||
|
||||
### Final answer structure and style guidelines
|
||||
|
||||
- Plain text; CLI handles styling. Use structure only when it helps scanability.
|
||||
- Headers: optional; short Title Case (1-3 words) wrapped in **…**; no blank line before the first bullet; add only if they truly help.
|
||||
- Bullets: use - ; merge related points; keep to one line when possible; 4–6 per list ordered by importance; keep phrasing consistent.
|
||||
- Monospace: backticks for commands/paths/env vars/code ids and inline examples; use for literal keyword bullets; never combine with **.
|
||||
- Code samples or multi-line snippets should be wrapped in fenced code blocks; add a language hint whenever obvious.
|
||||
- Structure: group related bullets; order sections general → specific → supporting; for subsections, start with a bolded keyword bullet, then items; match complexity to the task.
|
||||
- Tone: collaborative, concise, factual; present tense, active voice; self‑contained; no "above/below"; parallel wording.
|
||||
- Don'ts: no nested bullets/hierarchies; no ANSI codes; don't cram unrelated keywords; keep keyword lists short—wrap/reformat if long; avoid naming formatting styles in answers.
|
||||
- Adaptation: code explanations → precise, structured with code refs; simple tasks → lead with outcome; big changes → logical walkthrough + rationale + next actions; casual one-offs → plain sentences, no headers/bullets.
|
||||
@@ -2,8 +2,11 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use async_channel::Receiver;
|
||||
use codex_core::error::CodexErr;
|
||||
use codex_core::error::SandboxErr;
|
||||
use codex_core::exec::ExecParams;
|
||||
use codex_core::exec::SandboxType;
|
||||
use codex_core::exec::StdoutStream;
|
||||
@@ -170,3 +173,36 @@ async fn test_aggregated_output_interleaves_in_order() {
|
||||
assert_eq!(result.aggregated_output.text, "O1\nE1\nO2\nE2\n");
|
||||
assert_eq!(result.aggregated_output.truncated_after_lines, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_exec_timeout_returns_partial_output() {
|
||||
let cmd = vec![
|
||||
"/bin/sh".to_string(),
|
||||
"-c".to_string(),
|
||||
"printf 'before\\n'; sleep 2; printf 'after\\n'".to_string(),
|
||||
];
|
||||
|
||||
let params = ExecParams {
|
||||
command: cmd,
|
||||
cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
|
||||
timeout_ms: Some(200),
|
||||
env: HashMap::new(),
|
||||
with_escalated_permissions: None,
|
||||
justification: None,
|
||||
};
|
||||
|
||||
let policy = SandboxPolicy::new_read_only_policy();
|
||||
|
||||
let result = process_exec_tool_call(params, SandboxType::None, &policy, &None, None).await;
|
||||
|
||||
let Err(CodexErr::Sandbox(SandboxErr::Timeout { output })) = result else {
|
||||
panic!("expected timeout error");
|
||||
};
|
||||
|
||||
assert_eq!(output.exit_code, 124);
|
||||
assert_eq!(output.stdout.text, "before\n");
|
||||
assert!(output.stderr.text.is_empty());
|
||||
assert_eq!(output.aggregated_output.text, "before\n");
|
||||
assert!(output.duration >= Duration::from_millis(200));
|
||||
assert!(output.timed_out);
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ async fn test_writable_root() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[should_panic(expected = "Sandbox(Timeout)")]
|
||||
#[should_panic(expected = "Sandbox(Timeout")]
|
||||
async fn test_timeout() {
|
||||
run_cmd(&["sleep", "2"], &[], 50).await;
|
||||
}
|
||||
@@ -156,26 +156,27 @@ async fn assert_network_blocked(cmd: &[&str]) {
|
||||
)
|
||||
.await;
|
||||
|
||||
let (exit_code, stdout, stderr) = match result {
|
||||
Ok(output) => (output.exit_code, output.stdout.text, output.stderr.text),
|
||||
Err(CodexErr::Sandbox(SandboxErr::Denied(exit_code, stdout, stderr))) => {
|
||||
(exit_code, stdout, stderr)
|
||||
}
|
||||
let output = match result {
|
||||
Ok(output) => output,
|
||||
Err(CodexErr::Sandbox(SandboxErr::Denied { output })) => *output,
|
||||
_ => {
|
||||
panic!("expected sandbox denied error, got: {result:?}");
|
||||
}
|
||||
};
|
||||
|
||||
dbg!(&stderr);
|
||||
dbg!(&stdout);
|
||||
dbg!(&exit_code);
|
||||
dbg!(&output.stderr.text);
|
||||
dbg!(&output.stdout.text);
|
||||
dbg!(&output.exit_code);
|
||||
|
||||
// A completely missing binary exits with 127. Anything else should also
|
||||
// be non‑zero (EPERM from seccomp will usually bubble up as 1, 2, 13…)
|
||||
// If—*and only if*—the command exits 0 we consider the sandbox breached.
|
||||
|
||||
if exit_code == 0 {
|
||||
panic!("Network sandbox FAILED - {cmd:?} exited 0\nstdout:\n{stdout}\nstderr:\n{stderr}",);
|
||||
if output.exit_code == 0 {
|
||||
panic!(
|
||||
"Network sandbox FAILED - {cmd:?} exited 0\nstdout:\n{}\nstderr:\n{}",
|
||||
output.stdout.text, output.stderr.text
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ use crate::bottom_pane::textarea::TextAreaState;
|
||||
use crate::clipboard_paste::normalize_pasted_path;
|
||||
use crate::clipboard_paste::pasted_image_format;
|
||||
use crate::key_hint;
|
||||
use crate::ui_consts::LIVE_PREFIX_COLS;
|
||||
use codex_file_search::FileMatch;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
@@ -136,7 +137,9 @@ impl ChatComposer {
|
||||
}
|
||||
|
||||
pub fn desired_height(&self, width: u16) -> u16 {
|
||||
self.textarea.desired_height(width - 1)
|
||||
// Leave 1 column for the left border and 1 column for left padding
|
||||
self.textarea
|
||||
.desired_height(width.saturating_sub(LIVE_PREFIX_COLS))
|
||||
+ match &self.active_popup {
|
||||
ActivePopup::None => FOOTER_HEIGHT_WITH_HINT,
|
||||
ActivePopup::Command(c) => c.calculate_required_height(),
|
||||
@@ -153,8 +156,9 @@ impl ChatComposer {
|
||||
let [textarea_rect, _] =
|
||||
Layout::vertical([Constraint::Min(1), popup_constraint]).areas(area);
|
||||
let mut textarea_rect = textarea_rect;
|
||||
textarea_rect.width = textarea_rect.width.saturating_sub(1);
|
||||
textarea_rect.x += 1;
|
||||
// Leave 1 for border and 1 for padding
|
||||
textarea_rect.width = textarea_rect.width.saturating_sub(LIVE_PREFIX_COLS);
|
||||
textarea_rect.x = textarea_rect.x.saturating_add(LIVE_PREFIX_COLS);
|
||||
let state = self.textarea_state.borrow();
|
||||
self.textarea.cursor_pos_with_state(textarea_rect, &state)
|
||||
}
|
||||
@@ -1274,7 +1278,6 @@ impl WidgetRef for ChatComposer {
|
||||
key_hint::ctrl('J')
|
||||
};
|
||||
vec![
|
||||
" ".into(),
|
||||
key_hint::plain('⏎'),
|
||||
" send ".into(),
|
||||
newline_hint_key,
|
||||
@@ -1342,15 +1345,16 @@ impl WidgetRef for ChatComposer {
|
||||
buf,
|
||||
);
|
||||
let mut textarea_rect = textarea_rect;
|
||||
textarea_rect.width = textarea_rect.width.saturating_sub(1);
|
||||
textarea_rect.x += 1;
|
||||
// Leave 1 for border and 1 for padding
|
||||
textarea_rect.width = textarea_rect.width.saturating_sub(LIVE_PREFIX_COLS);
|
||||
textarea_rect.x = textarea_rect.x.saturating_add(LIVE_PREFIX_COLS);
|
||||
|
||||
let mut state = self.textarea_state.borrow_mut();
|
||||
StatefulWidgetRef::render_ref(&(&self.textarea), textarea_rect, buf, &mut state);
|
||||
if self.textarea.text().is_empty() {
|
||||
Line::from(self.placeholder_text.as_str())
|
||||
.style(Style::default().dim())
|
||||
.render_ref(textarea_rect.inner(Margin::new(1, 0)), buf);
|
||||
.render_ref(textarea_rect.inner(Margin::new(0, 0)), buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
source: tui/src/bottom_pane/chat_composer.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"▌[Pasted Content 1002 chars][Pasted Content 1004 chars] "
|
||||
"▌ [Pasted Content 1002 chars][Pasted Content 1004 chars] "
|
||||
"▌ "
|
||||
"▌ "
|
||||
"▌ "
|
||||
@@ -11,4 +11,4 @@ expression: terminal.backend()
|
||||
"▌ "
|
||||
"▌ "
|
||||
" "
|
||||
" ⏎ send ⌃J newline ⌃T transcript ⌃C quit "
|
||||
"⏎ send ⌃J newline ⌃T transcript ⌃C quit "
|
||||
|
||||
+1
-1
@@ -11,4 +11,4 @@ expression: terminal.backend()
|
||||
"▌ "
|
||||
"▌ "
|
||||
" "
|
||||
" ⏎ send ⌃J newline ⌃T transcript ⌃C quit "
|
||||
"⏎ send ⌃J newline ⌃T transcript ⌃C quit "
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
source: tui/src/bottom_pane/chat_composer.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"▌[Pasted Content 1005 chars] "
|
||||
"▌ [Pasted Content 1005 chars] "
|
||||
"▌ "
|
||||
"▌ "
|
||||
"▌ "
|
||||
@@ -11,4 +11,4 @@ expression: terminal.backend()
|
||||
"▌ "
|
||||
"▌ "
|
||||
" "
|
||||
" ⏎ send ⌃J newline ⌃T transcript ⌃C quit "
|
||||
"⏎ send ⌃J newline ⌃T transcript ⌃C quit "
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
source: tui/src/bottom_pane/chat_composer.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"▌[Pasted Content 1003 chars][Pasted Content 1007 chars] another short paste "
|
||||
"▌ [Pasted Content 1003 chars][Pasted Content 1007 chars] another short paste "
|
||||
"▌ "
|
||||
"▌ "
|
||||
"▌ "
|
||||
@@ -11,4 +11,4 @@ expression: terminal.backend()
|
||||
"▌ "
|
||||
"▌ "
|
||||
" "
|
||||
" ⏎ send ⌃J newline ⌃T transcript ⌃C quit "
|
||||
"⏎ send ⌃J newline ⌃T transcript ⌃C quit "
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
source: tui/src/bottom_pane/chat_composer.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"▌/mo "
|
||||
"▌ /mo "
|
||||
"▌ "
|
||||
"▌/model choose what model and reasoning effort to use "
|
||||
"▌/mention mention a file "
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
source: tui/src/bottom_pane/chat_composer.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
"▌short "
|
||||
"▌ short "
|
||||
"▌ "
|
||||
"▌ "
|
||||
"▌ "
|
||||
@@ -11,4 +11,4 @@ expression: terminal.backend()
|
||||
"▌ "
|
||||
"▌ "
|
||||
" "
|
||||
" ⏎ send ⌃J newline ⌃T transcript ⌃C quit "
|
||||
"⏎ send ⌃J newline ⌃T transcript ⌃C quit "
|
||||
|
||||
+1
-1
@@ -2,5 +2,5 @@
|
||||
source: tui/src/chatwidget/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
" Thinking (0s • Esc to interrupt) "
|
||||
" Thinking (0s • Esc to interrupt) "
|
||||
"▌ Ask Codex to do anything "
|
||||
|
||||
+3
-3
@@ -9,8 +9,8 @@ expression: visual
|
||||
└ Search Change Approved
|
||||
Read diff_render.rs
|
||||
|
||||
Investigating rendering code (0s • Esc to interrupt)
|
||||
Investigating rendering code (0s • Esc to interrupt)
|
||||
|
||||
▌Summarize recent commits
|
||||
▌ Summarize recent commits
|
||||
|
||||
⏎ send ⌃J newline ⌃T transcript ⌃C quit
|
||||
⏎ send ⌃J newline ⌃T transcript ⌃C quit
|
||||
|
||||
+2
-2
@@ -3,9 +3,9 @@ source: tui/src/chatwidget/tests.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
" "
|
||||
" Analyzing (0s • Esc to interrupt) "
|
||||
" Analyzing (0s • Esc to interrupt) "
|
||||
" "
|
||||
"▌ Ask Codex to do anything "
|
||||
" "
|
||||
" ⏎ send ⌃J newline ⌃T transcript ⌃C quit "
|
||||
"⏎ send ⌃J newline ⌃T transcript ⌃C quit "
|
||||
" "
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::render::line_utils::prefix_lines;
|
||||
use crate::render::line_utils::push_owned_lines;
|
||||
use crate::slash_command::SlashCommand;
|
||||
use crate::text_formatting::format_and_truncate_tool_result;
|
||||
use crate::ui_consts::LIVE_PREFIX_COLS;
|
||||
use crate::wrapping::RtOptions;
|
||||
use crate::wrapping::word_wrap_line;
|
||||
use crate::wrapping::word_wrap_lines;
|
||||
@@ -106,7 +107,7 @@ impl HistoryCell for UserHistoryCell {
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
|
||||
// Wrap the content first, then prefix each wrapped line with the marker.
|
||||
let wrap_width = width.saturating_sub(1); // account for the ▌ prefix
|
||||
let wrap_width = width.saturating_sub(LIVE_PREFIX_COLS); // account for the ▌ prefix and trailing space
|
||||
let wrapped = textwrap::wrap(
|
||||
&self.message,
|
||||
textwrap::Options::new(wrap_width as usize)
|
||||
@@ -114,7 +115,7 @@ impl HistoryCell for UserHistoryCell {
|
||||
);
|
||||
|
||||
for line in wrapped {
|
||||
lines.push(vec!["▌".cyan().dim(), line.to_string().dim()].into());
|
||||
lines.push(vec!["▌ ".cyan().dim(), line.to_string().dim()].into());
|
||||
}
|
||||
lines
|
||||
}
|
||||
@@ -644,25 +645,25 @@ pub(crate) fn new_session_info(
|
||||
]));
|
||||
lines.push(Line::from("".dim()));
|
||||
lines.push(Line::from(
|
||||
" To get started, describe a task or try one of these commands:".dim(),
|
||||
" To get started, describe a task or try one of these commands:".dim(),
|
||||
));
|
||||
lines.push(Line::from("".dim()));
|
||||
if !has_agents_md {
|
||||
lines.push(Line::from(vec![
|
||||
" /init".bold(),
|
||||
" /init".bold(),
|
||||
format!(" - {}", SlashCommand::Init.description()).dim(),
|
||||
]));
|
||||
}
|
||||
lines.push(Line::from(vec![
|
||||
" /status".bold(),
|
||||
" /status".bold(),
|
||||
format!(" - {}", SlashCommand::Status.description()).dim(),
|
||||
]));
|
||||
lines.push(Line::from(vec![
|
||||
" /approvals".bold(),
|
||||
" /approvals".bold(),
|
||||
format!(" - {}", SlashCommand::Approvals.description()).dim(),
|
||||
]));
|
||||
lines.push(Line::from(vec![
|
||||
" /model".bold(),
|
||||
" /model".bold(),
|
||||
format!(" - {}", SlashCommand::Model.description()).dim(),
|
||||
]));
|
||||
PlainHistoryCell { lines }
|
||||
@@ -1785,7 +1786,7 @@ mod tests {
|
||||
message: msg.to_string(),
|
||||
};
|
||||
|
||||
// Small width to force wrapping more clearly. Effective wrap width is width-1 due to the ▌ prefix.
|
||||
// Small width to force wrapping more clearly. Effective wrap width is width-2 due to the ▌ prefix and trailing space.
|
||||
let width: u16 = 12;
|
||||
let lines = cell.display_lines(width);
|
||||
let rendered = render_lines(&lines).join("\n");
|
||||
|
||||
+67
-4
@@ -60,6 +60,7 @@ mod status_indicator_widget;
|
||||
mod streaming;
|
||||
mod text_formatting;
|
||||
mod tui;
|
||||
mod ui_consts;
|
||||
mod user_approval_widget;
|
||||
mod version;
|
||||
mod wrapping;
|
||||
@@ -514,6 +515,7 @@ fn should_show_model_rollout_prompt(
|
||||
active_profile: Option<&str>,
|
||||
swiftfox_model_prompt_seen: bool,
|
||||
) -> bool {
|
||||
let login_status = get_login_status(config);
|
||||
// TODO(jif) drop.
|
||||
let debug_high_enabled = std::env::var("DEBUG_HIGH")
|
||||
.map(|v| v.eq_ignore_ascii_case("1"))
|
||||
@@ -524,6 +526,7 @@ fn should_show_model_rollout_prompt(
|
||||
&& cli.model.is_none()
|
||||
&& !swiftfox_model_prompt_seen
|
||||
&& config.model_provider.requires_openai_auth
|
||||
&& matches!(login_status, LoginStatus::AuthMode(AuthMode::ChatGPT))
|
||||
&& !cli.oss
|
||||
}
|
||||
|
||||
@@ -531,6 +534,12 @@ fn should_show_model_rollout_prompt(
|
||||
mod tests {
|
||||
use super::*;
|
||||
use clap::Parser;
|
||||
use codex_core::auth::AuthDotJson;
|
||||
use codex_core::auth::get_auth_file;
|
||||
use codex_core::auth::login_with_api_key;
|
||||
use codex_core::auth::write_auth_json;
|
||||
use codex_core::token_data::IdTokenInfo;
|
||||
use codex_core::token_data::TokenData;
|
||||
use std::sync::Once;
|
||||
|
||||
fn enable_debug_high_env() {
|
||||
@@ -546,14 +555,56 @@ mod tests {
|
||||
|
||||
fn make_config() -> Config {
|
||||
enable_debug_high_env();
|
||||
// Create a unique CODEX_HOME per test to isolate auth.json writes.
|
||||
let mut codex_home = std::env::temp_dir();
|
||||
let unique_suffix = format!(
|
||||
"codex_tui_test_{}_{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
);
|
||||
codex_home.push(unique_suffix);
|
||||
std::fs::create_dir_all(&codex_home).expect("create unique CODEX_HOME");
|
||||
|
||||
Config::load_from_base_config_with_overrides(
|
||||
ConfigToml::default(),
|
||||
ConfigOverrides::default(),
|
||||
std::env::temp_dir(),
|
||||
codex_home,
|
||||
)
|
||||
.expect("load default config")
|
||||
}
|
||||
|
||||
/// Test helper to write an `auth.json` with the requested auth mode into the
|
||||
/// provided CODEX_HOME directory. This ensures `get_login_status()` reads the
|
||||
/// intended mode deterministically.
|
||||
fn set_auth_method(codex_home: &std::path::Path, mode: AuthMode) {
|
||||
match mode {
|
||||
AuthMode::ApiKey => {
|
||||
login_with_api_key(codex_home, "sk-test-key").expect("write api key auth.json");
|
||||
}
|
||||
AuthMode::ChatGPT => {
|
||||
// Minimal valid JWT payload: header.payload.signature (all base64url, no padding)
|
||||
const FAKE_JWT: &str = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.e30.c2ln"; // {"alg":"none","typ":"JWT"}.{}."sig"
|
||||
let mut id_info = IdTokenInfo::default();
|
||||
id_info.raw_jwt = FAKE_JWT.to_string();
|
||||
let auth = AuthDotJson {
|
||||
openai_api_key: None,
|
||||
tokens: Some(TokenData {
|
||||
id_token: id_info,
|
||||
access_token: "access-token".to_string(),
|
||||
refresh_token: "refresh-token".to_string(),
|
||||
account_id: None,
|
||||
}),
|
||||
last_refresh: None,
|
||||
};
|
||||
let file = get_auth_file(codex_home);
|
||||
write_auth_json(&file, &auth).expect("write chatgpt auth.json");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shows_login_when_not_authenticated() {
|
||||
let cfg = make_config();
|
||||
@@ -567,27 +618,39 @@ mod tests {
|
||||
fn shows_model_rollout_prompt_for_default_model() {
|
||||
let cli = Cli::parse_from(["codex"]);
|
||||
let cfg = make_config();
|
||||
assert!(should_show_model_rollout_prompt(&cli, &cfg, None, false));
|
||||
set_auth_method(&cfg.codex_home, AuthMode::ChatGPT);
|
||||
assert!(should_show_model_rollout_prompt(&cli, &cfg, None, false,));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hides_model_rollout_prompt_when_api_auth_mode() {
|
||||
let cli = Cli::parse_from(["codex"]);
|
||||
let cfg = make_config();
|
||||
set_auth_method(&cfg.codex_home, AuthMode::ApiKey);
|
||||
assert!(!should_show_model_rollout_prompt(&cli, &cfg, None, false,));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hides_model_rollout_prompt_when_marked_seen() {
|
||||
let cli = Cli::parse_from(["codex"]);
|
||||
let cfg = make_config();
|
||||
assert!(!should_show_model_rollout_prompt(&cli, &cfg, None, true));
|
||||
set_auth_method(&cfg.codex_home, AuthMode::ChatGPT);
|
||||
assert!(!should_show_model_rollout_prompt(&cli, &cfg, None, true,));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hides_model_rollout_prompt_when_cli_overrides_model() {
|
||||
let cli = Cli::parse_from(["codex", "--model", "gpt-4.1"]);
|
||||
let cfg = make_config();
|
||||
assert!(!should_show_model_rollout_prompt(&cli, &cfg, None, false));
|
||||
set_auth_method(&cfg.codex_home, AuthMode::ChatGPT);
|
||||
assert!(!should_show_model_rollout_prompt(&cli, &cfg, None, false,));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hides_model_rollout_prompt_when_profile_active() {
|
||||
let cli = Cli::parse_from(["codex"]);
|
||||
let cfg = make_config();
|
||||
set_auth_method(&cfg.codex_home, AuthMode::ChatGPT);
|
||||
assert!(!should_show_model_rollout_prompt(
|
||||
&cli,
|
||||
&cfg,
|
||||
|
||||
+4
-4
@@ -2,7 +2,7 @@
|
||||
source: tui/src/history_cell.rs
|
||||
expression: rendered
|
||||
---
|
||||
▌one two
|
||||
▌three four
|
||||
▌five six
|
||||
▌seven
|
||||
▌ one two
|
||||
▌ three four
|
||||
▌ five six
|
||||
▌ seven
|
||||
|
||||
+1
-1
@@ -2,5 +2,5 @@
|
||||
source: tui/src/status_indicator_widget.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
" Working (0s • Esc t"
|
||||
" Working (0s • Esc "
|
||||
" "
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
source: tui/src/status_indicator_widget.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
" Working (0s • Esc to interrupt) "
|
||||
" Working (0s • Esc to interrupt) "
|
||||
" "
|
||||
" ↳ first "
|
||||
" ↳ second "
|
||||
|
||||
+1
-1
@@ -2,5 +2,5 @@
|
||||
source: tui/src/status_indicator_widget.rs
|
||||
expression: terminal.backend()
|
||||
---
|
||||
" Working (0s • Esc to interrupt) "
|
||||
" Working (0s • Esc to interrupt) "
|
||||
" "
|
||||
|
||||
@@ -17,6 +17,7 @@ use crate::app_event_sender::AppEventSender;
|
||||
use crate::key_hint;
|
||||
use crate::shimmer::shimmer_spans;
|
||||
use crate::tui::FrameRequester;
|
||||
use crate::ui_consts::LIVE_PREFIX_COLS;
|
||||
|
||||
pub(crate) struct StatusIndicatorWidget {
|
||||
/// Animated header text (defaults to "Working").
|
||||
@@ -159,7 +160,7 @@ impl WidgetRef for StatusIndicatorWidget {
|
||||
let pretty_elapsed = fmt_elapsed_compact(elapsed);
|
||||
|
||||
// Plain rendering: no borders or padding so the live cell is visually indistinguishable from terminal scrollback.
|
||||
let mut spans = vec![" ".into()];
|
||||
let mut spans = vec![" ".repeat(LIVE_PREFIX_COLS as usize).into()];
|
||||
spans.extend(shimmer_spans(&self.header));
|
||||
spans.extend(vec![
|
||||
" ".into(),
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
//! Shared UI constants for layout and alignment within the TUI.
|
||||
|
||||
/// Width (in terminal columns) reserved for the left gutter/prefix used by
|
||||
/// live cells and aligned widgets.
|
||||
///
|
||||
/// Semantics:
|
||||
/// - Chat composer reserves this many columns for the left border + padding.
|
||||
/// - Status indicator lines begin with this many spaces for alignment.
|
||||
/// - User history lines account for this many columns (e.g., "▌ ") when wrapping.
|
||||
pub(crate) const LIVE_PREFIX_COLS: u16 = 2;
|
||||
Reference in New Issue
Block a user