mirror of
https://github.com/openai/codex.git
synced 2026-11-15 21:50:46 +00:00
## Why Cloud conversations previously skipped TUI title generation, leaving them without automatically saved names. ## What changed - Generate structured titles using the selected Cloud account and its backend routing, without agent tools or a temporary conversation. - Read and save names outside the conversation command queue without replacing the active attachment. Preserve an existing name if it no longer matches the expected value. - Fall back to the first-message title when generation is unavailable, and allow up to three seconds for pending saves during shutdown. - Report a retryable error when a manual rename encounters an automatic save in progress, keeping the UI responsive. ## Testing Add coverage for selected-account title generation, saved-name reads without attachment, first-message fallback persistence, and manual rename retries after automatic saves. GitOrigin-RevId: 48030cc0b75e790a2004af018f54e5751665b760
1040 lines
37 KiB
Rust
1040 lines
37 KiB
Rust
use super::THREAD_TITLE_MAX_CHARS;
|
|
use super::THREAD_TITLE_PROMPT_MAX_BYTES;
|
|
use super::THREAD_TITLE_RECENT_MESSAGES;
|
|
use super::parse_thread_title;
|
|
use super::recent_conversation_messages;
|
|
use super::recent_conversation_thread_title_prompt;
|
|
use super::thread_title_prompt;
|
|
use crate::app::session_lifecycle::ThreadAttachPresentation;
|
|
use crate::app::test_support::make_test_app;
|
|
use crate::app::thread_events::ThreadBufferedEvent;
|
|
use crate::app_command::AppCommand;
|
|
use crate::app_event::AppEvent;
|
|
use crate::app_event::ThreadTitleDestination;
|
|
use crate::app_event_sender::AppEventSender;
|
|
use crate::app_server_session::ResumeModelSettings;
|
|
use crate::chatwidget::tests::helpers::normalize_snapshot_paths;
|
|
use crate::chatwidget::tests::helpers::render_bottom_popup;
|
|
use crate::test_support::PathBufExt;
|
|
use codex_app_server_client::AppServerEvent;
|
|
use codex_app_server_protocol::ItemCompletedNotification;
|
|
use codex_app_server_protocol::ServerNotification;
|
|
use codex_app_server_protocol::ThreadItem;
|
|
use codex_app_server_protocol::ThreadItemPayload;
|
|
use codex_app_server_protocol::ThreadSource;
|
|
use codex_app_server_protocol::Turn;
|
|
use codex_app_server_protocol::TurnStatus;
|
|
use codex_app_server_protocol::UserInput;
|
|
use codex_model_provider_info::ModelProviderInfo;
|
|
use codex_protocol::ThreadId;
|
|
use codex_protocol::models::MessagePhase;
|
|
use core_test_support::responses;
|
|
use crossterm::event::KeyCode;
|
|
use crossterm::event::KeyEvent;
|
|
use crossterm::event::KeyModifiers;
|
|
use futures::FutureExt;
|
|
use pretty_assertions::assert_eq;
|
|
use tempfile::tempdir;
|
|
use tokio::sync::mpsc::unbounded_channel;
|
|
use tokio_util::sync::CancellationToken;
|
|
|
|
const EXPECTED_THREAD_TITLE_INSTRUCTIONS: &str = concat!(
|
|
"Generate a concise, single-line task title of at most 36 characters ",
|
|
"and under five words where possible. Start with an imperative verb. ",
|
|
"Capitalize only the first word unless the user's language, proper nouns, ",
|
|
"acronyms, or code terms require otherwise. Preserve ticket references ",
|
|
"exactly. Write in the user's language. Do not use quotes, markdown, ",
|
|
"or trailing punctuation. Do not answer the request."
|
|
);
|
|
|
|
#[test]
|
|
fn trims_user_message_in_title_prompt() {
|
|
let prompt = thread_title_prompt(" Fix the login form \n");
|
|
|
|
assert_eq!(
|
|
prompt,
|
|
format!("{EXPECTED_THREAD_TITLE_INSTRUCTIONS}\n\nUser prompt:\nFix the login form")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn truncates_title_prompt_without_splitting_unicode() {
|
|
let user_message = "🚀".repeat(THREAD_TITLE_PROMPT_MAX_BYTES);
|
|
let prompt = thread_title_prompt(&user_message);
|
|
let expected_instructions = format!("{EXPECTED_THREAD_TITLE_INSTRUCTIONS}\n\n");
|
|
let prefix = format!("{expected_instructions}User prompt:\n");
|
|
let available_bytes = THREAD_TITLE_PROMPT_MAX_BYTES - prefix.len();
|
|
let expected = "🚀".repeat(available_bytes / '🚀'.len_utf8());
|
|
|
|
assert_eq!(
|
|
prompt.rsplit_once("User prompt:\n"),
|
|
Some((expected_instructions.as_str(), expected.as_str()))
|
|
);
|
|
assert!(prompt.len() <= THREAD_TITLE_PROMPT_MAX_BYTES);
|
|
}
|
|
|
|
#[test]
|
|
fn bounds_the_entire_title_prompt_for_dense_unicode() {
|
|
let repeated_characters = THREAD_TITLE_PROMPT_MAX_BYTES * 3;
|
|
for message in [
|
|
"🚀".repeat(repeated_characters),
|
|
"漢".repeat(repeated_characters),
|
|
"x".repeat(repeated_characters),
|
|
] {
|
|
let prompt = thread_title_prompt(&message);
|
|
|
|
assert!(
|
|
prompt.len() <= THREAD_TITLE_PROMPT_MAX_BYTES,
|
|
"{} bytes for {:?}",
|
|
prompt.len(),
|
|
message.chars().next()
|
|
);
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn cloud_conversations_save_the_first_message_if_generation_is_unavailable()
|
|
-> color_eyre::Result<()> {
|
|
use codex_app_server_client::CloudOperation;
|
|
use codex_app_server_protocol::ClientRequest;
|
|
|
|
let mut app = make_test_app().await;
|
|
let thread_id = ThreadId::new();
|
|
let (client, mut commands, _server_events) =
|
|
codex_app_server_client::CloudClient::channel(/*capacity*/ 1);
|
|
let mut app_server = crate::app_server_session::AppServerSession::new(
|
|
crate::backend_id::BackendId::new(),
|
|
codex_app_server_client::AppServerClient::Cloud(client),
|
|
crate::app_server_session::ThreadParamsMode::Cloud,
|
|
);
|
|
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
let (tx, mut events) = unbounded_channel();
|
|
app.app_event_tx = AppEventSender::new(tx);
|
|
app.active_thread_id = Some(thread_id);
|
|
app.chat_widget
|
|
.handle_thread_session(crate::app::tests::test_thread_session(
|
|
thread_id,
|
|
app.config.cwd.to_path_buf(),
|
|
));
|
|
app.chat_widget
|
|
.setup_terminal_title(vec![crate::bottom_pane::TerminalTitleItem::ThreadName]);
|
|
|
|
app.handle_active_thread_event(
|
|
&mut tui,
|
|
&mut app_server,
|
|
ThreadBufferedEvent::Notification(Box::new(ServerNotification::ItemCompleted(
|
|
ItemCompletedNotification::new(
|
|
thread_id.to_string(),
|
|
"first-turn".to_string(),
|
|
title_user_message("first-message", "Fix the **login** timeout"),
|
|
/*started_at_ms*/ None,
|
|
/*completed_at_ms*/ 0,
|
|
),
|
|
))),
|
|
)
|
|
.await?;
|
|
insta::assert_snapshot!(
|
|
app.chat_widget.last_terminal_title.as_deref().unwrap_or_default(),
|
|
@"Fix the login timeout"
|
|
);
|
|
let read = commands.recv().await.expect("read the saved Cloud title");
|
|
assert!(matches!(
|
|
read.operation,
|
|
CloudOperation::Request(request)
|
|
if matches!(request.as_ref(), ClientRequest::ThreadRead { params, .. }
|
|
if params.thread_id == thread_id.to_string() && !params.include_turns)
|
|
));
|
|
let mut thread = crate::app::agents_overview::tests::overview_thread(
|
|
thread_id,
|
|
/*parent_thread_id*/ None,
|
|
"",
|
|
codex_app_server_protocol::ThreadStatus::Idle,
|
|
);
|
|
thread.name = None;
|
|
read.response
|
|
.send(Ok(Ok(serde_json::json!({"thread": thread}))))
|
|
.unwrap();
|
|
let rename = commands.recv().await.expect("save the Cloud title");
|
|
assert!(matches!(
|
|
rename.operation,
|
|
CloudOperation::Request(request)
|
|
if matches!(request.as_ref(), ClientRequest::ThreadSetName { params, .. }
|
|
if params.thread_id == thread_id.to_string() && params.name == "Fix the login timeout")
|
|
));
|
|
app.cloud_title_shutdown.send(()).unwrap();
|
|
assert!(app.cloud_title_shutdown.closed().now_or_never().is_none());
|
|
rename.response.send(Ok(Ok(serde_json::json!({})))).unwrap();
|
|
app.cloud_title_shutdown.closed().await;
|
|
loop {
|
|
let event = events.recv().await.expect("title generation completes");
|
|
if matches!(&event, AppEvent::GeneratedThreadTitle { .. }) {
|
|
app.handle_event(&mut tui, &mut app_server, event).await?;
|
|
break;
|
|
}
|
|
}
|
|
|
|
assert!(app.pending_thread_titles.is_empty());
|
|
assert!(commands.try_recv().is_err());
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn automatic_thread_title_respects_origin_metadata_after_switching() -> color_eyre::Result<()>
|
|
{
|
|
for (switch_threads, fork_name, manual_name) in [
|
|
(true, None, None),
|
|
(true, Some("Release plan"), None),
|
|
(true, Some("Release plan"), Some("Manual title")),
|
|
(true, None, Some("Manual title")),
|
|
(false, None, Some("Manual title")),
|
|
] {
|
|
let mut app = make_test_app().await;
|
|
let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
|
let started = app_server.start_thread(&app.config).await?;
|
|
let thread_id = started.session.thread_id;
|
|
let user_message = serde_json::from_str(
|
|
r#"{"type":"message","role":"user","content":[{"type":"input_text","text":"Fix the login timeout"}]}"#,
|
|
)?;
|
|
app_server
|
|
.thread_inject_items(thread_id, vec![user_message])
|
|
.await?;
|
|
app.enqueue_primary_thread_session(started.session, started.turns)
|
|
.await?;
|
|
app.pending_thread_titles.insert(
|
|
(thread_id, ThreadTitleDestination::Automatic),
|
|
CancellationToken::new(),
|
|
);
|
|
|
|
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
if let Some(name) = fork_name {
|
|
app_server
|
|
.thread_set_name(thread_id, name.to_owned())
|
|
.await?;
|
|
}
|
|
let automatic =
|
|
app_server.automatic_thread_name_writer(thread_id, fork_name.map(str::to_owned));
|
|
if switch_threads {
|
|
let second = app_server.start_thread(&app.config).await?;
|
|
let second_id = second.session.thread_id;
|
|
app.ensure_thread_channel(second_id)
|
|
.store
|
|
.lock()
|
|
.await
|
|
.set_session(second.session, second.turns);
|
|
app.select_agent_thread(&mut tui, &mut app_server, second_id)
|
|
.await?;
|
|
}
|
|
if let Some(name) = manual_name {
|
|
// The saved name must win even before its notification reaches the widget.
|
|
app_server
|
|
.thread_set_name(thread_id, name.to_string())
|
|
.await?;
|
|
}
|
|
let displayed_thread = (app.chat_widget.thread_id(), app.chat_widget.thread_name());
|
|
automatic
|
|
.save("Generated title".into(), &CancellationToken::new())
|
|
.await;
|
|
app.handle_event(
|
|
&mut tui,
|
|
&mut app_server,
|
|
AppEvent::GeneratedThreadTitle {
|
|
cancellation: CancellationToken::new(),
|
|
thread_id,
|
|
temporary_thread_id: Some(ThreadId::new()),
|
|
destination: ThreadTitleDestination::Automatic,
|
|
result: Ok(r#"{"title":"Generated title"}"#.to_string()),
|
|
},
|
|
)
|
|
.now_or_never()
|
|
.expect("title dispatch must return to keyboard polling")?;
|
|
let expected_name = Some(manual_name.unwrap_or("Generated title").to_string());
|
|
assert_eq!(
|
|
app_server
|
|
.thread_read(thread_id, /*include_turns*/ false)
|
|
.await?
|
|
.name,
|
|
expected_name
|
|
);
|
|
assert_eq!(
|
|
(app.chat_widget.thread_id(), app.chat_widget.thread_name()),
|
|
displayed_thread
|
|
);
|
|
assert!(app.pending_thread_titles.is_empty());
|
|
let resumed = app_server
|
|
.resume_thread(
|
|
&app.local_settings,
|
|
app.config.clone(),
|
|
thread_id,
|
|
ResumeModelSettings::PreserveExistingThread,
|
|
)
|
|
.await?;
|
|
assert_eq!(resumed.session.thread_name, expected_name);
|
|
app_server.shutdown().await?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn slash_rename_generates_editable_title_through_embedded_app_server()
|
|
-> color_eyre::Result<()> {
|
|
check_thread_title_generation(TitleScenario::Suggestion).await
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn automatic_thread_title_replaces_the_provisional_name() -> color_eyre::Result<()> {
|
|
check_thread_title_generation(TitleScenario::Automatic).await
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn automatic_thread_title_saves_the_first_message_if_generation_fails()
|
|
-> color_eyre::Result<()> {
|
|
check_thread_title_generation(TitleScenario::Fallback).await
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn manual_rename_cancels_running_thread_title() -> color_eyre::Result<()> {
|
|
check_thread_title_generation(TitleScenario::ManualRename).await
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn overview_rename_cancels_running_thread_title() -> color_eyre::Result<()> {
|
|
check_thread_title_generation(TitleScenario::OverviewRename).await
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
enum TitleScenario {
|
|
Automatic,
|
|
Fallback,
|
|
Suggestion,
|
|
ManualRename,
|
|
OverviewRename,
|
|
}
|
|
|
|
async fn check_thread_title_generation(scenario: TitleScenario) -> color_eyre::Result<()> {
|
|
let automatic = !matches!(scenario, TitleScenario::Suggestion);
|
|
let cancel = matches!(
|
|
scenario,
|
|
TitleScenario::ManualRename | TitleScenario::OverviewRename
|
|
);
|
|
let server = wiremock::MockServer::start().await;
|
|
let user_message = if matches!(scenario, TitleScenario::Fallback) {
|
|
"Fix the **login**\n[timeout](https://example.test/issue)"
|
|
} else {
|
|
"Fix the login timeout"
|
|
};
|
|
let title_message = if matches!(scenario, TitleScenario::Fallback) {
|
|
"{}"
|
|
} else {
|
|
r#"{"title":"Fix login timeout"}"#
|
|
};
|
|
let mut template = responses::sse_response(responses::sse(vec![
|
|
responses::ev_response_created("title-response"),
|
|
responses::ev_assistant_message("title-message", title_message),
|
|
responses::ev_completed("title-response"),
|
|
]));
|
|
if cancel {
|
|
template = template.set_delay(std::time::Duration::from_secs(/*secs*/ 60));
|
|
}
|
|
let response = responses::mount_response_once(&server, template).await;
|
|
let codex_home = tempdir()?;
|
|
let provider_id = "thread-title-test";
|
|
std::fs::write(
|
|
codex_home.path().join("config.toml"),
|
|
format!(
|
|
"model = \"gpt-5.2\"\n\
|
|
model_provider = \"{provider_id}\"\n\n\
|
|
[model_providers.{provider_id}]\n\
|
|
name = \"Thread title test\"\n\
|
|
base_url = \"{}/v1\"\n\
|
|
wire_api = \"responses\"\n\
|
|
request_max_retries = 0\n\
|
|
stream_max_retries = 0\n",
|
|
server.uri()
|
|
),
|
|
)?;
|
|
|
|
let mut app = make_test_app().await;
|
|
let (event_tx, mut event_rx) = unbounded_channel();
|
|
app.local_settings.tui.animations = false;
|
|
app.app_event_tx = AppEventSender::new(event_tx);
|
|
app.config.codex_home = codex_home.path().to_path_buf().abs();
|
|
app.config.sqlite =
|
|
codex_state::SqliteConfig::new_for_testing(codex_home.path().to_path_buf().abs());
|
|
app.config.model = Some("gpt-5.2".to_string());
|
|
app.config.model_provider_id = provider_id.to_string();
|
|
app.config.model_provider = ModelProviderInfo {
|
|
name: "Thread title test".to_string(),
|
|
base_url: Some(format!("{}/v1", server.uri())),
|
|
request_max_retries: Some(0),
|
|
stream_max_retries: Some(0),
|
|
..ModelProviderInfo::default()
|
|
};
|
|
|
|
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
|
let started = app_server.start_thread(&app.config).await?;
|
|
let thread_id = started.session.thread_id;
|
|
app.replace_chat_widget_with_app_server_thread(
|
|
&mut tui,
|
|
started,
|
|
ThreadAttachPresentation::SessionLineage,
|
|
/*initial_user_message*/ None,
|
|
)
|
|
.await?;
|
|
app.ensure_thread_channel(thread_id)
|
|
.store
|
|
.lock()
|
|
.await
|
|
.turns
|
|
.push(Turn {
|
|
id: "existing-turn".to_string(),
|
|
root_turn_id: None,
|
|
items: vec![ThreadItem::untimed(title_user_message(
|
|
"user-message",
|
|
user_message,
|
|
))],
|
|
items_view: Default::default(),
|
|
status: TurnStatus::Completed,
|
|
error: None,
|
|
started_at: None,
|
|
completed_at: None,
|
|
duration_ms: None,
|
|
});
|
|
while event_rx.try_recv().is_ok() {}
|
|
|
|
if automatic {
|
|
for _ in 0..2 {
|
|
app.handle_active_thread_event(
|
|
&mut tui,
|
|
&mut app_server,
|
|
ThreadBufferedEvent::Notification(Box::new(ServerNotification::ItemCompleted(
|
|
ItemCompletedNotification::new(
|
|
thread_id.to_string(),
|
|
"existing-turn".to_string(),
|
|
title_user_message("user-message", user_message),
|
|
/*started_at_ms*/ None,
|
|
/*completed_at_ms*/ 0,
|
|
),
|
|
))),
|
|
)
|
|
.await?;
|
|
}
|
|
assert_eq!(
|
|
app.chat_widget.thread_name().as_deref(),
|
|
Some("Fix the login timeout")
|
|
);
|
|
if matches!(scenario, TitleScenario::Automatic) {
|
|
app.chat_widget.refresh_status_surfaces();
|
|
insta::assert_snapshot!(
|
|
"automatic_thread_title_pending",
|
|
normalize_snapshot_paths(format!(
|
|
"terminal title: {}\nfooter:\n{}",
|
|
app.chat_widget
|
|
.last_terminal_title
|
|
.as_deref()
|
|
.unwrap_or_default(),
|
|
render_bottom_popup(&app.chat_widget, /*width*/ 120)
|
|
))
|
|
);
|
|
}
|
|
assert_eq!(
|
|
app_server
|
|
.thread_read(thread_id, /*include_turns*/ false)
|
|
.await?
|
|
.name,
|
|
None
|
|
);
|
|
} else {
|
|
app.chat_widget.apply_external_edit("/rename".to_string());
|
|
app.chat_widget
|
|
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
|
assert!(render_bottom_popup(&app.chat_widget, /*width*/ 80).contains("Generating"));
|
|
}
|
|
|
|
enum TitleDriveEvent {
|
|
Ui(Box<AppEvent>),
|
|
Server(crate::app_server_session::AppServerSessionEvent),
|
|
RequestStarted,
|
|
}
|
|
|
|
let mut renamed = false;
|
|
let mut generated = false;
|
|
let mut interrupted = false;
|
|
let mut temporary_thread_id = None;
|
|
loop {
|
|
let event = tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 10), async {
|
|
tokio::select! {
|
|
event = event_rx.recv() => event.map(|event| TitleDriveEvent::Ui(Box::new(event))),
|
|
event = app_server.next_event() => event.map(TitleDriveEvent::Server),
|
|
() = async {
|
|
while response.requests().is_empty() {
|
|
tokio::time::sleep(std::time::Duration::from_millis(/*millis*/ 10)).await;
|
|
}
|
|
}, if cancel && !renamed => Some(TitleDriveEvent::RequestStarted),
|
|
}
|
|
})
|
|
.await?
|
|
.ok_or_else(|| color_eyre::eyre::eyre!("title event stream ended"))?;
|
|
|
|
match event {
|
|
TitleDriveEvent::Ui(event) => {
|
|
if let AppEvent::ThreadTitleStarted { result, .. } = event.as_ref() {
|
|
temporary_thread_id =
|
|
Some(result.as_ref().expect("hidden title thread").clone());
|
|
}
|
|
generated |= matches!(event.as_ref(), AppEvent::GeneratedThreadTitle { .. });
|
|
app.handle_event(&mut tui, &mut app_server, *event).await?;
|
|
}
|
|
TitleDriveEvent::Server(event) => {
|
|
if let AppServerEvent::ServerNotification(notification) = &event.event
|
|
&& let ServerNotification::ThreadStarted(started) = notification.as_ref()
|
|
&& started.thread.ephemeral
|
|
{
|
|
assert_eq!(
|
|
started.thread.thread_source,
|
|
Some(ThreadSource::Feature("thread_title".to_string())),
|
|
);
|
|
}
|
|
if let AppServerEvent::ServerNotification(notification) = &event.event
|
|
&& let ServerNotification::TurnCompleted(completed) = notification.as_ref()
|
|
&& Some(&completed.thread_id) == temporary_thread_id.as_ref()
|
|
{
|
|
interrupted = completed.turn.status == TurnStatus::Interrupted;
|
|
}
|
|
app.handle_backend_event(&app_server, event).await;
|
|
}
|
|
TitleDriveEvent::RequestStarted => {
|
|
let name = "Keep this title".to_string();
|
|
let event = match scenario {
|
|
TitleScenario::ManualRename => {
|
|
AppEvent::CodexOp(AppCommand::set_thread_name(name))
|
|
}
|
|
TitleScenario::OverviewRename => {
|
|
AppEvent::RenameAgentsOverviewThread { thread_id, name }
|
|
}
|
|
TitleScenario::Automatic
|
|
| TitleScenario::Fallback
|
|
| TitleScenario::Suggestion => unreachable!(),
|
|
};
|
|
app.handle_event(&mut tui, &mut app_server, event).await?;
|
|
assert!(app.pending_thread_titles.is_empty());
|
|
let popup = render_bottom_popup(&app.chat_widget, /*width*/ 120);
|
|
assert!(popup.contains("Keep this title"));
|
|
if matches!(scenario, TitleScenario::ManualRename) {
|
|
insta::assert_snapshot!(
|
|
"manual_rename_cancels_thread_title",
|
|
normalize_snapshot_paths(popup)
|
|
);
|
|
}
|
|
renamed = true;
|
|
}
|
|
}
|
|
if generated && automatic && !cancel {
|
|
app.drain_active_thread_events(&mut tui).await?;
|
|
}
|
|
if generated
|
|
&& (!cancel || interrupted)
|
|
&& (!matches!(scenario, TitleScenario::Automatic)
|
|
|| app.chat_widget.thread_name().as_deref() == Some("Fix login timeout"))
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
if automatic {
|
|
let expected_name = if cancel {
|
|
"Keep this title"
|
|
} else if matches!(scenario, TitleScenario::Fallback) {
|
|
"Fix the login timeout"
|
|
} else {
|
|
"Fix login timeout"
|
|
};
|
|
assert_eq!(
|
|
app.chat_widget.thread_name(),
|
|
Some(expected_name.to_string())
|
|
);
|
|
assert_eq!(
|
|
app_server
|
|
.thread_read(thread_id, /*include_turns*/ false)
|
|
.await?
|
|
.name,
|
|
Some(expected_name.to_string())
|
|
);
|
|
assert!(app.pending_thread_titles.is_empty());
|
|
} else {
|
|
let popup = render_bottom_popup(&app.chat_widget, /*width*/ 80);
|
|
assert!(popup.contains("Fix login timeout"));
|
|
assert!(!popup.contains("Generating a title suggestion"));
|
|
assert_eq!(
|
|
app_server
|
|
.thread_read(thread_id, /*include_turns*/ false)
|
|
.await?
|
|
.name,
|
|
None
|
|
);
|
|
}
|
|
assert!(app.temporary_structured_requests.is_empty());
|
|
assert!(app.pending_thread_titles.is_empty());
|
|
|
|
let request = response.single_request();
|
|
assert!(
|
|
request
|
|
.message_input_texts("user")
|
|
.iter()
|
|
.any(|prompt| prompt.contains(user_message))
|
|
);
|
|
|
|
app_server.shutdown().await?;
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn canceled_thread_title_ignores_late_start_and_completion() -> color_eyre::Result<()> {
|
|
let mut app = make_test_app().await;
|
|
let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
|
let started = app_server.start_thread(&app.config).await?;
|
|
let thread_id = started.session.thread_id;
|
|
app.enqueue_primary_thread_session(started.session, started.turns)
|
|
.await?;
|
|
let hidden = app_server.start_thread(&app.config).await?;
|
|
let temporary_thread_id = hidden.session.thread_id;
|
|
let cancellation = CancellationToken::new();
|
|
let destination = ThreadTitleDestination::Automatic;
|
|
app.pending_thread_titles
|
|
.insert((thread_id, destination), cancellation.clone());
|
|
|
|
let writer = app_server.automatic_thread_name_writer(thread_id, /*expected_name*/ None);
|
|
let token = cancellation.clone();
|
|
let mut automatic = std::pin::pin!(writer.save("Stale title".into(), &token));
|
|
assert!(automatic.as_mut().now_or_never().is_none());
|
|
|
|
app.try_submit_active_thread_op_via_app_server(
|
|
&mut app_server,
|
|
thread_id,
|
|
&AppCommand::set_thread_name("Keep this title".to_string()),
|
|
)
|
|
.await?;
|
|
automatic
|
|
.now_or_never()
|
|
.expect("canceled metadata read must finish");
|
|
assert!(cancellation.is_cancelled());
|
|
assert!(app.pending_thread_titles.is_empty());
|
|
|
|
// A canceled producer must not clear a replacement request or launch its hidden turn.
|
|
let replacement = CancellationToken::new();
|
|
app.pending_thread_titles
|
|
.insert((thread_id, destination), replacement.clone());
|
|
app.on_thread_title_started(
|
|
&mut app_server,
|
|
thread_id,
|
|
destination,
|
|
"prompt".to_string(),
|
|
/*expected_name*/ None,
|
|
/*fallback_title*/ None,
|
|
/*effort*/ None,
|
|
Ok(temporary_thread_id.to_string()),
|
|
cancellation.clone(),
|
|
);
|
|
assert!(app.temporary_structured_requests.is_empty());
|
|
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
app.handle_event(
|
|
&mut tui,
|
|
&mut app_server,
|
|
AppEvent::GeneratedThreadTitle {
|
|
cancellation,
|
|
thread_id,
|
|
temporary_thread_id: Some(temporary_thread_id),
|
|
destination,
|
|
result: Ok(r#"{"title":"Late automatic title"}"#.to_string()),
|
|
},
|
|
)
|
|
.await?;
|
|
assert!(
|
|
app.pending_thread_titles
|
|
.contains_key(&(thread_id, destination))
|
|
);
|
|
assert!(!replacement.is_cancelled());
|
|
assert_eq!(
|
|
app_server
|
|
.thread_read(thread_id, /*include_turns*/ false)
|
|
.await?
|
|
.name,
|
|
Some("Keep this title".to_string()),
|
|
);
|
|
app_server.shutdown().await?;
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn cloud_manual_rename_can_retry_after_an_in_flight_automatic_write() -> color_eyre::Result<()>
|
|
{
|
|
let thread_id = ThreadId::new();
|
|
let (client, mut requests, _events) =
|
|
codex_app_server_client::CloudClient::channel(/*capacity*/ 1);
|
|
let mut session = crate::app_server_session::AppServerSession::new(
|
|
crate::backend_id::BackendId::new(),
|
|
codex_app_server_client::AppServerClient::Cloud(client),
|
|
crate::app_server_session::ThreadParamsMode::Remote,
|
|
);
|
|
let writer = session.automatic_thread_name_writer(thread_id, /*expected_name*/ None);
|
|
let token = CancellationToken::new();
|
|
let mut automatic = std::pin::pin!(writer.save("Generated".into(), &token));
|
|
assert!(automatic.as_mut().now_or_never().is_none());
|
|
let mut thread = crate::app::agents_overview::tests::overview_thread(
|
|
thread_id,
|
|
/*parent_thread_id*/ None,
|
|
"",
|
|
codex_app_server_protocol::ThreadStatus::Idle,
|
|
);
|
|
thread.name = None;
|
|
requests
|
|
.try_recv()?
|
|
.response
|
|
.send(Ok(Ok(serde_json::json!({"thread": thread}))))
|
|
.unwrap();
|
|
assert!(automatic.as_mut().now_or_never().is_none());
|
|
let write = requests.try_recv()?;
|
|
|
|
let error = session
|
|
.thread_set_name(thread_id, "Manual".into())
|
|
.now_or_never()
|
|
.expect("a pending automatic Cloud write must not block the UI")
|
|
.expect_err("manual rename must report that the write is still in flight");
|
|
assert_eq!(
|
|
error.to_string(),
|
|
"An automatic title is still being saved. Try renaming the thread again."
|
|
);
|
|
assert!(
|
|
requests.try_recv().is_err(),
|
|
"manual rename raced the automatic write"
|
|
);
|
|
let acknowledge = |request: codex_app_server_client::CloudCommand| {
|
|
request
|
|
.response
|
|
.send(Ok(Ok(serde_json::json!({}))))
|
|
.unwrap();
|
|
};
|
|
acknowledge(write);
|
|
automatic
|
|
.now_or_never()
|
|
.expect("automatic write acknowledged");
|
|
|
|
let mut manual = std::pin::pin!(session.thread_set_name(thread_id, "Manual".into()));
|
|
assert!(manual.as_mut().now_or_never().is_none());
|
|
acknowledge(requests.try_recv()?);
|
|
manual.await?;
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn recent_conversation_messages_escape_markup_and_ignore_commentary() {
|
|
let items = vec![
|
|
title_user_message("user-1", " Investigate <flaky> & slow tests "),
|
|
title_agent_message(
|
|
"commentary",
|
|
"Checking files",
|
|
Some(MessagePhase::Commentary),
|
|
),
|
|
title_user_message("user-2", "Fix > flaky tests"),
|
|
title_agent_message(
|
|
"answer",
|
|
" Tests now pass ",
|
|
Some(MessagePhase::FinalAnswer),
|
|
),
|
|
];
|
|
|
|
assert_eq!(
|
|
recent_conversation_messages(&items),
|
|
Some(
|
|
"<conversation>\n<message role=\"user\">Investigate <flaky> & slow tests</message>\n<message role=\"user\">Fix > flaky tests</message>\n<message role=\"assistant\">Tests now pass</message>\n</conversation>"
|
|
.to_string()
|
|
)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn recent_conversation_messages_strip_ide_context_before_escaping() {
|
|
let ide_context = "x".repeat(THREAD_TITLE_PROMPT_MAX_BYTES + 1);
|
|
let user_message = format!(
|
|
"# Context from my IDE setup:\n{ide_context}\n## My request for Codex:\n\nEarlier request\n## My request for Codex:\n Fix <login> & retries "
|
|
);
|
|
let items = vec![title_user_message("user-1", &user_message)];
|
|
|
|
assert_eq!(
|
|
recent_conversation_messages(&items),
|
|
Some(
|
|
"<conversation>\n<message role=\"user\">Fix <login> & retries</message>\n</conversation>"
|
|
.to_string()
|
|
)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn recent_conversation_messages_keep_only_the_latest_substantive_items() {
|
|
let items = (0..THREAD_TITLE_RECENT_MESSAGES + 2)
|
|
.map(|index| title_user_message(&index.to_string(), &format!("message-{index}")))
|
|
.collect::<Vec<_>>();
|
|
|
|
let expected_messages = (2..THREAD_TITLE_RECENT_MESSAGES + 2)
|
|
.map(|index| format!("<message role=\"user\">message-{index}</message>"))
|
|
.collect::<Vec<_>>()
|
|
.join("\n");
|
|
|
|
assert_eq!(
|
|
recent_conversation_messages(&items),
|
|
Some(format!(
|
|
"<conversation>\n{expected_messages}\n</conversation>"
|
|
))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn recent_conversation_messages_require_substantive_content() {
|
|
assert_eq!(recent_conversation_messages(&[]), None);
|
|
|
|
let items = vec![
|
|
title_user_message("blank", " \n\t "),
|
|
title_agent_message("commentary", "Thinking", Some(MessagePhase::Commentary)),
|
|
];
|
|
|
|
assert_eq!(recent_conversation_messages(&items), None);
|
|
}
|
|
|
|
#[test]
|
|
fn recent_conversation_prompt_trims_messages_and_prioritizes_latest_request() {
|
|
let prompt = recent_conversation_thread_title_prompt(
|
|
" User: Fix login\nAssistant: Investigating the auth flow \n",
|
|
);
|
|
|
|
assert_eq!(
|
|
prompt,
|
|
format!(
|
|
"{EXPECTED_THREAD_TITLE_INSTRUCTIONS}\nPrioritize the current task and latest substantive user request.\n\nRecent conversation messages:\nUser: Fix login\nAssistant: Investigating the auth flow"
|
|
)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn recent_conversation_prompt_keeps_latest_unicode_characters() {
|
|
let conversation = format!("discarded-{}x", "🚀".repeat(THREAD_TITLE_PROMPT_MAX_BYTES));
|
|
let prompt = recent_conversation_thread_title_prompt(&conversation);
|
|
let expected_instructions = format!(
|
|
"{EXPECTED_THREAD_TITLE_INSTRUCTIONS}\nPrioritize the current task and latest substantive user request.\n\n"
|
|
);
|
|
let prefix = format!("{expected_instructions}Recent conversation messages:\n");
|
|
let remaining_bytes = THREAD_TITLE_PROMPT_MAX_BYTES - prefix.len();
|
|
let expected = format!("{}x", "🚀".repeat((remaining_bytes - 1) / '🚀'.len_utf8()));
|
|
|
|
assert_eq!(
|
|
prompt.rsplit_once("Recent conversation messages:\n"),
|
|
Some((expected_instructions.as_str(), expected.as_str()))
|
|
);
|
|
assert!(prompt.len() <= THREAD_TITLE_PROMPT_MAX_BYTES);
|
|
}
|
|
|
|
#[test]
|
|
fn recent_conversation_prompt_preserves_latest_user_request_and_complete_markup() {
|
|
let items = vec![
|
|
title_user_message("user", "Fix <authentication> & login regressions"),
|
|
title_agent_message(
|
|
"assistant",
|
|
&format!("{}&<>", "🚀".repeat(THREAD_TITLE_PROMPT_MAX_BYTES)),
|
|
Some(MessagePhase::FinalAnswer),
|
|
),
|
|
];
|
|
let conversation = recent_conversation_messages(&items).expect("substantive conversation");
|
|
let prompt = recent_conversation_thread_title_prompt(&conversation);
|
|
|
|
assert!(prompt.len() <= THREAD_TITLE_PROMPT_MAX_BYTES);
|
|
assert!(prompt.contains("<conversation>\n"));
|
|
assert!(prompt.contains("</conversation>"));
|
|
assert!(prompt.contains(
|
|
"<message role=\"user\">Fix <authentication> & login regressions</message>"
|
|
));
|
|
assert!(prompt.contains("<message role=\"assistant\">"));
|
|
assert_eq!(prompt.matches("<message role=").count(), 2);
|
|
assert_eq!(prompt.matches("</message>").count(), 2);
|
|
}
|
|
|
|
#[test]
|
|
fn recent_conversation_prompt_never_splits_an_escaped_markup_entity() {
|
|
let items = vec![title_user_message(
|
|
"user",
|
|
&"<&>".repeat(THREAD_TITLE_PROMPT_MAX_BYTES),
|
|
)];
|
|
let conversation = recent_conversation_messages(&items).expect("substantive conversation");
|
|
let prompt = recent_conversation_thread_title_prompt(&conversation);
|
|
|
|
assert!(prompt.len() <= THREAD_TITLE_PROMPT_MAX_BYTES);
|
|
let text = conversation
|
|
.strip_prefix("<conversation>\n<message role=\"user\">")
|
|
.and_then(|text| text.strip_suffix("</message>\n</conversation>"))
|
|
.expect("complete message markup");
|
|
for fragment in text.split('&').skip(/*n*/ 1) {
|
|
assert!(
|
|
fragment.starts_with("lt;")
|
|
|| fragment.starts_with("gt;")
|
|
|| fragment.starts_with("amp;")
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn normalizes_generated_title_whitespace() {
|
|
assert_eq!(
|
|
parse_thread_title(r#"{"title":" Fix \n\t login errors "}"#),
|
|
Some("Fix login errors".to_string())
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn removes_wrapping_quotes_and_trailing_punctuation_from_generated_titles() {
|
|
for title in [
|
|
r#""Fix login errors!""#,
|
|
"'Fix login errors?'",
|
|
"`Fix login errors.`",
|
|
"“Fix login errors!”",
|
|
] {
|
|
let response = serde_json::json!({ "title": title }).to_string();
|
|
|
|
assert_eq!(
|
|
parse_thread_title(&response),
|
|
Some("Fix login errors".to_string()),
|
|
"response: {response}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn preserves_meaningful_leading_punctuation_in_generated_titles() {
|
|
for (title, expected) in [
|
|
(".NET migration.", ".NET migration"),
|
|
("!important styling!", "!important styling"),
|
|
] {
|
|
let response = serde_json::json!({ "title": title }).to_string();
|
|
|
|
assert_eq!(
|
|
parse_thread_title(&response),
|
|
Some(expected.to_string()),
|
|
"response: {response}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_invalid_or_empty_generated_titles() {
|
|
for response in [
|
|
"",
|
|
"not json",
|
|
"null",
|
|
"true",
|
|
"42",
|
|
"[]",
|
|
r#"["title"]"#,
|
|
r#""plain title""#,
|
|
"{}",
|
|
r#"{"title":7}"#,
|
|
r#"{"title":"valid","extra":true}"#,
|
|
r#"{"title":""}"#,
|
|
r#"{"title":" \t "}"#,
|
|
] {
|
|
assert_eq!(parse_thread_title(response), None, "response: {response}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn truncates_generated_titles_without_splitting_unicode() {
|
|
let expected = "🚀".repeat(THREAD_TITLE_MAX_CHARS);
|
|
let response = serde_json::json!({ "title": format!("{expected}x") }).to_string();
|
|
|
|
assert_eq!(parse_thread_title(&response), Some(expected));
|
|
}
|
|
|
|
fn title_user_message(id: &str, text: &str) -> ThreadItemPayload {
|
|
ThreadItemPayload::UserMessage {
|
|
id: id.to_string(),
|
|
client_id: None,
|
|
content: vec![UserInput::Text {
|
|
text: text.to_string(),
|
|
text_elements: Vec::new(),
|
|
}],
|
|
}
|
|
}
|
|
|
|
fn title_agent_message(id: &str, text: &str, phase: Option<MessagePhase>) -> ThreadItemPayload {
|
|
ThreadItemPayload::AgentMessage {
|
|
moderation: None,
|
|
id: id.to_string(),
|
|
text: text.to_string(),
|
|
phase,
|
|
memory_citation: None,
|
|
delivery: None,
|
|
questions: None,
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn failed_thread_title_requests_are_removed() -> color_eyre::Result<()> {
|
|
let mut app = make_test_app().await;
|
|
let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
|
let started = app_server.start_thread(&app.config).await?;
|
|
let thread_id = started.session.thread_id;
|
|
app.enqueue_primary_thread_session(started.session, started.turns)
|
|
.await?;
|
|
let suggestion = ThreadTitleDestination::RenameSuggestion {
|
|
request_id: uuid::Uuid::new_v4(),
|
|
};
|
|
app.pending_thread_titles.extend([
|
|
(
|
|
(thread_id, ThreadTitleDestination::Automatic),
|
|
CancellationToken::new(),
|
|
),
|
|
((thread_id, suggestion), CancellationToken::new()),
|
|
]);
|
|
|
|
app.on_thread_title_started(
|
|
&mut app_server,
|
|
thread_id,
|
|
ThreadTitleDestination::Automatic,
|
|
"prompt".to_string(),
|
|
/*expected_name*/ None,
|
|
/*fallback_title*/ None,
|
|
/*effort*/ None,
|
|
Err("startup failed".to_string()),
|
|
CancellationToken::new(),
|
|
);
|
|
app.on_thread_title_started(
|
|
&mut app_server,
|
|
thread_id,
|
|
suggestion,
|
|
"prompt".to_string(),
|
|
/*expected_name*/ None,
|
|
/*fallback_title*/ None,
|
|
/*effort*/ None,
|
|
Ok("invalid-thread-id".to_string()),
|
|
CancellationToken::new(),
|
|
);
|
|
assert!(app.pending_thread_titles.is_empty());
|
|
|
|
let mut tui = crate::tui::test_support::make_test_tui()?;
|
|
app.pending_thread_titles.insert(
|
|
(thread_id, ThreadTitleDestination::Automatic),
|
|
CancellationToken::new(),
|
|
);
|
|
app.handle_event(
|
|
&mut tui,
|
|
&mut app_server,
|
|
AppEvent::GeneratedThreadTitle {
|
|
cancellation: CancellationToken::new(),
|
|
thread_id,
|
|
temporary_thread_id: Some(ThreadId::new()),
|
|
destination: ThreadTitleDestination::Automatic,
|
|
result: Err("generation failed".to_string()),
|
|
},
|
|
)
|
|
.await?;
|
|
assert!(app.pending_thread_titles.is_empty());
|
|
app_server.shutdown().await?;
|
|
Ok(())
|
|
}
|