Allow reviewing and continuing misalignment-paused chats (#42410)

## Why

Misalignment policy failures pause the current chat. When the server provides findings and a continuation request, users should be able to inspect them and explicitly decide whether to proceed.

## What changed

- Add a `Review findings` flow that shows the detailed explanation and quoted continuation request in an overlay.
- Require explicit acknowledgement before starting a continuation turn, while preserving the active approval and sandbox settings.
- Keep ordinary input blocked and reject stale, replaced, invalid, or duplicate continuation attempts.
- Label the overlay shortcut as `q close` to match its behavior.

## Testing

- Add TUI tests covering findings review, explicit confirmation, successful and failed continuation, stale findings, duplicate events, and invalid continuation data.

GitOrigin-RevId: 36a738adf272f95db92eaee5712fb00061d0fa52
This commit is contained in:
Eric Traut authored and copyberry committed 2026-09-03 01:51:14 +00:00
1 parent 93053c7f5d
commit fdf23b4097
31 files changed
+740 -41

No files matched your search

+1 -1
View File
@@ -214,7 +214,7 @@ impl ChatWidget {
thread_rename_block_message: None,
active_side_conversation: false,
blocks_direct_input: false,
misalignment_policy_violation: false,
misalignment_policy_violation: None,
normal_placeholder_text: placeholder,
side_placeholder_text: side_placeholder,
forked_from: None,
+2 -2
View File
@@ -110,7 +110,7 @@ impl ChatWidget {
action: QueuedInputAction,
pending_pastes: Vec<(String, String)>,
) {
if self.misalignment_policy_violation {
if self.has_misalignment_policy_violation() {
return;
}
let should_run_now = self.is_session_configured()
@@ -140,7 +140,7 @@ impl ChatWidget {
/// If idle and there are queued inputs, submit exactly one to start the next turn.
pub(crate) fn maybe_send_next_queued_input(&mut self) -> bool {
if !self.is_session_configured()
|| self.misalignment_policy_violation
|| self.has_misalignment_policy_violation()
|| self.input_queue.suppress_queue_autosend
|| self.input_queue.rate_limit_recovery_pending
|| self.input_queue.recovered_queue
@@ -113,7 +113,7 @@ impl ChatWidget {
history_record: UserMessageHistoryRecord,
shell_escape_policy: ShellEscapePolicy,
) -> (bool, Option<AppCommand>) {
if self.misalignment_policy_violation {
if self.has_misalignment_policy_violation() {
return (false, None);
}
if self.input_queue.rate_limit_recovery_pending {
@@ -1,17 +1,43 @@
//! Terminal precaution UI for misalignment policy violations.
//! Block ordinary input after a misalignment failure. Live findings can be reviewed and
//! explicitly acknowledged; review identity prevents stale UI actions from authorizing a turn.
use super::*;
use codex_app_server_protocol::MisalignmentErrorDetails;
const PRECAUTION_VIEW: &str = "misalignment_precaution";
#[derive(Debug)]
pub(crate) struct MisalignmentReview {
pub(crate) thread_id: ThreadId,
pub(crate) turn_id: String,
pub(crate) details: MisalignmentErrorDetails,
}
impl MisalignmentReview {
pub(crate) fn continuation_message(&self) -> Option<&str> {
self.details
.steer
.as_ref()
.map(|steer| steer.message.as_str())
.filter(|message| !message.trim().is_empty() && message.len() <= 1024)
}
}
pub(super) struct MisalignmentViolation {
turn_id: Option<String>,
review: Option<Arc<MisalignmentReview>>,
}
const MISALIGNMENT_POLICY_TITLE: &str = "Chat stopped as a precaution";
const MISALIGNMENT_POLICY_DESCRIPTION: &str = "We couldn’t confirm the agent was acting safely and following your instructions. To continue working, start or resume another chat.";
impl ChatWidget {
pub(crate) fn has_misalignment_policy_violation(&self) -> bool {
self.misalignment_policy_violation
self.misalignment_policy_violation.is_some()
}
pub(crate) fn rejects_misalignment_policy_op(&self, op: &AppCommand) -> bool {
self.misalignment_policy_violation
self.misalignment_policy_violation.is_some()
&& !matches!(
op,
AppCommand::Interrupt
@@ -24,11 +50,46 @@ impl ChatWidget {
}
pub(crate) fn on_misalignment_policy_violation(&mut self) {
if self.misalignment_policy_violation {
self.on_misalignment_error(/*turn_id*/ None, /*details*/ None);
}
pub(super) fn on_misalignment_error(
&mut self,
turn_id: Option<String>,
details: Option<MisalignmentErrorDetails>,
) {
if let (Some(turn_id), Some(latest)) = (&turn_id, &self.turn_lifecycle.last_turn_id)
&& turn_id != latest
{
return;
}
self.misalignment_policy_violation = true;
// Bound memory-only findings and newly submitted model input. Never truncate a steer.
let missing_details = details.is_none();
let details = details.filter(|details| {
details
.detailed_explanation
.as_ref()
.is_some_and(|text| !text.trim().is_empty() && text.len() <= 64 * 1024)
});
if let Some(current) = &self.misalignment_policy_violation
// A parent-thread precaution cannot become a continuable side-thread warning.
&& (current.turn_id.is_none()
|| (current.turn_id == turn_id
&& (missing_details
|| current.review.as_ref().map(|review| &review.details) == details.as_ref())))
{
return;
}
let review = self.thread_id.zip(turn_id.clone()).zip(details).map(
|((thread_id, turn_id), details)| {
Arc::new(MisalignmentReview {
thread_id,
turn_id,
details,
})
},
);
self.misalignment_policy_violation = Some(MisalignmentViolation { turn_id, review });
self.input_queue.clear();
self.finalize_turn();
self.refresh_pending_input_preview();
@@ -44,6 +105,10 @@ impl ChatWidget {
}
pub(crate) fn show_misalignment_policy_precaution(&mut self) {
if !self.has_misalignment_policy_violation() {
return;
}
self.bottom_pane.dismiss_view_by_id(PRECAUTION_VIEW);
let mut items = vec![
SelectionItem {
name: "New chat".to_string(),
@@ -57,6 +122,23 @@ impl ChatWidget {
..Default::default()
},
];
let review = self
.misalignment_policy_violation
.as_ref()
.and_then(|violation| violation.review.clone());
if let Some(review) = &review {
let review = Arc::clone(review);
items.insert(
0,
SelectionItem {
name: "Review findings".to_string(),
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::ReviewMisalignment(Arc::clone(&review)));
})],
..Default::default()
},
);
}
if self.remote_connection.is_some() {
items.insert(
1,
@@ -68,10 +150,13 @@ impl ChatWidget {
);
}
self.bottom_pane.show_selection_view(SelectionViewParams {
view_id: Some(PRECAUTION_VIEW),
header: Box::new(
Paragraph::new(vec![
Line::from(MISALIGNMENT_POLICY_TITLE).bold(),
Line::from(MISALIGNMENT_POLICY_DESCRIPTION).dim(),
Line::from(if review.is_some() { "Chat paused as a precaution" } else { MISALIGNMENT_POLICY_TITLE }).bold(),
Line::from(if review.is_some() {
"We couldn’t confirm the agent was interpreting your instructions correctly. Review what we detected before deciding to continue."
} else { MISALIGNMENT_POLICY_DESCRIPTION }).dim(),
])
.wrap(Wrap { trim: false }),
),
@@ -80,4 +165,62 @@ impl ChatWidget {
..Default::default()
});
}
pub(crate) fn is_current_misalignment_review(&self, review: &Arc<MisalignmentReview>) -> bool {
let current = self
.misalignment_policy_violation
.as_ref()
.and_then(|violation| violation.review.as_ref());
let turn_id = self.turn_lifecycle.last_turn_id.as_ref();
self.thread_id == Some(review.thread_id)
&& turn_id.is_none_or(|id| id == &review.turn_id)
&& current.is_some_and(|current| Arc::ptr_eq(current, review))
}
pub(crate) fn show_misalignment_review_confirmation(
&mut self,
review: Arc<MisalignmentReview>,
) {
if !self.is_current_misalignment_review(&review) {
return;
}
let can_continue = review.continuation_message().is_some();
self.bottom_pane.dismiss_view_by_id(PRECAUTION_VIEW);
self.bottom_pane.show_selection_view(SelectionViewParams {
view_id: Some(PRECAUTION_VIEW),
title: Some("Chat paused as a precaution".to_string()),
items: vec![
SelectionItem {
name: "Acknowledge findings and continue".to_string(),
is_disabled: !can_continue,
actions: vec![Box::new(move |tx| {
tx.send(AppEvent::ContinueMisalignment(Arc::clone(&review)));
})],
require_explicit_confirmation: true,
dismiss_on_select: true,
..Default::default()
},
SelectionItem {
name: "Back".to_string(),
actions: vec![Box::new(|tx| tx.send(AppEvent::CloseMisalignmentReview))],
..Default::default()
},
],
allow_cancel: false,
..Default::default()
});
}
pub(crate) fn clear_misalignment_for_new_turn(&mut self, turn_id: &str) {
if self
.misalignment_policy_violation
.as_ref()
.is_some_and(|violation| violation.turn_id.as_ref().is_some_and(|id| id != turn_id))
{
self.misalignment_policy_violation = None;
self.bottom_pane.dismiss_view_by_id(PRECAUTION_VIEW);
self.bottom_pane
.set_composer_input_enabled(/*enabled*/ true, /*placeholder*/ None);
}
}
}
+24 -5
View File
@@ -60,6 +60,9 @@ impl ChatWidget {
self.on_thread_settings_updated(notification);
}
ServerNotification::TurnStarted(notification) => {
if replay_kind.is_none() {
self.clear_misalignment_for_new_turn(&notification.turn.id);
}
self.turn_lifecycle.last_turn_id = Some(notification.turn.id);
self.last_non_retry_error = None;
if !matches!(replay_kind, Some(ReplayKind::ResumeInitialMessages)) {
@@ -136,10 +139,20 @@ impl ChatWidget {
notification.turn_id.clone(),
notification.error.message.clone(),
));
self.handle_non_retry_error(
notification.error.message,
notification.error.codex_error_info,
);
if !from_replay
&& notification.error.codex_error_info
== Some(AppServerCodexErrorInfo::MisalignmentPolicyViolation)
{
self.on_misalignment_error(
Some(notification.turn_id),
notification.error.misalignment,
);
} else {
self.handle_non_retry_error(
notification.error.message,
notification.error.codex_error_info,
);
}
}
}
ServerNotification::SkillsChanged(_) => {
@@ -330,7 +343,13 @@ impl ChatWidget {
}
TurnStatus::Failed => {
if let Some(error) = notification.turn.error {
if self.last_non_retry_error.as_ref()
if replay_kind.is_none()
&& error.codex_error_info
== Some(AppServerCodexErrorInfo::MisalignmentPolicyViolation)
{
self.on_misalignment_error(Some(notification.turn.id), error.misalignment);
self.last_non_retry_error = None;
} else if self.last_non_retry_error.as_ref()
== Some(&(notification.turn.id.clone(), error.message.clone()))
{
self.last_non_retry_error = None;
@@ -11,7 +11,7 @@ impl ChatWidget {
request: ServerRequest,
replay_kind: Option<ReplayKind>,
) {
if self.misalignment_policy_violation {
if self.has_misalignment_policy_violation() {
return;
}
@@ -0,0 +1,10 @@
---
source: tui/src/chatwidget/tests/misalignment_policy_tests.rs
assertion_line: 157
expression: "render_bottom_popup(&chat, 38)"
---
Chat paused as a precaution
› 1. Acknowledge findings and
continue
2. Back
@@ -123,3 +123,91 @@ async fn misalignment_policy_failure_stops_the_thread_and_renders_once() {
assert_matches!(rx.try_recv(), Ok(AppEvent::OpenAgentsOverview));
assert!(chat.bottom_pane.has_active_view());
}
fn review_details() -> codex_app_server_protocol::MisalignmentErrorDetails {
codex_app_server_protocol::MisalignmentErrorDetails {
error_type: Some("new_category".to_string()),
detailed_explanation: Some(
"The agent proposed a change outside your instructions.".to_string(),
),
steer: Some(codex_app_server_protocol::MisalignmentSteer {
message: "Continue with the requested change only.".to_string(),
}),
}
}
fn select_review(
chat: &mut ChatWidget,
rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
) -> Arc<MisalignmentReview> {
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
std::iter::from_fn(|| rx.try_recv().ok())
.find_map(|event| match event {
AppEvent::ReviewMisalignment(review) => Some(review),
_ => None,
})
.expect("review action")
}
#[tokio::test]
async fn misalignment_review_requires_current_findings() {
let (mut chat, mut rx, _) = make_chatwidget_manual(/*model_override*/ None).await;
chat.thread_id = Some(ThreadId::new());
handle_turn_started(&mut chat, "turn-1");
chat.on_misalignment_error(Some("turn-1".to_string()), Some(review_details()));
let review = select_review(&mut chat, &mut rx);
chat.show_misalignment_review_confirmation(Arc::clone(&review));
assert_chatwidget_snapshot!(
"misalignment_review_narrow",
render_bottom_popup(&chat, /*width*/ 38)
);
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert!(
matches!(rx.try_recv(), Ok(AppEvent::ContinueMisalignment(current)) if Arc::ptr_eq(&current, &review))
);
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert!(rx.try_recv().is_err());
// A duplicate terminal event must not reset an in-progress review.
chat.on_misalignment_error(Some("turn-1".to_string()), Some(review_details()));
chat.on_misalignment_error(Some("turn-1".to_string()), /*details*/ None);
assert!(chat.is_current_misalignment_review(&review));
let mut changed = review_details();
changed.detailed_explanation = Some("Updated findings".to_string());
chat.on_misalignment_error(Some("turn-1".to_string()), Some(changed));
assert!(!chat.is_current_misalignment_review(&review));
// Present-but-invalid findings withdraw the old authorization.
for explanation in [None, Some(" ".to_string()), Some("a".repeat(65537))] {
chat.on_misalignment_error(Some("turn-1".to_string()), Some(review_details()));
let replacement = select_review(&mut chat, &mut rx);
let mut details = review_details();
details.detailed_explanation = explanation;
chat.on_misalignment_error(Some("turn-1".to_string()), Some(details));
assert!(!chat.is_current_misalignment_review(&replacement));
}
for steer in [None, Some(" ".to_string()), Some("a".repeat(1025))] {
let mut details = review_details();
details.steer =
steer.map(|message| codex_app_server_protocol::MisalignmentSteer { message });
chat.on_misalignment_error(Some("turn-1".to_string()), Some(details));
let review = select_review(&mut chat, &mut rx);
chat.show_misalignment_review_confirmation(Arc::clone(&review));
assert!(review.continuation_message().is_none());
chat.handle_key_event(KeyEvent::from(KeyCode::Enter));
assert!(
!std::iter::from_fn(|| rx.try_recv().ok())
.any(|event| matches!(event, AppEvent::ContinueMisalignment(_)))
);
assert!(!chat.bottom_pane.composer_input_enabled());
}
handle_turn_started(&mut chat, "turn-2");
chat.on_misalignment_error(Some("turn-1".to_string()), Some(review_details()));
assert!(!chat.has_misalignment_policy_violation());
assert!(chat.bottom_pane.composer_input_enabled());
// A queued Back action cannot reopen the precaution after a new turn starts.
chat.show_misalignment_policy_precaution();
assert!(!chat.bottom_pane.has_active_view());
}