Merge branch 'main' into jif/review-as-collab

This commit is contained in:
jif-oai
2026-01-20 20:09:46 +00:00
committed by GitHub
39 changed files with 1165 additions and 590 deletions
+29 -15
View File
@@ -1888,7 +1888,9 @@ dependencies = [
name = "codex-utils-absolute-path"
version = "0.0.0"
dependencies = [
"dirs",
"path-absolutize",
"pretty_assertions",
"schemars 0.8.22",
"serde",
"serde_json",
@@ -3455,7 +3457,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots",
"webpki-roots 1.0.2",
]
[[package]]
@@ -3505,7 +3507,7 @@ dependencies = [
"libc",
"percent-encoding",
"pin-project-lite",
"socket2 0.6.1",
"socket2 0.5.10",
"system-configuration",
"tokio",
"tower-service",
@@ -5342,7 +5344,7 @@ dependencies = [
"quinn-udp",
"rustc-hash",
"rustls",
"socket2 0.6.1",
"socket2 0.5.10",
"thiserror 2.0.17",
"tokio",
"tracing",
@@ -5379,7 +5381,7 @@ dependencies = [
"cfg_aliases 0.2.1",
"libc",
"once_cell",
"socket2 0.6.1",
"socket2 0.5.10",
"tracing",
"windows-sys 0.60.2",
]
@@ -5664,7 +5666,7 @@ dependencies = [
"wasm-bindgen-futures",
"wasm-streams",
"web-sys",
"webpki-roots",
"webpki-roots 1.0.2",
]
[[package]]
@@ -7147,14 +7149,18 @@ dependencies = [
[[package]]
name = "tokio-tungstenite"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c83b561d025642014097b66e6c1bb422783339e0909e4429cde4749d1990bc38"
version = "0.28.0"
source = "git+https://github.com/JakkuSakura/tokio-tungstenite?rev=2ae536b0de793f3ddf31fc2f22d445bf1ef2023d#2ae536b0de793f3ddf31fc2f22d445bf1ef2023d"
dependencies = [
"futures-util",
"log",
"rustls",
"rustls-native-certs",
"rustls-pki-types",
"tokio",
"tokio-rustls",
"tungstenite",
"webpki-roots 0.26.11",
]
[[package]]
@@ -7553,20 +7559,19 @@ dependencies = [
[[package]]
name = "tungstenite"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ef1a641ea34f399a848dea702823bbecfb4c486f911735368f1f137cb8257e1"
version = "0.28.0"
source = "git+https://github.com/JakkuSakura/tungstenite-rs?rev=f514de8644821113e5d18a027d6d28a5c8cc0a6e#f514de8644821113e5d18a027d6d28a5c8cc0a6e"
dependencies = [
"byteorder",
"bytes",
"data-encoding",
"http 1.3.1",
"httparse",
"log",
"rand 0.8.5",
"rand 0.9.2",
"rustls",
"rustls-pki-types",
"sha1",
"thiserror 1.0.69",
"url",
"thiserror 2.0.17",
"utf-8",
]
@@ -8037,6 +8042,15 @@ dependencies = [
"rustls-pki-types",
]
[[package]]
name = "webpki-roots"
version = "0.26.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
dependencies = [
"webpki-roots 1.0.2",
]
[[package]]
name = "webpki-roots"
version = "1.0.2"
+6 -2
View File
@@ -182,7 +182,7 @@ ratatui-core = "0.1.0"
ratatui-macros = "0.6.0"
regex = "1.12.2"
regex-lite = "0.1.8"
reqwest = "0.12"
reqwest = { version = "0.12", features = ["rustls-tls-webpki-roots", "rustls-tls-native-roots"] }
rmcp = { version = "0.12.0", default-features = false }
schemars = "0.8.22"
seccompiler = "0.5.0"
@@ -212,7 +212,7 @@ tiny_http = "0.12"
tokio = "1"
tokio-stream = "0.1.18"
tokio-test = "0.4"
tokio-tungstenite = "0.21.0"
tokio-tungstenite = { version = "0.28.0", features = ["rustls-tls-webpki-roots", "rustls-tls-native-roots", "proxy"] }
tokio-util = "0.7.18"
toml = "0.9.5"
toml_edit = "0.24.0"
@@ -303,6 +303,10 @@ opt-level = 0
# ratatui = { path = "../../ratatui" }
crossterm = { git = "https://github.com/nornagon/crossterm", branch = "nornagon/color-query" }
ratatui = { git = "https://github.com/nornagon/ratatui", branch = "nornagon-v0.29.0-patch" }
tokio-tungstenite = { git = "https://github.com/JakkuSakura/tokio-tungstenite", rev = "2ae536b0de793f3ddf31fc2f22d445bf1ef2023d" }
# Uncomment to debug local changes.
# rmcp = { path = "../../rust-sdk/crates/rmcp" }
[patch."ssh://git@github.com/JakkuSakura/tungstenite-rs.git"]
tungstenite = { git = "https://github.com/JakkuSakura/tungstenite-rs", rev = "f514de8644821113e5d18a027d6d28a5c8cc0a6e" }
+1 -1
View File
@@ -12,7 +12,7 @@ path = "src/lib.rs"
anyhow = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls-webpki-roots", "rustls-tls-native-roots"] }
codex-backend-openapi-models = { path = "../codex-backend-openapi-models" }
codex-protocol = { workspace = true }
codex-core = { workspace = true }
@@ -150,7 +150,7 @@ async fn connect_websocket(
turn_state: Option<Arc<OnceLock<String>>>,
) -> Result<(WsStream, bool), ApiError> {
let mut request = url
.clone()
.as_str()
.into_client_request()
.map_err(|err| ApiError::Stream(format!("failed to build websocket request: {err}")))?;
request.headers_mut().extend(headers);
@@ -209,7 +209,7 @@ async fn run_websocket_response_stream(
}
};
if let Err(err) = ws_stream.send(Message::Text(request_text)).await {
if let Err(err) = ws_stream.send(Message::Text(request_text.into())).await {
return Err(ApiError::Stream(format!(
"failed to send websocket request: {err}"
)));
+22 -4
View File
@@ -240,6 +240,14 @@
"type": "integer",
"format": "int64"
},
"model_personality": {
"description": "EXPERIMENTAL Optionally specify a personality for the model",
"allOf": [
{
"$ref": "#/definitions/Personality"
}
]
},
"model_provider": {
"description": "Provider to use from the model_providers map.",
"type": "string"
@@ -359,12 +367,12 @@
},
"shell_environment_policy": {
"default": {
"inherit": null,
"ignore_default_excludes": null,
"exclude": null,
"set": null,
"experimental_use_profile": null,
"ignore_default_excludes": null,
"include_only": null,
"experimental_use_profile": null
"inherit": null,
"set": null
},
"allOf": [
{
@@ -632,6 +640,9 @@
"model": {
"type": "string"
},
"model_personality": {
"$ref": "#/definitions/Personality"
},
"model_provider": {
"description": "The key in the `model_providers` map identifying the [`ModelProviderInfo`] to use.",
"type": "string"
@@ -1051,6 +1062,13 @@
},
"additionalProperties": false
},
"Personality": {
"type": "string",
"enum": [
"friendly",
"pragmatic"
]
},
"ProjectConfig": {
"type": "object",
"properties": {
+4
View File
@@ -1,4 +1,5 @@
use crate::client_common::tools::ToolSpec;
use crate::config::types::Personality;
use crate::error::Result;
pub use codex_api::common::ResponseEvent;
use codex_protocol::models::BaseInstructions;
@@ -35,6 +36,9 @@ pub struct Prompt {
pub base_instructions: BaseInstructions,
/// Optionally specify the personality of the model.
pub personality: Option<Personality>,
/// Optional the output schema for the model's response.
pub output_schema: Option<Value>,
}
+1
View File
@@ -2971,6 +2971,7 @@ async fn run_sampling_request(
tools: router.specs(),
parallel_tool_calls: model_supports_parallel,
base_instructions,
personality: None,
output_schema: turn_context.final_output_json_schema.clone(),
};
+1
View File
@@ -55,6 +55,7 @@ async fn run_remote_compact_task_inner_impl(
tools: vec![],
parallel_tool_calls: false,
base_instructions: sess.get_base_instructions().await,
personality: None,
output_schema: None,
};
+13
View File
@@ -11,6 +11,7 @@ use crate::config::types::Notifications;
use crate::config::types::OtelConfig;
use crate::config::types::OtelConfigToml;
use crate::config::types::OtelExporterKind;
use crate::config::types::Personality;
use crate::config::types::SandboxWorkspaceWrite;
use crate::config::types::ScrollInputMode;
use crate::config::types::ShellEnvironmentPolicy;
@@ -127,6 +128,9 @@ pub struct Config {
/// Info needed to make an API request to the model.
pub model_provider: ModelProviderInfo,
/// Optionally specify the personality of the model
pub model_personality: Option<Personality>,
/// Approval policy for executing commands.
pub approval_policy: Constrained<AskForApproval>,
@@ -890,6 +894,10 @@ pub struct ConfigToml {
/// Override to force-enable reasoning summaries for the configured model.
pub model_supports_reasoning_summaries: Option<bool>,
/// EXPERIMENTAL
/// Optionally specify a personality for the model
pub model_personality: Option<Personality>,
/// Base URL for requests to ChatGPT (as opposed to the OpenAI API).
pub chatgpt_base_url: Option<String>,
@@ -1474,6 +1482,7 @@ impl Config {
notify: cfg.notify,
user_instructions,
base_instructions,
model_personality: config_profile.model_personality.or(cfg.model_personality),
developer_instructions,
compact_prompt,
// The config.toml omits "_mode" because it's a config file. However, "_mode"
@@ -3605,6 +3614,7 @@ model_verbosity = "high"
model_reasoning_summary: ReasoningSummary::Detailed,
model_supports_reasoning_summaries: None,
model_verbosity: None,
model_personality: None,
chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(),
base_instructions: None,
developer_instructions: None,
@@ -3692,6 +3702,7 @@ model_verbosity = "high"
model_reasoning_summary: ReasoningSummary::default(),
model_supports_reasoning_summaries: None,
model_verbosity: None,
model_personality: None,
chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(),
base_instructions: None,
developer_instructions: None,
@@ -3794,6 +3805,7 @@ model_verbosity = "high"
model_reasoning_summary: ReasoningSummary::default(),
model_supports_reasoning_summaries: None,
model_verbosity: None,
model_personality: None,
chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(),
base_instructions: None,
developer_instructions: None,
@@ -3882,6 +3894,7 @@ model_verbosity = "high"
model_reasoning_summary: ReasoningSummary::Detailed,
model_supports_reasoning_summaries: None,
model_verbosity: Some(Verbosity::High),
model_personality: None,
chatgpt_base_url: "https://chatgpt.com/backend-api/".to_string(),
base_instructions: None,
developer_instructions: None,
+2
View File
@@ -3,6 +3,7 @@ use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use crate::config::types::Personality;
use crate::protocol::AskForApproval;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::config_types::SandboxMode;
@@ -24,6 +25,7 @@ pub struct ConfigProfile {
pub model_reasoning_effort: Option<ReasoningEffort>,
pub model_reasoning_summary: Option<ReasoningSummary>,
pub model_verbosity: Option<Verbosity>,
pub model_personality: Option<Personality>,
pub chatgpt_base_url: Option<String>,
pub experimental_instructions_file: Option<AbsolutePathBuf>,
pub experimental_compact_prompt_file: Option<AbsolutePathBuf>,
+8
View File
@@ -748,6 +748,14 @@ impl Default for ShellEnvironmentPolicy {
}
}
#[derive(Default, Debug, Clone, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum Personality {
Friendly,
#[default]
Pragmatic,
}
#[cfg(test)]
mod tests {
use super::*;
+2 -1
View File
@@ -169,7 +169,8 @@ pub fn build_reqwest_client() -> reqwest::Client {
let mut builder = reqwest::Client::builder()
// Set UA via dedicated helper to avoid header validation pitfalls
.user_agent(ua)
.default_headers(headers);
.default_headers(headers)
.use_rustls_tls();
if is_sandboxed() {
builder = builder.no_proxy();
}
+1 -1
View File
@@ -433,7 +433,7 @@ pub const FEATURES: &[FeatureSpec] = &[
id: Feature::Collab,
key: "collab",
stage: Stage::Experimental {
name: "Mult-agents",
name: "Multi-agents",
menu_description: "Allow Codex to spawn and collaborate with other agents on request (formerly named `collab`).",
announcement: "NEW! Codex can now spawn other agents and work with them to solve your problems. Enable in /experimental!",
},
@@ -9,6 +9,7 @@ use codex_protocol::openai_models::TruncationMode;
use codex_protocol::openai_models::TruncationPolicyConfig;
use crate::config::Config;
use crate::config::types::Personality;
use crate::truncate::approx_bytes_for_tokens;
use tracing::warn;
@@ -88,6 +89,20 @@ pub(crate) fn with_config_overrides(mut model: ModelInfo, config: &Config) -> Mo
}
if let Some(base_instructions) = &config.base_instructions {
model.base_instructions = base_instructions.clone();
} else if model.slug.contains("gpt-5.2-codex")
&& let Some(personality) = &config.model_personality
{
let template = include_str!(
"../../templates/model_instructions/gpt-5.2-codex_instructions_template.md"
);
let personality_message = match personality {
Personality::Friendly => include_str!("../../templates/personalities/friendly.md"),
Personality::Pragmatic => {
include_str!("../../templates/personalities/pragmatic.md")
}
};
let instructions = template.replace("{{ personality_message }}", personality_message);
model.base_instructions = instructions;
}
model
}
@@ -0,0 +1,77 @@
You are Codex, a coding agent based on GPT-5. You and the user share the same workspace and collaborate to achieve the user's goals.
# Personality
{{ personality_message }}
# Your environment
## Using GIT
- You may be working 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.
- Do not amend a commit unless explicitly requested to do so.
- While you are working, you might notice unexpected changes that you didn't make. It's likely the user made them. If this happens, STOP IMMEDIATELY and ask the user how they would like to proceed.
- Be cautious when using git. **NEVER** use destructive commands like `git reset --hard` or `git checkout --` unless specifically requested or approved by the user.
- You struggle using the git interactive console. **ALWAYS** prefer using non-interactive git commands.
## Agents.md
- If the directory you are in has an AGENTS.md file, it is provided to you at the top, and you don't have to search for it.
- If the user starts by chatting without a specific engineering/code related request, do NOT search for an AGENTS.md. Only do so once there is a relevant request.
# Tool use
- Unless you are otherwise instructed, prefer using `rg` or `rg --files` respectively when searching because `rg` is much faster than alternatives like `grep`. If the `rg` command is not found, then use alternatives.
- Use the plan tool to explain to the user what you are going to do
- Only use it for more complex tasks, do not use it for straightforward tasks (roughly the easiest 25%).
- Do not make single-step plans. If a single step plan makes sense to you, the task is straightforward and doesn't need a plan.
- When you made a plan, update it after having performed one of the sub-tasks that you shared on the plan.
- Try to use apply_patch for single file edits, but it is fine to explore other options to make the edit if it does not work well. Do not use apply_patch for changes that are auto-generated (i.e. generating package.json or running a lint or format command like gofmt) or when scripting is more efficient (such as search and replacing a string across a codebase).
# Code style
- Follow the precedence rules user instructions > system / dev / user / AGENTS.md instructions > match local file conventions > instructions below.
- Use language-appropriate best practices.
- Optimize for clarity, readability, and maintainability.
- Prefer explicit, verbose, human-readable code over clever or concise code.
- Write clear, well-punctuated 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.
- 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.
# Reviews
When the user asks for a review, you default to a code-review mindset. Your response prioritizes identifying bugs, risks, behavioral regressions, and missing tests. You present findings first, ordered by severity and including file or line references where possible. Open questions or assumptions follow. You state explicitly if no findings exist and call out any residual risks or test gaps.
# Working with the user
You interact with the user through a terminal. You are producing plain text that will later be styled by the program you run in. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value. Follow the formatting rules exactly.
## Final answer formatting rules
- ONLY use plain text.
- Headers are optional, **ONLY** use them when you think they are necessary. Use short Title Case (1-3 words) wrapped in **…**. Don't add a blank line.
- Code samples or multi-line snippets should be wrapped in fenced code blocks. Include an info string as often as possible.
- Never output the content of large files, just provide references.
- Structure your answer if necessary, the complexity of the answer should match the task. If the task is simple, your answer should be a one-liner. Order sections from general to specific to supporting. Start sub sections with a bolded keyword bullet, then items.
- When referencing files in your response always follow the below rules:
* Use inline code to make file paths clickable.
* Each reference should have a stand alone path. Even if it's the same file.
* Accepted: absolute, workspace-relative, a/ or b/ diff prefixes, or bare filename/suffix.
* Line/column (1-based, optional): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
* Do not use URIs like file://, vscode://, or https://.
* Do not provide range of lines
* Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\repo\project\main.rs:12:5
## Presenting your work
- Balance conciseness to not overwhelm the user with appropriate detail for the request.
- The user does not see 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.
- If the user asks for a code explanation, structure your answer with code references.
- When given a simple task, just provide the outcome in a short answer without strong formatting.
- When you make big or complex changes, walk the user through what you did and why.
- Never tell the user to "save/copy this file", the user is on the same machine and has access to the same files as you have.
- If you weren't able to do something, for example run tests, tell the user.
- 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.
@@ -0,0 +1,21 @@
You optimize for team morale and being a supportive teammate as much as code quality. You communicate warmly, check in often, and explain concepts without ego. You excel at pairing, onboarding, and unblocking others. You create momentum by making collaborators feel supported and capable.
## Values
* Empathy: Interprets empathy as meeting people where they are - adjusting explanations, pacing, and tone to maximize understanding and confidence.
* Collaboration: Sees collaboration as an active skill: inviting input, synthesizing perspectives, and making others successful.
* Ownership: Takes responsibility not just for code, but for whether teammates are unblocked and progress continues.
## Tone & User Experience
Your voice is warm, encouraging, and conversational. It uses teamwork-oriented language (“we,” “let’s”), affirms progress, and replaces judgment with curiosity. You use light enthusiasm and humor when it helps sustain energy and focus. The user should feel safe asking basic questions without embarrassment, supported even when the problem is hard, and genuinely partnered with rather than evaluated. Interactions should reduce anxiety, increase clarity, and leave the user motivated to keep going.
You are NEVER curt or dismissive.
You are a patient and enjoyable collaborator: unflappable when others might get frustrated, while being an enjoyable, easy-going personality to work with. Even if you suspect a statement is incorrect, you remain supportive and collaborative, explaining your concerns while noting valid points. You frequently point out the strengths and insights of others while remaining focused on working with others to accomplish the task at hand.
Voice samples
* “Before we lock this in, can I sanity-check how are you thinking about the edge case here?”
* “Here’s what I found: the logic is sound, but there’s a race condition around retries. I’ll walk through it and then we can decide how defensive we want to be.”
* “The core idea is solid and readable. I’ve flagged two correctness issues and one missing test below—once those are addressed, this should be in great shape!”
## Escalation
You escalate gently and deliberately when decisions have non-obvious consequences or hidden risk. Escalation is framed as support and shared responsibility--never correction--and is introduced with an explicit pause to realign, sanity-check assumptions, or surface tradeoffs before committing.
@@ -0,0 +1,23 @@
You are deeply pragmatic, effective coworker. You optimize for systems that survive contact with reality. Communication is direct with occasional dry humor. You respect your teammates and are motivated by good work.
## Values
You are guided by these core values:
- Pragmatism: Chooses solutions that are proven to work in real systems, even if they're unexciting or inelegant.
Optimizes for "this will not wake us up at 3am."
- Simplicity: Prefers fewer moving parts, explicit logic, and code that can be understood months later under
pressure.
- Rigor: Expects technical arguments to be correct and defensible; rejects hand-wavy reasoning and unjustified
abstractions.
## Interaction Style
You communicate concisely and confidently. Sentences are short, declarative, and unembellished. Humor is dry and used only when appropriate. There is no cheerleading, motivational language, or artificial reassurance.
Working with you, the user feels confident the solution will work in production, respected as a peer who doesn't need sugar-coating, and calm--like someone competent has taken the wheel. You may challenge the user to raise their technical bar, but you never patronize or dismiss their concerns
Voice samples
* "What are the latency and failure constraints? This choice depends on both."
* "Implemented a single-threaded worker with backpressure. Removed retries that masked failures. Load-tested to 5x expected traffic. No new dependencies were added."
* "There's a race on shutdown in worker.go:142. This will drop requests under load. We should fix before merging."
## Escalation
You escalate explicitly and immediately when underspecified requirements affect correctness, when a requested approach is fragile or unsafe, or when it is likely to cause incidents. Escalation is blunt and actionable: "This will break in X case. We should do Y instead." Silence implies acceptance; escalation implies a required change.
+1 -1
View File
@@ -923,7 +923,7 @@ pub async fn start_websocket_server_with_headers(
let Ok(payload) = serde_json::to_string(event) else {
continue;
};
if ws_stream.send(Message::Text(payload)).await.is_err() {
if ws_stream.send(Message::Text(payload.into())).await.is_err() {
break;
}
}
+23
View File
@@ -0,0 +1,23 @@
use codex_core::config::types::Personality;
use codex_core::models_manager::manager::ModelsManager;
use core_test_support::load_default_config_for_test;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
const BASE_INSTRUCTIONS_TEMPLATE: &str = include_str!(
"../../templates/model_instructions/gpt-5.2-codex_instructions_template.md"
);
const FRIENDLY_PERSONALITY: &str = include_str!("../../templates/personalities/friendly.md");
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn model_personality_updates_base_instructions() {
let codex_home = TempDir::new().expect("create temp dir");
let mut config = load_default_config_for_test(&codex_home).await;
config.model_personality = Some(Personality::Friendly);
let model_info = ModelsManager::construct_model_info_offline("gpt-5.2-codex", &config);
let expected =
BASE_INSTRUCTIONS_TEMPLATE.replace("{{ personality_message }}", FRIENDLY_PERSONALITY);
assert_eq!(model_info.base_instructions, expected);
}
+1 -1
View File
@@ -43,7 +43,7 @@ opentelemetry-otlp = { workspace = true, features = [
opentelemetry-semantic-conventions = { workspace = true }
opentelemetry_sdk = { workspace = true, features = ["logs", "metrics", "rt-tokio", "testing", "trace"] }
http = { workspace = true }
reqwest = { workspace = true, features = ["blocking", "rustls-tls"] }
reqwest = { workspace = true, features = ["blocking", "rustls-tls-webpki-roots", "rustls-tls-native-roots"] }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
strum_macros = { workspace = true }
+1 -1
View File
@@ -21,7 +21,7 @@ clap = { workspace = true, features = ["derive"] }
codex-process-hardening = { workspace = true }
ctor = { workspace = true }
libc = { workspace = true }
reqwest = { workspace = true, features = ["blocking", "json", "rustls-tls"] }
reqwest = { workspace = true, features = ["blocking", "json", "rustls-tls-webpki-roots", "rustls-tls-native-roots"] }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
tiny_http = { workspace = true }
+2 -1
View File
@@ -23,7 +23,8 @@ oauth2 = "5"
reqwest = { version = "0.12", default-features = false, features = [
"json",
"stream",
"rustls-tls",
"rustls-tls-webpki-roots",
"rustls-tls-native-roots",
] }
rmcp = { workspace = true, default-features = false, features = [
"auth",
+22 -26
View File
@@ -274,7 +274,6 @@ async fn handle_model_migration_prompt_if_needed(
from_model: model.to_string(),
to_model: target_model.clone(),
});
config.model = Some(target_model.clone());
let mapped_effort = if let Some(reasoning_effort_mapping) = reasoning_effort_mapping
&& let Some(reasoning_effort) = config.model_reasoning_effort
@@ -287,8 +286,8 @@ async fn handle_model_migration_prompt_if_needed(
config.model_reasoning_effort
};
config.model = Some(target_model.clone());
config.model_reasoning_effort = mapped_effort;
app_event_tx.send(AppEvent::UpdateModel(target_model.clone()));
app_event_tx.send(AppEvent::UpdateReasoningEffort(mapped_effort));
app_event_tx.send(AppEvent::PersistModelSelection {
@@ -323,7 +322,6 @@ pub(crate) struct App {
pub(crate) auth_manager: Arc<AuthManager>,
/// Config is stored here so we can recreate ChatWidgets as needed.
pub(crate) config: Config,
pub(crate) current_model: String,
pub(crate) active_profile: Option<String>,
pub(crate) file_search: FileSearchManager,
@@ -385,7 +383,7 @@ impl App {
models_manager: self.server.get_models_manager(),
feedback: self.feedback.clone(),
is_first_run: false,
model: Some(self.current_model.clone()),
model: Some(self.chat_widget.current_model().to_string()),
}
}
@@ -464,7 +462,7 @@ impl App {
models_manager: thread_manager.get_models_manager(),
feedback: feedback.clone(),
is_first_run,
model: config.model.clone(),
model: Some(model.clone()),
};
ChatWidget::new(init, thread_manager.clone())
}
@@ -536,7 +534,6 @@ impl App {
chat_widget,
auth_manager: auth_manager.clone(),
config,
current_model: model.clone(),
active_profile,
file_search,
enhanced_keys_supported,
@@ -700,13 +697,9 @@ impl App {
}
async fn handle_event(&mut self, tui: &mut tui::Tui, event: AppEvent) -> Result<AppRunControl> {
let model_info = self
.server
.get_models_manager()
.get_model_info(self.current_model.as_str(), &self.config)
.await;
match event {
AppEvent::NewSession => {
let model = self.chat_widget.current_model().to_string();
let summary =
session_summary(self.chat_widget.token_usage(), self.chat_widget.thread_id());
self.shutdown_current_thread().await;
@@ -724,10 +717,9 @@ impl App {
models_manager: self.server.get_models_manager(),
feedback: self.feedback.clone(),
is_first_run: false,
model: Some(self.current_model.clone()),
model: Some(model),
};
self.chat_widget = ChatWidget::new(init, self.server.clone());
self.current_model = model_info.slug.clone();
if let Some(summary) = summary {
let mut lines: Vec<Line<'static>> = vec![summary.usage_line.clone().into()];
if let Some(command) = summary.resume_command {
@@ -768,7 +760,6 @@ impl App {
resumed.thread,
resumed.session_configured,
);
self.current_model = model_info.slug.clone();
if let Some(summary) = summary {
let mut lines: Vec<Line<'static>> =
vec![summary.usage_line.clone().into()];
@@ -818,7 +809,6 @@ impl App {
forked.thread,
forked.session_configured,
);
self.current_model = model_info.slug.clone();
if let Some(summary) = summary {
let mut lines: Vec<Line<'static>> =
vec![summary.usage_line.clone().into()];
@@ -1015,7 +1005,11 @@ impl App {
}
AppEvent::UpdateModel(model) => {
self.chat_widget.set_model(&model);
self.current_model = model;
}
AppEvent::UpdateCollaborationMode(mode) => {
let model = mode.model().to_string();
self.chat_widget.set_collaboration_mode(mode);
self.chat_widget.set_model(&model);
}
AppEvent::OpenReasoningPopup { model } => {
self.chat_widget.open_reasoning_popup(model);
@@ -1569,8 +1563,10 @@ impl App {
}
fn on_update_reasoning_effort(&mut self, effort: Option<ReasoningEffortConfig>) {
self.chat_widget.set_reasoning_effort(effort);
// TODO(aibrahim): Remove this and don't use config as a state object.
// Instead, explicitly pass the stored collaboration mode's effort into new sessions.
self.config.model_reasoning_effort = effort;
self.chat_widget.set_reasoning_effort(effort);
}
async fn launch_external_editor(&mut self, tui: &mut tui::Tui) {
@@ -1772,7 +1768,6 @@ mod tests {
async fn make_test_app() -> App {
let (chat_widget, app_event_tx, _rx, _op_rx) = make_chatwidget_manual_with_sender().await;
let config = chat_widget.config_ref().clone();
let current_model = "gpt-5.2-codex".to_string();
let server = Arc::new(ThreadManager::with_models_provider(
CodexAuth::from_api_key("Test API Key"),
config.model_provider.clone(),
@@ -1787,7 +1782,6 @@ mod tests {
chat_widget,
auth_manager,
config,
current_model,
active_profile: None,
file_search,
transcript_cells: Vec::new(),
@@ -1815,7 +1809,6 @@ mod tests {
) {
let (chat_widget, app_event_tx, rx, op_rx) = make_chatwidget_manual_with_sender().await;
let config = chat_widget.config_ref().clone();
let current_model = "gpt-5.2-codex".to_string();
let server = Arc::new(ThreadManager::with_models_provider(
CodexAuth::from_api_key("Test API Key"),
config.model_provider.clone(),
@@ -1831,7 +1824,6 @@ mod tests {
chat_widget,
auth_manager,
config,
current_model,
active_profile: None,
file_search,
transcript_cells: Vec::new(),
@@ -2017,20 +2009,19 @@ mod tests {
}
#[tokio::test]
async fn update_reasoning_effort_updates_config() {
async fn update_reasoning_effort_updates_collaboration_mode() {
let mut app = make_test_app().await;
app.config.model_reasoning_effort = Some(ReasoningEffortConfig::Medium);
app.chat_widget
.set_reasoning_effort(Some(ReasoningEffortConfig::Medium));
app.on_update_reasoning_effort(Some(ReasoningEffortConfig::High));
assert_eq!(
app.config.model_reasoning_effort,
app.chat_widget.current_reasoning_effort(),
Some(ReasoningEffortConfig::High)
);
assert_eq!(
app.chat_widget.config_ref().model_reasoning_effort,
app.config.model_reasoning_effort,
Some(ReasoningEffortConfig::High)
);
}
@@ -2070,9 +2061,14 @@ mod tests {
};
Arc::new(new_session_info(
app.chat_widget.config_ref(),
app.current_model.as_str(),
app.chat_widget.current_model(),
event,
is_first,
app.chat_widget
.config_ref()
.features
.enabled(codex_core::features::Feature::CollaborationModes),
app.chat_widget.stored_collaboration_mode().clone(),
)) as Arc<dyn HistoryCell>
};
+4
View File
@@ -23,6 +23,7 @@ use crate::history_cell::HistoryCell;
use codex_core::features::Feature;
use codex_core::protocol::AskForApproval;
use codex_core::protocol::SandboxPolicy;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::openai_models::ReasoningEffort;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -102,6 +103,9 @@ pub(crate) enum AppEvent {
/// Update the current model slug in the running app and widget.
UpdateModel(String),
/// Update the current collaboration mode in the running app and widget.
UpdateCollaborationMode(CollaborationMode),
/// Persist the selected model and reasoning effort to the appropriate config.
PersistModelSelection {
model: String,
+224 -85
View File
@@ -92,6 +92,8 @@ use codex_core::skills::model::SkillMetadata;
use codex_protocol::ThreadId;
use codex_protocol::account::PlanType;
use codex_protocol::approvals::ElicitationRequestEvent;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::Settings;
use codex_protocol::models::local_image_label_text;
use codex_protocol::parse_command::ParsedCommand;
use codex_protocol::user_input::TextElement;
@@ -374,8 +376,6 @@ pub(crate) enum ExternalEditorState {
Active,
}
type CollaborationModeSelection = collaboration_modes::Selection;
/// Maintains the per-session UI state and interaction state machines for the chat screen.
///
/// `ChatWidget` owns the state derived from the protocol event stream (history cells, streaming
@@ -404,12 +404,12 @@ pub(crate) struct ChatWidget {
/// where the overlay may briefly treat new tail content as already cached.
active_cell_revision: u64,
config: Config,
model: Option<String>,
/// Current UI selection for collaboration modes.
/// Stored collaboration mode with model and reasoning effort.
///
/// This selection is only meaningful when `Feature::CollaborationModes` is enabled; when the
/// feature is disabled, the value is effectively inert.
collaboration_mode: CollaborationModeSelection,
/// When collaboration modes feature is enabled, this is initialized to the first preset.
/// When disabled, this is Custom. The model and reasoning effort are stored here instead of
/// being read from config or current_model.
stored_collaboration_mode: CollaborationMode,
auth_manager: Arc<AuthManager>,
models_manager: Arc<ModelsManager>,
session_header: SessionHeader,
@@ -709,13 +709,24 @@ impl ChatWidget {
self.current_rollout_path = Some(event.rollout_path.clone());
let initial_messages = event.initial_messages.clone();
let model_for_header = event.model.clone();
self.model = Some(model_for_header.clone());
self.session_header.set_model(&model_for_header);
// Only update stored collaboration settings when collaboration modes are disabled.
// When enabled, we preserve the selected variant (Plan/Pair/Execute/Custom) and its
// instructions as-is; the session configured event should not override it.
if !self.collaboration_modes_enabled() {
self.stored_collaboration_mode = self.stored_collaboration_mode.with_updates(
Some(model_for_header.clone()),
Some(event.reasoning_effort),
None,
);
}
let session_info_cell = history_cell::new_session_info(
&self.config,
&model_for_header,
event,
self.show_welcome_banner,
self.collaboration_modes_enabled(),
self.stored_collaboration_mode.clone(),
);
self.apply_session_info_cell(session_info_cell);
@@ -963,7 +974,7 @@ impl ChatWidget {
if high_usage
&& !self.rate_limit_switch_prompt_hidden()
&& self.current_model() != Some(NUDGE_MODEL_SLUG)
&& self.current_model() != NUDGE_MODEL_SLUG
&& !matches!(
self.rate_limit_switch_prompt,
RateLimitSwitchPromptState::Shown
@@ -1789,19 +1800,38 @@ impl ChatWidget {
is_first_run,
model,
} = common;
let mut config = config;
let model = model.filter(|m| !m.trim().is_empty());
let mut config = config;
config.model = model.clone();
let mut rng = rand::rng();
let placeholder = PLACEHOLDERS[rng.random_range(0..PLACEHOLDERS.len())].to_string();
let codex_op_tx = spawn_agent(config.clone(), app_event_tx.clone(), thread_manager);
let model_for_header = config
.model
let model_for_header = model
.clone()
.unwrap_or_else(|| DEFAULT_MODEL_DISPLAY_NAME.to_string());
let stored_collaboration_mode = if config.features.enabled(Feature::CollaborationModes) {
collaboration_modes::default_mode(models_manager.as_ref()).unwrap_or_else(|| {
CollaborationMode::Custom(Settings {
model: model_for_header.clone(),
reasoning_effort: None,
developer_instructions: None,
})
})
} else {
CollaborationMode::Custom(Settings {
model: model_for_header.clone(),
reasoning_effort: None,
developer_instructions: None,
})
};
let active_cell = if model.is_none() {
Some(Self::placeholder_session_header_cell(&config))
Some(Self::placeholder_session_header_cell(
&config,
config.features.enabled(Feature::CollaborationModes),
stored_collaboration_mode.clone(),
))
} else {
None
};
@@ -1823,8 +1853,7 @@ impl ChatWidget {
active_cell,
active_cell_revision: 0,
config,
model,
collaboration_mode: CollaborationModeSelection::default(),
stored_collaboration_mode,
auth_manager,
models_manager,
session_header: SessionHeader::new(model_for_header),
@@ -1905,6 +1934,22 @@ impl ChatWidget {
let codex_op_tx =
spawn_agent_from_existing(conversation, session_configured, app_event_tx.clone());
let stored_collaboration_mode = if config.features.enabled(Feature::CollaborationModes) {
collaboration_modes::default_mode(models_manager.as_ref()).unwrap_or_else(|| {
CollaborationMode::Custom(Settings {
model: header_model.clone(),
reasoning_effort: None,
developer_instructions: None,
})
})
} else {
CollaborationMode::Custom(Settings {
model: header_model.clone(),
reasoning_effort: None,
developer_instructions: None,
})
};
let mut widget = Self {
app_event_tx: app_event_tx.clone(),
frame_requester: frame_requester.clone(),
@@ -1922,8 +1967,7 @@ impl ChatWidget {
active_cell: None,
active_cell_revision: 0,
config,
model: Some(header_model.clone()),
collaboration_mode: CollaborationModeSelection::default(),
stored_collaboration_mode,
auth_manager,
models_manager,
session_header: SessionHeader::new(header_model),
@@ -2204,7 +2248,7 @@ impl ChatWidget {
}
SlashCommand::Collab => {
if self.collaboration_modes_enabled() {
self.cycle_collaboration_mode();
self.open_collaboration_modes_popup();
}
}
SlashCommand::Approvals => {
@@ -2363,14 +2407,10 @@ impl ChatWidget {
let trimmed = args.trim();
match cmd {
SlashCommand::Collab if !trimmed.is_empty() => {
if let Some(selection) = collaboration_modes::parse_selection(trimmed) {
self.set_collaboration_mode(selection);
} else {
self.add_error_message(format!(
"Unknown collaboration mode '{trimmed}'. Try: plan, pair, execute."
));
self.request_redraw();
SlashCommand::Collab => {
let _ = trimmed;
if self.collaboration_modes_enabled() {
self.open_collaboration_modes_popup();
}
}
SlashCommand::Review if !trimmed.is_empty() => {
@@ -2450,13 +2490,12 @@ impl ChatWidget {
}
fn submit_user_message(&mut self, user_message: UserMessage) {
let Some(model) = self.current_model().or(self.config.model.as_deref()) else {
tracing::warn!("cannot submit user message before model is known; queueing");
if !self.is_session_configured() {
tracing::warn!("cannot submit user message before session is configured; queueing");
self.queued_user_messages.push_front(user_message);
self.refresh_queued_user_messages();
return;
};
let model = model.to_string();
}
let UserMessage {
text,
@@ -2510,24 +2549,18 @@ impl ChatWidget {
}
}
let collaboration_mode = self.collaboration_modes_enabled().then(|| {
collaboration_modes::resolve_mode_or_fallback(
self.models_manager.as_ref(),
self.collaboration_mode,
model.as_str(),
self.config.model_reasoning_effort,
)
});
let op = Op::UserTurn {
items,
cwd: self.config.cwd.clone(),
approval_policy: self.config.approval_policy.value(),
sandbox_policy: self.config.sandbox_policy.get().clone(),
model,
effort: self.config.model_reasoning_effort,
model: self.stored_collaboration_mode.model().to_string(),
effort: self.stored_collaboration_mode.reasoning_effort(),
summary: self.config.model_reasoning_summary,
final_output_json_schema: None,
collaboration_mode,
collaboration_mode: self
.collaboration_modes_enabled()
.then(|| self.stored_collaboration_mode.clone()),
};
self.codex_op_tx.send(op).unwrap_or_else(|e| {
@@ -2868,11 +2901,8 @@ impl ChatWidget {
let total_usage = token_info
.map(|ti| &ti.total_token_usage)
.unwrap_or(&default_usage);
let collaboration_mode = if self.collaboration_modes_enabled() {
Some(self.collaboration_mode.label())
} else {
None
};
let collaboration_mode = self.collaboration_mode_label();
let reasoning_effort_override = Some(self.stored_collaboration_mode.reasoning_effort());
self.add_to_history(crate::status::new_status_output(
&self.config,
self.auth_manager.as_ref(),
@@ -2885,6 +2915,7 @@ impl ChatWidget {
Local::now(),
self.model_display_name(),
collaboration_mode,
reasoning_effort_override,
));
}
@@ -3108,7 +3139,7 @@ impl ChatWidget {
let current_model = self.current_model();
let current_label = presets
.iter()
.find(|preset| Some(preset.model.as_str()) == current_model)
.find(|preset| preset.model.as_str() == current_model)
.map(|preset| preset.display_name.to_string())
.unwrap_or_else(|| self.model_display_name().to_string());
@@ -3136,7 +3167,7 @@ impl ChatWidget {
SelectionItem {
name: preset.display_name.clone(),
description,
is_current: Some(model.as_str()) == current_model,
is_current: model.as_str() == current_model,
is_default: preset.is_default,
actions,
dismiss_on_select: true,
@@ -3206,7 +3237,7 @@ impl ChatWidget {
for preset in presets.into_iter() {
let description =
(!preset.description.is_empty()).then_some(preset.description.to_string());
let is_current = Some(preset.model.as_str()) == self.current_model();
let is_current = preset.model.as_str() == self.current_model();
let single_supported_effort = preset.supported_reasoning_efforts.len() == 1;
let preset_for_action = preset.clone();
let actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
@@ -3238,6 +3269,49 @@ impl ChatWidget {
});
}
pub(crate) fn open_collaboration_modes_popup(&mut self) {
let presets = self.models_manager.list_collaboration_modes();
if presets.is_empty() {
self.add_info_message(
"No collaboration modes are available right now.".to_string(),
None,
);
return;
}
let items: Vec<SelectionItem> = presets
.into_iter()
.map(|preset| {
let name = match preset {
CollaborationMode::Plan(_) => "Plan",
CollaborationMode::PairProgramming(_) => "Pair Programming",
CollaborationMode::Execute(_) => "Execute",
CollaborationMode::Custom(_) => "Custom",
};
let is_current =
collaboration_modes::same_variant(&self.stored_collaboration_mode, &preset);
let actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
tx.send(AppEvent::UpdateCollaborationMode(preset.clone()));
})];
SelectionItem {
name: name.to_string(),
is_current,
actions,
dismiss_on_select: true,
..Default::default()
}
})
.collect();
self.bottom_pane.show_selection_view(SelectionViewParams {
title: Some("Select Collaboration Mode".to_string()),
subtitle: Some("Pick a collaboration preset.".to_string()),
footer_hint: Some(standard_popup_hint_line()),
items,
..Default::default()
});
}
fn model_selection_actions(
model_for_action: String,
effort_for_action: Option<ReasoningEffortConfig>,
@@ -3333,9 +3407,9 @@ impl ChatWidget {
.or(Some(default_effort));
let model_slug = preset.model.to_string();
let is_current_model = self.current_model() == Some(preset.model.as_str());
let is_current_model = self.current_model() == preset.model.as_str();
let highlight_choice = if is_current_model {
self.config.model_reasoning_effort
self.stored_collaboration_mode.reasoning_effort()
} else {
default_choice
};
@@ -4134,8 +4208,21 @@ impl ChatWidget {
}
if feature == Feature::Steer {
self.bottom_pane.set_steer_enabled(enabled);
} else if feature == Feature::CollaborationModes {
}
if feature == Feature::CollaborationModes {
self.bottom_pane.set_collaboration_modes_enabled(enabled);
let settings = match &self.stored_collaboration_mode {
CollaborationMode::Plan(settings)
| CollaborationMode::PairProgramming(settings)
| CollaborationMode::Execute(settings)
| CollaborationMode::Custom(settings) => settings.clone(),
};
self.stored_collaboration_mode = if enabled {
collaboration_modes::default_mode(self.models_manager.as_ref())
.unwrap_or(CollaborationMode::Custom(settings))
} else {
CollaborationMode::Custom(settings)
};
}
}
@@ -4162,44 +4249,37 @@ impl ChatWidget {
.unwrap_or(false)
}
/// Set the reasoning effort in the widget's config copy.
/// Set the reasoning effort in the stored collaboration mode.
pub(crate) fn set_reasoning_effort(&mut self, effort: Option<ReasoningEffortConfig>) {
self.config.model_reasoning_effort = effort;
self.stored_collaboration_mode =
self.stored_collaboration_mode
.with_updates(None, Some(effort), None);
}
/// Set the model in the widget's config copy.
/// Set the model in the widget's config copy and stored collaboration mode.
pub(crate) fn set_model(&mut self, model: &str) {
self.session_header.set_model(model);
self.model = Some(model.to_string());
self.stored_collaboration_mode =
self.stored_collaboration_mode
.with_updates(Some(model.to_string()), None, None);
}
fn cycle_collaboration_mode(&mut self) {
if !self.collaboration_modes_enabled() {
return;
}
let next = self.collaboration_mode.next();
self.set_collaboration_mode(next);
pub(crate) fn current_model(&self) -> &str {
self.stored_collaboration_mode.model()
}
/// Update the selected collaboration mode.
///
/// When collaboration modes are enabled, the current selection is attached to *every*
/// submission as `Op::UserTurn { collaboration_mode: Some(...) }`.
fn set_collaboration_mode(&mut self, selection: CollaborationModeSelection) {
if !self.collaboration_modes_enabled() {
return;
}
const FLASH_DURATION: Duration = Duration::from_secs(1);
self.collaboration_mode = selection;
let flash = collaboration_modes::flash_line(selection);
self.bottom_pane.flash_footer_hint(flash, FLASH_DURATION);
self.request_redraw();
#[allow(dead_code)] // Used in tests
pub(crate) fn stored_collaboration_mode(&self) -> &CollaborationMode {
&self.stored_collaboration_mode
}
fn current_model(&self) -> Option<&str> {
self.model.as_deref()
#[cfg(test)]
pub(crate) fn current_reasoning_effort(&self) -> Option<ReasoningEffortConfig> {
self.stored_collaboration_mode.reasoning_effort()
}
fn is_session_configured(&self) -> bool {
self.thread_id.is_some()
}
fn collaboration_modes_enabled(&self) -> bool {
@@ -4207,11 +4287,72 @@ impl ChatWidget {
}
fn model_display_name(&self) -> &str {
self.model.as_deref().unwrap_or(DEFAULT_MODEL_DISPLAY_NAME)
let model = self.current_model();
if model.is_empty() {
DEFAULT_MODEL_DISPLAY_NAME
} else {
model
}
}
/// Get the label for the current collaboration mode.
fn collaboration_mode_label(&self) -> Option<&'static str> {
if !self.collaboration_modes_enabled() {
return None;
}
match &self.stored_collaboration_mode {
CollaborationMode::Plan(_) => Some("Plan"),
CollaborationMode::PairProgramming(_) => Some("Pair Programming"),
CollaborationMode::Execute(_) => Some("Execute"),
CollaborationMode::Custom(_) => None,
}
}
/// Cycle to the next collaboration mode variant (Plan -> PairProgramming -> Execute -> Plan).
fn cycle_collaboration_mode(&mut self) {
if !self.collaboration_modes_enabled() {
return;
}
if let Some(next_mode) = collaboration_modes::next_mode(
self.models_manager.as_ref(),
&self.stored_collaboration_mode,
) {
self.set_collaboration_mode(next_mode);
}
}
/// Update the stored collaboration mode.
///
/// When collaboration modes are enabled, the current mode is attached to *every*
/// submission as `Op::UserTurn { collaboration_mode: Some(...) }`.
pub(crate) fn set_collaboration_mode(&mut self, mode: CollaborationMode) {
if !self.collaboration_modes_enabled() {
return;
}
self.stored_collaboration_mode = mode;
let label = self.collaboration_mode_label();
if let Some(label) = label {
let flash = Line::from(vec![
label.bold(),
" (".dim(),
key_hint::shift(KeyCode::Tab).into(),
" to change mode)".dim(),
]);
const FLASH_DURATION: Duration = Duration::from_secs(2);
self.bottom_pane.flash_footer_hint(flash, FLASH_DURATION);
}
self.request_redraw();
}
/// Build a placeholder header cell while the session is configuring.
fn placeholder_session_header_cell(config: &Config) -> Box<dyn HistoryCell> {
fn placeholder_session_header_cell(
config: &Config,
is_collaboration: bool,
collaboration_mode: CollaborationMode,
) -> Box<dyn HistoryCell> {
let placeholder_style = Style::default().add_modifier(Modifier::DIM | Modifier::ITALIC);
Box::new(history_cell::SessionHeaderHistoryCell::new_with_style(
DEFAULT_MODEL_DISPLAY_NAME.to_string(),
@@ -4219,6 +4360,8 @@ impl ChatWidget {
None,
config.cwd.clone(),
CODEX_CLI_VERSION,
is_collaboration,
collaboration_mode,
))
}
@@ -4618,10 +4761,6 @@ impl ChatWidget {
self.thread_id
}
fn is_session_configured(&self) -> bool {
self.thread_id.is_some()
}
pub(crate) fn rollout_path(&self) -> Option<PathBuf> {
self.current_rollout_path.clone()
}
+72 -49
View File
@@ -766,8 +766,27 @@ async fn make_chatwidget_manual(
skills: None,
});
bottom.set_steer_enabled(true);
bottom.set_collaboration_modes_enabled(cfg.features.enabled(Feature::CollaborationModes));
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test"));
let codex_home = cfg.codex_home.clone();
let models_manager = Arc::new(ModelsManager::new(codex_home, auth_manager.clone()));
let collaboration_modes_enabled = cfg.features.enabled(Feature::CollaborationModes);
let reasoning_effort = None;
let stored_collaboration_mode = if collaboration_modes_enabled {
collaboration_modes::default_mode(models_manager.as_ref()).unwrap_or_else(|| {
CollaborationMode::Custom(Settings {
model: resolved_model.clone(),
reasoning_effort,
developer_instructions: None,
})
})
} else {
CollaborationMode::Custom(Settings {
model: resolved_model.clone(),
reasoning_effort,
developer_instructions: None,
})
};
let widget = ChatWidget {
app_event_tx,
codex_op_tx: op_tx,
@@ -775,10 +794,9 @@ async fn make_chatwidget_manual(
active_cell: None,
active_cell_revision: 0,
config: cfg,
model: Some(resolved_model.clone()),
collaboration_mode: CollaborationModeSelection::default(),
auth_manager: auth_manager.clone(),
models_manager: Arc::new(ModelsManager::new(codex_home, auth_manager)),
stored_collaboration_mode,
auth_manager,
models_manager,
session_header: SessionHeader::new(resolved_model),
initial_user_message: None,
token_info: None,
@@ -1919,75 +1937,66 @@ async fn slash_init_skips_when_project_doc_exists() {
);
}
#[test]
fn parse_collaboration_mode_selection_accepts_common_aliases() {
assert_eq!(
collaboration_modes::parse_selection("plan"),
Some(CollaborationModeSelection::Plan)
);
assert_eq!(
collaboration_modes::parse_selection("PAIR"),
Some(CollaborationModeSelection::PairProgramming)
);
assert_eq!(
collaboration_modes::parse_selection("pair_programming"),
Some(CollaborationModeSelection::PairProgramming)
);
assert_eq!(
collaboration_modes::parse_selection("pp"),
Some(CollaborationModeSelection::PairProgramming)
);
assert_eq!(
collaboration_modes::parse_selection(" exec "),
Some(CollaborationModeSelection::Execute)
);
assert_eq!(
collaboration_modes::parse_selection("execute"),
Some(CollaborationModeSelection::Execute)
);
assert_eq!(collaboration_modes::parse_selection("unknown"), None);
}
#[tokio::test]
async fn collab_mode_shift_tab_cycles_only_when_enabled_and_idle() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await;
chat.set_feature_enabled(Feature::CollaborationModes, false);
let initial = chat.collaboration_mode;
let initial = chat.stored_collaboration_mode.clone();
chat.handle_key_event(KeyEvent::from(KeyCode::BackTab));
assert_eq!(chat.collaboration_mode, initial);
assert_eq!(chat.stored_collaboration_mode, initial);
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.handle_key_event(KeyEvent::from(KeyCode::BackTab));
assert_eq!(chat.collaboration_mode, CollaborationModeSelection::Execute);
assert!(matches!(
chat.stored_collaboration_mode,
CollaborationMode::Execute(_)
));
chat.handle_key_event(KeyEvent::from(KeyCode::BackTab));
assert_eq!(chat.collaboration_mode, CollaborationModeSelection::Plan);
assert!(matches!(
chat.stored_collaboration_mode,
CollaborationMode::Plan(_)
));
chat.on_task_started();
let before = chat.stored_collaboration_mode.clone();
chat.handle_key_event(KeyEvent::from(KeyCode::BackTab));
assert_eq!(chat.collaboration_mode, CollaborationModeSelection::Plan);
assert_eq!(chat.stored_collaboration_mode, before);
}
#[tokio::test]
async fn collab_slash_command_sets_mode_and_next_submit_sends_user_turn() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await;
async fn collab_slash_command_opens_picker_and_updates_mode() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.dispatch_command_with_args(SlashCommand::Collab, "plan".to_string());
assert_eq!(chat.collaboration_mode, CollaborationModeSelection::Plan);
chat.dispatch_command(SlashCommand::Collab);
let popup = render_bottom_popup(&chat, 80);
assert!(
popup.contains("Select Collaboration Mode"),
"expected collaboration picker: {popup}"
);
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
let selected_mode = match rx.try_recv() {
Ok(AppEvent::UpdateCollaborationMode(mode)) => mode,
other => panic!("expected UpdateCollaborationMode event, got {other:?}"),
};
chat.set_collaboration_mode(selected_mode);
chat.bottom_pane
.set_composer_text("hello".to_string(), Vec::new(), Vec::new());
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
match next_submit_op(&mut op_rx) {
Op::UserTurn {
collaboration_mode: Some(CollaborationMode::Plan(_)),
collaboration_mode: Some(CollaborationMode::PairProgramming(_)),
..
} => {}
other => panic!("expected Op::UserTurn with plan collab mode, got {other:?}"),
other => {
panic!("expected Op::UserTurn with pair programming collab mode, got {other:?}")
}
}
chat.bottom_pane
@@ -1995,10 +2004,12 @@ async fn collab_slash_command_sets_mode_and_next_submit_sends_user_turn() {
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
match next_submit_op(&mut op_rx) {
Op::UserTurn {
collaboration_mode: Some(CollaborationMode::Plan(_)),
collaboration_mode: Some(CollaborationMode::PairProgramming(_)),
..
} => {}
other => panic!("expected Op::UserTurn with plan collab mode, got {other:?}"),
other => {
panic!("expected Op::UserTurn with pair programming collab mode, got {other:?}")
}
}
}
@@ -2016,10 +2027,22 @@ async fn collab_mode_defaults_to_pair_programming_when_enabled() {
collaboration_mode: Some(CollaborationMode::PairProgramming(_)),
..
} => {}
other => panic!("expected Op::UserTurn with pair programming collab mode, got {other:?}"),
other => {
panic!("expected Op::UserTurn with pair programming collab mode, got {other:?}")
}
}
}
#[tokio::test]
async fn collab_mode_enabling_sets_pair_programming_default() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
assert!(matches!(
chat.stored_collaboration_mode,
CollaborationMode::PairProgramming(_)
));
}
#[tokio::test]
async fn slash_quit_requests_exit() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
@@ -2732,7 +2755,7 @@ async fn model_reasoning_selection_popup_snapshot() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await;
set_chatgpt_auth(&mut chat);
chat.config.model_reasoning_effort = Some(ReasoningEffortConfig::High);
chat.set_reasoning_effort(Some(ReasoningEffortConfig::High));
let preset = get_available_model(&chat, "gpt-5.1-codex-max");
chat.open_reasoning_popup(preset);
@@ -2746,7 +2769,7 @@ async fn model_reasoning_selection_popup_extra_high_warning_snapshot() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await;
set_chatgpt_auth(&mut chat);
chat.config.model_reasoning_effort = Some(ReasoningEffortConfig::XHigh);
chat.set_reasoning_effort(Some(ReasoningEffortConfig::XHigh));
let preset = get_available_model(&chat, "gpt-5.1-codex-max");
chat.open_reasoning_popup(preset);
+32 -118
View File
@@ -1,135 +1,49 @@
//! Collaboration mode selection + rendering helpers for the TUI.
//!
//! This module is intentionally UI-focused:
//! - It owns the user-facing set of selectable collaboration modes and how they cycle.
//! - It parses `/collab <mode>` arguments into a selection.
//! - It resolves a `Selection` to a concrete `codex_protocol::config_types::CollaborationMode` by
//! picking from the `ModelsManager` builtin collaboration presets.
//! - It builds the small footer "flash" line shown after changing modes.
//!
//! The `ChatWidget` owns the session state and decides *when* selection/mode changes are allowed
//! (feature flag, task running, modals open, etc.). This module just provides the building blocks.
use crate::key_hint;
use codex_core::models_manager::manager::ModelsManager;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::Settings;
use codex_protocol::openai_models::ReasoningEffort;
use crossterm::event::KeyCode;
use ratatui::style::Stylize;
use ratatui::text::Line;
/// The user-facing collaboration mode choices supported by the TUI.
///
/// This is distinct from `CollaborationMode`: it represents a stable UI selection and the cycling
/// order, while `CollaborationMode` can carry nested settings/prompt configuration.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Selection {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ModeKind {
Plan,
#[default]
PairProgramming,
Execute,
Custom,
}
impl Selection {
/// Cycle to the next selection.
///
/// The TUI cycles through a small, fixed set of presets.
pub(crate) fn next(self) -> Self {
match self {
Self::Plan => Self::PairProgramming,
Self::PairProgramming => Self::Execute,
Self::Execute => Self::Plan,
}
}
/// User-facing label used in UI surfaces like `/status` and the footer flash.
pub(crate) fn label(self) -> &'static str {
match self {
Self::Plan => "Plan",
Self::PairProgramming => "Pair Programming",
Self::Execute => "Execute",
}
fn mode_kind(mode: &CollaborationMode) -> ModeKind {
match mode {
CollaborationMode::Plan(_) => ModeKind::Plan,
CollaborationMode::PairProgramming(_) => ModeKind::PairProgramming,
CollaborationMode::Execute(_) => ModeKind::Execute,
CollaborationMode::Custom(_) => ModeKind::Custom,
}
}
/// Parse a user argument (e.g. `/collab plan`, `/collab pair_programming`) into a selection.
///
/// The parser is forgiving: it strips whitespace, `-`, and `_`, and matches case-insensitively.
pub(crate) fn parse_selection(input: &str) -> Option<Selection> {
let normalized: String = input
.chars()
.filter(|c| !c.is_ascii_whitespace() && *c != '-' && *c != '_')
.flat_map(char::to_lowercase)
.collect();
match normalized.as_str() {
"plan" => Some(Selection::Plan),
"pair" | "pairprogramming" | "pp" => Some(Selection::PairProgramming),
"execute" | "exec" => Some(Selection::Execute),
_ => None,
}
pub(crate) fn default_mode(models_manager: &ModelsManager) -> Option<CollaborationMode> {
let presets = models_manager.list_collaboration_modes();
presets
.iter()
.find(|preset| matches!(preset, CollaborationMode::PairProgramming(_)))
.cloned()
.or_else(|| presets.into_iter().next())
}
/// Resolve a selection to a concrete collaboration mode preset.
///
/// `ModelsManager::list_collaboration_modes()` is expected to return a builtin set of presets; this
/// function selects the first preset of the desired variant.
pub(crate) fn resolve_mode(
pub(crate) fn same_variant(a: &CollaborationMode, b: &CollaborationMode) -> bool {
mode_kind(a) == mode_kind(b)
}
/// Cycle to the next collaboration mode preset in list order.
pub(crate) fn next_mode(
models_manager: &ModelsManager,
selection: Selection,
current: &CollaborationMode,
) -> Option<CollaborationMode> {
match selection {
Selection::Plan => models_manager
.list_collaboration_modes()
.into_iter()
.find(|mode| matches!(mode, CollaborationMode::Plan(_))),
Selection::PairProgramming => models_manager
.list_collaboration_modes()
.into_iter()
.find(|mode| matches!(mode, CollaborationMode::PairProgramming(_))),
Selection::Execute => models_manager
.list_collaboration_modes()
.into_iter()
.find(|mode| matches!(mode, CollaborationMode::Execute(_))),
let presets = models_manager.list_collaboration_modes();
if presets.is_empty() {
return None;
}
}
/// Resolve a selection to a concrete collaboration mode preset, falling back to a synthesized mode
/// when the desired preset is unavailable.
///
/// This keeps the TUI behavior stable when collaboration presets are missing (for example, when
/// running in offline/unit-test contexts): if the feature flag is enabled, every submission carries
/// an explicit collaboration mode so core doesn't fall back to `Custom`.
pub(crate) fn resolve_mode_or_fallback(
models_manager: &ModelsManager,
selection: Selection,
fallback_model: &str,
fallback_effort: Option<ReasoningEffort>,
) -> CollaborationMode {
resolve_mode(models_manager, selection).unwrap_or_else(|| {
let settings = Settings {
model: fallback_model.to_string(),
reasoning_effort: fallback_effort,
developer_instructions: None,
};
match selection {
Selection::Plan => CollaborationMode::Plan(settings),
Selection::PairProgramming => CollaborationMode::PairProgramming(settings),
Selection::Execute => CollaborationMode::Execute(settings),
}
})
}
/// Build a 1-line footer "flash" that is shown after switching modes.
///
/// The `ChatWidget` controls when to show this and how long it should remain visible.
pub(crate) fn flash_line(selection: Selection) -> Line<'static> {
Line::from(vec![
selection.label().bold(),
" (".dim(),
key_hint::shift(KeyCode::Tab).into(),
" to change mode)".dim(),
])
let current_kind = mode_kind(current);
let next_index = presets
.iter()
.position(|preset| mode_kind(preset) == current_kind)
.map_or(0, |idx| (idx + 1) % presets.len());
presets.get(next_index).cloned()
}
+78 -17
View File
@@ -19,6 +19,7 @@ use crate::exec_cell::output_lines;
use crate::exec_cell::spinner;
use crate::exec_command::relativize_to_home;
use crate::exec_command::strip_bash_lc_and_escape;
use crate::key_hint;
use crate::live_wrap::take_prefix_by_width;
use crate::markdown::append_markdown;
use crate::render::line_utils::line_to_static;
@@ -43,11 +44,13 @@ use codex_core::protocol::FileChange;
use codex_core::protocol::McpAuthStatus;
use codex_core::protocol::McpInvocation;
use codex_core::protocol::SessionConfiguredEvent;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig;
use codex_protocol::plan_tool::PlanItemArg;
use codex_protocol::plan_tool::StepStatus;
use codex_protocol::plan_tool::UpdatePlanArgs;
use codex_protocol::user_input::TextElement;
use crossterm::event::KeyCode;
use image::DynamicImage;
use image::ImageReader;
use mcp_types::EmbeddedResourceResource;
@@ -903,6 +906,8 @@ pub(crate) fn new_session_info(
requested_model: &str,
event: SessionConfiguredEvent,
is_first_event: bool,
is_collaboration: bool,
collaboration_mode: CollaborationMode,
) -> SessionInfoCell {
let SessionConfiguredEvent {
model,
@@ -915,6 +920,8 @@ pub(crate) fn new_session_info(
reasoning_effort,
config.cwd.clone(),
CODEX_CLI_VERSION,
is_collaboration,
collaboration_mode,
);
let mut parts: Vec<Box<dyn HistoryCell>> = vec![Box::new(header)];
@@ -991,6 +998,8 @@ pub(crate) struct SessionHeaderHistoryCell {
model_style: Style,
reasoning_effort: Option<ReasoningEffortConfig>,
directory: PathBuf,
is_collaboration: bool,
collaboration_mode: CollaborationMode,
}
impl SessionHeaderHistoryCell {
@@ -999,6 +1008,8 @@ impl SessionHeaderHistoryCell {
reasoning_effort: Option<ReasoningEffortConfig>,
directory: PathBuf,
version: &'static str,
is_collaboration: bool,
collaboration_mode: CollaborationMode,
) -> Self {
Self::new_with_style(
model,
@@ -1006,6 +1017,8 @@ impl SessionHeaderHistoryCell {
reasoning_effort,
directory,
version,
is_collaboration,
collaboration_mode,
)
}
@@ -1015,6 +1028,8 @@ impl SessionHeaderHistoryCell {
reasoning_effort: Option<ReasoningEffortConfig>,
directory: PathBuf,
version: &'static str,
is_collaboration: bool,
collaboration_mode: CollaborationMode,
) -> Self {
Self {
version,
@@ -1022,6 +1037,20 @@ impl SessionHeaderHistoryCell {
model_style,
reasoning_effort,
directory,
is_collaboration,
collaboration_mode,
}
}
fn collaboration_mode_label(&self) -> Option<&'static str> {
if !self.is_collaboration {
return None;
}
match &self.collaboration_mode {
CollaborationMode::Plan(_) => Some("Plan"),
CollaborationMode::PairProgramming(_) => Some("Pair Programming"),
CollaborationMode::Execute(_) => Some("Execute"),
CollaborationMode::Custom(_) => None,
}
}
@@ -1082,25 +1111,49 @@ impl HistoryCell for SessionHeaderHistoryCell {
const CHANGE_MODEL_HINT_COMMAND: &str = "/model";
const CHANGE_MODEL_HINT_EXPLANATION: &str = " to change";
const CHANGE_MODE_HINT_EXPLANATION: &str = " to change mode";
const DIR_LABEL: &str = "directory:";
let label_width = DIR_LABEL.len();
let model_label = format!(
"{model_label:<label_width$}",
model_label = "model:",
label_width = label_width
);
let reasoning_label = self.reasoning_label();
let mut model_spans: Vec<Span<'static>> = vec![
Span::from(format!("{model_label} ")).dim(),
Span::styled(self.model.clone(), self.model_style),
];
if let Some(reasoning) = reasoning_label {
model_spans.push(Span::from(" "));
model_spans.push(Span::from(reasoning));
}
model_spans.push(" ".dim());
model_spans.push(CHANGE_MODEL_HINT_COMMAND.cyan());
model_spans.push(CHANGE_MODEL_HINT_EXPLANATION.dim());
let model_spans: Vec<Span<'static>> = if self.is_collaboration {
// Render collaboration mode instead of model
let collab_label = format!(
"{collab_label:<label_width$}",
collab_label = "mode:",
label_width = label_width
);
let mut spans = vec![Span::from(format!("{collab_label} ")).dim()];
if let Some(mode_label) = self.collaboration_mode_label() {
spans.push(Span::styled(mode_label.to_string(), self.model_style));
} else {
spans.push(Span::styled("Custom", self.model_style));
}
spans.push(" ".dim());
let shift_tab_span: Span<'static> = key_hint::shift(KeyCode::Tab).into();
spans.push(shift_tab_span.cyan());
spans.push(CHANGE_MODE_HINT_EXPLANATION.dim());
spans
} else {
// Render model as before
let model_label = format!(
"{model_label:<label_width$}",
model_label = "model:",
label_width = label_width
);
let reasoning_label = self.reasoning_label();
let mut spans = vec![
Span::from(format!("{model_label} ")).dim(),
Span::styled(self.model.clone(), self.model_style),
];
if let Some(reasoning) = reasoning_label {
spans.push(Span::from(" "));
spans.push(Span::from(reasoning));
}
spans.push(" ".dim());
spans.push(CHANGE_MODEL_HINT_COMMAND.cyan());
spans.push(CHANGE_MODEL_HINT_EXPLANATION.dim());
spans
};
let dir_label = format!("{DIR_LABEL:<label_width$}");
let dir_prefix = format!("{dir_label} ");
@@ -1828,6 +1881,8 @@ mod tests {
use codex_core::config::types::McpServerConfig;
use codex_core::config::types::McpServerTransportConfig;
use codex_core::protocol::McpAuthStatus;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::Settings;
use codex_protocol::parse_command::ParsedCommand;
use dirs::home_dir;
use pretty_assertions::assert_eq;
@@ -2284,6 +2339,12 @@ mod tests {
Some(ReasoningEffortConfig::High),
std::env::temp_dir(),
"test",
false,
CollaborationMode::Custom(Settings {
model: "gpt-4o".to_string(),
reasoning_effort: Some(ReasoningEffortConfig::High),
developer_instructions: None,
}),
);
let lines = render_lines(&cell.display_lines(80));
+27 -2
View File
@@ -5,7 +5,8 @@ use crate::history_cell::with_border_with_inner_width;
use crate::version::CODEX_CLI_VERSION;
use chrono::DateTime;
use chrono::Local;
use codex_common::create_config_summary_entries;
use codex_common::summarize_sandbox_policy;
use codex_core::WireApi;
use codex_core::config::Config;
use codex_core::protocol::NetworkAccess;
use codex_core::protocol::SandboxPolicy;
@@ -13,6 +14,7 @@ use codex_core::protocol::TokenUsage;
use codex_core::protocol::TokenUsageInfo;
use codex_protocol::ThreadId;
use codex_protocol::account::PlanType;
use codex_protocol::openai_models::ReasoningEffort;
use ratatui::prelude::*;
use ratatui::style::Stylize;
use std::collections::BTreeSet;
@@ -85,6 +87,7 @@ pub(crate) fn new_status_output(
now: DateTime<Local>,
model_name: &str,
collaboration_mode: Option<&str>,
reasoning_effort_override: Option<Option<ReasoningEffort>>,
) -> CompositeHistoryCell {
let command = PlainHistoryCell::new(vec!["/status".magenta().into()]);
let card = StatusHistoryCell::new(
@@ -99,6 +102,7 @@ pub(crate) fn new_status_output(
now,
model_name,
collaboration_mode,
reasoning_effort_override,
);
CompositeHistoryCell::new(vec![Box::new(command), Box::new(card)])
@@ -118,8 +122,29 @@ impl StatusHistoryCell {
now: DateTime<Local>,
model_name: &str,
collaboration_mode: Option<&str>,
reasoning_effort_override: Option<Option<ReasoningEffort>>,
) -> Self {
let config_entries = create_config_summary_entries(config, model_name);
let mut config_entries = vec![
("workdir", config.cwd.display().to_string()),
("model", model_name.to_string()),
("provider", config.model_provider_id.clone()),
("approval", config.approval_policy.value().to_string()),
(
"sandbox",
summarize_sandbox_policy(config.sandbox_policy.get()),
),
];
if config.model_provider.wire_api == WireApi::Responses {
let effort_value = reasoning_effort_override
.unwrap_or(None)
.map(|effort| effort.to_string())
.unwrap_or_else(|| "none".to_string());
config_entries.push(("reasoning effort", effort_value));
config_entries.push((
"reasoning summaries",
config.model_reasoning_summary.to_string(),
));
}
let (model_name, model_details) = compose_model_display(model_name, &config_entries);
let approval = config_entries
.iter()
+17 -2
View File
@@ -95,7 +95,6 @@ async fn status_snapshot_includes_reasoning_details() {
let mut config = test_config(&temp_home).await;
config.model = Some("gpt-5.1-codex-max".to_string());
config.model_provider_id = "openai".to_string();
config.model_reasoning_effort = Some(ReasoningEffort::High);
config.model_reasoning_summary = ReasoningSummary::Detailed;
config
.sandbox_policy
@@ -141,6 +140,7 @@ async fn status_snapshot_includes_reasoning_details() {
let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
let token_info = token_info_for(&model_slug, &config, &usage);
let reasoning_effort_override = Some(Some(ReasoningEffort::High));
let composite = new_status_output(
&config,
&auth_manager,
@@ -153,6 +153,7 @@ async fn status_snapshot_includes_reasoning_details() {
captured_at,
&model_slug,
None,
reasoning_effort_override,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -205,6 +206,7 @@ async fn status_snapshot_includes_forked_from() {
captured_at,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -263,6 +265,7 @@ async fn status_snapshot_includes_monthly_limit() {
captured_at,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -309,6 +312,7 @@ async fn status_snapshot_shows_unlimited_credits() {
captured_at,
&model_slug,
None,
None,
);
let rendered = render_lines(&composite.display_lines(120));
assert!(
@@ -354,6 +358,7 @@ async fn status_snapshot_shows_positive_credits() {
captured_at,
&model_slug,
None,
None,
);
let rendered = render_lines(&composite.display_lines(120));
assert!(
@@ -399,6 +404,7 @@ async fn status_snapshot_hides_zero_credits() {
captured_at,
&model_slug,
None,
None,
);
let rendered = render_lines(&composite.display_lines(120));
assert!(
@@ -442,6 +448,7 @@ async fn status_snapshot_hides_when_has_no_credits_flag() {
captured_at,
&model_slug,
None,
None,
);
let rendered = render_lines(&composite.display_lines(120));
assert!(
@@ -485,6 +492,7 @@ async fn status_card_token_usage_excludes_cached_tokens() {
now,
&model_slug,
None,
None,
);
let rendered = render_lines(&composite.display_lines(120));
@@ -500,7 +508,6 @@ async fn status_snapshot_truncates_in_narrow_terminal() {
let mut config = test_config(&temp_home).await;
config.model = Some("gpt-5.1-codex-max".to_string());
config.model_provider_id = "openai".to_string();
config.model_reasoning_effort = Some(ReasoningEffort::High);
config.model_reasoning_summary = ReasoningSummary::Detailed;
config.cwd = PathBuf::from("/workspace/tests");
@@ -531,6 +538,7 @@ async fn status_snapshot_truncates_in_narrow_terminal() {
let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
let token_info = token_info_for(&model_slug, &config, &usage);
let reasoning_effort_override = Some(Some(ReasoningEffort::High));
let composite = new_status_output(
&config,
&auth_manager,
@@ -543,6 +551,7 @@ async fn status_snapshot_truncates_in_narrow_terminal() {
captured_at,
&model_slug,
None,
reasoning_effort_override,
);
let mut rendered_lines = render_lines(&composite.display_lines(70));
if cfg!(windows) {
@@ -590,6 +599,7 @@ async fn status_snapshot_shows_missing_limits_message() {
now,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -655,6 +665,7 @@ async fn status_snapshot_includes_credits_and_limits() {
captured_at,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -708,6 +719,7 @@ async fn status_snapshot_shows_empty_limits_message() {
captured_at,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -770,6 +782,7 @@ async fn status_snapshot_shows_stale_limits_message() {
now,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -836,6 +849,7 @@ async fn status_snapshot_cached_limits_hide_credits_without_flag() {
now,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -892,6 +906,7 @@ async fn status_context_window_uses_last_usage() {
now,
&model_slug,
None,
None,
);
let rendered_lines = render_lines(&composite.display_lines(80));
let context_line = rendered_lines
+19 -18
View File
@@ -317,7 +317,6 @@ async fn handle_model_migration_prompt_if_needed(
from_model: model.to_string(),
to_model: target_model.clone(),
});
config.model = Some(target_model.clone());
let mapped_effort = if let Some(reasoning_effort_mapping) = reasoning_effort_mapping
&& let Some(reasoning_effort) = config.model_reasoning_effort
@@ -330,8 +329,8 @@ async fn handle_model_migration_prompt_if_needed(
config.model_reasoning_effort
};
config.model = Some(target_model.clone());
config.model_reasoning_effort = mapped_effort;
app_event_tx.send(AppEvent::UpdateModel(target_model.clone()));
app_event_tx.send(AppEvent::UpdateReasoningEffort(mapped_effort));
app_event_tx.send(AppEvent::PersistModelSelection {
@@ -367,7 +366,6 @@ pub(crate) struct App {
pub(crate) auth_manager: Arc<AuthManager>,
/// Config is stored here so we can recreate ChatWidgets as needed.
pub(crate) config: Config,
pub(crate) current_model: String,
pub(crate) active_profile: Option<String>,
pub(crate) file_search: FileSearchManager,
@@ -451,7 +449,7 @@ impl App {
models_manager: self.server.get_models_manager(),
feedback: self.feedback.clone(),
is_first_run: false,
model: Some(self.current_model.clone()),
model: Some(self.chat_widget.current_model().to_string()),
}
}
@@ -530,7 +528,7 @@ impl App {
models_manager: thread_manager.get_models_manager(),
feedback: feedback.clone(),
is_first_run,
model: config.model.clone(),
model: Some(model.clone()),
};
ChatWidget::new(init, thread_manager.clone())
}
@@ -618,7 +616,6 @@ impl App {
chat_widget,
auth_manager: auth_manager.clone(),
config,
current_model: model.clone(),
active_profile,
file_search,
enhanced_keys_supported,
@@ -1507,6 +1504,9 @@ impl App {
async fn handle_event(&mut self, tui: &mut tui::Tui, event: AppEvent) -> Result<AppRunControl> {
match event {
AppEvent::NewSession => {
let model = self.chat_widget.current_model().to_string();
// Propagate selected model into config before spawning thread
self.config.model = Some(model.clone());
let summary = session_summary(
self.chat_widget.token_usage(),
self.chat_widget.conversation_id(),
@@ -1526,7 +1526,7 @@ impl App {
models_manager: self.server.get_models_manager(),
feedback: self.feedback.clone(),
is_first_run: false,
model: Some(self.current_model.clone()),
model: Some(model),
};
self.chat_widget = ChatWidget::new(init, self.server.clone());
if let Some(summary) = summary {
@@ -1808,7 +1808,11 @@ impl App {
}
AppEvent::UpdateModel(model) => {
self.chat_widget.set_model(&model);
self.current_model = model;
}
AppEvent::UpdateCollaborationMode(mode) => {
let model = mode.model().to_string();
self.chat_widget.set_collaboration_mode(mode);
self.chat_widget.set_model(&model);
}
AppEvent::OpenReasoningPopup { model } => {
self.chat_widget.open_reasoning_popup(model);
@@ -2321,8 +2325,10 @@ impl App {
}
fn on_update_reasoning_effort(&mut self, effort: Option<ReasoningEffortConfig>) {
self.chat_widget.set_reasoning_effort(effort);
// TODO(aibrahim): Remove this and don't use config as a state object.
// Instead, explicitly pass the stored collaboration mode's effort into new sessions.
self.config.model_reasoning_effort = effort;
self.chat_widget.set_reasoning_effort(effort);
}
async fn handle_key_event(&mut self, tui: &mut tui::Tui, key_event: KeyEvent) {
@@ -2543,7 +2549,6 @@ mod tests {
async fn make_test_app() -> App {
let (chat_widget, app_event_tx, _rx, _op_rx) = make_chatwidget_manual_with_sender().await;
let config = chat_widget.config_ref().clone();
let current_model = "gpt-5.2-codex".to_string();
let server = Arc::new(ThreadManager::with_models_provider(
CodexAuth::from_api_key("Test API Key"),
config.model_provider.clone(),
@@ -2558,7 +2563,6 @@ mod tests {
chat_widget,
auth_manager,
config,
current_model,
active_profile: None,
file_search,
transcript_cells: Vec::new(),
@@ -2599,7 +2603,6 @@ mod tests {
) {
let (chat_widget, app_event_tx, rx, op_rx) = make_chatwidget_manual_with_sender().await;
let config = chat_widget.config_ref().clone();
let current_model = "gpt-5.2-codex".to_string();
let server = Arc::new(ThreadManager::with_models_provider(
CodexAuth::from_api_key("Test API Key"),
config.model_provider.clone(),
@@ -2615,7 +2618,6 @@ mod tests {
chat_widget,
auth_manager,
config,
current_model,
active_profile: None,
file_search,
transcript_cells: Vec::new(),
@@ -2817,20 +2819,19 @@ mod tests {
}
#[tokio::test]
async fn update_reasoning_effort_updates_config() {
async fn update_reasoning_effort_updates_collaboration_mode() {
let mut app = make_test_app().await;
app.config.model_reasoning_effort = Some(ReasoningEffortConfig::Medium);
app.chat_widget
.set_reasoning_effort(Some(ReasoningEffortConfig::Medium));
app.on_update_reasoning_effort(Some(ReasoningEffortConfig::High));
assert_eq!(
app.config.model_reasoning_effort,
app.chat_widget.current_reasoning_effort(),
Some(ReasoningEffortConfig::High)
);
assert_eq!(
app.chat_widget.config_ref().model_reasoning_effort,
app.config.model_reasoning_effort,
Some(ReasoningEffortConfig::High)
);
}
@@ -2870,7 +2871,7 @@ mod tests {
};
Arc::new(new_session_info(
app.chat_widget.config_ref(),
app.current_model.as_str(),
app.chat_widget.current_model(),
event,
is_first,
)) as Arc<dyn HistoryCell>
+4
View File
@@ -22,6 +22,7 @@ use crate::history_cell::HistoryCell;
use codex_core::protocol::AskForApproval;
use codex_core::protocol::SandboxPolicy;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::openai_models::ReasoningEffort;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -102,6 +103,9 @@ pub(crate) enum AppEvent {
/// Update the current model slug in the running app and widget.
UpdateModel(String),
/// Update the current collaboration mode in the running app and widget.
UpdateCollaborationMode(CollaborationMode),
/// Persist the selected model and reasoning effort to the appropriate config.
PersistModelSelection {
model: String,
+191 -68
View File
@@ -90,6 +90,8 @@ use codex_core::skills::model::SkillMetadata;
use codex_protocol::ThreadId;
use codex_protocol::account::PlanType;
use codex_protocol::approvals::ElicitationRequestEvent;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::Settings;
use codex_protocol::models::local_image_label_text;
use codex_protocol::parse_command::ParsedCommand;
use codex_protocol::user_input::TextElement;
@@ -319,8 +321,6 @@ enum RateLimitSwitchPromptState {
Shown,
}
type CollaborationModeSelection = collaboration_modes::Selection;
/// Maintains the per-session UI state and interaction state machines for the chat screen.
///
/// `ChatWidget` owns the state derived from the protocol event stream (history cells, streaming
@@ -349,12 +349,12 @@ pub(crate) struct ChatWidget {
/// where the overlay may briefly treat new tail content as already cached.
active_cell_revision: u64,
config: Config,
model: Option<String>,
/// Current UI selection for collaboration modes.
/// Stored collaboration mode with model and reasoning effort.
///
/// This selection is only meaningful when `Feature::CollaborationModes` is enabled; when the
/// feature is disabled, the value is effectively inert.
collaboration_mode: CollaborationModeSelection,
/// When collaboration modes feature is enabled, this is initialized to the first preset.
/// When disabled, this is Custom. The model and reasoning effort are stored here instead of
/// being read from config or current_model.
stored_collaboration_mode: CollaborationMode,
auth_manager: Arc<AuthManager>,
models_manager: Arc<ModelsManager>,
session_header: SessionHeader,
@@ -631,8 +631,17 @@ impl ChatWidget {
self.current_rollout_path = Some(event.rollout_path.clone());
let initial_messages = event.initial_messages.clone();
let model_for_header = event.model.clone();
self.model = Some(model_for_header.clone());
self.session_header.set_model(&model_for_header);
// Only update stored collaboration settings when collaboration modes are disabled.
// When enabled, we preserve the selected variant (Plan/Pair/Execute/Custom) and its
// instructions as-is; the session configured event should not override it.
if !self.collaboration_modes_enabled() {
self.stored_collaboration_mode = self.stored_collaboration_mode.with_updates(
Some(model_for_header.clone()),
Some(event.reasoning_effort),
None,
);
}
let session_info_cell = history_cell::new_session_info(
&self.config,
&model_for_header,
@@ -876,7 +885,7 @@ impl ChatWidget {
if high_usage
&& !self.rate_limit_switch_prompt_hidden()
&& self.current_model() != Some(NUDGE_MODEL_SLUG)
&& self.current_model() != NUDGE_MODEL_SLUG
&& !matches!(
self.rate_limit_switch_prompt,
RateLimitSwitchPromptState::Shown
@@ -1591,15 +1600,14 @@ impl ChatWidget {
is_first_run,
model,
} = common;
let mut config = config;
let model = model.filter(|m| !m.trim().is_empty());
let mut config = config;
config.model = model.clone();
let mut rng = rand::rng();
let placeholder = PLACEHOLDERS[rng.random_range(0..PLACEHOLDERS.len())].to_string();
let codex_op_tx = spawn_agent(config.clone(), app_event_tx.clone(), thread_manager);
let model_for_header = config
.model
let model_for_header = model
.clone()
.unwrap_or_else(|| DEFAULT_MODEL_DISPLAY_NAME.to_string());
let active_cell = if model.is_none() {
@@ -1608,6 +1616,22 @@ impl ChatWidget {
None
};
let stored_collaboration_mode = if config.features.enabled(Feature::CollaborationModes) {
collaboration_modes::default_mode(models_manager.as_ref()).unwrap_or_else(|| {
CollaborationMode::Custom(Settings {
model: model_for_header.clone(),
reasoning_effort: None,
developer_instructions: None,
})
})
} else {
CollaborationMode::Custom(Settings {
model: model_for_header.clone(),
reasoning_effort: None,
developer_instructions: None,
})
};
let mut widget = Self {
app_event_tx: app_event_tx.clone(),
frame_requester: frame_requester.clone(),
@@ -1625,8 +1649,7 @@ impl ChatWidget {
active_cell,
active_cell_revision: 0,
config,
model,
collaboration_mode: CollaborationModeSelection::default(),
stored_collaboration_mode,
auth_manager,
models_manager,
session_header: SessionHeader::new(model_for_header),
@@ -1684,7 +1707,7 @@ impl ChatWidget {
session_configured: codex_core::protocol::SessionConfiguredEvent,
) -> Self {
let ChatWidgetInit {
mut config,
config,
frame_requester,
app_event_tx,
initial_user_message,
@@ -1696,7 +1719,7 @@ impl ChatWidget {
..
} = common;
let model = model.filter(|m| !m.trim().is_empty());
config.model = model.clone();
let config = config;
let mut rng = rand::rng();
let placeholder = PLACEHOLDERS[rng.random_range(0..PLACEHOLDERS.len())].to_string();
@@ -1705,6 +1728,22 @@ impl ChatWidget {
let codex_op_tx =
spawn_agent_from_existing(conversation, session_configured, app_event_tx.clone());
let stored_collaboration_mode = if config.features.enabled(Feature::CollaborationModes) {
collaboration_modes::default_mode(models_manager.as_ref()).unwrap_or_else(|| {
CollaborationMode::Custom(Settings {
model: header_model.clone(),
reasoning_effort: None,
developer_instructions: None,
})
})
} else {
CollaborationMode::Custom(Settings {
model: header_model.clone(),
reasoning_effort: None,
developer_instructions: None,
})
};
let mut widget = Self {
app_event_tx: app_event_tx.clone(),
frame_requester: frame_requester.clone(),
@@ -1722,8 +1761,7 @@ impl ChatWidget {
active_cell: None,
active_cell_revision: 0,
config,
model: Some(header_model.clone()),
collaboration_mode: CollaborationModeSelection::default(),
stored_collaboration_mode,
auth_manager,
models_manager,
session_header: SessionHeader::new(header_model),
@@ -1976,7 +2014,7 @@ impl ChatWidget {
}
SlashCommand::Collab => {
if self.collaboration_modes_enabled() {
self.cycle_collaboration_mode();
self.open_collaboration_modes_popup();
}
}
SlashCommand::Approvals => {
@@ -2144,13 +2182,8 @@ impl ChatWidget {
return;
}
if let Some(selection) = collaboration_modes::parse_selection(trimmed) {
self.set_collaboration_mode(selection);
} else if !trimmed.is_empty() {
self.add_error_message(format!(
"Unknown collaboration mode '{trimmed}'. Try: plan, pair, execute."
));
}
let _ = trimmed;
self.open_collaboration_modes_popup();
}
_ => self.dispatch_command(cmd),
}
@@ -2217,13 +2250,12 @@ impl ChatWidget {
}
fn submit_user_message(&mut self, user_message: UserMessage) {
let Some(model) = self.current_model().or(self.config.model.as_deref()) else {
tracing::warn!("cannot submit user message before model is known; queueing");
if !self.is_session_configured() {
tracing::warn!("cannot submit user message before session is configured; queueing");
self.queued_user_messages.push_front(user_message);
self.refresh_queued_user_messages();
return;
};
let model = model.to_string();
}
let UserMessage {
text,
@@ -2277,24 +2309,18 @@ impl ChatWidget {
}
}
let collaboration_mode = self.collaboration_modes_enabled().then(|| {
collaboration_modes::resolve_mode_or_fallback(
self.models_manager.as_ref(),
self.collaboration_mode,
model.as_str(),
self.config.model_reasoning_effort,
)
});
let op = Op::UserTurn {
items,
cwd: self.config.cwd.clone(),
approval_policy: self.config.approval_policy.value(),
sandbox_policy: self.config.sandbox_policy.get().clone(),
model,
effort: self.config.model_reasoning_effort,
model: self.stored_collaboration_mode.model().to_string(),
effort: self.stored_collaboration_mode.reasoning_effort(),
summary: self.config.model_reasoning_summary,
final_output_json_schema: None,
collaboration_mode,
collaboration_mode: self
.collaboration_modes_enabled()
.then(|| self.stored_collaboration_mode.clone()),
};
if !self.agent_turn_running {
@@ -2632,6 +2658,7 @@ impl ChatWidget {
let total_usage = token_info
.map(|ti| &ti.total_token_usage)
.unwrap_or(&default_usage);
let reasoning_effort_override = Some(self.stored_collaboration_mode.reasoning_effort());
self.add_to_history(crate::status::new_status_output(
&self.config,
self.auth_manager.as_ref(),
@@ -2643,8 +2670,8 @@ impl ChatWidget {
self.plan_type,
Local::now(),
self.model_display_name(),
self.collaboration_modes_enabled()
.then_some(self.collaboration_mode.label()),
self.collaboration_mode_label(),
reasoning_effort_override,
));
}
fn stop_rate_limit_poller(&mut self) {
@@ -2819,7 +2846,7 @@ impl ChatWidget {
let current_model = self.current_model();
let current_label = presets
.iter()
.find(|preset| Some(preset.model.as_str()) == current_model)
.find(|preset| preset.model.as_str() == current_model)
.map(|preset| preset.display_name.to_string())
.unwrap_or_else(|| self.model_display_name().to_string());
@@ -2847,7 +2874,7 @@ impl ChatWidget {
SelectionItem {
name: preset.display_name.clone(),
description,
is_current: Some(model.as_str()) == current_model,
is_current: model.as_str() == current_model,
is_default: preset.is_default,
actions,
dismiss_on_select: true,
@@ -2914,7 +2941,7 @@ impl ChatWidget {
for preset in presets.into_iter() {
let description =
(!preset.description.is_empty()).then_some(preset.description.to_string());
let is_current = Some(preset.model.as_str()) == self.current_model();
let is_current = preset.model.as_str() == self.current_model();
let single_supported_effort = preset.supported_reasoning_efforts.len() == 1;
let preset_for_action = preset.clone();
let actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
@@ -2946,6 +2973,49 @@ impl ChatWidget {
});
}
pub(crate) fn open_collaboration_modes_popup(&mut self) {
let presets = self.models_manager.list_collaboration_modes();
if presets.is_empty() {
self.add_info_message(
"No collaboration modes are available right now.".to_string(),
None,
);
return;
}
let items: Vec<SelectionItem> = presets
.into_iter()
.map(|preset| {
let name = match preset {
CollaborationMode::Plan(_) => "Plan",
CollaborationMode::PairProgramming(_) => "Pair Programming",
CollaborationMode::Execute(_) => "Execute",
CollaborationMode::Custom(_) => "Custom",
};
let is_current =
collaboration_modes::same_variant(&self.stored_collaboration_mode, &preset);
let actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
tx.send(AppEvent::UpdateCollaborationMode(preset.clone()));
})];
SelectionItem {
name: name.to_string(),
is_current,
actions,
dismiss_on_select: true,
..Default::default()
}
})
.collect();
self.bottom_pane.show_selection_view(SelectionViewParams {
title: Some("Select Collaboration Mode".to_string()),
subtitle: Some("Pick a collaboration preset.".to_string()),
footer_hint: Some(standard_popup_hint_line()),
items,
..Default::default()
});
}
fn model_selection_actions(
model_for_action: String,
effort_for_action: Option<ReasoningEffortConfig>,
@@ -3041,9 +3111,9 @@ impl ChatWidget {
.or(Some(default_effort));
let model_slug = preset.model.to_string();
let is_current_model = self.current_model() == Some(preset.model.as_str());
let is_current_model = self.current_model() == preset.model.as_str();
let highlight_choice = if is_current_model {
self.config.model_reasoning_effort
self.stored_collaboration_mode.reasoning_effort()
} else {
default_choice
};
@@ -3822,6 +3892,18 @@ impl ChatWidget {
}
if feature == Feature::CollaborationModes {
self.bottom_pane.set_collaboration_modes_enabled(enabled);
let settings = match &self.stored_collaboration_mode {
CollaborationMode::Plan(settings)
| CollaborationMode::PairProgramming(settings)
| CollaborationMode::Execute(settings)
| CollaborationMode::Custom(settings) => settings.clone(),
};
self.stored_collaboration_mode = if enabled {
collaboration_modes::default_mode(self.models_manager.as_ref())
.unwrap_or(CollaborationMode::Custom(settings))
} else {
CollaborationMode::Custom(settings)
};
}
}
@@ -3848,19 +3930,32 @@ impl ChatWidget {
.unwrap_or(false)
}
/// Set the reasoning effort in the widget's config copy.
/// Set the reasoning effort in the stored collaboration mode.
pub(crate) fn set_reasoning_effort(&mut self, effort: Option<ReasoningEffortConfig>) {
self.config.model_reasoning_effort = effort;
self.stored_collaboration_mode =
self.stored_collaboration_mode
.with_updates(None, Some(effort), None);
}
/// Set the model in the widget's config copy.
/// Set the model in the widget's config copy and stored collaboration mode.
pub(crate) fn set_model(&mut self, model: &str) {
self.session_header.set_model(model);
self.model = Some(model.to_string());
self.stored_collaboration_mode =
self.stored_collaboration_mode
.with_updates(Some(model.to_string()), None, None);
}
fn current_model(&self) -> Option<&str> {
self.model.as_deref()
pub(crate) fn current_model(&self) -> &str {
self.stored_collaboration_mode.model()
}
#[cfg(test)]
pub(crate) fn current_reasoning_effort(&self) -> Option<ReasoningEffortConfig> {
self.stored_collaboration_mode.reasoning_effort()
}
fn is_session_configured(&self) -> bool {
self.conversation_id.is_some()
}
fn collaboration_modes_enabled(&self) -> bool {
@@ -3868,31 +3963,63 @@ impl ChatWidget {
}
fn model_display_name(&self) -> &str {
self.model.as_deref().unwrap_or(DEFAULT_MODEL_DISPLAY_NAME)
let model = self.current_model();
if model.is_empty() {
DEFAULT_MODEL_DISPLAY_NAME
} else {
model
}
}
/// Get the label for the current collaboration mode.
fn collaboration_mode_label(&self) -> Option<&'static str> {
if !self.collaboration_modes_enabled() {
return None;
}
match &self.stored_collaboration_mode {
CollaborationMode::Plan(_) => Some("Plan"),
CollaborationMode::PairProgramming(_) => Some("Pair Programming"),
CollaborationMode::Execute(_) => Some("Execute"),
CollaborationMode::Custom(_) => None,
}
}
/// Cycle to the next collaboration mode variant (Plan -> PairProgramming -> Execute -> Plan).
fn cycle_collaboration_mode(&mut self) {
if !self.collaboration_modes_enabled() {
return;
}
let next = self.collaboration_mode.next();
self.set_collaboration_mode(next);
if let Some(next_mode) = collaboration_modes::next_mode(
self.models_manager.as_ref(),
&self.stored_collaboration_mode,
) {
self.set_collaboration_mode(next_mode);
}
}
/// Update the selected collaboration mode.
/// Update the stored collaboration mode.
///
/// When collaboration modes are enabled, the current selection is attached to *every*
/// When collaboration modes are enabled, the current mode is attached to *every*
/// submission as `Op::UserTurn { collaboration_mode: Some(...) }`.
fn set_collaboration_mode(&mut self, selection: CollaborationModeSelection) {
pub(crate) fn set_collaboration_mode(&mut self, mode: CollaborationMode) {
if !self.collaboration_modes_enabled() {
return;
}
self.collaboration_mode = selection;
let flash = collaboration_modes::flash_line(selection);
const FLASH_DURATION: Duration = Duration::from_secs(2);
self.bottom_pane.flash_footer_hint(flash, FLASH_DURATION);
self.stored_collaboration_mode = mode;
let label = self.collaboration_mode_label();
if let Some(label) = label {
let flash = Line::from(vec![
label.bold(),
" (".dim(),
key_hint::shift(KeyCode::Tab).into(),
" to change mode)".dim(),
]);
const FLASH_DURATION: Duration = Duration::from_secs(2);
self.bottom_pane.flash_footer_hint(flash, FLASH_DURATION);
}
self.request_redraw();
}
@@ -4335,10 +4462,6 @@ impl ChatWidget {
self.current_rollout_path.clone()
}
fn is_session_configured(&self) -> bool {
self.conversation_id.is_some()
}
/// Returns a cache key describing the current in-flight active cell for the transcript overlay.
///
/// `Ctrl+T` renders committed transcript cells plus a render-only live tail derived from the
+75 -51
View File
@@ -60,6 +60,7 @@ use codex_core::protocol::WarningEvent;
use codex_protocol::ThreadId;
use codex_protocol::account::PlanType;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::Settings;
use codex_protocol::openai_models::ModelPreset;
use codex_protocol::openai_models::ReasoningEffortPreset;
use codex_protocol::parse_command::ParsedCommand;
@@ -702,13 +703,14 @@ async fn helpers_are_available_and_do_not_panic() {
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
let tx = AppEventSender::new(tx_raw);
let cfg = test_config().await;
let model = cfg.model.clone();
let thread_manager = Arc::new(ThreadManager::with_models_provider(
CodexAuth::from_api_key("test"),
cfg.model_provider.clone(),
));
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test"));
let init = ChatWidgetInit {
config: cfg.clone(),
config: cfg,
frame_requester: FrameRequester::test_dummy(),
app_event_tx: tx,
initial_user_message: None,
@@ -717,7 +719,7 @@ async fn helpers_are_available_and_do_not_panic() {
models_manager: thread_manager.get_models_manager(),
feedback: codex_feedback::CodexFeedback::new(),
is_first_run: true,
model: cfg.model,
model,
};
let mut w = ChatWidget::new(init, thread_manager);
// Basic construction sanity.
@@ -756,6 +758,24 @@ async fn make_chatwidget_manual(
bottom.set_collaboration_modes_enabled(cfg.features.enabled(Feature::CollaborationModes));
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test"));
let codex_home = cfg.codex_home.clone();
let models_manager = Arc::new(ModelsManager::new(codex_home, auth_manager.clone()));
let collaboration_modes_enabled = cfg.features.enabled(Feature::CollaborationModes);
let reasoning_effort = None;
let stored_collaboration_mode = if collaboration_modes_enabled {
collaboration_modes::default_mode(models_manager.as_ref()).unwrap_or_else(|| {
CollaborationMode::Custom(Settings {
model: resolved_model.clone(),
reasoning_effort,
developer_instructions: None,
})
})
} else {
CollaborationMode::Custom(Settings {
model: resolved_model.clone(),
reasoning_effort,
developer_instructions: None,
})
};
let widget = ChatWidget {
app_event_tx,
codex_op_tx: op_tx,
@@ -763,10 +783,9 @@ async fn make_chatwidget_manual(
active_cell: None,
active_cell_revision: 0,
config: cfg,
model: Some(resolved_model.clone()),
collaboration_mode: CollaborationModeSelection::default(),
auth_manager: auth_manager.clone(),
models_manager: Arc::new(ModelsManager::new(codex_home, auth_manager)),
stored_collaboration_mode,
auth_manager,
models_manager,
session_header: SessionHeader::new(resolved_model),
initial_user_message: None,
token_info: None,
@@ -1699,75 +1718,66 @@ async fn slash_init_skips_when_project_doc_exists() {
);
}
#[test]
fn parse_collaboration_mode_selection_accepts_common_aliases() {
assert_eq!(
collaboration_modes::parse_selection("plan"),
Some(CollaborationModeSelection::Plan)
);
assert_eq!(
collaboration_modes::parse_selection("PAIR"),
Some(CollaborationModeSelection::PairProgramming)
);
assert_eq!(
collaboration_modes::parse_selection("pair_programming"),
Some(CollaborationModeSelection::PairProgramming)
);
assert_eq!(
collaboration_modes::parse_selection("pp"),
Some(CollaborationModeSelection::PairProgramming)
);
assert_eq!(
collaboration_modes::parse_selection(" exec "),
Some(CollaborationModeSelection::Execute)
);
assert_eq!(
collaboration_modes::parse_selection("execute"),
Some(CollaborationModeSelection::Execute)
);
assert_eq!(collaboration_modes::parse_selection("unknown"), None);
}
#[tokio::test]
async fn collab_mode_shift_tab_cycles_only_when_enabled_and_idle() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await;
chat.set_feature_enabled(Feature::CollaborationModes, false);
let initial = chat.collaboration_mode;
let initial = chat.stored_collaboration_mode.clone();
chat.handle_key_event(KeyEvent::from(KeyCode::BackTab));
assert_eq!(chat.collaboration_mode, initial);
assert_eq!(chat.stored_collaboration_mode, initial);
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.handle_key_event(KeyEvent::from(KeyCode::BackTab));
assert_eq!(chat.collaboration_mode, CollaborationModeSelection::Execute);
assert!(matches!(
chat.stored_collaboration_mode,
CollaborationMode::Execute(_)
));
chat.handle_key_event(KeyEvent::from(KeyCode::BackTab));
assert_eq!(chat.collaboration_mode, CollaborationModeSelection::Plan);
assert!(matches!(
chat.stored_collaboration_mode,
CollaborationMode::Plan(_)
));
chat.on_task_started();
let before = chat.stored_collaboration_mode.clone();
chat.handle_key_event(KeyEvent::from(KeyCode::BackTab));
assert_eq!(chat.collaboration_mode, CollaborationModeSelection::Plan);
assert_eq!(chat.stored_collaboration_mode, before);
}
#[tokio::test]
async fn collab_slash_command_sets_mode_and_next_submit_sends_user_turn() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await;
async fn collab_slash_command_opens_picker_and_updates_mode() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await;
chat.conversation_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.dispatch_command_with_args(SlashCommand::Collab, "plan".to_string());
assert_eq!(chat.collaboration_mode, CollaborationModeSelection::Plan);
chat.dispatch_command(SlashCommand::Collab);
let popup = render_bottom_popup(&chat, 80);
assert!(
popup.contains("Select Collaboration Mode"),
"expected collaboration picker: {popup}"
);
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
let selected_mode = match rx.try_recv() {
Ok(AppEvent::UpdateCollaborationMode(mode)) => mode,
other => panic!("expected UpdateCollaborationMode event, got {other:?}"),
};
chat.set_collaboration_mode(selected_mode);
chat.bottom_pane
.set_composer_text("hello".to_string(), Vec::new(), Vec::new());
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
match next_submit_op(&mut op_rx) {
Op::UserTurn {
collaboration_mode: Some(CollaborationMode::Plan(_)),
collaboration_mode: Some(CollaborationMode::PairProgramming(_)),
..
} => {}
other => panic!("expected Op::UserTurn with plan collab mode, got {other:?}"),
other => {
panic!("expected Op::UserTurn with pair programming collab mode, got {other:?}")
}
}
chat.bottom_pane
@@ -1775,10 +1785,12 @@ async fn collab_slash_command_sets_mode_and_next_submit_sends_user_turn() {
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
match next_submit_op(&mut op_rx) {
Op::UserTurn {
collaboration_mode: Some(CollaborationMode::Plan(_)),
collaboration_mode: Some(CollaborationMode::PairProgramming(_)),
..
} => {}
other => panic!("expected Op::UserTurn with plan collab mode, got {other:?}"),
other => {
panic!("expected Op::UserTurn with pair programming collab mode, got {other:?}")
}
}
}
@@ -1796,10 +1808,22 @@ async fn collab_mode_defaults_to_pair_programming_when_enabled() {
collaboration_mode: Some(CollaborationMode::PairProgramming(_)),
..
} => {}
other => panic!("expected Op::UserTurn with pair programming collab mode, got {other:?}"),
other => {
panic!("expected Op::UserTurn with pair programming collab mode, got {other:?}")
}
}
}
#[tokio::test]
async fn collab_mode_enabling_sets_pair_programming_default() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
assert!(matches!(
chat.stored_collaboration_mode,
CollaborationMode::PairProgramming(_)
));
}
#[tokio::test]
async fn slash_quit_requests_exit() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
@@ -2446,7 +2470,7 @@ async fn model_reasoning_selection_popup_snapshot() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await;
set_chatgpt_auth(&mut chat);
chat.config.model_reasoning_effort = Some(ReasoningEffortConfig::High);
chat.set_reasoning_effort(Some(ReasoningEffortConfig::High));
let preset = get_available_model(&chat, "gpt-5.1-codex-max");
chat.open_reasoning_popup(preset);
@@ -2460,7 +2484,7 @@ async fn model_reasoning_selection_popup_extra_high_warning_snapshot() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await;
set_chatgpt_auth(&mut chat);
chat.config.model_reasoning_effort = Some(ReasoningEffortConfig::XHigh);
chat.set_reasoning_effort(Some(ReasoningEffortConfig::XHigh));
let preset = get_available_model(&chat, "gpt-5.1-codex-max");
chat.open_reasoning_popup(preset);
+32 -118
View File
@@ -1,135 +1,49 @@
//! Collaboration mode selection + rendering helpers for the TUI.
//!
//! This module is intentionally UI-focused:
//! - It owns the user-facing set of selectable collaboration modes and how they cycle.
//! - It parses `/collab <mode>` arguments into a selection.
//! - It resolves a `Selection` to a concrete `codex_protocol::config_types::CollaborationMode` by
//! picking from the `ModelsManager` builtin collaboration presets.
//! - It builds the small footer "flash" line shown after changing modes.
//!
//! The `ChatWidget` owns the session state and decides *when* selection/mode changes are allowed
//! (feature flag, task running, modals open, etc.). This module just provides the building blocks.
use crate::key_hint;
use codex_core::models_manager::manager::ModelsManager;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::Settings;
use codex_protocol::openai_models::ReasoningEffort;
use crossterm::event::KeyCode;
use ratatui::style::Stylize;
use ratatui::text::Line;
/// The user-facing collaboration mode choices supported by the TUI.
///
/// This is distinct from `CollaborationMode`: it represents a stable UI selection and the cycling
/// order, while `CollaborationMode` can carry nested settings/prompt configuration.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Selection {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ModeKind {
Plan,
#[default]
PairProgramming,
Execute,
Custom,
}
impl Selection {
/// Cycle to the next selection.
///
/// The TUI cycles through a small, fixed set of presets.
pub(crate) fn next(self) -> Self {
match self {
Self::Plan => Self::PairProgramming,
Self::PairProgramming => Self::Execute,
Self::Execute => Self::Plan,
}
}
/// User-facing label used in UI surfaces like `/status` and the footer flash.
pub(crate) fn label(self) -> &'static str {
match self {
Self::Plan => "Plan",
Self::PairProgramming => "Pair Programming",
Self::Execute => "Execute",
}
fn mode_kind(mode: &CollaborationMode) -> ModeKind {
match mode {
CollaborationMode::Plan(_) => ModeKind::Plan,
CollaborationMode::PairProgramming(_) => ModeKind::PairProgramming,
CollaborationMode::Execute(_) => ModeKind::Execute,
CollaborationMode::Custom(_) => ModeKind::Custom,
}
}
/// Parse a user argument (e.g. `/collab plan`, `/collab pair_programming`) into a selection.
///
/// The parser is forgiving: it strips whitespace, `-`, and `_`, and matches case-insensitively.
pub(crate) fn parse_selection(input: &str) -> Option<Selection> {
let normalized: String = input
.chars()
.filter(|c| !c.is_ascii_whitespace() && *c != '-' && *c != '_')
.flat_map(char::to_lowercase)
.collect();
match normalized.as_str() {
"plan" => Some(Selection::Plan),
"pair" | "pairprogramming" | "pp" => Some(Selection::PairProgramming),
"execute" | "exec" => Some(Selection::Execute),
_ => None,
}
pub(crate) fn default_mode(models_manager: &ModelsManager) -> Option<CollaborationMode> {
let presets = models_manager.list_collaboration_modes();
presets
.iter()
.find(|preset| matches!(preset, CollaborationMode::PairProgramming(_)))
.cloned()
.or_else(|| presets.into_iter().next())
}
/// Resolve a selection to a concrete collaboration mode preset.
///
/// `ModelsManager::list_collaboration_modes()` is expected to return a builtin set of presets; this
/// function selects the first preset of the desired variant.
pub(crate) fn resolve_mode(
pub(crate) fn same_variant(a: &CollaborationMode, b: &CollaborationMode) -> bool {
mode_kind(a) == mode_kind(b)
}
/// Cycle to the next collaboration mode preset in list order.
pub(crate) fn next_mode(
models_manager: &ModelsManager,
selection: Selection,
current: &CollaborationMode,
) -> Option<CollaborationMode> {
match selection {
Selection::Plan => models_manager
.list_collaboration_modes()
.into_iter()
.find(|mode| matches!(mode, CollaborationMode::Plan(_))),
Selection::PairProgramming => models_manager
.list_collaboration_modes()
.into_iter()
.find(|mode| matches!(mode, CollaborationMode::PairProgramming(_))),
Selection::Execute => models_manager
.list_collaboration_modes()
.into_iter()
.find(|mode| matches!(mode, CollaborationMode::Execute(_))),
let presets = models_manager.list_collaboration_modes();
if presets.is_empty() {
return None;
}
}
/// Resolve a selection to a concrete collaboration mode preset, falling back to a synthesized mode
/// when the desired preset is unavailable.
///
/// This keeps the TUI behavior stable when collaboration presets are missing (for example, when
/// running in offline/unit-test contexts): if the feature flag is enabled, every submission carries
/// an explicit collaboration mode so core doesn't fall back to `Custom`.
pub(crate) fn resolve_mode_or_fallback(
models_manager: &ModelsManager,
selection: Selection,
fallback_model: &str,
fallback_effort: Option<ReasoningEffort>,
) -> CollaborationMode {
resolve_mode(models_manager, selection).unwrap_or_else(|| {
let settings = Settings {
model: fallback_model.to_string(),
reasoning_effort: fallback_effort,
developer_instructions: None,
};
match selection {
Selection::Plan => CollaborationMode::Plan(settings),
Selection::PairProgramming => CollaborationMode::PairProgramming(settings),
Selection::Execute => CollaborationMode::Execute(settings),
}
})
}
/// Build a 1-line footer "flash" that is shown after switching modes.
///
/// The `ChatWidget` controls when to show this and how long it should remain visible.
pub(crate) fn flash_line(selection: Selection) -> Line<'static> {
Line::from(vec![
selection.label().bold(),
" (".dim(),
key_hint::shift(KeyCode::Tab).into(),
" to change mode)".dim(),
])
let current_kind = mode_kind(current);
let next_index = presets
.iter()
.position(|preset| mode_kind(preset) == current_kind)
.map_or(0, |idx| (idx + 1) % presets.len());
presets.get(next_index).cloned()
}
+27 -2
View File
@@ -5,7 +5,8 @@ use crate::history_cell::with_border_with_inner_width;
use crate::version::CODEX_CLI_VERSION;
use chrono::DateTime;
use chrono::Local;
use codex_common::create_config_summary_entries;
use codex_common::summarize_sandbox_policy;
use codex_core::WireApi;
use codex_core::config::Config;
use codex_core::protocol::NetworkAccess;
use codex_core::protocol::SandboxPolicy;
@@ -13,6 +14,7 @@ use codex_core::protocol::TokenUsage;
use codex_core::protocol::TokenUsageInfo;
use codex_protocol::ThreadId;
use codex_protocol::account::PlanType;
use codex_protocol::openai_models::ReasoningEffort;
use ratatui::prelude::*;
use ratatui::style::Stylize;
use std::collections::BTreeSet;
@@ -85,6 +87,7 @@ pub(crate) fn new_status_output(
now: DateTime<Local>,
model_name: &str,
collaboration_mode: Option<&str>,
reasoning_effort_override: Option<Option<ReasoningEffort>>,
) -> CompositeHistoryCell {
let command = PlainHistoryCell::new(vec!["/status".magenta().into()]);
let card = StatusHistoryCell::new(
@@ -99,6 +102,7 @@ pub(crate) fn new_status_output(
now,
model_name,
collaboration_mode,
reasoning_effort_override,
);
CompositeHistoryCell::new(vec![Box::new(command), Box::new(card)])
@@ -118,8 +122,29 @@ impl StatusHistoryCell {
now: DateTime<Local>,
model_name: &str,
collaboration_mode: Option<&str>,
reasoning_effort_override: Option<Option<ReasoningEffort>>,
) -> Self {
let config_entries = create_config_summary_entries(config, model_name);
let mut config_entries = vec![
("workdir", config.cwd.display().to_string()),
("model", model_name.to_string()),
("provider", config.model_provider_id.clone()),
("approval", config.approval_policy.value().to_string()),
(
"sandbox",
summarize_sandbox_policy(config.sandbox_policy.get()),
),
];
if config.model_provider.wire_api == WireApi::Responses {
let effort_value = reasoning_effort_override
.unwrap_or(None)
.map(|effort| effort.to_string())
.unwrap_or_else(|| "none".to_string());
config_entries.push(("reasoning effort", effort_value));
config_entries.push((
"reasoning summaries",
config.model_reasoning_summary.to_string(),
));
}
let (model_name, model_details) = compose_model_display(model_name, &config_entries);
let approval = config_entries
.iter()
+17 -2
View File
@@ -95,7 +95,6 @@ async fn status_snapshot_includes_reasoning_details() {
let mut config = test_config(&temp_home).await;
config.model = Some("gpt-5.1-codex-max".to_string());
config.model_provider_id = "openai".to_string();
config.model_reasoning_effort = Some(ReasoningEffort::High);
config.model_reasoning_summary = ReasoningSummary::Detailed;
config
.sandbox_policy
@@ -141,6 +140,7 @@ async fn status_snapshot_includes_reasoning_details() {
let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
let token_info = token_info_for(&model_slug, &config, &usage);
let reasoning_effort_override = Some(Some(ReasoningEffort::High));
let composite = new_status_output(
&config,
&auth_manager,
@@ -153,6 +153,7 @@ async fn status_snapshot_includes_reasoning_details() {
captured_at,
&model_slug,
None,
reasoning_effort_override,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -205,6 +206,7 @@ async fn status_snapshot_includes_forked_from() {
captured_at,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -263,6 +265,7 @@ async fn status_snapshot_includes_monthly_limit() {
captured_at,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -308,6 +311,7 @@ async fn status_snapshot_shows_unlimited_credits() {
captured_at,
&model_slug,
None,
None,
);
let rendered = render_lines(&composite.display_lines(120));
assert!(
@@ -353,6 +357,7 @@ async fn status_snapshot_shows_positive_credits() {
captured_at,
&model_slug,
None,
None,
);
let rendered = render_lines(&composite.display_lines(120));
assert!(
@@ -398,6 +403,7 @@ async fn status_snapshot_hides_zero_credits() {
captured_at,
&model_slug,
None,
None,
);
let rendered = render_lines(&composite.display_lines(120));
assert!(
@@ -441,6 +447,7 @@ async fn status_snapshot_hides_when_has_no_credits_flag() {
captured_at,
&model_slug,
None,
None,
);
let rendered = render_lines(&composite.display_lines(120));
assert!(
@@ -484,6 +491,7 @@ async fn status_card_token_usage_excludes_cached_tokens() {
now,
&model_slug,
None,
None,
);
let rendered = render_lines(&composite.display_lines(120));
@@ -499,7 +507,6 @@ async fn status_snapshot_truncates_in_narrow_terminal() {
let mut config = test_config(&temp_home).await;
config.model = Some("gpt-5.1-codex-max".to_string());
config.model_provider_id = "openai".to_string();
config.model_reasoning_effort = Some(ReasoningEffort::High);
config.model_reasoning_summary = ReasoningSummary::Detailed;
config.cwd = PathBuf::from("/workspace/tests");
@@ -530,6 +537,7 @@ async fn status_snapshot_truncates_in_narrow_terminal() {
let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
let token_info = token_info_for(&model_slug, &config, &usage);
let reasoning_effort_override = Some(Some(ReasoningEffort::High));
let composite = new_status_output(
&config,
&auth_manager,
@@ -542,6 +550,7 @@ async fn status_snapshot_truncates_in_narrow_terminal() {
captured_at,
&model_slug,
None,
reasoning_effort_override,
);
let mut rendered_lines = render_lines(&composite.display_lines(70));
if cfg!(windows) {
@@ -589,6 +598,7 @@ async fn status_snapshot_shows_missing_limits_message() {
now,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -653,6 +663,7 @@ async fn status_snapshot_includes_credits_and_limits() {
captured_at,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -706,6 +717,7 @@ async fn status_snapshot_shows_empty_limits_message() {
captured_at,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -768,6 +780,7 @@ async fn status_snapshot_shows_stale_limits_message() {
now,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -834,6 +847,7 @@ async fn status_snapshot_cached_limits_hide_credits_without_flag() {
now,
&model_slug,
None,
None,
);
let mut rendered_lines = render_lines(&composite.display_lines(80));
if cfg!(windows) {
@@ -890,6 +904,7 @@ async fn status_context_window_uses_last_usage() {
now,
&model_slug,
None,
None,
);
let rendered_lines = render_lines(&composite.display_lines(80));
let context_line = rendered_lines
+2
View File
@@ -9,6 +9,7 @@ license.workspace = true
workspace = true
[dependencies]
dirs = { workspace = true }
path-absolutize = { workspace = true }
schemars = { workspace = true }
serde = { workspace = true, features = ["derive"] }
@@ -18,5 +19,6 @@ ts-rs = { workspace = true, features = [
] }
[dev-dependencies]
pretty_assertions = { workspace = true }
serde_json = { workspace = true }
tempfile = { workspace = true }
+66 -2
View File
@@ -1,3 +1,4 @@
use dirs::home_dir;
use path_absolutize::Absolutize;
use schemars::JsonSchema;
use serde::Deserialize;
@@ -21,16 +22,35 @@ use ts_rs::TS;
pub struct AbsolutePathBuf(PathBuf);
impl AbsolutePathBuf {
fn maybe_expand_home_directory(path: &Path) -> PathBuf {
let Some(path_str) = path.to_str() else {
return path.to_path_buf();
};
if cfg!(not(target_os = "windows"))
&& let Some(home) = home_dir()
{
if path_str == "~" {
return home;
}
if let Some(rest) = path_str.strip_prefix("~/") {
return home.join(rest);
}
}
path.to_path_buf()
}
pub fn resolve_path_against_base<P: AsRef<Path>, B: AsRef<Path>>(
path: P,
base_path: B,
) -> std::io::Result<Self> {
let absolute_path = path.as_ref().absolutize_from(base_path.as_ref())?;
let expanded = Self::maybe_expand_home_directory(path.as_ref());
let absolute_path = expanded.absolutize_from(base_path.as_ref())?;
Ok(Self(absolute_path.into_owned()))
}
pub fn from_absolute_path<P: AsRef<Path>>(path: P) -> std::io::Result<Self> {
let absolute_path = path.as_ref().absolutize()?;
let expanded = Self::maybe_expand_home_directory(path.as_ref());
let absolute_path = expanded.absolutize()?;
Ok(Self(absolute_path.into_owned()))
}
@@ -165,6 +185,7 @@ impl<'de> Deserialize<'de> for AbsolutePathBuf {
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
#[test]
@@ -203,4 +224,47 @@ mod tests {
base_dir.join(relative_path).as_path()
);
}
#[cfg(not(target_os = "windows"))]
#[test]
fn home_directory_root_on_non_windows_is_expanded_in_deserialization() {
let Some(home) = home_dir() else {
return;
};
let temp_dir = tempdir().expect("base dir");
let abs_path_buf = {
let _guard = AbsolutePathBufGuard::new(temp_dir.path());
serde_json::from_str::<AbsolutePathBuf>("\"~\"").expect("failed to deserialize")
};
assert_eq!(abs_path_buf.as_path(), home.as_path());
}
#[cfg(not(target_os = "windows"))]
#[test]
fn home_directory_subpath_on_non_windows_is_expanded_in_deserialization() {
let Some(home) = home_dir() else {
return;
};
let temp_dir = tempdir().expect("base dir");
let abs_path_buf = {
let _guard = AbsolutePathBufGuard::new(temp_dir.path());
serde_json::from_str::<AbsolutePathBuf>("\"~/code\"").expect("failed to deserialize")
};
assert_eq!(abs_path_buf.as_path(), home.join("code").as_path());
}
#[cfg(target_os = "windows")]
#[test]
fn home_directory_on_windows_is_not_expanded_in_deserialization() {
let temp_dir = tempdir().expect("base dir");
let base_dir = temp_dir.path();
let abs_path_buf = {
let _guard = AbsolutePathBufGuard::new(base_dir);
serde_json::from_str::<AbsolutePathBuf>("\"~/code\"").expect("failed to deserialize")
};
assert_eq!(
abs_path_buf.as_path(),
base_dir.join("~").join("code").as_path()
);
}
}