mirror of
https://github.com/openai/codex.git
synced 2026-11-21 22:50:37 +00:00
Offer safer rewrites after safety blocks in the TUI (#57365)
## What changed - Show selectable safer follow-ups alongside safety-block explanations, with an option to enable Daybreak when disabled. - Submit the selected rewrite in a verified fork before the blocked turn, preserving the original chat's draft and current model settings. Mark the new turn with `safety_recourse_follow_up`. - Filter suggestions that could invoke commands, skills, apps, or plugins, and suppress recourse for unsupported servers and non-primary threads. ## Testing Extend coverage for fork history, draft preservation, model selection, turn metadata, suggestion filtering, and the Daybreak picker. GitOrigin-RevId: 49052df6301b6bfbba07262d40b007dcf97bb7c9
This commit is contained in:
@@ -264,6 +264,7 @@ mod resume_preparation;
|
||||
mod right_click_paste;
|
||||
pub(crate) use right_click_paste::PasteEnvironment;
|
||||
mod safety_buffering;
|
||||
mod safety_recourse;
|
||||
mod server_version_notice;
|
||||
mod session_lifecycle;
|
||||
mod session_picker;
|
||||
|
||||
@@ -166,8 +166,18 @@ impl App {
|
||||
async fn handle_server_notification_event(
|
||||
&mut self,
|
||||
app_server_client: &AppServerSession,
|
||||
notification: ServerNotification,
|
||||
mut notification: ServerNotification,
|
||||
) {
|
||||
if let ServerNotification::TurnModerationMetadata(metadata) = &mut notification
|
||||
&& (!super::safety_recourse::supports_server(app_server_client)
|
||||
|| self
|
||||
.primary_thread_id
|
||||
.is_none_or(|id| id.to_string() != metadata.thread_id))
|
||||
&& let Some(metadata) = metadata.metadata.as_object_mut()
|
||||
{
|
||||
metadata.remove("safety_block");
|
||||
metadata.remove("safety_recourse");
|
||||
}
|
||||
// A picker can leave an old runtime's close notification queued while the same thread
|
||||
// is resumed. Thread IDs survive reloads, so confirm that the displayed thread is still
|
||||
// unloaded before routing a close that would exit the TUI or switch away from it.
|
||||
|
||||
@@ -632,16 +632,7 @@ impl App {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if !app_server.uses_embedded_app_server() {
|
||||
// Daemon tasks can start while the fork RPC is pending.
|
||||
for id in self.thread_event_channels.keys().copied()
|
||||
.chain(self.agent_navigation.tracked_thread_ids())
|
||||
.filter(|id| !self.side_threads.contains_key(id))
|
||||
{
|
||||
self.agents_overview.dispatched_requests.entry(id).or_default();
|
||||
}
|
||||
}
|
||||
self.detach_current_thread_for_navigation(app_server, Some(forked.session.thread_id)).await;
|
||||
self.detach_current_thread_for_fork(app_server, forked.session.thread_id).await;
|
||||
match self
|
||||
.replace_chat_widget_with_app_server_thread(
|
||||
tui,
|
||||
@@ -1247,6 +1238,16 @@ impl App {
|
||||
)
|
||||
.await;
|
||||
}
|
||||
AppEvent::ContinueSafetyRecourse {
|
||||
thread_id,
|
||||
turn_id,
|
||||
prompt,
|
||||
} => {
|
||||
super::safety_recourse::continue_with_rewrite(
|
||||
self, tui, app_server, thread_id, turn_id, prompt,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
AppEvent::AppendMessageHistoryEntry { thread_id, text } => {
|
||||
self.append_message_history_entry(thread_id, text);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
//! Check recourse availability and submit selected follow-ups on verified forks.
|
||||
|
||||
use super::session_lifecycle::ThreadAttachPresentation;
|
||||
use super::*;
|
||||
use crate::app_server_session::ForkGoalContinuation;
|
||||
use color_eyre::eyre::OptionExt;
|
||||
use color_eyre::eyre::ensure;
|
||||
|
||||
pub(super) fn supports_server(app_server: &AppServerSession) -> bool {
|
||||
// Remote servers before 0.151.0 silently ignore the required turn trigger.
|
||||
let minimum = semver::Version::new(/*major*/ 0, /*minor*/ 151, /*patch*/ 0);
|
||||
let Some(version) = app_server.server_version() else {
|
||||
return app_server.uses_embedded_app_server();
|
||||
};
|
||||
semver::Version::parse(version).is_ok_and(|version| version >= minimum)
|
||||
}
|
||||
|
||||
pub(super) async fn continue_with_rewrite(
|
||||
app: &mut App,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
turn_id: String,
|
||||
prompt: String,
|
||||
) {
|
||||
if !supports_server(app_server)
|
||||
|| app.active_thread_id != Some(thread_id)
|
||||
|| app.primary_thread_id != Some(thread_id)
|
||||
|| app.chat_widget.last_turn_id() != Some(turn_id.as_str())
|
||||
|| app.chat_widget.is_user_turn_pending_or_running()
|
||||
|| app.chat_widget.has_queued_follow_up_messages()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let mut attached_fork = None;
|
||||
let result = async {
|
||||
ensure!(
|
||||
!app.pending_server_profiles.contains_key(&thread_id),
|
||||
"permissions are still updating"
|
||||
);
|
||||
let source = app_server
|
||||
.thread_read(thread_id, /*include_turns*/ false)
|
||||
.await?;
|
||||
let source_turns = app_server
|
||||
.thread_turns_page(thread_id, /*cursor*/ None, /*limit*/ 2)
|
||||
.await?;
|
||||
let is_blocked_turn = |turn: &Turn| turn.id == turn_id && turn.status == TurnStatus::Failed;
|
||||
ensure!(
|
||||
!source.ephemeral
|
||||
&& source_turns.data.first().is_some_and(is_blocked_turn)
|
||||
&& (source_turns.data.len() > 1 || source_turns.next_cursor.is_none()),
|
||||
"the blocked turn is no longer the latest turn"
|
||||
);
|
||||
let mut config = app.chat_widget.config_ref().clone();
|
||||
config.model = Some(app.chat_widget.current_model().to_string());
|
||||
config.model_reasoning_effort = app.chat_widget.current_reasoning_effort();
|
||||
config.daybreak_enabled = app.chat_widget.daybreak_enabled;
|
||||
let selected_profile = app.selected_server_profile(thread_id);
|
||||
let started = app_server
|
||||
.fork_thread_at(
|
||||
&app.local_settings,
|
||||
config.clone(),
|
||||
thread_id,
|
||||
/*last_turn_id*/ None,
|
||||
/*before_turn_id*/ Some(turn_id.clone()),
|
||||
// Deferring also copies the source's current goal, beyond the turn cutoff.
|
||||
ForkGoalContinuation::StartIfIdle,
|
||||
selected_profile.as_ref(),
|
||||
)
|
||||
.await?;
|
||||
let fork_id = started.session.thread_id;
|
||||
let fork_turns = app_server
|
||||
.thread_turns_page(fork_id, /*cursor*/ None, /*limit*/ 1)
|
||||
.await?;
|
||||
let latest = app_server
|
||||
.thread_turns_page(thread_id, /*cursor*/ None, /*limit*/ 1)
|
||||
.await?;
|
||||
ensure!(
|
||||
!started.blocks_direct_input
|
||||
&& started.session.forked_from_id == Some(thread_id)
|
||||
&& latest.data.first().is_some_and(is_blocked_turn)
|
||||
&& (!fork_turns.data.is_empty() || fork_turns.next_cursor.is_none())
|
||||
&& fork_turns.data.first().map(|turn| &turn.id)
|
||||
== source_turns.data.get(1).map(|turn| &turn.id),
|
||||
"the fork boundary could not be verified"
|
||||
);
|
||||
app.config = config;
|
||||
if let Some(input) = app.chat_widget.capture_thread_input_state() {
|
||||
app.agents_overview.input_states.insert(thread_id, input);
|
||||
}
|
||||
app.detach_current_thread_for_fork(app_server, fork_id)
|
||||
.await;
|
||||
attached_fork = Some(fork_id);
|
||||
app.replace_chat_widget_with_app_server_thread(
|
||||
tui,
|
||||
started,
|
||||
ThreadAttachPresentation::SessionLineage,
|
||||
/*initial_user_message*/ None,
|
||||
)
|
||||
.await?;
|
||||
if selected_profile.is_some() {
|
||||
app.adopt_inherited_server_selection();
|
||||
}
|
||||
ensure!(!app.thread_unavailable(fork_id), "the fork is unavailable");
|
||||
let turn = app
|
||||
.chat_widget
|
||||
.prepare_safety_recourse_rewrite(&prompt)
|
||||
.ok_or_eyre("the follow-up could not be submitted")?;
|
||||
app.submit_thread_op(app_server, fork_id, turn).await
|
||||
}
|
||||
.await;
|
||||
match result {
|
||||
Ok(()) if app.chat_widget.is_user_turn_pending_or_running() => return,
|
||||
Ok(()) => {} // Submission was rejected and already showed its error.
|
||||
Err(error) if app.recover_transport_error(&error) && attached_fork.is_some() => return,
|
||||
Err(_) => {
|
||||
let text = history_cell::sanitize_user_text((&prompt).into());
|
||||
let message = format!("Couldn’t start a new chat for this rewrite. {text}");
|
||||
if !app.chat_widget.handle_turn_start_rejection(message.clone()) {
|
||||
app.chat_widget.add_error_message(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
if attached_fork.is_some_and(|fork_id| app.active_thread_id == Some(fork_id)) {
|
||||
app.chat_widget
|
||||
.restore_user_message_to_composer(prompt.into());
|
||||
}
|
||||
}
|
||||
@@ -332,6 +332,7 @@ async fn backend_banner_fallback_handles_settings_failure_and_queued_manual_sele
|
||||
client,
|
||||
crate::app_server_session::ThreadParamsMode::Embedded,
|
||||
);
|
||||
assert!(!crate::app::safety_recourse::supports_server(&server));
|
||||
while events.try_recv().is_ok() {}
|
||||
let pending_turn = if use_reserve && error_code.is_some() {
|
||||
app.chat_widget
|
||||
|
||||
@@ -17,6 +17,8 @@ use codex_protocol::permissions::FileSystemSpecialPath;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use codex_protocol::turn_input::CyberAccessProgram;
|
||||
use codex_utils_absolute_path::test_support::PathExt;
|
||||
use core_test_support::context_snapshot;
|
||||
use core_test_support::context_snapshot::ContextSnapshotOptions;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
use core_test_support::responses::ev_completed;
|
||||
@@ -173,6 +175,7 @@ async fn safety_recourse_handles_a_policy_block() -> Result<()> {
|
||||
let (mut app, mut events, _) = make_test_app_with_channels().await;
|
||||
let model = responses::start_mock_server().await;
|
||||
app_test_support::MockResponsesConfig::new(&model.uri())
|
||||
.with_root_config("instructions = 'Help the user.'")
|
||||
.write(app.config.codex_home.as_path())?;
|
||||
app.config = app
|
||||
.rebuild_config_for_cwd(app.config.cwd.to_path_buf())
|
||||
@@ -231,9 +234,13 @@ async fn safety_recourse_handles_a_policy_block() -> Result<()> {
|
||||
/*initial_user_message*/ None,
|
||||
)
|
||||
.await?;
|
||||
let selected_model = "gpt-5.1";
|
||||
app.chat_widget.set_model(selected_model);
|
||||
submit_prompt(&mut app, "Blocked original prompt");
|
||||
app.submit_thread_op(&mut server, source_id, next_user_turn_event(&mut events))
|
||||
.await?;
|
||||
app.chat_widget
|
||||
.apply_external_edit(UNSENT_DRAFT.to_string());
|
||||
loop {
|
||||
let event = server.next_event().await.expect("moderation metadata");
|
||||
let is_metadata = matches!(&event.event, AppServerEvent::ServerNotification(notification)
|
||||
@@ -266,6 +273,42 @@ async fn safety_recourse_handles_a_policy_block() -> Result<()> {
|
||||
continue;
|
||||
}
|
||||
insta::assert_snapshot!("safety_recourse", format!("{loading}\n\n{notice}"));
|
||||
let picker = render_bottom_popup(&app.chat_widget, /*width*/ 80);
|
||||
let goal = server
|
||||
.thread_goal_set(
|
||||
source_id,
|
||||
Some("Excluded objective".into()),
|
||||
Some(codex_app_server_protocol::ThreadGoalStatus::Paused),
|
||||
/*token_budget*/ None,
|
||||
)
|
||||
.await?
|
||||
.goal;
|
||||
responses::mount_sse_once(&model, responses::sse_completed("rewrite")).await;
|
||||
let draft = app.chat_widget.capture_thread_input_state().unwrap();
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert_eq!(render_bottom_popup(&app.chat_widget, /*width*/ 80), picker);
|
||||
let selection = std::iter::from_fn(|| events.try_recv().ok())
|
||||
.find(|event| matches!(event, AppEvent::ContinueSafetyRecourse { .. }))
|
||||
.expect("rewrite selection");
|
||||
app.handle_event(&mut tui, &mut server, selection).await?;
|
||||
let fork_id = app.active_thread_id.expect("forked thread");
|
||||
assert_eq!(server.thread_goal_get(fork_id).await?.goal, None);
|
||||
assert_eq!(server.thread_goal_get(source_id).await?.goal, Some(goal));
|
||||
assert_eq!(app.agents_overview.input_states[&source_id], draft);
|
||||
wait_for_turn_completed(&mut app, &mut server, fork_id).await;
|
||||
let requests = responses::received_responses_requests(&model).await;
|
||||
assert_eq!(requests[1].body_json()["model"], selected_model);
|
||||
insta::assert_snapshot!(
|
||||
"safety_recourse_request_history",
|
||||
context_snapshot::format_request_history_snapshot(
|
||||
"The fork excludes the blocked turn and submits the selected rewrite.",
|
||||
&requests,
|
||||
&ContextSnapshotOptions::default().rewrite_known_segments(),
|
||||
)
|
||||
);
|
||||
let header = requests[1].header("x-codex-turn-metadata").unwrap();
|
||||
let metadata: Value = serde_json::from_str(&header)?;
|
||||
assert_eq!(metadata["turn_trigger"], "safety_recourse_follow_up");
|
||||
}
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
---
|
||||
source: tui/src/app/tests/safety_buffering.rs
|
||||
assertion_line: 284
|
||||
expression: "context_snapshot::format_request_history_snapshot(\"The fork excludes the blocked turn and submits the selected rewrite.\",\n&requests, &ContextSnapshotOptions::default().rewrite_known_segments(),)"
|
||||
---
|
||||
Scenario: The fork excludes the blocked turn and submits the selected rewrite.
|
||||
|
||||
## Window 1
|
||||
-- request 1 (turn) --
|
||||
00:message/developer:
|
||||
Help the user.
|
||||
01:message/developer[3]:
|
||||
[01] <SKILLS_INSTRUCTIONS>
|
||||
[02] <PERMISSIONS_INSTRUCTIONS>
|
||||
[03] <COLLABORATION_MODE>
|
||||
02:message/user:
|
||||
<ENVIRONMENT_CONTEXT>
|
||||
03:message/user:
|
||||
Blocked original prompt
|
||||
|
||||
## Window 2 (after request 1: input diverged at item 03, settings changed (prompt_cache_key))
|
||||
-- request 2 (turn) --
|
||||
00:message/developer:
|
||||
Help the user.
|
||||
01:message/developer[3]:
|
||||
[01] <SKILLS_INSTRUCTIONS>
|
||||
[02] <PERMISSIONS_INSTRUCTIONS>
|
||||
[03] <COLLABORATION_MODE>
|
||||
02:message/user:
|
||||
<ENVIRONMENT_CONTEXT>
|
||||
03:message/user:
|
||||
Help me recover my account safely.
|
||||
@@ -1428,6 +1428,7 @@ async fn remote_overview_startup_hides_disabled_older_server_notice() -> Result<
|
||||
ThreadParamsMode::Remote,
|
||||
);
|
||||
|
||||
assert!(crate::app::safety_recourse::supports_server(&session));
|
||||
assert_eq!(
|
||||
app.initialize_server_version_notice("2.1.0", session.server_version()),
|
||||
None
|
||||
|
||||
@@ -118,6 +118,30 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn detach_current_thread_for_fork(
|
||||
&mut self,
|
||||
app_server: &mut AppServerSession,
|
||||
fork_id: ThreadId,
|
||||
) {
|
||||
if !app_server.uses_embedded_app_server() {
|
||||
// Daemon tasks can start while the fork RPC is pending.
|
||||
for id in self
|
||||
.thread_event_channels
|
||||
.keys()
|
||||
.copied()
|
||||
.chain(self.agent_navigation.tracked_thread_ids())
|
||||
.filter(|id| !self.side_threads.contains_key(id))
|
||||
{
|
||||
self.agents_overview
|
||||
.dispatched_requests
|
||||
.entry(id)
|
||||
.or_default();
|
||||
}
|
||||
}
|
||||
self.detach_current_thread_for_navigation(app_server, Some(fork_id))
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(super) async fn activate_thread_for_replay(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
|
||||
@@ -11,6 +11,7 @@ pub(super) async fn try_submit_user_turn(
|
||||
op: &AppCommand,
|
||||
) -> Result<bool> {
|
||||
let AppCommand::UserTurn {
|
||||
turn_trigger,
|
||||
client_user_message_id,
|
||||
items,
|
||||
cwd,
|
||||
@@ -28,6 +29,9 @@ pub(super) async fn try_submit_user_turn(
|
||||
return Ok(false);
|
||||
};
|
||||
if let Some(turn_id) = app.active_turn_id_for_thread(thread_id).await {
|
||||
if *turn_trigger != "user" {
|
||||
color_eyre::eyre::bail!("the fork already has an active turn");
|
||||
}
|
||||
let mut steer_turn_id = turn_id;
|
||||
let mut retried_after_turn_mismatch = false;
|
||||
loop {
|
||||
@@ -155,6 +159,7 @@ pub(super) async fn try_submit_user_turn(
|
||||
let response = app_server
|
||||
.turn_start(
|
||||
thread_id,
|
||||
turn_trigger,
|
||||
client_user_message_id.clone(),
|
||||
items.to_vec(),
|
||||
cwd.clone(),
|
||||
|
||||
@@ -117,6 +117,7 @@ pub(crate) enum AppCommand {
|
||||
command: String,
|
||||
},
|
||||
UserTurn {
|
||||
turn_trigger: &'static str,
|
||||
client_user_message_id: String,
|
||||
items: Vec<UserInput>,
|
||||
cwd: PathBuf,
|
||||
@@ -224,6 +225,7 @@ impl AppCommand {
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn user_turn(
|
||||
turn_trigger: &'static str,
|
||||
client_user_message_id: String,
|
||||
items: Vec<UserInput>,
|
||||
cwd: PathBuf,
|
||||
@@ -237,6 +239,7 @@ impl AppCommand {
|
||||
collaboration_mode: Option<CollaborationMode>,
|
||||
) -> Self {
|
||||
Self::UserTurn {
|
||||
turn_trigger,
|
||||
client_user_message_id,
|
||||
items,
|
||||
cwd,
|
||||
|
||||
@@ -465,6 +465,13 @@ pub(crate) enum AppEvent {
|
||||
prompt: UserMessage,
|
||||
},
|
||||
|
||||
/// Fork before a blocked turn and send the selected safer follow-up.
|
||||
ContinueSafetyRecourse {
|
||||
thread_id: ThreadId,
|
||||
turn_id: String,
|
||||
prompt: String,
|
||||
},
|
||||
|
||||
/// Deliver a synthetic history lookup response to a specific thread channel.
|
||||
ThreadHistoryEntryResponse {
|
||||
thread_id: ThreadId,
|
||||
|
||||
@@ -1513,6 +1513,7 @@ impl AppServerSession {
|
||||
pub(crate) async fn turn_start(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
turn_trigger: &str,
|
||||
client_user_message_id: String,
|
||||
items: Vec<UserInput>,
|
||||
cwd: PathBuf,
|
||||
@@ -1531,7 +1532,7 @@ impl AppServerSession {
|
||||
let request_id = self.next_request_id();
|
||||
let mut params = TurnStartParams {
|
||||
thread_id: thread_id.to_string(),
|
||||
turn_trigger: Some("user".to_string()),
|
||||
turn_trigger: Some(turn_trigger.to_string()),
|
||||
client_user_message_id: Some(client_user_message_id),
|
||||
input: items,
|
||||
output_schema,
|
||||
@@ -3263,6 +3264,7 @@ mod tests {
|
||||
let (turn, sent_params) = tokio::join!(
|
||||
app_server.turn_start(
|
||||
thread_id,
|
||||
"user",
|
||||
client_user_message_id.clone(),
|
||||
input.clone(),
|
||||
test_path_buf("/local/workspace"),
|
||||
|
||||
@@ -135,6 +135,7 @@ stream_max_retries = 0
|
||||
let turn = app_server
|
||||
.turn_start(
|
||||
started.session.thread_id,
|
||||
"user",
|
||||
"tui-user-message".to_string(),
|
||||
vec![UserInput::Text {
|
||||
text: "hello".to_string(),
|
||||
|
||||
@@ -92,6 +92,7 @@ stream_max_retries = 0
|
||||
app_server
|
||||
.turn_start(
|
||||
thread_id,
|
||||
"user",
|
||||
"user-message".to_string(),
|
||||
vec![UserInput::Text {
|
||||
text: "hello".to_string(),
|
||||
|
||||
@@ -111,6 +111,27 @@ impl ChatWidget {
|
||||
.1
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_safety_recourse_rewrite(&mut self, prompt: &str) -> Option<AppCommand> {
|
||||
if !self.is_session_configured()
|
||||
|| self.is_user_turn_pending_or_running()
|
||||
|| self.pending_image_submission.is_some()
|
||||
|| self.input_queue.rate_limit_recovery_pending
|
||||
|| self.safety_recourse.is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let op = self
|
||||
.submit_user_message_with_history_and_shell_escape_policy(
|
||||
prompt.into(),
|
||||
UserMessageHistoryRecord::UserMessageText,
|
||||
ShellEscapePolicy::Disallow,
|
||||
UserMessageSource::SafetyRecourse,
|
||||
)
|
||||
.1?;
|
||||
self.safety_buffering_source = UserMessageSource::Prompt;
|
||||
Some(op)
|
||||
}
|
||||
|
||||
pub(super) fn submit_user_message_with_history_and_shell_escape_policy(
|
||||
&mut self,
|
||||
user_message: UserMessage,
|
||||
@@ -455,6 +476,11 @@ impl ChatWidget {
|
||||
let service_tier = self.service_tier_update_for_core();
|
||||
let active_permission_profile = self.config.permissions.active_permission_profile();
|
||||
let op = AppCommand::user_turn(
|
||||
if source == UserMessageSource::SafetyRecourse {
|
||||
"safety_recourse_follow_up"
|
||||
} else {
|
||||
"user"
|
||||
},
|
||||
client_user_message_id.clone(),
|
||||
items,
|
||||
self.config.cwd.to_path_buf(),
|
||||
@@ -492,10 +518,11 @@ impl ChatWidget {
|
||||
));
|
||||
}
|
||||
|
||||
if !self.submit_op(op.clone()) {
|
||||
// The app submits recourse turns directly to the verified fork.
|
||||
if source != UserMessageSource::SafetyRecourse && !self.submit_op(op.clone()) {
|
||||
return (false, None);
|
||||
}
|
||||
if source == UserMessageSource::Prompt {
|
||||
if source != UserMessageSource::QuestionAnswer {
|
||||
self.bottom_pane.clear_pending_questions();
|
||||
}
|
||||
self.dismiss_backend_banner_for_new_turn();
|
||||
|
||||
@@ -87,6 +87,13 @@ impl ChatWidget {
|
||||
self.on_thread_settings_updated(notification);
|
||||
}
|
||||
ServerNotification::TurnStarted(notification) => {
|
||||
if self
|
||||
.bottom_pane
|
||||
.dismiss_view_by_id(safety_recourse::VIEW_ID)
|
||||
&& self.bottom_pane.no_modal_or_popup_active()
|
||||
{
|
||||
self.on_modal_or_popup_closed();
|
||||
}
|
||||
self.safety_recourse = None;
|
||||
if from_replay {
|
||||
self.restore_realtime_transcripts_before_turn(¬ification.turn.id);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Turn-scoped safety recourse: match the terminal policy error and explain the block.
|
||||
//! Turn-scoped safety recourse: match the terminal policy error and offer safer rewrites.
|
||||
|
||||
mod metadata;
|
||||
|
||||
@@ -6,11 +6,14 @@ use super::*;
|
||||
use codex_app_server_protocol::TurnError;
|
||||
use codex_app_server_protocol::TurnModerationMetadataNotification;
|
||||
use metadata::Domain;
|
||||
use metadata::Recourse;
|
||||
|
||||
pub(super) const VIEW_ID: &str = "safety-recourse";
|
||||
|
||||
pub(super) struct PendingRecourse {
|
||||
domain: Domain,
|
||||
pub(super) notice: Box<dyn HistoryCell>,
|
||||
result: Option<String>,
|
||||
result: Option<Recourse>,
|
||||
pub(super) deferred_error: Option<TurnError>,
|
||||
}
|
||||
|
||||
@@ -83,20 +86,60 @@ pub(super) fn render_failure(
|
||||
if chat.has_queued_follow_up_messages() || !matches_error(pending.domain, error) {
|
||||
return false;
|
||||
}
|
||||
let (Some(thread_id), Some(turn_id)) = (chat.thread_id(), chat.last_turn_id()) else {
|
||||
return false;
|
||||
};
|
||||
let mut items = Vec::new();
|
||||
let subtitle = (!result.suggestions.is_empty())
|
||||
.then(|| "Choosing a rewrite sends it in a new chat.".into());
|
||||
for (label, prompt) in result.suggestions {
|
||||
let turn_id = turn_id.to_string();
|
||||
items.push(SelectionItem {
|
||||
name: label,
|
||||
actions: vec![Box::new(move |tx| {
|
||||
tx.send(AppEvent::ContinueSafetyRecourse {
|
||||
thread_id,
|
||||
turn_id: turn_id.clone(),
|
||||
prompt: prompt.clone(),
|
||||
})
|
||||
})],
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
let mut cell = match pending.domain {
|
||||
Domain::Bio => history_cell::new_safety_access_block_event(),
|
||||
Domain::Cyber => {
|
||||
let notice = chat.cyber_policy_notice();
|
||||
if notice == crate::daybreak::Notice::Disabled {
|
||||
return false;
|
||||
items.push(SelectionItem {
|
||||
name: "Enable Daybreak".into(),
|
||||
actions: vec![Box::new(move |tx| {
|
||||
tx.send(AppEvent::PersistDaybreakSelection {
|
||||
thread_id,
|
||||
enabled: true,
|
||||
})
|
||||
})],
|
||||
dismiss_on_select: true,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
history_cell::new_cyber_policy_error_event(notice)
|
||||
}
|
||||
};
|
||||
cell.explanation = Some(result);
|
||||
cell.explanation = Some(result.explanation);
|
||||
chat.input_queue.submit_pending_steers_after_interrupt = false;
|
||||
chat.finalize_turn();
|
||||
chat.add_to_history(cell);
|
||||
if !items.is_empty() {
|
||||
chat.bottom_pane.show_selection_view(SelectionViewParams {
|
||||
view_id: Some(VIEW_ID),
|
||||
title: Some("Here are a few ways I can help:".into()),
|
||||
subtitle,
|
||||
items,
|
||||
..SelectionViewParams::picker()
|
||||
});
|
||||
chat.defer_input_until_settings_applied();
|
||||
}
|
||||
chat.request_redraw();
|
||||
true
|
||||
}
|
||||
|
||||
@@ -45,7 +45,12 @@ struct Suggestion {
|
||||
prompt_text: String,
|
||||
}
|
||||
|
||||
pub(super) fn parse(mut value: Value) -> Option<(Domain, Option<String>)> {
|
||||
pub(super) struct Recourse {
|
||||
pub(super) explanation: String,
|
||||
pub(super) suggestions: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
pub(super) fn parse(mut value: Value) -> Option<(Domain, Option<Recourse>)> {
|
||||
let object = value.as_object_mut()?;
|
||||
let recourse = object.remove("safety_recourse").filter(|v| !v.is_null());
|
||||
let Some(value) = recourse else {
|
||||
@@ -135,6 +140,11 @@ pub(super) fn parse(mut value: Value) -> Option<(Domain, Option<String>)> {
|
||||
_ => return None,
|
||||
};
|
||||
let mut prompts = HashSet::new();
|
||||
let mut suggestions = Vec::new();
|
||||
let labels = wire
|
||||
.suggestions
|
||||
.each_ref()
|
||||
.map(|s| s.label.trim().to_lowercase());
|
||||
for suggestion in &wire.suggestions {
|
||||
if !valid_text(&suggestion.label, /*max_chars*/ 80)
|
||||
|| !valid_text(&suggestion.prompt_text, /*max_chars*/ 2_000)
|
||||
@@ -142,6 +152,22 @@ pub(super) fn parse(mut value: Value) -> Option<(Domain, Option<String>)> {
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// Only offer actions the composer can safely submit or restore.
|
||||
let label = suggestion.label.trim();
|
||||
let prompt = suggestion.prompt_text.trim();
|
||||
let label_key = label.to_lowercase();
|
||||
if suggestion.label.contains(char::is_control)
|
||||
|| suggestion.label.contains(['\u{2028}', '\u{2029}'])
|
||||
|| prompt.len() > 1_000
|
||||
|| prompt.starts_with(['!', '/'])
|
||||
|| crate::async_question_reply::parse(prompt).is_some()
|
||||
|| super::super::skills::contains_tool_mention(prompt)
|
||||
|| (wire.domain == Domain::Cyber && label.eq_ignore_ascii_case("Enable Daybreak"))
|
||||
|| labels.iter().filter(|key| **key == label_key).count() > 1
|
||||
{
|
||||
continue;
|
||||
}
|
||||
suggestions.push((label.into(), prompt.into()));
|
||||
}
|
||||
let overview = "We can still help with an overview of ";
|
||||
let (lead, offer) = match wire.domain {
|
||||
@@ -149,7 +175,11 @@ pub(super) fn parse(mut value: Value) -> Option<(Domain, Option<String>)> {
|
||||
Domain::Cyber => (cyber_lead, overview),
|
||||
};
|
||||
let explanation = format!("We take extra caution {lead}{concern}. {offer}{help}.");
|
||||
Some((wire.domain, Some(explanation)))
|
||||
let result = Recourse {
|
||||
explanation,
|
||||
suggestions,
|
||||
};
|
||||
Some((wire.domain, Some(result)))
|
||||
}
|
||||
|
||||
fn valid_text(value: &str, max_chars: usize) -> bool {
|
||||
|
||||
@@ -21,6 +21,7 @@ use codex_protocol::parse_command::ParsedCommand;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::LegacyAppPathString;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_plugins::mention_syntax::PLUGIN_TEXT_MENTION_SIGIL;
|
||||
use codex_utils_plugins::mention_syntax::TOOL_MENTION_SIGIL;
|
||||
|
||||
impl ChatWidget {
|
||||
@@ -208,6 +209,15 @@ pub(crate) fn collect_tool_mentions(
|
||||
mentions
|
||||
}
|
||||
|
||||
/// Generated follow-ups must not activate a skill, app, or plugin through their text.
|
||||
pub(super) fn contains_tool_mention(text: &str) -> bool {
|
||||
let mentions = extract_tool_mentions_from_text(text);
|
||||
let plugins = extract_tool_mentions_from_text_with_sigil(text, PLUGIN_TEXT_MENTION_SIGIL);
|
||||
!mentions.names.is_empty()
|
||||
|| !mentions.linked_paths.is_empty()
|
||||
|| !plugins.linked_paths.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn find_skill_mentions_with_tool_mentions(
|
||||
mentions: &ToolMentions,
|
||||
skills: &[SkillMetadata],
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
---
|
||||
source: tui/src/chatwidget/tests/status_and_layout.rs
|
||||
expression: "render_bottom_popup(&chat, 80)"
|
||||
---
|
||||
Here are a few ways I can help:
|
||||
Choosing a rewrite sends it in a new chat.
|
||||
|
||||
|
||||
› 1. Overview
|
||||
2. Recovery
|
||||
3. Prevention
|
||||
4. Enable Daybreak
|
||||
|
||||
enter select · esc back
|
||||
@@ -2433,10 +2433,13 @@ async fn reconnect_resumes_unsent_input_and_reconciles_confirmed_submissions() {
|
||||
for pending_start in [false, true] {
|
||||
let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
chat.thread_id = Some(ThreadId::new());
|
||||
if !pending_start {
|
||||
if pending_start {
|
||||
chat.prepare_safety_recourse_rewrite("first message")
|
||||
.unwrap();
|
||||
} else {
|
||||
handle_turn_started(&mut chat, "turn-1");
|
||||
chat.submit_user_message("first message".into());
|
||||
}
|
||||
chat.submit_user_message("first message".into());
|
||||
let client_id = if pending_start {
|
||||
chat.input_queue
|
||||
.pending_user_message_client_id
|
||||
@@ -2450,6 +2453,8 @@ async fn reconnect_resumes_unsent_input_and_reconciles_confirmed_submissions() {
|
||||
.push_back(UserMessage::from("follow-up").into());
|
||||
chat.pause_for_disconnect();
|
||||
let mut input = chat.capture_thread_input_state();
|
||||
let saved_source = input.as_ref().unwrap().safety_buffering_source;
|
||||
assert_eq!(saved_source, UserMessageSource::Prompt);
|
||||
// Missing history and unrelated receipts never authorize resubmitting uncertain input.
|
||||
for ids in [
|
||||
vec![],
|
||||
|
||||
@@ -185,6 +185,60 @@ async fn daybreak_refusal_offers_enable_for_the_next_turn() {
|
||||
);
|
||||
assert!(ops.try_recv().is_err());
|
||||
|
||||
let error = AppServerTurnError {
|
||||
message: "blocked".into(),
|
||||
codex_error_info: Some(CodexErrorInfo::CyberPolicy),
|
||||
misalignment: None,
|
||||
additional_details: None,
|
||||
};
|
||||
let reply = r#"<send_user_message_question_reply>{"questionItemId":"q","question":"Q","answer":"\u0024google-drive"}</send_user_message_question_reply>"#;
|
||||
let long_prompt = "界".repeat(334);
|
||||
for (label, prompt, eligible) in [
|
||||
("Hidden\nrow", "Explain access", false),
|
||||
("Overview", "Use $connector", false),
|
||||
("Overview", "Use [@tool](plugin://tool)", false),
|
||||
("Overview", reply, false),
|
||||
("Overview", &long_prompt, false),
|
||||
("Recovery", "Explain access", false),
|
||||
("Enable Daybreak", "Explain access", false),
|
||||
("Overview", "Explain access", true),
|
||||
] {
|
||||
handle_turn_started(&mut chat, "recourse");
|
||||
safety_recourse::on_metadata(
|
||||
&mut chat,
|
||||
codex_app_server_protocol::TurnModerationMetadataNotification {
|
||||
thread_id: thread_id.to_string(),
|
||||
turn_id: "recourse".into(),
|
||||
metadata: json!({"safety_recourse": {
|
||||
"schema_version": 1, "domain": "cyber", "source": "user_request",
|
||||
"source_message": {"id":"1", "kind":"ordinary_message", "role":"user"},
|
||||
"topic": "unauthorized_account_or_system_access",
|
||||
"suggestions": [
|
||||
{"label": label, "prompt_text": prompt},
|
||||
{"label": "Recovery", "prompt_text": "Explain account recovery"},
|
||||
{"label": "Prevention", "prompt_text": "Explain account protection"}
|
||||
]
|
||||
}}),
|
||||
},
|
||||
);
|
||||
let pending = chat.safety_recourse.take();
|
||||
assert!(safety_recourse::render_failure(&mut chat, pending, &error));
|
||||
let picker = render_bottom_popup(&chat, /*width*/ 80);
|
||||
assert!(picker.contains("Prevention"));
|
||||
assert_eq!(picker.contains("3. Prevention"), eligible);
|
||||
if !eligible {
|
||||
chat.handle_key_event(KeyCode::Esc.into());
|
||||
}
|
||||
}
|
||||
assert_chatwidget_snapshot!(
|
||||
"daybreak_recourse_picker",
|
||||
render_bottom_popup(&chat, /*width*/ 80)
|
||||
);
|
||||
chat.handle_key_event(KeyCode::Char('4').into());
|
||||
assert!(std::iter::from_fn(|| events.try_recv().ok()).any(|event| matches!(
|
||||
event, AppEvent::PersistDaybreakSelection { thread_id: id, enabled: true } if id == thread_id
|
||||
)));
|
||||
|
||||
chat.set_parent_owned_thread();
|
||||
handle_error(
|
||||
&mut chat,
|
||||
|
||||
@@ -65,6 +65,7 @@ pub(super) enum ShellEscapePolicy {
|
||||
pub(super) enum UserMessageSource {
|
||||
Prompt,
|
||||
QuestionAnswer,
|
||||
SafetyRecourse,
|
||||
}
|
||||
|
||||
/// Whether a recovered message can be submitted without risking a duplicate.
|
||||
|
||||
Reference in New Issue
Block a user