Show reconnect guidance when disconnecting from tasks (#40629)

## Why

Exiting a TUI connected to a persistent app server can leave work running, so
the existing session-exit summary does not explain how to reconnect or stop the
active turn.

## What changed

- Distinguish disconnects, interrupted turns, and removed threads when building
  exit summaries.
- For daemon and remote sessions, report whether work may still be running and
  print commands to reconnect or stop the current turn.
- Sanitize remote WebSocket addresses in displayed commands and preserve the
  configured remote authentication environment-variable option.
- Keep the existing token-usage and resume summary for embedded sessions.

## Testing

Add coverage for daemon, remote, interrupted, embedded, archived, and deleted
session exits, including credential sanitization.

GitOrigin-RevId: 9cbbf9c7dd36423a5ed99909a2b4cb32e3e87712
This commit is contained in:
Eric Traut authored and copyberry committed 2026-08-25 15:55:35 +00:00
1 parent 0cdb1f1c83
commit a63cb33e8d
16 files changed
+408 -96

No files matched your search

@@ -1,6 +1,75 @@
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn daemon_disconnect_exit_summary_includes_reconnect_and_stop_instructions() -> Result<()> {
let (mut app, _, _) = make_test_app_with_channels().await;
let thread_id = prepare_running_local_daemon(&mut app)?;
app.keymap.agents.stop = vec![crate::key_hint::plain(KeyCode::F(10))];
let mut exit_info = app.exit_info(ExitReason::UserRequested);
exit_info.token_usage = TokenUsage {
input_tokens: 10,
output_tokens: 2,
total_tokens: 12,
..Default::default()
};
let output = exit_info
.format_exit_messages(/*color_enabled*/ false)
.join("\n")
.replace(&thread_id.to_string(), "THREAD_ID");
assert_snapshot!("daemon_disconnect_exit", output);
Ok(())
}
#[tokio::test]
async fn remote_disconnect_exit_summary_does_not_require_a_local_rollout_or_print_credentials() {
let (mut app, _, _) = make_test_app_with_channels().await;
app.app_server_target = AppServerTarget::Remote {
endpoint: crate::RemoteAppServerEndpoint::WebSocket {
websocket_url: "wss://user:secret@example.com:443/?token=private#secret".to_string(),
auth_token: Some("secret-token".to_string()),
},
};
let thread_id = ThreadId::from_string("123e4567-e89b-12d3-a456-426614174000").unwrap();
app.active_thread_id = Some(thread_id);
app.chat_widget.handle_thread_session(test_thread_session(
thread_id,
test_path_buf("/tmp/project"),
));
let exit_info = app.exit_info(ExitReason::Fatal("connection lost".to_string()));
let lines = exit_info.format_exit_messages(/*color_enabled*/ false);
let command = shlex::split(lines[1].strip_prefix("Reconnect: ").unwrap()).unwrap();
assert_eq!(
crate::resolve_remote_addr(&command[2]).unwrap(),
crate::RemoteAppServerEndpoint::WebSocket {
websocket_url: "wss://example.com/".to_string(),
auth_token: None,
}
);
assert_snapshot!("remote_disconnect_exit", lines.join("\n"));
}
#[tokio::test]
async fn embedded_exit_keeps_the_session_summary() {
let (mut app, _, _) = make_test_app_with_channels().await;
prepare_local_daemon_thread(&mut app).unwrap();
app.app_server_target = AppServerTarget::Embedded;
let mut exit_info = app.exit_info(ExitReason::UserRequested);
exit_info.token_usage = TokenUsage {
output_tokens: 2,
total_tokens: 2,
..Default::default()
};
exit_info.resume_hint = Some("codex resume THREAD_ID".to_string());
assert_eq!(
exit_info.format_exit_messages(/*color_enabled*/ false),
vec![
"Token usage: total=2 input=0 output=2",
"To continue this session, run codex resume THREAD_ID",
]
);
}
fn prepare_local_daemon_thread(app: &mut App) -> Result<ThreadId> {
app.app_server_target = AppServerTarget::LocalDaemon {
endpoint: crate::RemoteAppServerEndpoint::UnixSocket {
@@ -226,10 +295,21 @@ async fn exit_interrupts_before_requesting_shutdown() -> Result<()> {
assert_matches!(control, AppRunControl::Continue);
assert!(op_rx.try_recv().is_err());
assert_matches!(
app_event_rx.try_recv(),
Ok(AppEvent::Exit(ExitMode::ShutdownFirst))
);
let exit_event = app_event_rx.try_recv()?;
assert_matches!(exit_event, AppEvent::Exit(ExitMode::ShutdownAfterInterrupt));
let AppRunControl::Exit(reason) = app
.handle_event(&mut tui, &mut app_server, exit_event)
.await?
else {
panic!("stop-and-exit must exit");
};
assert_matches!(reason, ExitReason::TurnInterrupted);
let output = app
.exit_info(reason)
.format_exit_messages(/*color_enabled*/ false)
.join("\n")
.replace(&thread_id.to_string(), "THREAD_ID");
assert_snapshot!("interrupted_disconnect_exit", output);
Ok(())
}
@@ -348,6 +348,64 @@ async fn make_history_test_app() -> Result<(App, tempfile::TempDir)> {
Ok((app, codex_home))
}
#[tokio::test]
async fn removing_remote_thread_omits_disconnect_guidance() -> Result<()> {
for event in [
AppEvent::ArchiveCurrentThread,
AppEvent::DeleteCurrentThread,
] {
let (mut app, codex_home) = make_history_test_app().await?;
let thread_id = ThreadId::from_string(
&create_fake_rollout(
codex_home.path(),
"2026-01-01T00-00-00",
"2026-01-01T00:00:00Z",
"Saved user message",
Some(app.config.model_provider_id.as_str()),
/*git_info*/ None,
)
.expect("create rollout"),
)?;
let (mut server, _, proxy) = start_recording_app_server(
&app.config,
/*blocked_thread_list*/ None,
/*failed_thread_name*/ None,
)
.await?;
let resumed = server
.resume_thread(
app.config.clone(),
thread_id,
crate::app_server_session::ResumeModelSettings::RestoreFromThread,
)
.await?;
app.app_server_target = AppServerTarget::Remote {
endpoint: crate::resolve_remote_addr("ws://127.0.0.1:4500")?,
};
app.active_thread_id = Some(thread_id);
app.chat_widget.handle_thread_session(resumed.session);
let mut tui = crate::tui::test_support::make_test_tui()?;
let AppRunControl::Exit(reason) = app.handle_event(&mut tui, &mut server, event).await?
else {
panic!("removing the current thread must exit");
};
assert_matches!(reason, ExitReason::ThreadRemoved);
let mut exit_info = app.exit_info(reason);
exit_info.token_usage = TokenUsage {
output_tokens: 2,
total_tokens: 2,
..Default::default()
};
assert_eq!(
exit_info.format_exit_messages(/*color_enabled*/ false),
vec!["Token usage: total=2 input=0 output=2",]
);
server.shutdown().await?;
proxy.await??;
}
Ok(())
}
fn spawn_approved_task_tool_call(
app: &App,
app_server: &AppServerSession,
@@ -0,0 +1,8 @@
---
source: tui/src/app/tests/background_exit_tests.rs
expression: output
---
Disconnected from this task. Any running work continues.
Reconnect: codex resume THREAD_ID
Stop the current turn: run codex agents, select this task, and press f10.
Token usage so far: total=12 input=10 output=2
@@ -0,0 +1,6 @@
---
source: tui/src/app/tests/background_exit_tests.rs
expression: output
---
Disconnected from this task. The current turn was stopped.
Reconnect: codex resume THREAD_ID
@@ -0,0 +1,7 @@
---
source: tui/src/app/tests/background_exit_tests.rs
expression: "lines.join(\"\\n\")"
---
Disconnected from this task. Work may still be running.
Reconnect: codex --remote wss://example.com:443/ resume 123e4567-e89b-12d3-a456-426614174000
Stop the current turn: run codex --remote wss://example.com:443/ agents, select this task, and press ctrl + x.