Make parent-owned sub-agent threads read-only in the TUI (#33841)

## Why

Multi-agent V2 spawned threads are controlled by their parent and reject direct
app-server input. The TUI should expose that ownership instead of presenting an
input flow that the server will reject.

## What changed

- Add the experimental `Thread.canAcceptDirectInput` capability for loaded
  threads and populate it from the same policy used to validate `turn/start`
  and `turn/steer`. Stored, unloaded threads report `null`.
- Carry the capability through TUI thread discovery, selection, startup, and
  resume flows, with a compatibility fallback for older app servers.
- Present parent-owned threads as view-only, preserve drafts and queued input,
  block agent-directed commands and settings shortcuts, and keep local
  navigation and inspection commands available.

## Testing

- Cover V1 writable and V2 view-only spawned threads through selection and
  resume.
- Cover composer submission paths, queued and initial input preservation,
  allowed navigation commands, settings shortcuts, and the view-only UI.

GitOrigin-RevId: 495ad051249e5577fb0b0c1cc8c40a0998d04918
This commit is contained in:
Felipe Coury authored and copyberry committed 2026-07-17 15:14:47 +00:00
1 parent 315195492c
commit 3f0669dbd6
37 files changed
+781 -99

No files matched your search

+29
View File
@@ -6,6 +6,7 @@
//!
//! Responsibilities here are intentionally narrow:
//! - remember picker entries and their first-seen order
//! - remember which V2 child threads are owned by their parent agent
//! - answer traversal questions like "what is the next thread?"
//! - derive user-facing picker/footer text from cached thread metadata
//!
@@ -26,6 +27,7 @@ use crate::multi_agents::previous_agent_shortcut;
use codex_protocol::ThreadId;
use ratatui::text::Span;
use std::collections::HashMap;
use std::collections::HashSet;
/// Small state container for multi-agent picker ordering and labeling.
///
@@ -42,6 +44,8 @@ pub(crate) struct AgentNavigationState {
threads: HashMap<ThreadId, AgentPickerThreadEntry>,
/// Stable first-seen traversal order for picker rows and keyboard cycling.
order: Vec<ThreadId>,
/// Spawned child threads whose instructions are owned by their parent agent.
parent_owned_threads: HashSet<ThreadId>,
}
/// Direction of keyboard traversal through the stable picker order.
@@ -64,6 +68,15 @@ impl AgentNavigationState {
self.threads.get(thread_id)
}
pub(crate) fn is_parent_owned(&self, thread_id: ThreadId) -> bool {
self.parent_owned_threads.contains(&thread_id)
}
/// Marks a spawned child thread as view-only for direct user instructions.
pub(crate) fn mark_parent_owned(&mut self, thread_id: ThreadId) {
self.parent_owned_threads.insert(thread_id);
}
/// Returns whether the picker cache currently knows about any threads.
///
/// This is the cheapest way for `App` to decide whether opening the picker should show "No
@@ -162,6 +175,7 @@ impl AgentNavigationState {
pub(crate) fn clear(&mut self) {
self.threads.clear();
self.order.clear();
self.parent_owned_threads.clear();
}
/// Removes a tracked thread entirely from picker metadata and traversal order.
@@ -172,6 +186,7 @@ impl AgentNavigationState {
pub(crate) fn remove(&mut self, thread_id: ThreadId) {
self.threads.remove(&thread_id);
self.order.retain(|candidate| *candidate != thread_id);
self.parent_owned_threads.remove(&thread_id);
}
/// Returns whether there is at least one tracked thread other than the primary one.
@@ -376,6 +391,20 @@ mod tests {
);
}
#[test]
fn parent_owned_state_is_removed_with_thread_metadata() {
let (mut state, _main_thread_id, first_agent_id, second_agent_id) = populated_state();
state.mark_parent_owned(first_agent_id);
assert!(state.is_parent_owned(first_agent_id));
state.remove(first_agent_id);
assert!(!state.is_parent_owned(first_agent_id));
state.mark_parent_owned(second_agent_id);
state.clear();
assert!(!state.is_parent_owned(second_agent_id));
}
#[test]
fn adjacent_thread_id_wraps_in_spawn_order() {
let (state, main_thread_id, first_agent_id, second_agent_id) = populated_state();
+8 -1
View File
@@ -14,6 +14,7 @@
//! `SessionSource::SubAgent(ThreadSpawn { parent_thread_id, .. })` edges until no new children are
//! found. The primary thread itself is never included in the output.
use crate::app_server_session::thread_blocks_direct_input;
use codex_app_server_protocol::SessionSource;
use codex_app_server_protocol::Thread;
use codex_protocol::ThreadId;
@@ -29,6 +30,7 @@ pub(crate) struct LoadedSubagentThread {
pub(crate) agent_nickname: Option<String>,
pub(crate) agent_role: Option<String>,
pub(crate) agent_path: Option<String>,
pub(crate) blocks_direct_input: bool,
}
/// Walks the spawn tree rooted at `primary_thread_id` and returns every descendant subagent.
@@ -84,6 +86,7 @@ pub(crate) fn find_loaded_subagent_threads_for_primary(
threads_by_id
.remove(&thread_id)
.map(|thread| LoadedSubagentThread {
blocks_direct_input: thread_blocks_direct_input(&thread),
thread_id,
agent_nickname: thread.agent_nickname,
agent_role: thread.agent_role,
@@ -144,6 +147,7 @@ mod tests {
cwd: test_path_buf("/tmp").abs(),
cli_version: "0.0.0".to_string(),
source,
can_accept_direct_input: None,
thread_source: None,
agent_nickname: None,
agent_role: None,
@@ -191,6 +195,7 @@ mod tests {
);
child.agent_nickname = Some("Scout".to_string());
child.agent_role = Some("explorer".to_string());
child.can_accept_direct_input = Some(true);
let mut grandchild = test_thread(
grandchild_thread_id,
@@ -198,7 +203,7 @@ mod tests {
);
grandchild.agent_nickname = Some("Atlas".to_string());
grandchild.agent_role = Some("worker".to_string());
grandchild.can_accept_direct_input = Some(false);
let unrelated_child = test_thread(
unrelated_child_id,
thread_spawn_source(unrelated_parent_id, /*depth*/ 1, "Other", "researcher"),
@@ -218,12 +223,14 @@ mod tests {
loaded,
vec![
LoadedSubagentThread {
blocks_direct_input: false,
thread_id: child_thread_id,
agent_nickname: Some("Scout".to_string()),
agent_role: Some("explorer".to_string()),
agent_path: None,
},
LoadedSubagentThread {
blocks_direct_input: true,
thread_id: grandchild_thread_id,
agent_nickname: Some("Atlas".to_string()),
agent_role: Some("worker".to_string()),
+33 -3
View File
@@ -5,6 +5,8 @@
//! cache used for multi-agent navigation.
use super::*;
use crate::app_server_session::source_agent_path;
use crate::app_server_session::thread_blocks_direct_input;
#[derive(Clone, Copy)]
pub(super) enum ThreadAttachPresentation {
@@ -184,6 +186,12 @@ impl App {
self.sync_active_agent_label();
}
/// Persists the app-server's authoritative ownership flag and updates the active composer.
pub(super) fn mark_primary_thread_parent_owned(&mut self, thread_id: ThreadId) {
self.agent_navigation.mark_parent_owned(thread_id);
self.chat_widget.set_parent_owned_thread();
}
/// Marks a cached picker thread closed and recomputes the contextual footer label.
///
/// Closing a thread is not the same as removing it: users can still inspect finished agent
@@ -205,6 +213,8 @@ impl App {
.await
{
Ok(thread) => {
let is_parent_owned = thread_blocks_direct_input(&thread);
let agent_path = source_agent_path(&thread.source);
let is_running = matches!(
thread.status,
codex_app_server_protocol::ThreadStatus::Active { .. }
@@ -227,6 +237,10 @@ impl App {
}),
is_closed,
);
if is_parent_owned {
self.agent_navigation.mark_parent_owned(thread_id);
}
self.agent_navigation.set_agent_path(thread_id, agent_path);
self.agent_navigation.set_running(thread_id, is_running);
true
}
@@ -278,7 +292,12 @@ impl App {
.resume_thread(self.config.clone(), thread_id, self.resume_model_settings())
.await
{
Ok(started) => (started.session, started.turns, true),
Ok(started) => {
if started.blocks_direct_input {
self.agent_navigation.mark_parent_owned(thread_id);
}
(started.session, started.turns, true)
}
Err(resume_err) => {
tracing::warn!(
thread_id = %thread_id,
@@ -369,7 +388,6 @@ impl App {
.add_error_message(format!("Agent thread {thread_id} is no longer available."));
return Ok(());
}
let mut is_replay_only = self
.agent_navigation
.get(&thread_id)
@@ -398,7 +416,6 @@ impl App {
.add_error_message(format!("Agent thread {thread_id} is no longer available."));
return Ok(());
}
let previous_thread_id = self.active_thread_id;
self.store_active_thread_receiver().await;
self.active_thread_id = None;
@@ -419,6 +436,7 @@ impl App {
&mut snapshot,
)
.await;
let blocks_direct_input = self.agent_navigation.is_parent_owned(thread_id);
self.active_thread_id = Some(thread_id);
self.active_thread_rx = Some(receiver);
@@ -429,6 +447,9 @@ impl App {
/*initial_user_message*/ None,
);
self.replace_chat_widget(ChatWidget::new_with_app_event(init));
if blocks_direct_input {
self.chat_widget.set_parent_owned_thread();
}
self.reset_for_thread_switch(tui)?;
self.replay_thread_snapshot(snapshot, !is_replay_only);
@@ -519,6 +540,9 @@ impl App {
.set_queue_submissions_until_session_configured(/*queue*/ false);
match result {
Ok(started) => {
if started.blocks_direct_input {
self.mark_primary_thread_parent_owned(started.session.thread_id);
}
self.enqueue_primary_thread_session(started.session, started.turns)
.await?;
self.chat_widget.maybe_send_next_queued_input();
@@ -625,6 +649,9 @@ impl App {
initial_user_message,
);
self.replace_chat_widget(ChatWidget::new_with_app_event(init));
if started.blocks_direct_input {
self.mark_primary_thread_parent_owned(started.session.thread_id);
}
self.enqueue_primary_thread_session_with_presentation(
started.session,
started.turns,
@@ -694,6 +721,9 @@ impl App {
for thread in find_loaded_subagent_threads_for_primary(threads, primary_thread_id) {
let agent_path = thread.agent_path;
if thread.blocks_direct_input {
self.agent_navigation.mark_parent_owned(thread.thread_id);
}
self.upsert_agent_picker_thread(
thread.thread_id,
thread.agent_nickname,
+152
View File
@@ -99,7 +99,11 @@ use codex_protocol::models::NetworkPermissions;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::MAX_THREAD_GOAL_OBJECTIVE_CHARS;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::SessionMeta;
use codex_protocol::protocol::SessionSource as RolloutSessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::protocol::TurnCompleteEvent;
use codex_protocol::protocol::TurnStartedEvent;
use codex_protocol::protocol::UserMessageEvent;
@@ -1372,6 +1376,7 @@ async fn open_agent_picker_clears_completed_path_backed_agent_running_state() ->
agent_path: "/root/child".to_string(),
is_running_hint: true,
});
assert!(!app.agent_navigation.is_parent_owned(thread_id));
Box::pin(app.open_agent_picker(&mut app_server)).await;
@@ -1523,6 +1528,147 @@ fn open_agent_picker_marks_loaded_threads_open() -> Result<()> {
})
}
#[test]
fn selected_and_resumed_threads_use_server_capability_for_v1_and_v2_children() -> 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, 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 root = app_server
.start_thread(app.chat_widget.config_ref())
.await?;
let root_thread_id = root.session.thread_id;
app.enqueue_primary_thread_session(root.session, root.turns)
.await?;
let rollout_dir = app
.config
.codex_home
.join("sessions")
.join("2026")
.join("01")
.join("01");
std::fs::create_dir_all(&rollout_dir)?;
let mut child_thread_ids = Vec::new();
for (index, multi_agent_version) in [MultiAgentVersion::V1, MultiAgentVersion::V2]
.into_iter()
.enumerate()
{
let child_thread_id = ThreadId::new();
let timestamp = format!("2026-01-01T00:00:0{index}Z");
let session_meta = SessionMeta {
session_id: child_thread_id.into(),
id: child_thread_id,
parent_thread_id: Some(root_thread_id),
timestamp: timestamp.clone(),
cwd: app.config.cwd.to_path_buf(),
originator: "codex-tui-test".to_string(),
cli_version: "0.0.0".to_string(),
source: RolloutSessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id: root_thread_id,
depth: 1,
agent_path: None,
agent_nickname: Some(format!("child-{index}")),
agent_role: Some("worker".to_string()),
}),
model_provider: Some(app.config.model_provider_id.clone()),
multi_agent_version: Some(multi_agent_version),
..SessionMeta::default()
};
let rollout_path = rollout_dir.join(format!(
"rollout-2026-01-01T00-00-0{index}-{child_thread_id}.jsonl"
));
let session_meta_line = serde_json::json!({
"timestamp": timestamp,
"type": "session_meta",
"payload": serde_json::to_value(session_meta)?,
});
std::fs::write(rollout_path, format!("{session_meta_line}\n"))?;
assert!(
app.attach_live_thread_for_selection(&mut app_server, child_thread_id)
.await?
);
assert_eq!(
app.agent_navigation.is_parent_owned(child_thread_id),
multi_agent_version == MultiAgentVersion::V2
);
child_thread_ids.push(child_thread_id);
}
assert!(app.backfill_loaded_subagent_threads(&mut app_server).await);
assert!(!app.agent_navigation.is_parent_owned(child_thread_ids[0]));
assert!(app.agent_navigation.is_parent_owned(child_thread_ids[1]));
let mut tui = crate::tui::test_support::make_test_tui()?;
app.select_agent_thread(&mut tui, &mut app_server, child_thread_ids[0])
.await?;
while app_event_rx.try_recv().is_ok() {}
app.chat_widget
.restore_user_message_to_composer("v1 remains writable".into());
app.chat_widget
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert!(
std::iter::from_fn(|| app_event_rx.try_recv().ok())
.any(|event| matches!(event, AppEvent::CodexOp(Op::UserTurn { .. })))
);
app.select_agent_thread(&mut tui, &mut app_server, child_thread_ids[1])
.await?;
while app_event_rx.try_recv().is_ok() {}
app.chat_widget
.restore_user_message_to_composer("v2 stays view-only".into());
let draft = app.chat_widget.composer_text_with_pending();
app.chat_widget
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert_eq!(app.chat_widget.composer_text_with_pending(), draft);
assert!(
!std::iter::from_fn(|| app_event_rx.try_recv().ok())
.any(|event| matches!(event, AppEvent::CodexOp(Op::UserTurn { .. })))
);
let resumed = app_server
.resume_thread(
app.config.clone(),
child_thread_ids[1],
app.resume_model_settings(),
)
.await?;
assert!(resumed.blocks_direct_input);
app.replace_chat_widget_with_app_server_thread(
&mut tui,
&mut app_server,
resumed,
crate::app::session_lifecycle::ThreadAttachPresentation::SessionLineage,
/*initial_user_message*/ None,
)
.await?;
while app_event_rx.try_recv().is_ok() {}
app.chat_widget
.restore_user_message_to_composer("direct resume stays view-only".into());
let draft = app.chat_widget.composer_text_with_pending();
app.chat_widget
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
assert_eq!(app.chat_widget.composer_text_with_pending(), draft);
assert!(
!std::iter::from_fn(|| app_event_rx.try_recv().ok())
.any(|event| matches!(event, AppEvent::CodexOp(Op::UserTurn { .. })))
);
Ok(())
})
}
#[test]
fn attach_live_thread_for_selection_rejects_empty_non_ephemeral_fallback_threads() -> Result<()> {
const WORKER_THREADS: usize = 1;
@@ -2947,6 +3093,7 @@ async fn inactive_thread_started_notification_initializes_replay_session() -> Re
cwd: test_path_buf("/tmp/agent").abs(),
cli_version: "0.0.0".to_string(),
source: codex_app_server_protocol::SessionSource::Unknown,
can_accept_direct_input: None,
thread_source: None,
agent_nickname: Some("Robie".to_string()),
agent_role: Some("explorer".to_string()),
@@ -3042,6 +3189,7 @@ async fn inactive_thread_started_notification_preserves_primary_model_when_path_
cwd: test_path_buf("/tmp/agent").abs(),
cli_version: "0.0.0".to_string(),
source: codex_app_server_protocol::SessionSource::Unknown,
can_accept_direct_input: None,
thread_source: None,
agent_nickname: Some("Robie".to_string()),
agent_role: Some("explorer".to_string()),
@@ -3104,6 +3252,7 @@ async fn thread_read_session_state_does_not_reuse_primary_permission_profile() {
cwd: test_path_buf("/tmp/read").abs(),
cli_version: "0.0.0".to_string(),
source: codex_app_server_protocol::SessionSource::Unknown,
can_accept_direct_input: None,
thread_source: None,
agent_nickname: None,
agent_role: None,
@@ -3586,6 +3735,7 @@ async fn primary_thread_ignores_child_mcp_startup_notifications() {
AppServerStartedThread {
session: test_thread_session(child_thread_id, test_path_buf("/tmp/child")),
turns: Vec::new(),
blocks_direct_input: false,
},
&mut child_snapshot,
)
@@ -5778,11 +5928,13 @@ async fn refreshed_snapshot_session_persists_resumed_turns() {
AppServerStartedThread {
session: resumed_session.clone(),
turns: resumed_turns.clone(),
blocks_direct_input: true,
},
&mut snapshot,
)
.await;
assert!(app.agent_navigation.is_parent_owned(thread_id));
assert_eq!(snapshot.session, Some(resumed_session.clone()));
assert_eq!(snapshot.turns, resumed_turns);
+2
View File
@@ -162,6 +162,7 @@ async fn startup_thread_started_submits_queued_startup_input() {
Ok(AppServerStartedThread {
session: test_thread_session(thread_id, test_path_buf("/tmp/project")),
turns: Vec::new(),
blocks_direct_input: false,
}),
)
.await
@@ -239,6 +240,7 @@ fn stale_startup_thread_started_removes_local_routing_state() -> Result<()> {
Ok(AppServerStartedThread {
session: test_thread_session(stale_thread_id, test_path_buf("/tmp/project")),
turns: Vec::new(),
blocks_direct_input: false,
}),
)
.await?;
+4 -1
View File
@@ -1245,7 +1245,10 @@ impl App {
started: AppServerStartedThread,
snapshot: &mut ThreadEventSnapshot,
) {
let AppServerStartedThread { session, turns } = started;
if started.blocks_direct_input {
self.agent_navigation.mark_parent_owned(thread_id);
}
let AppServerStartedThread { session, turns, .. } = started;
if let Some(channel) = self.thread_event_channels.get(&thread_id) {
let mut store = channel.store.lock().await;
store.set_session(session.clone(), turns.clone());
@@ -425,6 +425,7 @@ mod tests {
cwd: test_path_buf("/tmp/read").abs(),
cli_version: "0.0.0".to_string(),
source: codex_app_server_protocol::SessionSource::Unknown,
can_accept_direct_input: None,
thread_source: None,
agent_nickname: None,
agent_role: None,