mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
Validate thread identity across TUI backends (#65190)
## Why Different backends can return the same thread ID. A Cloud environment selection must apply to the draft on the backend that opened the picker. When the TUI reads or resumes a specific thread, an unexpected server response can otherwise attach history or apply settings to the wrong thread. ## What changed - Match Cloud environment selections against both the backend and the draft thread ID. - Reject mismatched thread IDs in read and resume flows before hydrating history or applying resume permission settings. Preserve subscription bookkeeping so a rejected resume can still be cleaned up. ## Testing Add regression coverage for a thread start that reuses an ID from another backend and a mismatched resume that preserves the active conversation, composer draft, and approval override without sending a settings update. GitOrigin-RevId: 603efe7aa37e510dacf91b58487a94469c7f183d
This commit is contained in:
committed by
copyberry
parent
283fca1c98
commit
a3bca8a1b5
@@ -1,10 +1,10 @@
|
||||
//! Shows saved Cloud environments before starting a conversation on the Cloud backend.
|
||||
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::backend_id::ThreadKey;
|
||||
use crate::bottom_pane::SelectionItem;
|
||||
use crate::bottom_pane::SelectionViewParams;
|
||||
use codex_app_server_client::SavedEnvironment;
|
||||
use codex_protocol::ThreadId;
|
||||
|
||||
pub(super) const LOADING_VIEW_ID: &str = "cloud_environment_loading";
|
||||
|
||||
@@ -19,7 +19,7 @@ pub(super) fn loading_view() -> SelectionViewParams {
|
||||
|
||||
pub(super) fn cloud_environment_picker(
|
||||
result: Result<Vec<SavedEnvironment>, String>,
|
||||
source: ThreadId,
|
||||
source: ThreadKey,
|
||||
) -> SelectionViewParams {
|
||||
let (environments, subtitle) = match result {
|
||||
Ok(environments) => (environments, None),
|
||||
|
||||
@@ -9,7 +9,7 @@ use pretty_assertions::assert_eq;
|
||||
#[tokio::test]
|
||||
async fn cloud_environment_picker_shows_default_and_saved_choice() {
|
||||
let (mut app, mut events, _) = make_test_app_with_channels().await;
|
||||
let source = ThreadId::new();
|
||||
let source = crate::backend_id::BackendId::new().thread(codex_protocol::ThreadId::new());
|
||||
let saved = SavedEnvironment {
|
||||
id: "ws~asenvcfg_saved".into(),
|
||||
name: "Team Rust".into(),
|
||||
@@ -52,7 +52,10 @@ async fn dismissing_cloud_environment_loading_keeps_the_draft() {
|
||||
app.chat_widget.apply_external_edit("draft".into());
|
||||
app.chat_widget.show_selection_view(loading_view());
|
||||
app.chat_widget.handle_key_event(KeyCode::Esc.into());
|
||||
let view = cloud_environment_picker(Ok(Vec::new()), ThreadId::new());
|
||||
let view = cloud_environment_picker(
|
||||
Ok(Vec::new()),
|
||||
crate::backend_id::BackendId::new().thread(codex_protocol::ThreadId::new()),
|
||||
);
|
||||
assert!(
|
||||
!app.chat_widget
|
||||
.replace_selection_view_if_present(LOADING_VIEW_ID, view)
|
||||
|
||||
@@ -1750,13 +1750,13 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
app.chat_widget.show_selection_view(super::cloud_environments::loading_view());
|
||||
cloud_environment_picker = Some(Box::pin(async move {
|
||||
let environments = handle.list_saved_environments().await.map_err(|error| error.to_string());
|
||||
super::cloud_environments::cloud_environment_picker(environments, source)
|
||||
super::cloud_environments::cloud_environment_picker(environments, displayed_owner.thread(source))
|
||||
}));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
AppEvent::StartCloudConversation { source, saved_environment }
|
||||
if cloud_draft == Some(*source) =>
|
||||
if cloud_draft.map(|id| displayed_owner.thread(id)) == Some(*source) =>
|
||||
{
|
||||
Some((displayed_owner, NewBackendSession::ChangeCloudEnvironment(saved_environment.clone())))
|
||||
}
|
||||
|
||||
@@ -614,7 +614,7 @@ async fn reconnect_reconciles_offscreen_pending_profile_before_restoring_permiss
|
||||
"activePermissionProfile": if pending { Some(json!({"id": "server-only"})) } else { None },
|
||||
"reasoningEffort": null}})
|
||||
}
|
||||
"thread/read" => json!({"result": {"thread": thread(primary)}}),
|
||||
"thread/read" => json!({"result": {"thread": thread(ThreadId::from_string(id.unwrap()).unwrap())}}),
|
||||
"turn/start" => {
|
||||
let params = request.params.as_ref().unwrap();
|
||||
assert_eq!(params["permissions"], serde_json::Value::Null);
|
||||
|
||||
@@ -1524,6 +1524,89 @@ async fn backend_handoff_errors_are_snapshotted() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn mismatched_thread_server(config: &Config, id: ThreadId) -> Result<RecordingAppServer> {
|
||||
start_recording_app_server_with_history(
|
||||
config,
|
||||
HistoryCapabilities::MismatchedThreadId(id),
|
||||
/*blocked_thread_list*/ None,
|
||||
/*failed_thread_name*/ None,
|
||||
crate::app_server_session::ThreadParamsMode::Embedded,
|
||||
LoaderOverrides::without_managed_config_for_tests(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_accepts_a_shared_id_but_resume_requires_the_requested_id() -> Result<()> {
|
||||
let (mut app, _events, _) = make_test_app_with_channels().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let source = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
||||
let owner = source.backend_id();
|
||||
let current = ThreadId::new();
|
||||
app.app_server_backend_id = Some(owner);
|
||||
let cwd = app.config.cwd.to_path_buf();
|
||||
let session = test_thread_session(current, cwd.clone());
|
||||
app.enqueue_primary_thread_session(session, Vec::new())
|
||||
.await?;
|
||||
let draft = "private draft";
|
||||
app.chat_widget.insert_str(draft);
|
||||
let (destination, requests, proxy) = mismatched_thread_server(&app.config, current).await?;
|
||||
let backend_id = destination.backend_id();
|
||||
let mut backends = BackendSessions::from_initial(source, vec![destination]);
|
||||
backends.settings.insert(backend_id, app.backend_settings());
|
||||
let policy = RuntimeApprovalPolicyOverride::Explicit(AskForApproval::OnRequest);
|
||||
app.runtime_approval_policy_override = Some(policy);
|
||||
let slot = backends.slot(backend_id).unwrap();
|
||||
let server = backends.session_at_mut(slot);
|
||||
let started = server.start_thread(&app.config).await?;
|
||||
assert_eq!(started.session.thread_id, current);
|
||||
let loaded = server.thread_loaded_list(Default::default()).await?;
|
||||
let thread_id = ThreadId::from_string(&loaded.data[0])?;
|
||||
assert_ne!(thread_id, current);
|
||||
server.thread_inject_items(thread_id, vec![serde_json::from_str(
|
||||
r#"{"type":"message","role":"assistant","content":[{"type":"output_text","text":"history"}]}"#,
|
||||
)?]).await?;
|
||||
app.resume_backend_session(
|
||||
&mut tui,
|
||||
&mut backends,
|
||||
SessionTarget {
|
||||
backend_id,
|
||||
thread_id,
|
||||
path: None,
|
||||
cwd: None,
|
||||
history_mode: None,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(recorded_params(&requests, "thread/resume").len(), 1);
|
||||
assert!(recorded_params(&requests, "turn/start").is_empty());
|
||||
assert_eq!(backends.displayed_owner(), owner);
|
||||
assert_eq!(app.active_thread_id, Some(current));
|
||||
assert_eq!(app.runtime_approval_policy_override, Some(policy));
|
||||
assert_eq!(app.chat_widget.composer_text_with_pending(), draft);
|
||||
// A loaded thread can need a settings write to confirm --approve-for-me.
|
||||
let mut config = app.rebuild_config_for_cwd(cwd).await?;
|
||||
config.approvals_reviewer = ApprovalsReviewer::AutoReview;
|
||||
let model = app.resume_model_settings(&config);
|
||||
let mut attachment = backends.session_at_mut(slot).attachment_view(thread_id);
|
||||
let error = attachment
|
||||
.resume_thread_with_permission_overrides(
|
||||
&app.local_settings,
|
||||
config,
|
||||
thread_id,
|
||||
model,
|
||||
crate::resume_permissions::ResumePermissions::PRESET,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(attachment.take_attachment_metadata(thread_id).subscribed);
|
||||
assert!(recorded_params(&requests, "thread/settings/update").is_empty());
|
||||
assert!(error.to_string().contains("different thread"), "{error}");
|
||||
backends.shutdown().await?;
|
||||
proxy.await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn resumed_backend_handoff_detaches_through_the_source_connection() -> Result<()> {
|
||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
||||
|
||||
@@ -2656,6 +2656,7 @@ pub(super) enum HistoryCapabilities {
|
||||
ItemsAndSummaryTurnsFail,
|
||||
ThreadListFails,
|
||||
ThreadStartFails,
|
||||
MismatchedThreadId(ThreadId),
|
||||
ThreadStartWhileShuttingDown,
|
||||
ThreadStartDuringLegacyShutdown,
|
||||
ConfigReadUnsupported(i64),
|
||||
@@ -3090,7 +3091,20 @@ pub(super) async fn start_recording_app_server_with_realtime_speech(
|
||||
},
|
||||
})
|
||||
} else {
|
||||
let returning_thread = matches!(
|
||||
&request,
|
||||
ClientRequest::ThreadStart { .. }
|
||||
| ClientRequest::ThreadResume { .. }
|
||||
| ClientRequest::ThreadFork { .. }
|
||||
) || matches!(&request, ClientRequest::ThreadRead { params, .. } if params.include_turns);
|
||||
let mut result = embedded.request(request).await?;
|
||||
if returning_thread
|
||||
&& let HistoryCapabilities::MismatchedThreadId(id) =
|
||||
history_capabilities
|
||||
&& let Ok(value) = &mut result
|
||||
{
|
||||
value["thread"]["id"] = serde_json::json!(id);
|
||||
}
|
||||
if advertise_paginated && let Ok(value) = &mut result {
|
||||
value["thread"]["historyMode"] = serde_json::json!("paginated");
|
||||
}
|
||||
|
||||
@@ -764,7 +764,7 @@ pub(crate) enum AppEvent {
|
||||
|
||||
/// Move the empty Cloud draft to the selected environment.
|
||||
StartCloudConversation {
|
||||
source: ThreadId,
|
||||
source: crate::backend_id::ThreadKey,
|
||||
saved_environment: Option<codex_app_server_client::SavedEnvironment>,
|
||||
},
|
||||
|
||||
|
||||
@@ -1905,6 +1905,15 @@ impl AppServerSession {
|
||||
.wrap_err("failed to list loaded threads from app server")
|
||||
}
|
||||
|
||||
fn validate_thread_response(thread: &Thread, requested: ThreadId) -> Result<()> {
|
||||
let id = ThreadId::from_string(&thread.id)?;
|
||||
color_eyre::eyre::ensure!(
|
||||
requested == id,
|
||||
"server returned a different thread than requested"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn thread_read(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
@@ -1923,6 +1932,7 @@ impl AppServerSession {
|
||||
.await;
|
||||
let mut response: ThreadReadResponse = match response {
|
||||
Ok(response) => {
|
||||
Self::validate_thread_response(&response.thread, thread_id)?;
|
||||
// Freeze the metadata revision observed before history hydration.
|
||||
if !include_turns {
|
||||
self.remember_read_state(thread_id, response.read_state);
|
||||
@@ -1948,6 +1958,7 @@ impl AppServerSession {
|
||||
}
|
||||
Err(err) => return Err(err).wrap_err("thread/read failed during TUI session lookup"),
|
||||
};
|
||||
Self::validate_thread_response(&response.thread, thread_id)?;
|
||||
self.hydrate_initial_thread_history(
|
||||
&mut response.thread,
|
||||
/*turn_cursor*/ None,
|
||||
|
||||
@@ -195,6 +195,7 @@ impl AppServerSession {
|
||||
.map_err(|err| {
|
||||
bootstrap_request_error("thread/resume failed during TUI bootstrap", err)
|
||||
})?;
|
||||
Self::validate_thread_response(&response.thread, thread_id)?;
|
||||
let mut history = self.request_view();
|
||||
history.request_handle = AppServerRequestHandle::Cloud(scoped.clone());
|
||||
history
|
||||
@@ -376,6 +377,11 @@ impl AppServerSession {
|
||||
));
|
||||
}
|
||||
};
|
||||
// The server subscribed this connection even if we reject the payload.
|
||||
if let Some(subscribed) = &mut self.attachment_subscribed {
|
||||
*subscribed = true;
|
||||
}
|
||||
Self::validate_thread_response(&response.thread, thread_id)?;
|
||||
if permission_overrides.confirm_preset
|
||||
&& let Some(settings) =
|
||||
crate::resume_permissions::initial_resume_update(&config, &response)?
|
||||
@@ -400,6 +406,7 @@ impl AppServerSession {
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
Self::validate_thread_response(&response.thread, thread_id)?;
|
||||
if crate::resume_permissions::initial_resume_update(&config, &response)?.is_some() {
|
||||
color_eyre::eyre::bail!(
|
||||
"The server did not confirm the requested permissions for --approve-for-me."
|
||||
@@ -424,9 +431,7 @@ impl AppServerSession {
|
||||
mut response: ThreadResumeResponse,
|
||||
scope: HistoryHydrationScope<'_>,
|
||||
) -> Result<AppServerStartedThread> {
|
||||
if let Some(subscribed) = &mut self.attachment_subscribed {
|
||||
*subscribed = true;
|
||||
}
|
||||
Self::validate_thread_response(&response.thread, thread_id)?;
|
||||
self.hydrate_initial_thread_history(
|
||||
&mut response.thread,
|
||||
response.turns_backwards_cursor.clone(),
|
||||
|
||||
@@ -2,11 +2,34 @@
|
||||
//! Reconnecting and auxiliary picker connections reuse the launch owner; a different
|
||||
//! backend gets a fresh identity. These process-local IDs never appear on the wire.
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub(crate) struct BackendId(uuid::Uuid);
|
||||
|
||||
impl Default for BackendId {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl BackendId {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self(uuid::Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
/// An address in the TUI. Only the native thread ID goes to the server.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
pub(crate) struct ThreadKey {
|
||||
pub(crate) backend_id: BackendId,
|
||||
pub(crate) thread_id: ThreadId,
|
||||
}
|
||||
|
||||
impl BackendId {
|
||||
pub(crate) fn thread(self, thread_id: ThreadId) -> ThreadKey {
|
||||
ThreadKey {
|
||||
backend_id: self,
|
||||
thread_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user