mirror of
https://github.com/openai/codex.git
synced 2026-11-16 22:00:36 +00:00
## Why Archiving the current task waits for the server response before returning to the command center, blocking navigation while the request is pending. ## What changed - Run the archive request in the background after side chat and voice cleanup, hiding the task while it is pending. - Preserve drafts and approvals until archiving succeeds. On failure, show an error and make the task visible again. - Keep archive completions across reconnects and route dynamic tool replies through their original reply handles. - Show `Archiving…` during side chat cleanup. On exit, wait up to five seconds for pending archives and report failures or unconfirmed outcomes. ## Testing Add coverage for navigation before the archive response, success and failure handling across event channel replacement, preserved drafts, side chat cleanup failures, and exit warnings. GitOrigin-RevId: 7b6e35cb11159f5be1d0b9fb2082dbd8c7826a94
917 lines
40 KiB
Rust
917 lines
40 KiB
Rust
//! App-server event stream handling for the TUI app.
|
|
//! Hidden structured threads reject requests instead of entering interactive routing.
|
|
|
|
use super::App;
|
|
use super::ThreadBufferedEvent;
|
|
use super::app_server_event_targets::ServerNotificationThreadTarget;
|
|
use super::app_server_event_targets::server_notification_thread_target;
|
|
use super::app_server_event_targets::server_request_thread_id;
|
|
use super::app_server_requests::BufferedServerRequest;
|
|
use crate::app_command::AppCommand;
|
|
use crate::app_event::AppEvent;
|
|
use crate::app_event::RateLimitRefreshOrigin;
|
|
#[cfg(any(target_os = "windows", test))]
|
|
use crate::app_event::WindowsSandboxEnableMode;
|
|
use crate::app_info::app_info_from_api;
|
|
use crate::app_server_session::AppServerSession;
|
|
use crate::app_server_session::status_account_display_from_auth_mode;
|
|
use codex_app_server_client::AppServerEvent;
|
|
use codex_app_server_client::AppServerRequestHandle;
|
|
use codex_app_server_client::TypedRequestError;
|
|
use codex_app_server_protocol::AuthMode;
|
|
use codex_app_server_protocol::ClientRequest;
|
|
use codex_app_server_protocol::JSONRPCErrorError;
|
|
use codex_app_server_protocol::RateLimitReachedType;
|
|
use codex_app_server_protocol::RequestId;
|
|
use codex_app_server_protocol::ServerNotification;
|
|
use codex_app_server_protocol::ServerRequest;
|
|
use codex_app_server_protocol::SessionSource;
|
|
use codex_app_server_protocol::ThreadItemPayload;
|
|
use codex_app_server_protocol::ThreadReadParams;
|
|
use codex_app_server_protocol::ThreadReadResponse;
|
|
use codex_app_server_protocol::ThreadSource;
|
|
use codex_app_server_protocol::ThreadStatus;
|
|
use codex_protocol::ThreadId;
|
|
use codex_protocol::protocol::SubAgentSource;
|
|
use codex_protocol::request_permissions::RequestPermissionProfile as CoreRequestPermissionProfile;
|
|
use std::time::Duration;
|
|
|
|
impl App {
|
|
async fn reject_unsupported_app_server_request(
|
|
&mut self,
|
|
unsupported: super::app_server_requests::UnsupportedAppServerRequest,
|
|
request: &BufferedServerRequest,
|
|
) {
|
|
tracing::warn!(
|
|
request_id = ?unsupported.request_id,
|
|
message = unsupported.message,
|
|
"rejecting unsupported app-server request"
|
|
);
|
|
self.chat_widget
|
|
.add_error_message(unsupported.message.clone());
|
|
let result = request
|
|
.reply
|
|
.clone()
|
|
.reject(JSONRPCErrorError {
|
|
code: -32000,
|
|
message: unsupported.message,
|
|
data: None,
|
|
})
|
|
.await
|
|
.map_err(|err| format!("failed to reject app-server request: {err}"));
|
|
if let Err(err) = result {
|
|
tracing::warn!("{err}");
|
|
}
|
|
}
|
|
|
|
pub(super) async fn handle_app_server_event(
|
|
&mut self,
|
|
app_server_client: &AppServerSession,
|
|
event: AppServerEvent,
|
|
) {
|
|
match event {
|
|
AppServerEvent::Lagged { skipped } => {
|
|
tracing::warn!(
|
|
skipped,
|
|
"app-server event consumer lagged; dropping ignored events"
|
|
);
|
|
self.chat_widget.finish_mcp_startup_after_lag();
|
|
let owner = app_server_client.backend_id();
|
|
self.cancel_agents_overview_refresh(owner);
|
|
self.reset_agents_overview_discovery(owner);
|
|
let registry = &self.backend_registry;
|
|
let belongs_to_other =
|
|
|id: &ThreadId| registry.owner(*id).is_some_and(|known| known != owner);
|
|
self.agents_overview
|
|
.refresh_notifications
|
|
.retain(|id, _| belongs_to_other(id));
|
|
self.agents_overview
|
|
.activity
|
|
.retain(|id, _| belongs_to_other(id));
|
|
self.agents_overview
|
|
.last_messages
|
|
.retain(|id, _| belongs_to_other(id));
|
|
self.agents_overview
|
|
.usage
|
|
.retain(|id, _| belongs_to_other(id));
|
|
self.agents_overview.pending_usage = None;
|
|
self.agents_overview.usage_disabled = false;
|
|
self.repaint_agents_overview();
|
|
self.refresh_agents_overview_threads(app_server_client);
|
|
if let Some(primary_thread_id) = self.primary_thread_id
|
|
&& !self
|
|
.agent_navigation
|
|
.queue_picker_refresh(primary_thread_id)
|
|
{
|
|
self.refresh_agent_picker_threads(app_server_client, primary_thread_id);
|
|
}
|
|
}
|
|
AppServerEvent::ServerNotification(notification) => {
|
|
if let ServerNotificationThreadTarget::Thread(thread_id) =
|
|
server_notification_thread_target(notification.as_ref())
|
|
&& !self
|
|
.backend_registry
|
|
.observe(app_server_client.backend_id(), thread_id)
|
|
{
|
|
return;
|
|
}
|
|
let request_resolved = matches!(
|
|
notification.as_ref(),
|
|
ServerNotification::ServerRequestResolved(_)
|
|
);
|
|
self.handle_server_notification_event(app_server_client, *notification)
|
|
.await;
|
|
if request_resolved {
|
|
self.repaint_agents_overview();
|
|
}
|
|
}
|
|
AppServerEvent::ServerRequest(request) => {
|
|
let request =
|
|
BufferedServerRequest::new(*request, &app_server_client.request_handle());
|
|
self.handle_server_request_event(app_server_client, request)
|
|
.await;
|
|
self.repaint_agents_overview();
|
|
}
|
|
AppServerEvent::ThreadStreamReconnected(thread_id) => {
|
|
if let Ok(id) = ThreadId::from_string(&thread_id)
|
|
&& self.current_displayed_thread_id() == Some(id)
|
|
&& self.chat_widget.thread_id() == Some(id)
|
|
&& self.chat_widget.thread_stream_disconnected
|
|
&& let Some(channel) = self.thread_event_channels.get_mut(&id)
|
|
&& channel
|
|
.backend_id
|
|
.is_none_or(|owner| owner == app_server_client.backend_id())
|
|
{
|
|
channel.history_may_be_incomplete = true;
|
|
self.chat_widget.thread_stream_disconnected = false;
|
|
if self.active_turn_id_for_thread(id).await.is_none() {
|
|
self.chat_widget.maybe_send_next_queued_input();
|
|
}
|
|
}
|
|
}
|
|
AppServerEvent::ThreadStreamDisconnected(error) => {
|
|
if let Ok(id) = ThreadId::from_string(&error.thread_id)
|
|
&& self.current_displayed_thread_id() == Some(id)
|
|
&& self.chat_widget.thread_id() == Some(id)
|
|
&& self.thread_event_channels.get(&id).is_some_and(|channel| {
|
|
channel
|
|
.backend_id
|
|
.is_none_or(|owner| owner == app_server_client.backend_id())
|
|
})
|
|
&& let AppServerRequestHandle::Cloud(handle) =
|
|
app_server_client.request_handle()
|
|
{
|
|
self.chat_widget.thread_stream_disconnected = true;
|
|
if !self.chat_widget.is_user_turn_pending_or_running()
|
|
&& handle.reconnect_idle_thread(&error.thread_id)
|
|
{
|
|
return;
|
|
}
|
|
}
|
|
self.handle_server_notification_event(
|
|
app_server_client,
|
|
ServerNotification::Error(*error),
|
|
)
|
|
.await;
|
|
}
|
|
AppServerEvent::Disconnected { message } => {
|
|
// The request result distinguishes a refused start from a lost reply.
|
|
if self.pending_startup_thread_start
|
|
&& !matches!(self.app_server_target, crate::AppServerTarget::Embedded)
|
|
{
|
|
return;
|
|
}
|
|
if self.begin_reconnect() {
|
|
return;
|
|
}
|
|
tracing::warn!("app-server event stream disconnected: {message}");
|
|
self.chat_widget.add_error_message(message.clone());
|
|
self.app_event_tx.send(AppEvent::FatalExitRequest(message));
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn handle_server_notification_event(
|
|
&mut self,
|
|
app_server_client: &AppServerSession,
|
|
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.
|
|
if let ServerNotification::ThreadClosed(closed) = ¬ification
|
|
&& let Ok(thread_id) = ThreadId::from_string(&closed.thread_id)
|
|
&& self.current_displayed_thread_id() == Some(thread_id)
|
|
{
|
|
let deadline = tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 5);
|
|
for attempt in 0..2 {
|
|
let result = tokio::time::timeout_at(
|
|
deadline,
|
|
app_server_client
|
|
.request_handle()
|
|
.request_typed::<ThreadReadResponse>(ClientRequest::ThreadRead {
|
|
request_id: RequestId::String(format!(
|
|
"thread-closed-{thread_id}-{attempt}"
|
|
)),
|
|
params: ThreadReadParams {
|
|
thread_id: closed.thread_id.clone(),
|
|
include_turns: false,
|
|
},
|
|
}),
|
|
)
|
|
.await;
|
|
match result {
|
|
Ok(Ok(response))
|
|
if !matches!(response.thread.status, ThreadStatus::NotLoaded) =>
|
|
{
|
|
return;
|
|
}
|
|
Ok(Ok(_)) => break,
|
|
// Unpersisted closed threads can no longer be read. Preserve that close
|
|
// and compatibility with servers that do not support this request.
|
|
Ok(Err(TypedRequestError::Server { source, .. }))
|
|
if matches!(source.code, -32602..=-32600) =>
|
|
{
|
|
break;
|
|
}
|
|
Ok(Err(TypedRequestError::Server { source, .. }))
|
|
if source.code == -32603 && attempt == 0 =>
|
|
{
|
|
continue;
|
|
}
|
|
Ok(Err(_)) | Err(_) => {
|
|
// A failed read does not confirm closure. Remote connections recover
|
|
// through the normal reconnect path, rather than exiting the TUI.
|
|
tracing::warn!("could not confirm displayed thread closure");
|
|
if self.begin_reconnect() {
|
|
return;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if let ServerNotification::ThreadStatusChanged(status) = ¬ification {
|
|
let _ = self.dynamic_tool_status_updates.send(status.clone());
|
|
}
|
|
|
|
if let ServerNotification::ThreadStarted(started) = ¬ification
|
|
&& started.thread.ephemeral
|
|
&& matches!(
|
|
started.thread.thread_source.as_ref(),
|
|
Some(ThreadSource::Feature(feature)) if matches!(feature.as_str(), "system" | "thread_title")
|
|
)
|
|
{
|
|
return;
|
|
}
|
|
// Hidden helper threads must not enter visible thread routing or overview refreshes.
|
|
let target = server_notification_thread_target(¬ification);
|
|
if let ServerNotificationThreadTarget::Thread(thread_id) = target
|
|
&& let Some((_, sender)) = self.temporary_structured_requests.get(&thread_id)
|
|
{
|
|
if matches!(
|
|
¬ification,
|
|
ServerNotification::ItemCompleted(_) | ServerNotification::TurnCompleted(_)
|
|
) && sender.send(notification).is_err()
|
|
{
|
|
self.temporary_structured_requests.remove(&thread_id);
|
|
}
|
|
|
|
return;
|
|
}
|
|
self.handle_agent_picker_visibility_notification(app_server_client, ¬ification);
|
|
|
|
if let ServerNotification::ThreadStarted(started) = ¬ification
|
|
&& let SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
|
parent_thread_id, ..
|
|
}) = &started.thread.source
|
|
&& self
|
|
.agents_overview
|
|
.dispatched_requests
|
|
.contains_key(parent_thread_id)
|
|
&& let Ok(thread_id) = codex_protocol::ThreadId::from_string(&started.thread.id)
|
|
{
|
|
self.agents_overview
|
|
.dispatched_requests
|
|
.entry(thread_id)
|
|
.or_default();
|
|
}
|
|
self.track_agents_overview_notification(¬ification);
|
|
if let ServerNotification::ThreadSettingsUpdated(settings) = ¬ification
|
|
&& let Ok(thread_id) = ThreadId::from_string(&settings.thread_id)
|
|
&& self
|
|
.update_retained_blank_settings(thread_id, settings)
|
|
.await
|
|
&& let Some(input) = self.agents_overview.input_states.get_mut(&thread_id)
|
|
{
|
|
input.pending_thread_settings = Some(settings.clone());
|
|
}
|
|
if matches!(
|
|
¬ification,
|
|
ServerNotification::ThreadStarted(_)
|
|
| ServerNotification::ThreadStatusChanged(_)
|
|
| ServerNotification::ThreadSettingsUpdated(_)
|
|
| ServerNotification::ThreadNameUpdated(_)
|
|
| ServerNotification::ThreadArchived(_)
|
|
| ServerNotification::ThreadDeleted(_)
|
|
| ServerNotification::ThreadClosed(_)
|
|
) {
|
|
self.repaint_agents_overview();
|
|
self.refresh_changed_agents_overview_threads(app_server_client);
|
|
}
|
|
match ¬ification {
|
|
ServerNotification::ServerRequestResolved(notification) => {
|
|
if let Some((_, task)) = self.dynamic_tool_tasks.remove(¬ification.request_id) {
|
|
task.abort();
|
|
}
|
|
let notification_thread_id =
|
|
codex_protocol::ThreadId::from_string(¬ification.thread_id).ok();
|
|
self.pending_primary_events.retain(|event| {
|
|
!matches!(event, ThreadBufferedEvent::Request(request)
|
|
if request.id() == ¬ification.request_id
|
|
&& server_request_thread_id(request) == notification_thread_id)
|
|
});
|
|
if let Some(thread_id) = notification_thread_id
|
|
&& let Some(requests) =
|
|
self.agents_overview.dispatched_requests.get_mut(&thread_id)
|
|
{
|
|
requests.retain(|request| request.request.id() != ¬ification.request_id);
|
|
}
|
|
if let Some(resolved) = self
|
|
.pending_app_server_requests
|
|
.resolve_notification(¬ification.thread_id, ¬ification.request_id)
|
|
&& self.chat_widget.thread_id().map(|id| id.to_string())
|
|
== Some(resolved.thread_id)
|
|
{
|
|
self.chat_widget
|
|
.dismiss_app_server_request(&resolved.request);
|
|
if self.startup_pending_protected_request {
|
|
self.startup_pending_protected_request =
|
|
self.chat_widget.has_active_modal()
|
|
|| self.chat_widget.has_pending_protected_request();
|
|
}
|
|
}
|
|
}
|
|
ServerNotification::McpServerOauthLoginCompleted(notification) => {
|
|
// The start response identifies the new attempt. Hold completions until then
|
|
// so a replacement's cancellation cannot appear as a fresh login failure.
|
|
if let Some(pending) = self.pending_mcp_login_start.as_mut()
|
|
&& pending.name == notification.name
|
|
{
|
|
pending.completions.push(notification.clone());
|
|
return;
|
|
}
|
|
if let Some(login_id) = ¬ification.login_id
|
|
&& self.active_mcp_login_ids.remove(login_id).is_none()
|
|
{
|
|
return;
|
|
}
|
|
}
|
|
|
|
ServerNotification::AccountRateLimitsUpdated(notification) => {
|
|
let workspace_hard_stop = matches!(
|
|
notification.rate_limits.rate_limit_reached_type,
|
|
Some(
|
|
RateLimitReachedType::WorkspaceOwnerCreditsDepleted
|
|
| RateLimitReachedType::WorkspaceMemberCreditsDepleted
|
|
| RateLimitReachedType::WorkspaceOwnerUsageLimitReached
|
|
| RateLimitReachedType::WorkspaceMemberUsageLimitReached
|
|
)
|
|
) || notification.rate_limits.spend_control_reached
|
|
== Some(true);
|
|
if workspace_hard_stop {
|
|
self.rate_limit_hard_stop_generation =
|
|
self.rate_limit_hard_stop_generation.wrapping_add(1);
|
|
}
|
|
self.chat_widget
|
|
.on_rolling_rate_limit_snapshot(notification.rate_limits.clone());
|
|
if workspace_hard_stop && self.chat_widget.has_chatgpt_account() {
|
|
// Background inference may publish a hard stop without a foreground Error.
|
|
self.refresh_rate_limits(app_server_client, RateLimitRefreshOrigin::Recovery);
|
|
}
|
|
return;
|
|
}
|
|
ServerNotification::AccountUpdated(notification) => {
|
|
let owner = app_server_client.backend_id();
|
|
self.cancel_agents_overview_refresh(owner);
|
|
self.reset_agents_overview_discovery(owner);
|
|
self.refresh_changed_agents_overview_threads(app_server_client);
|
|
self.agents_overview.usage.clear();
|
|
self.agents_overview.pending_usage = None;
|
|
self.agents_overview.usage_disabled = false;
|
|
self.repaint_agents_overview();
|
|
self.chat_widget.invalidate_security_setup();
|
|
if let Some(crate::pager_overlay::Overlay::Analytics(view)) = &mut self.overlay {
|
|
view.refresh();
|
|
}
|
|
if let Some(view) = &mut self.retained_analytics {
|
|
view.cancel_loads();
|
|
}
|
|
self.rate_limit_hard_stop_generation =
|
|
self.rate_limit_hard_stop_generation.wrapping_add(1);
|
|
self.rate_limit_refresh_state.invalidate_recovery();
|
|
// Deferred terminal writes must never carry the previous account's billing into
|
|
// the newly authenticated identity, even when both accounts share one thread.
|
|
self.last_thread_usage_status_cell = None;
|
|
self.pending_thread_usage_history_refresh = false;
|
|
let has_codex_backend_auth = matches!(
|
|
notification.auth_mode,
|
|
Some(
|
|
AuthMode::Chatgpt
|
|
| AuthMode::ChatgptAuthTokens
|
|
| AuthMode::AgentIdentity
|
|
| AuthMode::PersonalAccessToken
|
|
)
|
|
);
|
|
let account_display = status_account_display_from_auth_mode(
|
|
notification.auth_mode,
|
|
notification.plan_type,
|
|
);
|
|
let has_chatgpt_account = notification
|
|
.auth_mode
|
|
.is_some_and(AuthMode::has_chatgpt_account);
|
|
self.account_email_request_id = None;
|
|
self.chat_widget.update_account_state(
|
|
account_display,
|
|
notification.plan_type,
|
|
has_chatgpt_account,
|
|
has_codex_backend_auth,
|
|
);
|
|
if self.chat_widget.has_chatgpt_account() {
|
|
self.refresh_account_email(app_server_client);
|
|
crate::security_setup::prefetch(
|
|
&self.config,
|
|
app_server_client,
|
|
self.app_event_tx.clone(),
|
|
self.chat_widget.security_setup_request_id,
|
|
);
|
|
}
|
|
return;
|
|
}
|
|
ServerNotification::ExternalAgentConfigImportCompleted(notification) => {
|
|
let should_report_completion = app_server_client
|
|
.consume_external_agent_config_import_completion(¬ification.import_id);
|
|
if !app_server_client.uses_remote_workspace()
|
|
&& let Err(err) = self.refresh_in_memory_config_from_disk().await
|
|
{
|
|
tracing::warn!(
|
|
error = %err,
|
|
"failed to refresh config after external agent config import"
|
|
);
|
|
}
|
|
let cwd = self.chat_widget.config_ref().cwd.to_path_buf();
|
|
self.chat_widget.refresh_plugin_mentions();
|
|
self.chat_widget.submit_op(AppCommand::reload_user_config());
|
|
self.fetch_plugins_list(app_server_client, cwd);
|
|
if should_report_completion {
|
|
self.chat_widget.add_plain_history_lines(
|
|
crate::external_agent_config_migration::flow::external_agent_config_migration_finished_lines(notification),
|
|
);
|
|
}
|
|
return;
|
|
}
|
|
ServerNotification::AppListUpdated(notification) => {
|
|
if self.current_displayed_thread_id().is_some() {
|
|
self.chat_widget
|
|
.refresh_connector_directory_after_notification(
|
|
notification
|
|
.data
|
|
.iter()
|
|
.cloned()
|
|
.map(app_info_from_api)
|
|
.collect(),
|
|
);
|
|
}
|
|
return;
|
|
}
|
|
_ => {}
|
|
}
|
|
|
|
match target {
|
|
ServerNotificationThreadTarget::Thread(thread_id) => {
|
|
if self.saved_openings.observe(
|
|
app_server_client.backend_id(),
|
|
thread_id,
|
|
self.thread_event_channels.get(&thread_id),
|
|
¬ification,
|
|
) {
|
|
return;
|
|
}
|
|
if self.current_displayed_thread_id() != Some(thread_id)
|
|
&& let ServerNotification::ItemCompleted(item) = ¬ification
|
|
&& let ThreadItemPayload::UserMessage {
|
|
client_id: Some(client_id),
|
|
..
|
|
} = &item.item.payload
|
|
{
|
|
// Acknowledge by ID before routing can discard the receipt. ID-less receipts
|
|
// cannot safely distinguish identical pending submissions.
|
|
let mut store = match self.thread_event_channels.get(&thread_id) {
|
|
Some(channel) => Some(channel.store.lock().await),
|
|
None => None,
|
|
};
|
|
for input in store
|
|
.as_mut()
|
|
.and_then(|store| store.input_state.as_mut())
|
|
.into_iter()
|
|
.chain(self.agents_overview.input_states.get_mut(&thread_id))
|
|
{
|
|
if input
|
|
.pending_steers
|
|
.front()
|
|
.is_some_and(|pending| pending.client_id == *client_id)
|
|
{
|
|
input.pending_steers.pop_front();
|
|
}
|
|
}
|
|
}
|
|
let background_voice = self.background_voice.as_ref().is_some_and(|owner| {
|
|
owner.thread_id() == Some(thread_id) && owner.realtime_conversation_is_running()
|
|
});
|
|
if self.primary_thread_id.is_none()
|
|
&& !self.pending_startup_thread_start
|
|
&& !background_voice
|
|
{
|
|
return;
|
|
}
|
|
let untracked_thread =
|
|
self.primary_thread_id.is_some() && !self.owns_thread_for_routing(thread_id);
|
|
if untracked_thread
|
|
&& !self
|
|
.owns_untracked_notification(app_server_client, thread_id, ¬ification)
|
|
.await
|
|
{
|
|
return;
|
|
}
|
|
let result = if self.primary_thread_id.is_none() && !background_voice {
|
|
self.enqueue_primary_thread_notification(notification).await
|
|
} else {
|
|
self.enqueue_thread_notification(thread_id, notification)
|
|
.await
|
|
};
|
|
|
|
if let Err(err) = result {
|
|
tracing::warn!("failed to enqueue app-server notification: {err}");
|
|
}
|
|
return;
|
|
}
|
|
ServerNotificationThreadTarget::InvalidThreadId(thread_id) => {
|
|
tracing::warn!(
|
|
thread_id,
|
|
"ignoring app-server notification with invalid thread_id"
|
|
);
|
|
return;
|
|
}
|
|
ServerNotificationThreadTarget::AppScoped => {
|
|
tracing::debug!(
|
|
"ignoring app-scoped MCP startup notification without a TUI app-level target"
|
|
);
|
|
return;
|
|
}
|
|
ServerNotificationThreadTarget::Global => {}
|
|
}
|
|
|
|
#[cfg(any(target_os = "windows", test))]
|
|
if let ServerNotification::WindowsSandboxSetupCompleted(result) = notification {
|
|
let Some((mode, preset, profile_selection)) =
|
|
self.windows_sandbox.pending_setup.clone()
|
|
else {
|
|
return;
|
|
};
|
|
let expected_mode = match mode {
|
|
WindowsSandboxEnableMode::Elevated => {
|
|
codex_app_server_protocol::WindowsSandboxSetupMode::Elevated
|
|
}
|
|
WindowsSandboxEnableMode::Legacy => {
|
|
codex_app_server_protocol::WindowsSandboxSetupMode::Unelevated
|
|
}
|
|
};
|
|
if result.mode != expected_mode {
|
|
return;
|
|
}
|
|
if result.success {
|
|
self.app_event_tx
|
|
.send(AppEvent::EnableWindowsSandboxForAgentMode {
|
|
preset,
|
|
mode,
|
|
profile_selection,
|
|
});
|
|
} else if mode == WindowsSandboxEnableMode::Elevated {
|
|
self.app_event_tx
|
|
.send(AppEvent::OpenWindowsSandboxFallbackPrompt {
|
|
preset,
|
|
profile_selection,
|
|
});
|
|
} else {
|
|
self.windows_sandbox.pending_setup = None;
|
|
self.chat_widget.clear_windows_sandbox_setup_status();
|
|
self.windows_sandbox.setup_started_at = None;
|
|
if self
|
|
.chat_widget
|
|
.recover_inline_permission_profile_selection()
|
|
{
|
|
self.app_event_tx.send(AppEvent::SettingsSelectionClosed);
|
|
} else {
|
|
self.chat_widget
|
|
.retain_input_after_failed_permission_selection();
|
|
}
|
|
self.chat_widget.add_error_message(format!(
|
|
"Windows sandbox setup failed: {}",
|
|
result.error.unwrap_or_else(|| "unknown error".to_string())
|
|
));
|
|
}
|
|
return;
|
|
}
|
|
|
|
self.chat_widget
|
|
.handle_server_notification(notification, /*replay_kind*/ None);
|
|
}
|
|
|
|
pub(in crate::app) async fn handle_server_request_event(
|
|
&mut self,
|
|
app_server_client: &AppServerSession,
|
|
buffered_request: BufferedServerRequest,
|
|
) {
|
|
let request = &buffered_request.request;
|
|
let thread_id = server_request_thread_id(request);
|
|
if let Some((kind, _)) =
|
|
thread_id.and_then(|id| self.temporary_structured_requests.get(&id))
|
|
{
|
|
// Managed policy can allow a title turn to ask a question. Keep it on
|
|
// the hidden thread until the structured turn times out, as on desktop.
|
|
if *kind == crate::temporary_structured_request::TemporaryThreadKind::Title
|
|
&& matches!(request, ServerRequest::ToolRequestUserInput { params, .. } if params.is_blocking)
|
|
{
|
|
return;
|
|
}
|
|
self.reject_unsupported_app_server_request(
|
|
super::app_server_requests::UnsupportedAppServerRequest {
|
|
request_id: request.id().clone(),
|
|
message:
|
|
"temporary structured threads cannot request tools or user interaction"
|
|
.to_string(),
|
|
},
|
|
&buffered_request,
|
|
)
|
|
.await;
|
|
return;
|
|
}
|
|
if let ServerRequest::DynamicToolCall { request_id, params } = &request {
|
|
let tui_tool = params.namespace.as_deref() == Some(crate::dynamic_tools::NAMESPACE);
|
|
// Another client may own this request on a shared server.
|
|
if self.dynamic_tool_tasks.contains_key(request_id)
|
|
|| (!tui_tool && !app_server_client.uses_embedded_app_server())
|
|
{
|
|
return;
|
|
}
|
|
|
|
let requires_mcp = crate::dynamic_tools::DELEGATION_TOOLS
|
|
.contains(¶ms.tool.as_str())
|
|
|| matches!(
|
|
app_server_client.thread_tool_transport(),
|
|
crate::dynamic_tools_mcp::ThreadToolTransport::Mcp(_)
|
|
);
|
|
let archiving =
|
|
thread_id.is_some_and(|id| self.agents_overview.pending_archives.contains_key(&id));
|
|
if !tui_tool
|
|
|| requires_mcp
|
|
|| archiving
|
|
|| codex_protocol::ThreadId::from_string(¶ms.thread_id)
|
|
.is_ok_and(|thread_id| self.abandoned_side_threads.contains(&thread_id))
|
|
{
|
|
let response = crate::dynamic_tools::failure_response(if requires_mcp {
|
|
"TUI task tools require the approval-gated MCP server"
|
|
} else if archiving {
|
|
"Source task is being archived"
|
|
} else {
|
|
"TUI dynamic tools require an active task in the TUI namespace"
|
|
});
|
|
self.app_event_tx.send(AppEvent::DynamicToolCallCompleted {
|
|
request_id: request_id.clone(),
|
|
response,
|
|
reply: Some(buffered_request.reply),
|
|
});
|
|
return;
|
|
}
|
|
|
|
let request_handle = app_server_client.request_handle();
|
|
let app_event_tx = self.app_event_tx.clone();
|
|
let status_updates = self.dynamic_tool_status_updates.subscribe();
|
|
let request_id = request_id.clone();
|
|
let task_request_id = request_id.clone();
|
|
let source_thread_id = params.thread_id.clone();
|
|
let inherits_task_tools = params.tool == "fork_thread"
|
|
&& params
|
|
.arguments
|
|
.get("threadId")
|
|
.and_then(serde_json::Value::as_str)
|
|
.and_then(|thread_id| ThreadId::from_string(thread_id).ok())
|
|
.is_none_or(|thread_id| app_server_client.task_tools_available(thread_id));
|
|
let params = params.clone();
|
|
let reply = buffered_request.reply;
|
|
let mut thread_start_params =
|
|
crate::app_server_session::thread_start_params_from_config(
|
|
&self.config,
|
|
app_server_client.thread_params_mode(),
|
|
app_server_client.remote_cwd_override(),
|
|
/*session_start_source*/ None,
|
|
);
|
|
app_server_client
|
|
.thread_tool_transport()
|
|
.configure(&mut thread_start_params);
|
|
let features = self.config.features.get().clone();
|
|
let task = tokio::spawn(async move {
|
|
let response = crate::dynamic_tools::execute(
|
|
request_handle,
|
|
params,
|
|
thread_start_params,
|
|
features,
|
|
status_updates,
|
|
Some(&app_event_tx),
|
|
)
|
|
.await;
|
|
if inherits_task_tools
|
|
&& response.success
|
|
&& let [
|
|
codex_app_server_protocol::DynamicToolCallOutputContentItem::InputText {
|
|
text,
|
|
},
|
|
] = response.content_items.as_slice()
|
|
&& let Ok(result) = serde_json::from_str::<serde_json::Value>(text)
|
|
&& let Some(thread_id) =
|
|
result.get("threadId").and_then(serde_json::Value::as_str)
|
|
&& let Ok(thread_id) = ThreadId::from_string(thread_id)
|
|
{
|
|
app_event_tx.send(AppEvent::TaskToolsAvailable { thread_id });
|
|
}
|
|
app_event_tx.send(AppEvent::DynamicToolCallCompleted {
|
|
request_id,
|
|
response,
|
|
reply: Some(reply),
|
|
});
|
|
});
|
|
self.dynamic_tool_tasks
|
|
.insert(task_request_id, (source_thread_id, task));
|
|
return;
|
|
}
|
|
|
|
let background_voice = self.background_voice.as_ref().is_some_and(|owner| {
|
|
owner.realtime_conversation_is_running()
|
|
&& owner.thread_id().is_some()
|
|
&& owner.thread_id() == thread_id
|
|
});
|
|
if thread_id.is_some_and(|thread_id| self.abandoned_side_threads.contains(&thread_id)) {
|
|
self.reject_unsupported_app_server_request(
|
|
super::app_server_requests::UnsupportedAppServerRequest {
|
|
request_id: request.id().clone(),
|
|
message: "side conversation was closed".to_string(),
|
|
},
|
|
&buffered_request,
|
|
)
|
|
.await;
|
|
return;
|
|
}
|
|
if thread_id.is_some()
|
|
&& self.primary_thread_id.is_none()
|
|
&& !background_voice
|
|
&& self.pending_startup_thread_start
|
|
{
|
|
if let Some(unsupported) = self
|
|
.pending_app_server_requests
|
|
.note_buffered_request(&buffered_request)
|
|
{
|
|
self.reject_unsupported_app_server_request(unsupported, &buffered_request)
|
|
.await;
|
|
return;
|
|
}
|
|
self.pending_primary_events
|
|
.push_back(ThreadBufferedEvent::Request(Box::new(
|
|
buffered_request.request,
|
|
)));
|
|
return;
|
|
}
|
|
let unsupported_request = matches!(
|
|
&request,
|
|
ServerRequest::DynamicToolCall { .. }
|
|
| ServerRequest::AttestationGenerate { .. }
|
|
| ServerRequest::ApplyPatchApproval { .. }
|
|
| ServerRequest::ExecCommandApproval { .. }
|
|
);
|
|
if let ServerRequest::PermissionsRequestApproval { request_id, params } = &request
|
|
&& let Err(err) = CoreRequestPermissionProfile::try_from(params.permissions.clone())
|
|
{
|
|
self.reject_unsupported_app_server_request(
|
|
super::app_server_requests::UnsupportedAppServerRequest {
|
|
request_id: request_id.clone(),
|
|
message: format!("failed to localize requested filesystem paths: {err}"),
|
|
},
|
|
&buffered_request,
|
|
)
|
|
.await;
|
|
return;
|
|
}
|
|
if self
|
|
.pending_app_server_requests
|
|
.contains_server_request(request)
|
|
{
|
|
return;
|
|
}
|
|
if let Some(thread_id) = thread_id
|
|
&& self.primary_thread_id != Some(thread_id)
|
|
&& self.active_thread_id != Some(thread_id)
|
|
&& !unsupported_request
|
|
&& !background_voice
|
|
&& let Some(requests) = self.agents_overview.dispatched_requests.get_mut(&thread_id)
|
|
{
|
|
requests.push(buffered_request);
|
|
return;
|
|
}
|
|
if thread_id.is_some()
|
|
&& self.primary_thread_id.is_none()
|
|
&& !background_voice
|
|
&& !self.pending_startup_thread_start
|
|
&& !unsupported_request
|
|
{
|
|
return;
|
|
}
|
|
if let Some(thread_id) = thread_id
|
|
&& self.primary_thread_id.is_some()
|
|
&& self.primary_thread_id != Some(thread_id)
|
|
&& !self.thread_event_channels.contains_key(&thread_id)
|
|
&& self.agent_navigation.get(&thread_id).is_none()
|
|
&& !self.side_threads.contains_key(&thread_id)
|
|
&& !unsupported_request
|
|
{
|
|
let thread = app_server_client
|
|
.request_handle()
|
|
.request_typed::<ThreadReadResponse>(ClientRequest::ThreadRead {
|
|
request_id: RequestId::String(format!("subagent-approval-{thread_id}")),
|
|
params: ThreadReadParams {
|
|
thread_id: thread_id.to_string(),
|
|
include_turns: false,
|
|
},
|
|
})
|
|
.await;
|
|
let Ok(ThreadReadResponse { thread, .. }) = thread else {
|
|
return;
|
|
};
|
|
let SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
|
parent_thread_id, ..
|
|
}) = thread.source
|
|
else {
|
|
return;
|
|
};
|
|
if !self.owns_thread_for_routing(parent_thread_id) {
|
|
if self
|
|
.agents_overview
|
|
.dispatched_requests
|
|
.contains_key(&parent_thread_id)
|
|
{
|
|
self.agents_overview
|
|
.dispatched_requests
|
|
.entry(thread_id)
|
|
.or_default()
|
|
.push(buffered_request);
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
|
|
let unsupported = self
|
|
.pending_app_server_requests
|
|
.note_buffered_request(&buffered_request);
|
|
if let Some(unsupported) = unsupported {
|
|
self.reject_unsupported_app_server_request(unsupported, &buffered_request)
|
|
.await;
|
|
return;
|
|
}
|
|
|
|
let Some(thread_id) = thread_id else {
|
|
tracing::warn!("ignoring threadless app-server request");
|
|
return;
|
|
};
|
|
|
|
let result = if self.primary_thread_id.is_none() && !background_voice {
|
|
self.enqueue_primary_thread_request(buffered_request.request)
|
|
.await
|
|
} else {
|
|
self.enqueue_thread_request(thread_id, buffered_request.request)
|
|
.await
|
|
};
|
|
if let Err(err) = result {
|
|
tracing::warn!("failed to enqueue app-server request: {err}");
|
|
}
|
|
}
|
|
}
|