Cancel folder trust prompts when the app server disconnects (#63262)

## Why

A daemon restart can invalidate the connection while a folder trust
prompt is open. A queued confirmation can otherwise still be handled
against that closed connection.

## What changed

Dismiss the folder trust prompt when the connection closes, giving the
disconnect priority over queued input. Leave the disconnect event for
the Agents overview to handle. During startup, exit with a message
asking the user to restart Codex.

## Testing

Add tests for daemon restarts during folder consent in the Agents
overview and at startup. Both check that the restart leaves the trust
setting unset. A unit test checks that disconnect wins over queued Enter.

GitOrigin-RevId: 21ee1ca625ed8bc2266a9a37a260254d4e87369d
This commit is contained in:
Anton Panasenko
2026-11-23 04:58:33 +00:00
committed by copyberry
parent 326bac6ce0
commit 794584993e
4 changed files with 115 additions and 6 deletions
@@ -637,6 +637,16 @@ impl RemoteAppServerClient {
}
impl RemoteAppServerRequestHandle {
/// Whether this connection has stopped accepting requests.
pub fn is_closed(&self) -> bool {
self.command_tx.is_closed()
}
/// Wait until this connection stops accepting requests without consuming client events.
pub async fn closed(&self) {
self.command_tx.closed().await;
}
pub async fn resolve_server_request(
&self,
request_id: RequestId,
+53 -5
View File
@@ -32,6 +32,18 @@ async fn agents_defers_launch_directory_trust_until_starting_a_task() -> Result<
daemon_startup("agents-untrusted").await
}
#[tokio::test]
#[cfg(unix)]
async fn agents_cancels_folder_consent_when_daemon_restarts() -> Result<()> {
daemon_startup("agents-trust-restart").await
}
#[tokio::test]
#[cfg(unix)]
async fn startup_folder_consent_explains_connection_loss() -> Result<()> {
daemon_startup("startup-trust-restart").await
}
#[tokio::test]
#[cfg(unix)]
async fn discovered_managed_daemon_can_restart_with_auto_start_disabled() -> Result<()> {
@@ -177,6 +189,14 @@ async fn daemon_startup(command: &str) -> Result<()> {
"failed to prepare CLI test executable"
);
let bedrock_onboarding = matches!(command, "bedrock" | "bedrock-running");
let trust_restart = matches!(command, "agents-trust-restart" | "startup-trust-restart");
if trust_restart {
fs::create_dir(workspace_path.join(".codex"))?;
fs::write(
workspace_path.join(".codex/config.toml"),
"# project settings\n",
)?;
}
fs::write(
home.path().join("config.toml"),
format!(
@@ -187,7 +207,7 @@ async fn daemon_startup(command: &str) -> Result<()> {
tui.disable_paste_burst = true\n\
{}\n\
notice.model_migrations.\"gpt-5.6-terra\" = \"gpt-6-sol\"\n\
[projects.{}]\ntrust_level = \"{}\"\n",
[projects.{}]\n{}\n",
if command == "discovered" {
"tui.status_line=[\"model\",\"thread-id\",\"thread-name\"]\nfeatures.daemon_auto_start=false"
} else if bedrock_onboarding {
@@ -196,10 +216,12 @@ async fn daemon_startup(command: &str) -> Result<()> {
""
},
serde_json::to_string(&workspace_path)?,
if command == "agents-untrusted" {
"untrusted"
if trust_restart {
""
} else if command == "agents-untrusted" {
"trust_level = \"untrusted\""
} else {
"trusted"
"trust_level = \"trusted\""
},
),
)?;
@@ -245,6 +267,7 @@ async fn daemon_startup(command: &str) -> Result<()> {
| "bedrock-running"
| "restrictive-job"
) || mismatch
|| trust_restart
{
// A selected package with a stopped daemon avoids installing a release.
let managed = home
@@ -314,6 +337,15 @@ async fn daemon_startup(command: &str) -> Result<()> {
steps.push_back(("GPT-5.6-Terra", b"/daemon\r"));
steps.push_back(("Restartbackgroundserver", b"\x1b[F\r"));
"Restartbackgroundserver?"
} else if trust_restart {
steps.push_back(("Trustandcontinue", b""));
if command == "agents-trust-restart" {
args.push("agents".into());
steps.push_front(("Notasksyet", b"n"));
"Notasksyet"
} else {
"RestartCodextocontinue."
}
} else if command == "agents-untrusted" {
args.push("agents".into());
steps.push_back(("Notasksyet", b"n"));
@@ -527,10 +559,26 @@ async fn daemon_startup(command: &str) -> Result<()> {
ensure!(settings["featureOverrides"]["auth_elicitation"].is_null());
}
}
writer.send(input.to_vec()).await?;
if trust_restart && *ready == "Trustandcontinue" {
let restarted = tokio::process::Command::new(&codex)
.env_clear()
.envs(&env)
.current_dir(&workspace_path)
.args(["app-server", "daemon", "restart"])
.kill_on_drop(true)
.output()
.await?;
ensure!(restarted.status.success(), "{}", String::from_utf8_lossy(&restarted.stderr));
} else {
writer.send(input.to_vec()).await?;
}
steps.pop_front();
output.clear();
} else if steps.is_empty() && text.contains(expected) {
if trust_restart {
let config = fs::read_to_string(home.path().join("config.toml"))?;
ensure!(!config.contains("trust_level"), "restart must not grant trust");
}
if command == "agents-untrusted" {
let transition = format!(
"{initial_agents_screen}\n\n--- Start a task ---\n\n{}",
+8
View File
@@ -2069,6 +2069,14 @@ async fn run_ratatui_app(
trust_decision_was_made = true;
}
} else if consent.should_exit {
// Startup cannot return to the overview's reconnect loop until bootstrap completes.
if let codex_app_server_client::AppServerRequestHandle::Remote(handle) =
app_server.request_handle()
&& handle.is_closed()
{
shutdown_startup_session(Some(app_server), &mut terminal_restore_guard).await;
color_eyre::eyre::bail!(onboarding::SETUP_CONNECTION_LOST);
}
if !uses_remote_workspace {
config = load_config_or_exit_with_fallback_cwd(
cli_kv_overrides.clone(),
@@ -58,6 +58,7 @@ use crate::tui::Tui;
use crate::tui::TuiEvent;
use color_eyre::eyre::Result;
use color_eyre::eyre::WrapErr;
use std::ops::ControlFlow;
use std::sync::Arc;
use std::sync::RwLock;
use uuid::Uuid;
@@ -697,6 +698,19 @@ pub(super) async fn run_onboarding_screen(
result.and_then(|result| restore.map(|()| result).map_err(Into::into))
}
// A queued confirmation must not accept a disconnected folder, even when opening
// restricted would complete without an RPC. Leave the disconnect event for the app.
async fn folder_input(
closed: impl Future<Output = ()>,
input: impl Future<Output = Option<TuiEvent>>,
) -> ControlFlow<(), Option<TuiEvent>> {
tokio::select! {
biased;
() = closed => ControlFlow::Break(()),
event = input => ControlFlow::Continue(event),
}
}
async fn run_onboarding_screen_inner(
mut onboarding_screen: OnboardingScreen,
app_server_request_handle: Option<AppServerRequestHandle>,
@@ -718,6 +732,14 @@ async fn run_onboarding_screen_inner(
tokio::pin!(tui_events);
let mut trust_step_was_active = onboarding_screen.is_trust_step_active();
let folder_connection = match (
&app_server_request_handle,
onboarding_screen.steps.as_slice(),
) {
(Some(AppServerRequestHandle::Remote(handle)), [Step::TrustDirectory(_)]) => Some(handle),
_ => None,
};
while !onboarding_screen.is_done() {
tokio::select! {
() = async {
@@ -726,7 +748,20 @@ async fn run_onboarding_screen_inner(
None => std::future::pending().await,
}
} => {}
event = tui_events.next() => {
event = async {
let input = tui_events.next();
match folder_connection {
Some(handle) => folder_input(handle.closed(), input).await,
None => ControlFlow::Continue(input.await),
}
} => {
let ControlFlow::Continue(event) = event else {
tui.discard_pending_input_before_interactive_screen()?;
return Ok(OnboardingResult {
should_exit: true,
..Default::default()
});
};
if let Some(event) = event {
tui.screen_size_for_event(&event)?;
match event {
@@ -1013,6 +1048,14 @@ mod tests {
use pretty_assertions::assert_eq;
use std::path::PathBuf;
#[tokio::test]
async fn folder_disconnect_wins_over_queued_enter() {
let enter = super::TuiEvent::Key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
let event =
super::folder_input(std::future::ready(()), std::future::ready(Some(enter))).await;
assert!(event.is_break());
}
#[test]
fn suppresses_printable_quit_key_during_api_key_entry() {
let suppressed = suppress_quit_while_typing(