mirror of
https://github.com/openai/codex.git
synced 2026-11-26 23:40:43 +00:00
tui: prevent /agent picker deadlock
This commit is contained in:
@@ -1287,6 +1287,22 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
}
|
||||
}
|
||||
|
||||
if self
|
||||
.pending_app_server_requests
|
||||
.agent_thread_selection
|
||||
.is_some()
|
||||
&& !matches!(event, TuiEvent::Draw | TuiEvent::Resize)
|
||||
{
|
||||
if let TuiEvent::Key(key_event) = &event
|
||||
&& key_event.code == KeyCode::Esc
|
||||
&& matches!(key_event.kind, KeyEventKind::Press | KeyEventKind::Repeat)
|
||||
{
|
||||
self.cancel_pending_agent_selection();
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
|
||||
if self.overlay.is_some() {
|
||||
let _ = self.handle_backtrack_overlay_event(tui, event).await?;
|
||||
} else {
|
||||
|
||||
@@ -12,6 +12,8 @@ use codex_app_server_protocol::McpServerElicitationRequestResponse;
|
||||
use codex_app_server_protocol::PermissionsRequestApprovalResponse;
|
||||
use codex_app_server_protocol::RequestId as AppServerRequestId;
|
||||
use codex_app_server_protocol::ServerRequest;
|
||||
use codex_protocol::ThreadId;
|
||||
use uuid::Uuid;
|
||||
|
||||
impl App {
|
||||
pub(super) async fn reject_app_server_request(
|
||||
@@ -73,6 +75,8 @@ pub(super) struct PendingAppServerRequests {
|
||||
permissions_approvals: HashMap<String, AppServerRequestId>,
|
||||
user_inputs: HashMap<String, VecDeque<PendingUserInputRequest>>,
|
||||
mcp_requests: HashMap<McpRequestKey, AppServerRequestId>,
|
||||
pub(super) agent_thread_selection: Option<(Uuid, ThreadId)>,
|
||||
pub(super) prepared_agent_thread_selection: Option<bool>,
|
||||
}
|
||||
|
||||
impl PendingAppServerRequests {
|
||||
@@ -82,6 +86,8 @@ impl PendingAppServerRequests {
|
||||
self.permissions_approvals.clear();
|
||||
self.user_inputs.clear();
|
||||
self.mcp_requests.clear();
|
||||
self.agent_thread_selection = None;
|
||||
self.prepared_agent_thread_selection = None;
|
||||
}
|
||||
|
||||
pub(super) fn note_server_request(
|
||||
|
||||
@@ -1716,6 +1716,26 @@ impl App {
|
||||
self.select_agent_thread_and_discard_side(tui, app_server, thread_id)
|
||||
.await?;
|
||||
}
|
||||
AppEvent::AgentThreadSelectionPrepared {
|
||||
request_id,
|
||||
thread_id,
|
||||
attaching,
|
||||
result,
|
||||
} => {
|
||||
if self
|
||||
.handle_agent_thread_selection_prepared(
|
||||
app_server, request_id, thread_id, attaching, result,
|
||||
)
|
||||
.await
|
||||
{
|
||||
self.select_agent_thread_and_discard_side(tui, app_server, thread_id)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
AppEvent::AgentThreadSelectionCleanupFinished(thread_id, result) => {
|
||||
self.handle_agent_thread_selection_cleanup_finished(thread_id, result)
|
||||
.await;
|
||||
}
|
||||
AppEvent::StartSide {
|
||||
parent_thread_id,
|
||||
user_message,
|
||||
|
||||
@@ -5,13 +5,22 @@
|
||||
//! cache used for multi-agent navigation.
|
||||
|
||||
use super::*;
|
||||
use crate::app_event::PreparedAgentThread;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::Thread;
|
||||
use codex_app_server_protocol::ThreadReadParams;
|
||||
use codex_app_server_protocol::ThreadReadResponse;
|
||||
use codex_app_server_protocol::ThreadResumeParams;
|
||||
use codex_app_server_protocol::ThreadResumeResponse;
|
||||
use codex_app_server_protocol::ThreadUnsubscribeParams;
|
||||
use codex_app_server_protocol::ThreadUnsubscribeResponse;
|
||||
|
||||
fn agent_request_id(operation: &str) -> RequestId {
|
||||
RequestId::String(format!("agent-thread-{operation}-{}", Uuid::new_v4()))
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) async fn open_agent_picker(&mut self, app_server: &mut AppServerSession) {
|
||||
self.backfill_loaded_subagent_threads(app_server).await;
|
||||
// V2 subagents are identified by canonical paths observed from activity events or loaded
|
||||
// thread metadata. Prefer local buffered turn state for liveness, and fall back to
|
||||
// thread/read only when no local event channel exists.
|
||||
pub(super) async fn open_agent_picker(&mut self, _app_server: &mut AppServerSession) {
|
||||
let path_backed_thread_ids: Vec<_> = self
|
||||
.agent_navigation
|
||||
.ordered_path_backed_subagent_threads(self.primary_thread_id)
|
||||
@@ -25,8 +34,8 @@ impl App {
|
||||
let is_running = channel.store.lock().await.active_turn_id().is_some();
|
||||
self.agent_navigation.set_running(thread_id, is_running);
|
||||
} else {
|
||||
self.refresh_agent_picker_thread_liveness(app_server, thread_id)
|
||||
.await;
|
||||
self.agent_navigation
|
||||
.set_running(thread_id, /*is_running*/ false);
|
||||
}
|
||||
}
|
||||
let path_backed_threads = self
|
||||
@@ -61,25 +70,6 @@ impl App {
|
||||
));
|
||||
return;
|
||||
}
|
||||
|
||||
let mut thread_ids = self.agent_navigation.tracked_thread_ids();
|
||||
for thread_id in self.thread_event_channels.keys().copied() {
|
||||
if !thread_ids.contains(&thread_id) {
|
||||
thread_ids.push(thread_id);
|
||||
}
|
||||
}
|
||||
for thread_id in thread_ids {
|
||||
if self.side_threads.contains_key(&thread_id) {
|
||||
continue;
|
||||
}
|
||||
if !self
|
||||
.refresh_agent_picker_thread_liveness(app_server, thread_id)
|
||||
.await
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let has_non_primary_agent_thread = self
|
||||
.agent_navigation
|
||||
.has_non_primary_thread(self.primary_thread_id);
|
||||
@@ -97,33 +87,34 @@ impl App {
|
||||
let mut initial_selected_idx = None;
|
||||
let items: Vec<SelectionItem> = self
|
||||
.agent_navigation
|
||||
.ordered_threads()
|
||||
.into_iter()
|
||||
.tracked_thread_ids()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, (thread_id, entry))| {
|
||||
if self.active_thread_id == Some(thread_id) {
|
||||
.filter_map(|(idx, thread_id)| {
|
||||
let entry = self.agent_navigation.get(thread_id)?;
|
||||
if self.active_thread_id == Some(*thread_id) {
|
||||
initial_selected_idx = Some(idx);
|
||||
}
|
||||
let id = thread_id;
|
||||
let is_primary = self.primary_thread_id == Some(thread_id);
|
||||
let id = *thread_id;
|
||||
let is_primary = self.primary_thread_id == Some(*thread_id);
|
||||
let name = format_agent_picker_item_name(
|
||||
entry.agent_nickname.as_deref(),
|
||||
entry.agent_role.as_deref(),
|
||||
is_primary,
|
||||
);
|
||||
let uuid = thread_id.to_string();
|
||||
SelectionItem {
|
||||
Some(SelectionItem {
|
||||
name: name.clone(),
|
||||
name_prefix_spans: agent_picker_status_dot_spans(entry.is_closed),
|
||||
description: Some(uuid.clone()),
|
||||
is_current: self.active_thread_id == Some(thread_id),
|
||||
is_current: self.active_thread_id == Some(*thread_id),
|
||||
actions: vec![Box::new(move |tx| {
|
||||
tx.send(AppEvent::SelectAgentThread(id));
|
||||
})],
|
||||
dismiss_on_select: true,
|
||||
search_value: Some(format!("{name} {uuid}")),
|
||||
..Default::default()
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -187,135 +178,291 @@ impl App {
|
||||
self.sync_active_agent_label();
|
||||
}
|
||||
|
||||
pub(super) async fn refresh_agent_picker_thread_liveness(
|
||||
pub(super) async fn begin_agent_thread_selection(
|
||||
&mut self,
|
||||
app_server: &mut AppServerSession,
|
||||
app_server: &AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
) -> bool {
|
||||
let existing_entry = self.agent_navigation.get(&thread_id).cloned();
|
||||
let has_replay_channel = self.thread_event_channels.contains_key(&thread_id);
|
||||
match app_server
|
||||
.thread_read(thread_id, /*include_turns*/ false)
|
||||
.await
|
||||
if self.active_thread_id == Some(thread_id)
|
||||
|| self
|
||||
.pending_app_server_requests
|
||||
.agent_thread_selection
|
||||
.is_some()
|
||||
{
|
||||
Ok(thread) => {
|
||||
let is_running = matches!(
|
||||
thread.status,
|
||||
codex_app_server_protocol::ThreadStatus::Active { .. }
|
||||
);
|
||||
let is_closed = matches!(
|
||||
thread.status,
|
||||
codex_app_server_protocol::ThreadStatus::NotLoaded
|
||||
);
|
||||
self.upsert_agent_picker_thread(
|
||||
thread_id,
|
||||
thread.agent_nickname.or_else(|| {
|
||||
existing_entry
|
||||
.as_ref()
|
||||
.and_then(|entry| entry.agent_nickname.clone())
|
||||
}),
|
||||
thread.agent_role.or_else(|| {
|
||||
existing_entry
|
||||
.as_ref()
|
||||
.and_then(|entry| entry.agent_role.clone())
|
||||
}),
|
||||
is_closed,
|
||||
);
|
||||
self.agent_navigation.set_running(thread_id, is_running);
|
||||
true
|
||||
return false;
|
||||
}
|
||||
|
||||
let is_replay_only = self
|
||||
.agent_navigation
|
||||
.get(&thread_id)
|
||||
.is_some_and(|entry| entry.is_closed);
|
||||
let attaching = if self.should_attach_live_thread_for_selection(thread_id) {
|
||||
true
|
||||
} else if let Some(channel) = self.thread_event_channels.get(&thread_id) {
|
||||
let snapshot = channel.store.lock().await.snapshot();
|
||||
if !self.should_refresh_snapshot_session(thread_id, is_replay_only, &snapshot) {
|
||||
return true;
|
||||
}
|
||||
Err(err) => {
|
||||
if Self::is_terminal_thread_read_error(&err) && !has_replay_channel {
|
||||
self.agent_navigation.remove(thread_id);
|
||||
return false;
|
||||
}
|
||||
let is_closed = Self::closed_state_for_thread_read_error(
|
||||
&err,
|
||||
existing_entry.as_ref().map(|entry| entry.is_closed),
|
||||
);
|
||||
if let Some(entry) = existing_entry {
|
||||
self.upsert_agent_picker_thread(
|
||||
thread_id,
|
||||
entry.agent_nickname,
|
||||
entry.agent_role,
|
||||
is_closed,
|
||||
);
|
||||
} else {
|
||||
self.upsert_agent_picker_thread(
|
||||
thread_id, /*agent_nickname*/ None, /*agent_role*/ None,
|
||||
is_closed,
|
||||
);
|
||||
}
|
||||
self.agent_navigation
|
||||
.set_running(thread_id, /*is_running*/ false);
|
||||
true
|
||||
false
|
||||
} else {
|
||||
return true;
|
||||
};
|
||||
|
||||
let request_id = Uuid::new_v4();
|
||||
self.pending_app_server_requests.agent_thread_selection = Some((request_id, thread_id));
|
||||
|
||||
let request_handle = app_server.request_handle();
|
||||
let config = self.config.clone();
|
||||
let thread_params_mode = app_server.thread_params_mode();
|
||||
let resume_params = crate::app_server_session::thread_resume_params_from_config(
|
||||
app_server.session_config_with_effective_service_tier(&config),
|
||||
thread_id,
|
||||
thread_params_mode,
|
||||
app_server.remote_cwd_override(),
|
||||
);
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = Self::prepare_agent_thread_selection(
|
||||
request_handle,
|
||||
config,
|
||||
thread_params_mode,
|
||||
resume_params,
|
||||
thread_id,
|
||||
attaching,
|
||||
)
|
||||
.await;
|
||||
app_event_tx.send(AppEvent::AgentThreadSelectionPrepared {
|
||||
request_id,
|
||||
thread_id,
|
||||
attaching,
|
||||
result,
|
||||
});
|
||||
});
|
||||
false
|
||||
}
|
||||
|
||||
async fn prepare_agent_thread_selection(
|
||||
request_handle: AppServerRequestHandle,
|
||||
config: Config,
|
||||
thread_params_mode: crate::app_server_session::ThreadParamsMode,
|
||||
resume_params: ThreadResumeParams,
|
||||
thread_id: ThreadId,
|
||||
attaching: bool,
|
||||
) -> std::result::Result<PreparedAgentThread, String> {
|
||||
let resume: Result<AppServerStartedThread> = async {
|
||||
let response: ThreadResumeResponse = request_handle
|
||||
.request_typed(ClientRequest::ThreadResume {
|
||||
request_id: agent_request_id("resume"),
|
||||
params: resume_params,
|
||||
})
|
||||
.await
|
||||
.map_err(|err| {
|
||||
color_eyre::eyre::eyre!("thread/resume failed during TUI bootstrap: {err}")
|
||||
})?;
|
||||
let mut started = crate::app_server_session::started_thread_from_resume_response(
|
||||
response,
|
||||
&config,
|
||||
thread_params_mode,
|
||||
)
|
||||
.await?;
|
||||
if let Some(fork_parent_id) = started.session.forked_from_id {
|
||||
started.session.fork_parent_title = Self::request_agent_thread_read(
|
||||
&request_handle,
|
||||
fork_parent_id,
|
||||
/*include_turns*/ false,
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|thread| thread.name);
|
||||
}
|
||||
Ok(started)
|
||||
}
|
||||
.await;
|
||||
let resume_err = match resume {
|
||||
Ok(started) => return Ok(PreparedAgentThread::Resumed(started)),
|
||||
Err(err) => err,
|
||||
};
|
||||
if !attaching {
|
||||
tracing::warn!(
|
||||
thread_id = %thread_id,
|
||||
error = %resume_err,
|
||||
"failed to refresh inferred thread session before replay"
|
||||
);
|
||||
return Err(format!("{resume_err:#}"));
|
||||
}
|
||||
|
||||
tracing::warn!(
|
||||
thread_id = %thread_id,
|
||||
error = %resume_err,
|
||||
"failed to resume live thread for selection; falling back to thread/read"
|
||||
);
|
||||
let thread = match Self::request_agent_thread_read(
|
||||
&request_handle,
|
||||
thread_id,
|
||||
/*include_turns*/ true,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(thread) => thread,
|
||||
Err(err)
|
||||
if Self::closed_state_for_thread_read_error(
|
||||
&err, /*existing_is_closed*/ None,
|
||||
) =>
|
||||
{
|
||||
return Ok(PreparedAgentThread::Unavailable);
|
||||
}
|
||||
Err(err) if Self::can_fallback_from_include_turns_error(&err) => {
|
||||
return Err(format!(
|
||||
"Agent thread {thread_id} is not yet available for replay or live attach."
|
||||
));
|
||||
}
|
||||
Err(err) => return Err(format!("{err:#}")),
|
||||
};
|
||||
if thread.turns.is_empty() {
|
||||
Err(format!(
|
||||
"Agent thread {thread_id} is not yet available for replay or live attach."
|
||||
))
|
||||
} else {
|
||||
Ok(PreparedAgentThread::Replay(thread))
|
||||
}
|
||||
}
|
||||
|
||||
/// Materializes a live thread into local replay state when the picker knows about it but the
|
||||
/// TUI has not cached a local event channel yet.
|
||||
///
|
||||
/// Resume-time backfill intentionally avoids creating empty placeholder channels, because those
|
||||
/// placeholders make stale `/agent` entries open blank transcripts. When a user later selects a
|
||||
/// still-live discovered thread, attach it on demand with a real resumed snapshot.
|
||||
pub(super) async fn attach_live_thread_for_selection(
|
||||
async fn request_agent_thread_read(
|
||||
request_handle: &AppServerRequestHandle,
|
||||
thread_id: ThreadId,
|
||||
include_turns: bool,
|
||||
) -> Result<Thread> {
|
||||
let response: ThreadReadResponse = request_handle
|
||||
.request_typed(ClientRequest::ThreadRead {
|
||||
request_id: agent_request_id("read"),
|
||||
params: ThreadReadParams {
|
||||
thread_id: thread_id.to_string(),
|
||||
include_turns,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.wrap_err("thread/read failed during TUI session lookup")?;
|
||||
Ok(response.thread)
|
||||
}
|
||||
|
||||
pub(super) fn cancel_pending_agent_selection(&mut self) {
|
||||
self.pending_app_server_requests.agent_thread_selection = None;
|
||||
}
|
||||
|
||||
pub(super) async fn handle_agent_thread_selection_prepared(
|
||||
&mut self,
|
||||
app_server: &mut AppServerSession,
|
||||
request_id: Uuid,
|
||||
thread_id: ThreadId,
|
||||
) -> Result<bool> {
|
||||
if self.thread_event_channels.contains_key(&thread_id) {
|
||||
return Ok(true);
|
||||
attaching: bool,
|
||||
result: std::result::Result<PreparedAgentThread, String>,
|
||||
) -> bool {
|
||||
if self.pending_app_server_requests.agent_thread_selection != Some((request_id, thread_id))
|
||||
{
|
||||
self.cleanup_agent_thread_subscription(app_server, thread_id, attaching);
|
||||
return false;
|
||||
}
|
||||
|
||||
let (session, turns, live_attached) = match app_server
|
||||
.resume_thread(self.config.clone(), thread_id)
|
||||
.await
|
||||
{
|
||||
Ok(started) => (started.session, started.turns, true),
|
||||
Err(resume_err) => {
|
||||
tracing::warn!(
|
||||
thread_id = %thread_id,
|
||||
error = %resume_err,
|
||||
"failed to resume live thread for selection; falling back to thread/read"
|
||||
);
|
||||
let (thread, turns) = match app_server
|
||||
.thread_read(thread_id, /*include_turns*/ true)
|
||||
.await
|
||||
{
|
||||
Ok(thread) => {
|
||||
let turns = thread.turns.clone();
|
||||
(thread, turns)
|
||||
}
|
||||
Err(err) if Self::can_fallback_from_include_turns_error(&err) => {
|
||||
let thread = app_server
|
||||
.thread_read(thread_id, /*include_turns*/ false)
|
||||
.await?;
|
||||
(thread, Vec::new())
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
if turns.is_empty() {
|
||||
// A `thread/read` fallback without turns would create a blank local replay
|
||||
// channel with no live listener attached, which blocks later real re-attach.
|
||||
return Err(color_eyre::eyre::eyre!(
|
||||
"Agent thread {thread_id} is not yet available for replay or live attach."
|
||||
));
|
||||
}
|
||||
let mut session = self.session_state_for_thread_read(thread_id, &thread).await;
|
||||
// `thread/read` can seed replay state, but it does not attach the app-server
|
||||
// listener that `thread/resume` establishes, so treat this path as replay-only.
|
||||
session.model.clear();
|
||||
(session, turns, false)
|
||||
self.pending_app_server_requests.agent_thread_selection = None;
|
||||
let keep_subscription = matches!(&result, Ok(PreparedAgentThread::Resumed(_)));
|
||||
let replay_only = match result {
|
||||
Ok(PreparedAgentThread::Resumed(started)) => {
|
||||
let channel = self.ensure_thread_channel(thread_id);
|
||||
let mut snapshot = channel.store.lock().await.snapshot();
|
||||
self.apply_refreshed_snapshot_thread(thread_id, started, &mut snapshot)
|
||||
.await;
|
||||
Some(false)
|
||||
}
|
||||
Ok(PreparedAgentThread::Replay(mut thread)) => {
|
||||
let mut session = self.session_state_for_thread_read(thread_id, &thread).await;
|
||||
session.model.clear();
|
||||
let channel = self.ensure_thread_channel(thread_id);
|
||||
channel.mark_replay_only();
|
||||
channel
|
||||
.store
|
||||
.lock()
|
||||
.await
|
||||
.set_session(session, std::mem::take(&mut thread.turns));
|
||||
Some(true)
|
||||
}
|
||||
Ok(PreparedAgentThread::Unavailable) => {
|
||||
self.agent_navigation.remove(thread_id);
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Agent thread {thread_id} is no longer available."));
|
||||
None
|
||||
}
|
||||
Err(err) if attaching => {
|
||||
self.chat_widget.add_error_message(format!(
|
||||
"Failed to attach to agent thread {thread_id}: {err}"
|
||||
));
|
||||
None
|
||||
}
|
||||
Err(_) => Some(false),
|
||||
};
|
||||
let channel = self.ensure_thread_channel(thread_id);
|
||||
if !live_attached {
|
||||
channel.mark_replay_only();
|
||||
if !keep_subscription {
|
||||
self.cleanup_agent_thread_subscription(app_server, thread_id, attaching);
|
||||
}
|
||||
let Some(replay_only) = replay_only else {
|
||||
return false;
|
||||
};
|
||||
self.pending_app_server_requests
|
||||
.prepared_agent_thread_selection = Some(replay_only);
|
||||
true
|
||||
}
|
||||
|
||||
fn cleanup_agent_thread_subscription(
|
||||
&self,
|
||||
app_server: &AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
attaching: bool,
|
||||
) {
|
||||
if !attaching
|
||||
|| self
|
||||
.pending_app_server_requests
|
||||
.agent_thread_selection
|
||||
.is_some_and(|pending| pending.1 == thread_id)
|
||||
|| self.active_thread_id == Some(thread_id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let request_handle = app_server.request_handle();
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = request_handle
|
||||
.request_typed::<ThreadUnsubscribeResponse>(ClientRequest::ThreadUnsubscribe {
|
||||
request_id: agent_request_id("unsubscribe"),
|
||||
params: ThreadUnsubscribeParams {
|
||||
thread_id: thread_id.to_string(),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|err| format!("thread/unsubscribe failed: {err}"));
|
||||
app_event_tx.send(AppEvent::AgentThreadSelectionCleanupFinished(
|
||||
thread_id, result,
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) async fn handle_agent_thread_selection_cleanup_finished(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
result: std::result::Result<(), String>,
|
||||
) {
|
||||
let thread_is_in_use = self.active_thread_id == Some(thread_id)
|
||||
|| matches!(
|
||||
self.pending_app_server_requests.agent_thread_selection,
|
||||
Some((_, pending_thread_id)) if pending_thread_id == thread_id
|
||||
);
|
||||
match result {
|
||||
Ok(()) if !thread_is_in_use => {
|
||||
self.abort_thread_event_listener(thread_id);
|
||||
self.thread_event_channels.remove(&thread_id);
|
||||
self.refresh_pending_thread_approvals().await;
|
||||
}
|
||||
Ok(()) => {}
|
||||
Err(err) => tracing::warn!(thread_id = %thread_id, "{err}"),
|
||||
}
|
||||
let mut store = channel.store.lock().await;
|
||||
store.set_session(session, turns);
|
||||
Ok(live_attached)
|
||||
}
|
||||
|
||||
/// Replaces the chat widget and re-seeds the new widget's collab metadata from the navigation
|
||||
@@ -352,42 +499,38 @@ impl App {
|
||||
thread_id: ThreadId,
|
||||
) -> Result<()> {
|
||||
if self.active_thread_id == Some(thread_id) {
|
||||
self.pending_app_server_requests
|
||||
.prepared_agent_thread_selection = None;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !self
|
||||
.refresh_agent_picker_thread_liveness(app_server, thread_id)
|
||||
.await
|
||||
let attached_replay_only = if let Some(replay_only) = self
|
||||
.pending_app_server_requests
|
||||
.prepared_agent_thread_selection
|
||||
.take()
|
||||
{
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Agent thread {thread_id} is no longer available."));
|
||||
return Ok(());
|
||||
}
|
||||
replay_only
|
||||
} else {
|
||||
if !self
|
||||
.begin_agent_thread_selection(app_server, thread_id)
|
||||
.await
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
false
|
||||
};
|
||||
|
||||
let mut is_replay_only = self
|
||||
.agent_navigation
|
||||
.get(&thread_id)
|
||||
.is_some_and(|entry| entry.is_closed);
|
||||
let mut attached_replay_only = false;
|
||||
if self.should_attach_live_thread_for_selection(thread_id) {
|
||||
match self
|
||||
.attach_live_thread_for_selection(app_server, thread_id)
|
||||
.await
|
||||
{
|
||||
Ok(live_attached) => {
|
||||
attached_replay_only = !live_attached;
|
||||
if attached_replay_only {
|
||||
is_replay_only = true;
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
self.chat_widget.add_error_message(format!(
|
||||
"Failed to attach to agent thread {thread_id}: {err}"
|
||||
));
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
} else if !self.thread_event_channels.contains_key(&thread_id) && is_replay_only {
|
||||
.is_some_and(|entry| entry.is_closed)
|
||||
|| self
|
||||
.thread_event_channels
|
||||
.get(&thread_id)
|
||||
.is_some_and(|channel| channel.attachment() == ThreadEventAttachment::ReplayOnly);
|
||||
if attached_replay_only {
|
||||
is_replay_only = true;
|
||||
}
|
||||
if !self.thread_event_channels.contains_key(&thread_id) && is_replay_only {
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Agent thread {thread_id} is no longer available."));
|
||||
return Ok(());
|
||||
@@ -396,8 +539,7 @@ impl App {
|
||||
let previous_thread_id = self.active_thread_id;
|
||||
self.store_active_thread_receiver().await;
|
||||
self.active_thread_id = None;
|
||||
let Some((receiver, mut snapshot)) = self.activate_thread_for_replay(thread_id).await
|
||||
else {
|
||||
let Some((receiver, snapshot)) = self.activate_thread_for_replay(thread_id).await else {
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Agent thread {thread_id} is already active."));
|
||||
if let Some(previous_thread_id) = previous_thread_id {
|
||||
@@ -405,15 +547,6 @@ impl App {
|
||||
}
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
self.refresh_snapshot_session_if_needed(
|
||||
app_server,
|
||||
thread_id,
|
||||
is_replay_only,
|
||||
&mut snapshot,
|
||||
)
|
||||
.await;
|
||||
|
||||
self.active_thread_id = Some(thread_id);
|
||||
self.active_thread_rx = Some(receiver);
|
||||
|
||||
|
||||
+85
-117
@@ -8,6 +8,7 @@ use super::*;
|
||||
use crate::app_backtrack::BacktrackSelection;
|
||||
use crate::app_backtrack::BacktrackState;
|
||||
use crate::app_backtrack::user_count;
|
||||
use crate::app_event::PreparedAgentThread;
|
||||
|
||||
use crate::chatwidget::ChatWidgetInit;
|
||||
use crate::chatwidget::create_initial_user_message;
|
||||
@@ -1207,7 +1208,7 @@ async fn collab_receiver_notification_does_not_cache_not_found_thread() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_agent_picker_keeps_missing_threads_for_replay() -> Result<()> {
|
||||
async fn open_agent_picker_uses_cached_navigation_without_backend_reads() -> Result<()> {
|
||||
let mut app = Box::pin(make_test_app()).await;
|
||||
let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker(
|
||||
app.chat_widget.config_ref(),
|
||||
@@ -1215,23 +1216,13 @@ async fn open_agent_picker_keeps_missing_threads_for_replay() -> Result<()> {
|
||||
.await
|
||||
.expect("embedded app server");
|
||||
let thread_id = ThreadId::new();
|
||||
app.thread_event_channels
|
||||
.insert(thread_id, ThreadEventChannel::new(/*capacity*/ 1));
|
||||
app.agent_navigation.upsert(
|
||||
thread_id, /*agent_nickname*/ None, /*agent_role*/ None, /*is_closed*/ false,
|
||||
);
|
||||
|
||||
Box::pin(app.open_agent_picker(&mut app_server)).await;
|
||||
|
||||
assert_eq!(app.thread_event_channels.contains_key(&thread_id), true);
|
||||
assert_eq!(
|
||||
app.agent_navigation.get(&thread_id),
|
||||
Some(&AgentPickerThreadEntry {
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
agent_path: None,
|
||||
is_running: false,
|
||||
is_closed: true,
|
||||
})
|
||||
);
|
||||
assert_eq!(app.agent_navigation.ordered_thread_ids(), vec![thread_id]);
|
||||
assert!(app.chat_widget.has_active_view());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1312,7 +1303,7 @@ async fn open_agent_picker_clears_completed_path_backed_agent_running_state() ->
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_agent_picker_refreshes_replay_only_path_backed_liveness() -> Result<()> {
|
||||
async fn open_agent_picker_clears_replay_only_path_backed_running_hint() -> Result<()> {
|
||||
let mut app = Box::pin(make_test_app()).await;
|
||||
let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker(
|
||||
app.chat_widget.config_ref(),
|
||||
@@ -1343,65 +1334,69 @@ async fn open_agent_picker_refreshes_replay_only_path_backed_liveness() -> Resul
|
||||
agent_role: None,
|
||||
agent_path: Some("/root/child".to_string()),
|
||||
is_running: false,
|
||||
is_closed: true,
|
||||
is_closed: false,
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_agent_picker_prunes_terminal_metadata_only_threads() -> Result<()> {
|
||||
let mut app = Box::pin(make_test_app()).await;
|
||||
let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker(
|
||||
app.chat_widget.config_ref(),
|
||||
))
|
||||
.await
|
||||
.expect("embedded app server");
|
||||
async fn selecting_uncached_agent_keeps_event_processing_available() -> Result<()> {
|
||||
let mut app = make_test_app().await;
|
||||
let app_server =
|
||||
crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?;
|
||||
let thread_id = ThreadId::new();
|
||||
app.agent_navigation.upsert(
|
||||
thread_id,
|
||||
Some("Ghost".to_string()),
|
||||
Some("Scout".to_string()),
|
||||
Some("worker".to_string()),
|
||||
/*is_closed*/ false,
|
||||
);
|
||||
|
||||
Box::pin(app.open_agent_picker(&mut app_server)).await;
|
||||
|
||||
assert_eq!(app.agent_navigation.get(&thread_id), None);
|
||||
assert!(app.agent_navigation.is_empty());
|
||||
assert!(
|
||||
!app.begin_agent_thread_selection(&app_server, thread_id)
|
||||
.await
|
||||
);
|
||||
app.handle_thread_event_now(ThreadBufferedEvent::Notification(
|
||||
turn_started_notification(ThreadId::new(), "turn-1"),
|
||||
));
|
||||
assert!(app.chat_widget.is_task_running_for_test());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn open_agent_picker_marks_terminal_read_errors_closed() -> Result<()> {
|
||||
let mut app = Box::pin(make_test_app()).await;
|
||||
let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker(
|
||||
app.chat_widget.config_ref(),
|
||||
))
|
||||
.await
|
||||
.expect("embedded app server");
|
||||
async fn escape_cancels_pending_agent_selection_and_ignores_late_result() -> Result<()> {
|
||||
let mut app = make_test_app().await;
|
||||
let mut app_server =
|
||||
crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?;
|
||||
let thread_id = ThreadId::new();
|
||||
let request_id = Uuid::new_v4();
|
||||
app.pending_app_server_requests.agent_thread_selection = Some((request_id, thread_id));
|
||||
app.cancel_pending_agent_selection();
|
||||
assert_eq!(app.pending_app_server_requests.agent_thread_selection, None);
|
||||
|
||||
app.thread_event_channels
|
||||
.insert(thread_id, ThreadEventChannel::new(/*capacity*/ 1));
|
||||
app.agent_navigation.upsert(
|
||||
thread_id,
|
||||
Some("Robie".to_string()),
|
||||
Some("explorer".to_string()),
|
||||
/*is_closed*/ false,
|
||||
thread_id, /*agent_nickname*/ None, /*agent_role*/ None, /*is_closed*/ false,
|
||||
);
|
||||
|
||||
Box::pin(app.open_agent_picker(&mut app_server)).await;
|
||||
|
||||
assert_eq!(
|
||||
app.agent_navigation.get(&thread_id),
|
||||
Some(&AgentPickerThreadEntry {
|
||||
agent_nickname: Some("Robie".to_string()),
|
||||
agent_role: Some("explorer".to_string()),
|
||||
agent_path: None,
|
||||
is_running: false,
|
||||
is_closed: true,
|
||||
})
|
||||
assert!(
|
||||
!app.handle_agent_thread_selection_prepared(
|
||||
&mut app_server,
|
||||
request_id,
|
||||
thread_id,
|
||||
/*attaching*/ true,
|
||||
Ok(PreparedAgentThread::Unavailable),
|
||||
)
|
||||
.await
|
||||
);
|
||||
|
||||
app.handle_agent_thread_selection_cleanup_finished(thread_id, Ok(()))
|
||||
.await;
|
||||
|
||||
assert!(!app.thread_event_channels.contains_key(&thread_id));
|
||||
assert!(app.agent_navigation.get(&thread_id).is_some());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1429,6 +1424,10 @@ fn open_agent_picker_marks_loaded_threads_open() -> Result<()> {
|
||||
let thread_id = started.session.thread_id;
|
||||
app.thread_event_channels
|
||||
.insert(thread_id, ThreadEventChannel::new(/*capacity*/ 1));
|
||||
app.agent_navigation.upsert(
|
||||
thread_id, /*agent_nickname*/ None, /*agent_role*/ None,
|
||||
/*is_closed*/ false,
|
||||
);
|
||||
|
||||
Box::pin(app.open_agent_picker(&mut app_server)).await;
|
||||
|
||||
@@ -1447,7 +1446,7 @@ fn open_agent_picker_marks_loaded_threads_open() -> Result<()> {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attach_live_thread_for_selection_rejects_empty_non_ephemeral_fallback_threads() -> Result<()> {
|
||||
fn agent_selection_rejects_empty_non_ephemeral_fallback_threads() -> Result<()> {
|
||||
const WORKER_THREADS: usize = 1;
|
||||
const TEST_STACK_SIZE_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
@@ -1458,55 +1457,12 @@ fn attach_live_thread_for_selection_rejects_empty_non_ephemeral_fallback_threads
|
||||
.build()?;
|
||||
|
||||
runtime.block_on(async {
|
||||
let config = {
|
||||
let app = make_test_app().await;
|
||||
app.chat_widget.config_ref().clone()
|
||||
};
|
||||
let mut app_server = crate::start_embedded_app_server_for_picker(&config)
|
||||
.await
|
||||
.expect("embedded app server");
|
||||
let started = app_server.start_thread(&config).await?;
|
||||
let thread_id = started.session.thread_id;
|
||||
let mut app = make_test_app().await;
|
||||
app.agent_navigation.upsert(
|
||||
thread_id,
|
||||
Some("Scout".to_string()),
|
||||
Some("worker".to_string()),
|
||||
/*is_closed*/ false,
|
||||
);
|
||||
|
||||
let err = app
|
||||
.attach_live_thread_for_selection(&mut app_server, thread_id)
|
||||
.await
|
||||
.expect_err("empty fallback should not attach as a blank replay-only thread");
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
format!("Agent thread {thread_id} is not yet available for replay or live attach.")
|
||||
);
|
||||
assert!(!app.thread_event_channels.contains_key(&thread_id));
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attach_live_thread_for_selection_rejects_unmaterialized_fallback_threads() -> Result<()> {
|
||||
const WORKER_THREADS: usize = 1;
|
||||
const TEST_STACK_SIZE_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(WORKER_THREADS)
|
||||
.thread_stack_size(TEST_STACK_SIZE_BYTES)
|
||||
.enable_all()
|
||||
.build()?;
|
||||
|
||||
runtime.block_on(async {
|
||||
let mut app = make_test_app().await;
|
||||
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
|
||||
let mut app_server =
|
||||
crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?;
|
||||
let mut ephemeral_config = app.chat_widget.config_ref().clone();
|
||||
ephemeral_config.ephemeral = true;
|
||||
let started = app_server.start_thread(&ephemeral_config).await?;
|
||||
let started = app_server
|
||||
.start_thread(app.chat_widget.config_ref())
|
||||
.await?;
|
||||
let thread_id = started.session.thread_id;
|
||||
app.agent_navigation.upsert(
|
||||
thread_id,
|
||||
@@ -1515,13 +1471,19 @@ fn attach_live_thread_for_selection_rejects_unmaterialized_fallback_threads() ->
|
||||
/*is_closed*/ false,
|
||||
);
|
||||
|
||||
let err = app
|
||||
.attach_live_thread_for_selection(&mut app_server, thread_id)
|
||||
.await
|
||||
.expect_err("ephemeral fallback should not attach as a blank live thread");
|
||||
assert!(
|
||||
!app.begin_agent_thread_selection(&app_server, thread_id)
|
||||
.await
|
||||
);
|
||||
let err = match app_event_rx.recv().await {
|
||||
Some(AppEvent::AgentThreadSelectionPrepared {
|
||||
result: Err(err), ..
|
||||
}) => err,
|
||||
other => panic!("expected failed agent preparation, got {other:?}"),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
err,
|
||||
format!("Agent thread {thread_id} is not yet available for replay or live attach.")
|
||||
);
|
||||
assert!(!app.thread_event_channels.contains_key(&thread_id));
|
||||
@@ -1556,27 +1518,30 @@ async fn should_attach_live_thread_for_selection_skips_closed_metadata_only_thre
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refresh_agent_picker_thread_liveness_prunes_closed_metadata_only_threads() -> Result<()> {
|
||||
let mut app = Box::pin(make_test_app()).await;
|
||||
let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker(
|
||||
app.chat_widget.config_ref(),
|
||||
))
|
||||
.await
|
||||
.expect("embedded app server");
|
||||
async fn local_agent_selection_needs_no_backend_preparation() -> Result<()> {
|
||||
let mut app = make_test_app().await;
|
||||
let app_server =
|
||||
crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?;
|
||||
let thread_id = ThreadId::new();
|
||||
let mut session = test_thread_session(thread_id, test_path_buf("/tmp/agent"));
|
||||
session.rollout_path = Some(test_path_buf("/tmp/agent-rollout.jsonl"));
|
||||
app.thread_event_channels.insert(
|
||||
thread_id,
|
||||
ThreadEventChannel::new_with_session(/*capacity*/ 1, session, Vec::new()),
|
||||
);
|
||||
app.agent_navigation.upsert(
|
||||
thread_id,
|
||||
Some("Ghost".to_string()),
|
||||
Some("Scout".to_string()),
|
||||
Some("worker".to_string()),
|
||||
/*is_closed*/ false,
|
||||
);
|
||||
|
||||
let is_available =
|
||||
Box::pin(app.refresh_agent_picker_thread_liveness(&mut app_server, thread_id)).await;
|
||||
assert!(
|
||||
app.begin_agent_thread_selection(&app_server, thread_id)
|
||||
.await
|
||||
);
|
||||
|
||||
assert!(!is_available);
|
||||
assert_eq!(app.agent_navigation.get(&thread_id), None);
|
||||
assert!(!app.thread_event_channels.contains_key(&thread_id));
|
||||
assert_eq!(app.pending_app_server_requests.agent_thread_selection, None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2160,6 +2125,9 @@ async fn open_agent_picker_allows_existing_agent_threads_when_feature_is_disable
|
||||
let thread_id = ThreadId::new();
|
||||
app.thread_event_channels
|
||||
.insert(thread_id, ThreadEventChannel::new(/*capacity*/ 1));
|
||||
app.agent_navigation.upsert(
|
||||
thread_id, /*agent_nickname*/ None, /*agent_role*/ None, /*is_closed*/ false,
|
||||
);
|
||||
|
||||
Box::pin(app.open_agent_picker(&mut app_server)).await;
|
||||
app.chat_widget
|
||||
|
||||
@@ -1177,35 +1177,6 @@ impl App {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn refresh_snapshot_session_if_needed(
|
||||
&mut self,
|
||||
app_server: &mut AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
is_replay_only: bool,
|
||||
snapshot: &mut ThreadEventSnapshot,
|
||||
) {
|
||||
if !self.should_refresh_snapshot_session(thread_id, is_replay_only, snapshot) {
|
||||
return;
|
||||
}
|
||||
|
||||
match app_server
|
||||
.resume_thread(self.config.clone(), thread_id)
|
||||
.await
|
||||
{
|
||||
Ok(started) => {
|
||||
self.apply_refreshed_snapshot_thread(thread_id, started, snapshot)
|
||||
.await
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
thread_id = %thread_id,
|
||||
error = %err,
|
||||
"failed to refresh inferred thread session before replay"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn should_refresh_snapshot_session(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
|
||||
@@ -25,12 +25,14 @@ use codex_app_server_protocol::PluginReadResponse;
|
||||
use codex_app_server_protocol::PluginUninstallResponse;
|
||||
use codex_app_server_protocol::RateLimitSnapshot;
|
||||
use codex_app_server_protocol::SkillsListResponse;
|
||||
use codex_app_server_protocol::Thread;
|
||||
use codex_app_server_protocol::ThreadGoalStatus;
|
||||
use codex_file_search::FileMatch;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::openai_models::ModelPreset;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_approval_presets::ApprovalPreset;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::app_command::AppCommand;
|
||||
use crate::app_server_session::AppServerStartedThread;
|
||||
@@ -74,6 +76,13 @@ pub(crate) struct HistoryLookupResponse {
|
||||
pub(crate) entry: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum PreparedAgentThread {
|
||||
Resumed(AppServerStartedThread),
|
||||
Replay(Thread),
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
impl RealtimeAudioDeviceKind {
|
||||
pub(crate) fn title(self) -> &'static str {
|
||||
match self {
|
||||
@@ -140,6 +149,14 @@ pub(crate) enum AppEvent {
|
||||
OpenAgentPicker,
|
||||
/// Switch the active thread to the selected agent.
|
||||
SelectAgentThread(ThreadId),
|
||||
/// Deliver the result of preparing an agent thread for selection.
|
||||
AgentThreadSelectionPrepared {
|
||||
request_id: Uuid,
|
||||
thread_id: ThreadId,
|
||||
attaching: bool,
|
||||
result: Result<PreparedAgentThread, String>,
|
||||
},
|
||||
AgentThreadSelectionCleanupFinished(ThreadId, Result<(), String>),
|
||||
|
||||
/// Fork the current thread into a transient side conversation.
|
||||
StartSide {
|
||||
|
||||
@@ -476,7 +476,7 @@ impl AppServerSession {
|
||||
self.thread_params_mode
|
||||
}
|
||||
|
||||
fn session_config_with_effective_service_tier(&self, config: &Config) -> Config {
|
||||
pub(crate) fn session_config_with_effective_service_tier(&self, config: &Config) -> Config {
|
||||
let Some(model) = config.model.as_deref().or(self.default_model.as_deref()) else {
|
||||
return config.clone();
|
||||
};
|
||||
@@ -1423,7 +1423,7 @@ fn thread_start_params_from_config(
|
||||
}
|
||||
}
|
||||
|
||||
fn thread_resume_params_from_config(
|
||||
pub(crate) fn thread_resume_params_from_config(
|
||||
config: Config,
|
||||
thread_id: ThreadId,
|
||||
thread_params_mode: ThreadParamsMode,
|
||||
@@ -1525,7 +1525,7 @@ async fn started_thread_from_start_response(
|
||||
})
|
||||
}
|
||||
|
||||
async fn started_thread_from_resume_response(
|
||||
pub(crate) async fn started_thread_from_resume_response(
|
||||
response: ThreadResumeResponse,
|
||||
config: &Config,
|
||||
thread_params_mode: ThreadParamsMode,
|
||||
|
||||
Reference in New Issue
Block a user