Skip to content

Commit dc8b17a

Browse files
committed
Add startup thread name flag
1 parent 4241544 commit dc8b17a

6 files changed

Lines changed: 152 additions & 5 deletions

File tree

‎codex-rs/cli/src/main.rs‎

Lines changed: 107 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -394,11 +394,25 @@ impl Args for SessionTuiCli {
394394

395395
impl clap::FromArgMatches for SessionTuiCli {
396396
fn from_arg_matches(matches: &clap::ArgMatches) -> Result<Self, clap::Error> {
397-
TuiCli::from_arg_matches(matches).map(Self)
397+
let cli = TuiCli::from_arg_matches(matches)?;
398+
if cli.thread_name.is_some() {
399+
return Err(clap::Error::raw(
400+
clap::error::ErrorKind::ArgumentConflict,
401+
"`--name` is only supported when starting a fresh interactive session",
402+
));
403+
}
404+
Ok(Self(cli))
398405
}
399406

400407
fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches) -> Result<(), clap::Error> {
401-
self.0.update_from_arg_matches(matches)
408+
self.0.update_from_arg_matches(matches)?;
409+
if self.0.thread_name.is_some() {
410+
return Err(clap::Error::raw(
411+
clap::error::ErrorKind::ArgumentConflict,
412+
"`--name` is only supported when starting a fresh interactive session",
413+
));
414+
}
415+
Ok(())
402416
}
403417
}
404418

@@ -942,6 +956,7 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
942956
let root_remote_auth_token_env = remote.remote_auth_token_env;
943957
let root_strict_config = interactive.strict_config;
944958
reject_root_strict_config_for_subcommand(root_strict_config, &subcommand)?;
959+
reject_root_thread_name_for_subcommand(interactive.thread_name.as_deref(), &subcommand)?;
945960
if let Some(subcommand) = subcommand.as_ref() {
946961
profile_v2_for_subcommand(&interactive, subcommand)?;
947962
}
@@ -2003,6 +2018,56 @@ fn reject_root_strict_config_for_subcommand(
20032018
}
20042019
}
20052020

2021+
fn reject_root_thread_name_for_subcommand(
2022+
thread_name: Option<&str>,
2023+
subcommand: &Option<Subcommand>,
2024+
) -> anyhow::Result<()> {
2025+
if thread_name.is_none() {
2026+
return Ok(());
2027+
}
2028+
let Some(subcommand_name) = subcommand_name_for_thread_name_reject(subcommand) else {
2029+
return Ok(());
2030+
};
2031+
anyhow::bail!(
2032+
"`--name` is only supported when starting a fresh interactive session, not `codex {subcommand_name}`"
2033+
)
2034+
}
2035+
2036+
fn subcommand_name_for_thread_name_reject(subcommand: &Option<Subcommand>) -> Option<&'static str> {
2037+
match subcommand {
2038+
None => None,
2039+
Some(Subcommand::Exec(_)) => Some("exec"),
2040+
Some(Subcommand::Review(_)) => Some("review"),
2041+
Some(Subcommand::Login(_)) => Some("login"),
2042+
Some(Subcommand::Logout(_)) => Some("logout"),
2043+
Some(Subcommand::Mcp(_)) => Some("mcp"),
2044+
Some(Subcommand::Plugin(_)) => Some("plugin"),
2045+
Some(Subcommand::McpServer(_)) => Some("mcp-server"),
2046+
Some(Subcommand::AppServer(app_server)) => {
2047+
Some(app_server_subcommand_name(app_server.subcommand.as_ref()))
2048+
}
2049+
Some(Subcommand::RemoteControl(remote_control)) => Some(remote_control.subcommand_name()),
2050+
#[cfg(any(target_os = "macos", target_os = "windows"))]
2051+
Some(Subcommand::App(_)) => Some("app"),
2052+
Some(Subcommand::Completion(_)) => Some("completion"),
2053+
Some(Subcommand::Update) => Some("update"),
2054+
Some(Subcommand::Doctor(_)) => Some("doctor"),
2055+
Some(Subcommand::Sandbox(_)) => Some("sandbox"),
2056+
Some(Subcommand::Debug(_)) => Some("debug"),
2057+
Some(Subcommand::Execpolicy(_)) => Some("execpolicy"),
2058+
Some(Subcommand::Apply(_)) => Some("apply"),
2059+
Some(Subcommand::Resume(_)) => Some("resume"),
2060+
Some(Subcommand::Archive(_)) => Some("archive"),
2061+
Some(Subcommand::Unarchive(_)) => Some("unarchive"),
2062+
Some(Subcommand::Fork(_)) => Some("fork"),
2063+
Some(Subcommand::Cloud(_)) => Some("cloud"),
2064+
Some(Subcommand::ResponsesApiProxy(_)) => Some("responses-api-proxy"),
2065+
Some(Subcommand::StdioToUds(_)) => Some("stdio-to-uds"),
2066+
Some(Subcommand::ExecServer(_)) => Some("exec-server"),
2067+
Some(Subcommand::Features(_)) => Some("features"),
2068+
}
2069+
}
2070+
20062071
/// Return the selected subcommand name when a root-level `--strict-config`
20072072
/// flag should be rejected after parsing.
20082073
///
@@ -3046,6 +3111,46 @@ mod tests {
30463111
);
30473112
}
30483113

3114+
#[test]
3115+
fn root_name_flag_parses_for_fresh_interactive_session() {
3116+
let cli = MultitoolCli::try_parse_from(["codex", "--name", "desc-pay refund panel"])
3117+
.expect("parse");
3118+
3119+
assert_eq!(
3120+
cli.interactive.thread_name.as_deref(),
3121+
Some("desc-pay refund panel")
3122+
);
3123+
assert!(cli.subcommand.is_none());
3124+
}
3125+
3126+
#[test]
3127+
fn root_name_flag_is_rejected_for_subcommands() {
3128+
let cli = MultitoolCli::try_parse_from(["codex", "--name", "work", "resume"])
3129+
.expect("root flag parses before post-parse validation");
3130+
3131+
let err = reject_root_thread_name_for_subcommand(
3132+
cli.interactive.thread_name.as_deref(),
3133+
&cli.subcommand,
3134+
)
3135+
.expect_err("root --name should not apply to subcommands");
3136+
3137+
assert_eq!(
3138+
err.to_string(),
3139+
"`--name` is only supported when starting a fresh interactive session, not `codex resume`"
3140+
);
3141+
}
3142+
3143+
#[test]
3144+
fn session_commands_reject_scoped_name_flag() {
3145+
let err = MultitoolCli::try_parse_from(["codex", "resume", "--name", "work"])
3146+
.expect_err("resume --name should be rejected");
3147+
assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
3148+
3149+
let err = MultitoolCli::try_parse_from(["codex", "fork", "--name", "work"])
3150+
.expect_err("fork --name should be rejected");
3151+
assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
3152+
}
3153+
30493154
#[test]
30503155
fn resume_model_flag_applies_when_no_root_flags() {
30513156
let interactive =

‎codex-rs/tui/src/app.rs‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,7 @@ async fn resolve_runtime_model_provider_base_url(provider: &ModelProviderInfo) -
623623
fn spawn_startup_thread_start(
624624
app_server: &AppServerSession,
625625
config: Config,
626+
initial_thread_name: Option<String>,
626627
app_event_tx: AppEventSender,
627628
) {
628629
let request_handle = app_server.request_handle();
@@ -634,6 +635,7 @@ fn spawn_startup_thread_start(
634635
config,
635636
thread_params_mode,
636637
remote_cwd_override,
638+
initial_thread_name,
637639
)
638640
.await
639641
.map_err(|err| format!("{err:#}"));
@@ -769,6 +771,7 @@ impl App {
769771
startup_elapsed_before_app: Duration,
770772
startup_bootstrap: Option<AppServerBootstrap>,
771773
startup_hooks_browser: Option<HooksListEntry>,
774+
initial_thread_name: Option<String>,
772775
) -> Result<AppExitInfo> {
773776
use tokio_stream::StreamExt;
774777
let startup_started_at = Instant::now();
@@ -869,7 +872,12 @@ impl App {
869872
);
870873
let (mut chat_widget, initial_started_thread) = match session_selection {
871874
SessionSelection::StartFresh | SessionSelection::Exit => {
872-
spawn_startup_thread_start(&app_server, config.clone(), app_event_tx.clone());
875+
spawn_startup_thread_start(
876+
&app_server,
877+
config.clone(),
878+
initial_thread_name,
879+
app_event_tx.clone(),
880+
);
873881
// Count a startup tooltip once the initial chat widget can render it.
874882
let startup_tooltip_override =
875883
prepare_startup_tooltip_override(&mut config, &available_models, is_first_run)

‎codex-rs/tui/src/app_server_session.rs‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1112,8 +1112,9 @@ pub(crate) async fn start_thread_with_request_handle(
11121112
config: Config,
11131113
thread_params_mode: ThreadParamsMode,
11141114
remote_cwd_override: Option<PathBuf>,
1115+
initial_thread_name: Option<String>,
11151116
) -> Result<AppServerStartedThread> {
1116-
let response: ThreadStartResponse = request_handle
1117+
let mut response: ThreadStartResponse = request_handle
11171118
.request_typed(ClientRequest::ThreadStart {
11181119
request_id: RequestId::String(format!("startup-thread-start-{}", Uuid::new_v4())),
11191120
params: thread_start_params_from_config(
@@ -1125,6 +1126,24 @@ pub(crate) async fn start_thread_with_request_handle(
11251126
})
11261127
.await
11271128
.map_err(|err| bootstrap_request_error("thread/start failed during TUI bootstrap", err))?;
1129+
if let Some(name) = initial_thread_name {
1130+
let _: ThreadSetNameResponse = request_handle
1131+
.request_typed(ClientRequest::ThreadSetName {
1132+
request_id: RequestId::String(format!(
1133+
"startup-thread-set-name-{}",
1134+
Uuid::new_v4()
1135+
)),
1136+
params: ThreadSetNameParams {
1137+
thread_id: response.thread.id.clone(),
1138+
name: name.clone(),
1139+
},
1140+
})
1141+
.await
1142+
.map_err(|err| {
1143+
bootstrap_request_error("thread/name/set failed during TUI bootstrap", err)
1144+
})?;
1145+
response.thread.name = Some(name);
1146+
}
11281147
started_thread_from_start_response(response, &config, thread_params_mode).await
11291148
}
11301149

‎codex-rs/tui/src/chatwidget.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ fn queued_message_edit_hint_binding(
256256
.or_else(|| bindings.first().copied())
257257
}
258258

259-
fn normalize_thread_name(name: &str) -> Option<String> {
259+
pub(crate) fn normalize_thread_name(name: &str) -> Option<String> {
260260
let trimmed = name.trim();
261261
(!trimmed.is_empty()).then(|| trimmed.to_string())
262262
}

‎codex-rs/tui/src/cli.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ pub struct Cli {
1212
#[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)]
1313
pub prompt: Option<String>,
1414

15+
/// User-facing name for a fresh interactive session.
16+
#[arg(long = "name", value_name = "THREAD_NAME")]
17+
pub thread_name: Option<String>,
18+
1519
/// Error out when config.toml contains fields that are not recognized by this version of Codex.
1620
#[arg(long = "strict-config", default_value_t = false)]
1721
pub strict_config: bool,

‎codex-rs/tui/src/lib.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -914,6 +914,14 @@ pub async fn run_main(
914914
explicit_remote_endpoint: Option<RemoteAppServerEndpoint>,
915915
) -> std::io::Result<AppExitInfo> {
916916
let strict_config = cli.strict_config;
917+
let initial_thread_name = match cli.thread_name.take() {
918+
Some(name) => Some(
919+
crate::chatwidget::normalize_thread_name(&name).ok_or_else(|| {
920+
std::io::Error::new(std::io::ErrorKind::InvalidInput, "`--name` cannot be empty")
921+
})?,
922+
),
923+
None => None,
924+
};
917925
let (sandbox_mode, approval_policy) = if cli.dangerously_bypass_approvals_and_sandbox {
918926
(
919927
Some(SandboxMode::DangerFullAccess),
@@ -1324,6 +1332,7 @@ pub async fn run_main(
13241332
log_db,
13251333
state_db,
13261334
environment_manager,
1335+
initial_thread_name,
13271336
)
13281337
.await
13291338
.map_err(|err| std::io::Error::other(err.to_string()))
@@ -1346,6 +1355,7 @@ async fn run_ratatui_app(
13461355
log_db: Option<log_db::LogDbLayer>,
13471356
state_db: Option<StateDbHandle>,
13481357
environment_manager: Arc<EnvironmentManager>,
1358+
initial_thread_name: Option<String>,
13491359
) -> color_eyre::Result<AppExitInfo> {
13501360
let uses_remote_workspace = app_server_target.uses_remote_workspace();
13511361
color_eyre::install()?;
@@ -1853,6 +1863,7 @@ async fn run_ratatui_app(
18531863
startup_elapsed_before_app,
18541864
startup_bootstrap,
18551865
startup_hooks_browser,
1866+
initial_thread_name,
18561867
)
18571868
.await;
18581869

0 commit comments

Comments
 (0)