mirror of
https://github.com/openai/codex.git
synced 2026-12-05 01:00:54 +00:00
Retry TUI startup after a server shutdown refusal (#55409)
## Why A remote server can refuse the initial `thread/start` while shutting down. An explicit refusal establishes that no thread was created, allowing the TUI to retry without risking duplicate startup submissions. ## What changed - Wait for the draining connection to close, reconnect within a shared two-minute deadline, and retry startup once. - Preserve the initial prompt, confirmed draft, model, and reasoning effort across recovery. Keep drafts editable and allow cancellation of a pending submission. - Restore input without submitting if recovery fails or startup is refused again. Continue treating a lost startup reply as uncertain and avoid automatic resubmission. ## Testing Add regression coverage for successful reconnection with exactly one prompt submission, repeated refusal, disconnect event ordering, and draft cancellation, editing, and paste provenance during recovery. GitOrigin-RevId: 85b756e14f29c239c4774af2b32215fe251530ac
This commit is contained in:
@@ -1133,7 +1133,7 @@ impl App {
|
||||
let restrict_disconnected_input = self.reconnect.offline
|
||||
&& !self.chat_widget.keymap_contexts().is_warnings()
|
||||
&& self.reconnect.presentation
|
||||
== reconnect::ReconnectPresentation::Conversation
|
||||
!= reconnect::ReconnectPresentation::Overview
|
||||
&& !self
|
||||
.chat_widget
|
||||
.active_view_accepts_input_when_disconnected();
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! Worktrees start at the repository default branch and bind only the new session.
|
||||
|
||||
use super::*;
|
||||
use crate::app_server_session::is_server_shutting_down_error;
|
||||
use crate::startup_draft::StartupDraftInitialScreen;
|
||||
use crate::startup_draft::StartupDraftPump;
|
||||
use crate::startup_draft::StartupDraftSessionAction;
|
||||
@@ -167,17 +168,10 @@ impl App {
|
||||
let started = match result {
|
||||
Ok(started) => started,
|
||||
Err(error) => {
|
||||
// Older servers omit the reason. Only use their specific message when
|
||||
// data is absent, so other invalid requests aren't misclassified.
|
||||
let (title, message) = if matches!(
|
||||
error.downcast_ref::<TypedRequestError>(),
|
||||
Some(TypedRequestError::Server { source, .. })
|
||||
if source.code == -32600
|
||||
&& match &source.data {
|
||||
Some(data) => data.get("reason").and_then(serde_json::Value::as_str)
|
||||
== Some("serverShuttingDown"),
|
||||
None => source.message == "Server is draining; retry after reconnecting",
|
||||
}
|
||||
if is_server_shutting_down_error(source)
|
||||
) {
|
||||
let mut message = String::from(
|
||||
"New sessions are paused while active turns finish or are canceled. The default shutdown wait is up to one minute.",
|
||||
|
||||
@@ -147,6 +147,12 @@ impl App {
|
||||
self.repaint_agents_overview();
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ pub(super) enum ReconnectPresentation {
|
||||
#[default]
|
||||
Conversation,
|
||||
Overview,
|
||||
Startup(tokio::time::Instant),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -55,7 +56,12 @@ pub(super) async fn reconnect(
|
||||
}
|
||||
// Connecting already has transport deadlines. Give healthy history/inventory hydration one
|
||||
// shared budget instead of repeatedly discarding its progress on a short per-attempt timer.
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 120);
|
||||
let deadline = match presentation {
|
||||
ReconnectPresentation::Startup(deadline) => deadline,
|
||||
ReconnectPresentation::Conversation | ReconnectPresentation::Overview => {
|
||||
tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 120)
|
||||
}
|
||||
};
|
||||
for delay in [0, 1, 2, 4].into_iter().chain(std::iter::repeat(/*elt*/ 8)) {
|
||||
let attempt = async {
|
||||
tokio::time::sleep(Duration::from_secs(delay)).await;
|
||||
@@ -185,6 +191,24 @@ impl App {
|
||||
}
|
||||
|
||||
pub(super) fn begin_reconnect(&mut self) -> bool {
|
||||
self.pending_startup_thread_start = false;
|
||||
self.begin_reconnect_inner(/*preserve_startup_input*/ false)
|
||||
}
|
||||
|
||||
pub(super) fn begin_reconnect_for_rejected_startup(&mut self) -> bool {
|
||||
if matches!(
|
||||
self.reconnect.presentation,
|
||||
ReconnectPresentation::Startup(_)
|
||||
) {
|
||||
self.begin_reconnect();
|
||||
self.reconnect.failed = true;
|
||||
self.chat_widget.reconnect_failed();
|
||||
return true;
|
||||
}
|
||||
self.begin_reconnect_inner(/*preserve_startup_input*/ true)
|
||||
}
|
||||
|
||||
fn begin_reconnect_inner(&mut self, preserve_startup_input: bool) -> bool {
|
||||
if matches!(self.app_server_target, AppServerTarget::Embedded) {
|
||||
return false;
|
||||
}
|
||||
@@ -256,7 +280,16 @@ impl App {
|
||||
}
|
||||
ReconnectPresentation::Conversation
|
||||
};
|
||||
self.chat_widget.pause_for_disconnect();
|
||||
if preserve_startup_input {
|
||||
// Draining admission never reopens. Wait for this connection to close before
|
||||
// reconnecting, then give the ordinary startup path one more attempt.
|
||||
self.reconnect.presentation = ReconnectPresentation::Startup(
|
||||
tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 120),
|
||||
);
|
||||
self.chat_widget.pause_for_rejected_startup();
|
||||
} else {
|
||||
self.chat_widget.pause_for_disconnect();
|
||||
}
|
||||
self.startup_pending_protected_request = false;
|
||||
self.abort_all_thread_event_listeners();
|
||||
for (_, (_, task)) in self.dynamic_tool_tasks.drain() {
|
||||
@@ -397,7 +430,10 @@ impl App {
|
||||
for input in self.agents_overview.input_states.values_mut() {
|
||||
input.reconnect_pending = true;
|
||||
}
|
||||
self.pending_startup_thread_start = false;
|
||||
self.pending_startup_thread_start = matches!(
|
||||
self.reconnect.presentation,
|
||||
ReconnectPresentation::Startup(_)
|
||||
);
|
||||
// Move cached UI state into fresh channels. Old producers retain the old sender/store,
|
||||
// so their late requests cannot leak into recovery. Background threads attach on selection.
|
||||
for channel in self.thread_event_channels.values_mut() {
|
||||
@@ -577,6 +613,10 @@ impl App {
|
||||
self.chat_widget.add_server_version_warning(notice);
|
||||
}
|
||||
}
|
||||
if self.pending_startup_thread_start {
|
||||
self.chat_widget
|
||||
.set_queue_submissions_until_session_configured(/*queue*/ true);
|
||||
}
|
||||
if discard_replaced_view_input
|
||||
&& let Err(err) = tui.discard_pending_input_before_interactive_screen()
|
||||
{
|
||||
|
||||
@@ -9,6 +9,7 @@ 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::*;
|
||||
use crate::app_server_session::is_server_shutting_down_error;
|
||||
use crate::app_server_session::source_agent_path;
|
||||
use crate::app_server_session::thread_blocks_direct_input;
|
||||
use crate::chatwidget::ThreadInputStateRestoreMode;
|
||||
@@ -879,6 +880,18 @@ impl App {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// A refusal proves no thread was created.
|
||||
if let Err(error) = &result
|
||||
&& matches!(
|
||||
error.downcast_ref::<TypedRequestError>(),
|
||||
Some(TypedRequestError::Server { method, source })
|
||||
if method == "thread/start" && is_server_shutting_down_error(source)
|
||||
)
|
||||
&& self.begin_reconnect_for_rejected_startup()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.pending_startup_thread_start = false;
|
||||
self.chat_widget
|
||||
.set_queue_submissions_until_session_configured(/*queue*/ false);
|
||||
|
||||
@@ -535,7 +535,7 @@ impl App {
|
||||
&app_server,
|
||||
local_settings.clone(),
|
||||
config.clone(),
|
||||
launch_choices,
|
||||
launch_choices.clone(),
|
||||
app_event_tx.clone(),
|
||||
managed_worktree.clone(),
|
||||
);
|
||||
@@ -1206,6 +1206,12 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
"the initial backend is not registered"
|
||||
));
|
||||
};
|
||||
if !backends.is_listening(initial_owner)
|
||||
&& !app.pending_startup_thread_start
|
||||
&& !app.reconnect.offline
|
||||
{
|
||||
app.begin_reconnect();
|
||||
}
|
||||
// Reconnect can dismiss an overlay from the server-event path.
|
||||
if app.overlay.is_none() {
|
||||
if !tui.is_owned_screen() && tui.is_alt_screen_active() {
|
||||
@@ -1275,7 +1281,10 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
continue;
|
||||
}
|
||||
if app.reconnect.offline && !app.reconnect.failed && reconnect.is_none() {
|
||||
reconnect = Some(Box::pin(reconnect::reconnect(
|
||||
let presentation = app.reconnect.presentation;
|
||||
let wait_for_drain =
|
||||
app.pending_startup_thread_start && backends.is_listening(initial_owner);
|
||||
let attempt = reconnect::reconnect(
|
||||
initial_owner,
|
||||
app.app_server_target.clone(),
|
||||
app.config.clone(),
|
||||
@@ -1288,13 +1297,22 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
backends
|
||||
.session_at(displayed_session)
|
||||
.thread_tool_transport(),
|
||||
app.reconnect.presentation,
|
||||
)));
|
||||
presentation,
|
||||
);
|
||||
reconnect = Some(Box::pin(async move {
|
||||
if let reconnect::ReconnectPresentation::Startup(deadline) = presentation
|
||||
&& wait_for_drain
|
||||
{
|
||||
tokio::time::sleep_until(deadline).await;
|
||||
color_eyre::eyre::bail!("Server connection could not be restored");
|
||||
}
|
||||
attempt.await
|
||||
}));
|
||||
}
|
||||
// Replay queues history and operations. A buffered closure must not switch
|
||||
// widgets before those app events have been applied.
|
||||
let has_pending_app_events = !app_event_rx.is_empty();
|
||||
let paused_backend = (app.reconnect.offline
|
||||
let paused_backend = ((app.reconnect.offline && !app.pending_startup_thread_start)
|
||||
|| (!matches!(app.app_server_target, AppServerTarget::Embedded)
|
||||
&& has_pending_app_events))
|
||||
.then_some(initial_owner);
|
||||
@@ -1419,14 +1437,19 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
}
|
||||
(owner, app_server_event) = backends.next_event(paused_backend) => {
|
||||
match app_server_event {
|
||||
Some(event) => {
|
||||
Some(event) if owner != initial_owner || !app.reconnect.offline => {
|
||||
if let Some(session) = backends.session(owner) {
|
||||
app.handle_polled_backend_event(session, initial_owner, event).await;
|
||||
}
|
||||
}
|
||||
Some(_) => {}
|
||||
None => {
|
||||
if owner == initial_owner {
|
||||
app.begin_reconnect();
|
||||
if app.reconnect.offline && app.pending_startup_thread_start {
|
||||
reconnect = None;
|
||||
} else if !app.pending_startup_thread_start {
|
||||
app.begin_reconnect();
|
||||
}
|
||||
}
|
||||
tracing::warn!("app-server event stream closed");
|
||||
}
|
||||
@@ -1441,9 +1464,32 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
break Err(err);
|
||||
}
|
||||
backends.resume_events(initial_owner);
|
||||
waiting_for_initial_session_configured = false;
|
||||
waiting_for_initial_session_configured = app.pending_startup_thread_start;
|
||||
if app.pending_startup_thread_start {
|
||||
spawn_startup_thread_start(
|
||||
backends.session_at(displayed_session),
|
||||
app.local_settings.clone(),
|
||||
app.config.clone(),
|
||||
launch_choices.clone(),
|
||||
app.app_event_tx.clone(),
|
||||
managed_worktree.clone(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
if app.pending_startup_thread_start {
|
||||
app.pending_startup_thread_start = false;
|
||||
app.chat_widget.cancel_startup_submission();
|
||||
app.chat_widget
|
||||
.set_initial_user_message_submit_suppressed(
|
||||
/*suppressed*/ true,
|
||||
);
|
||||
if let Some(message) =
|
||||
app.chat_widget.initial_user_message.take()
|
||||
{
|
||||
app.chat_widget.restore_user_message_to_composer(message);
|
||||
}
|
||||
}
|
||||
app.reconnect.failed = true;
|
||||
app.chat_widget.reconnect_failed();
|
||||
app.chat_widget.add_error_message(error.to_string());
|
||||
@@ -1530,7 +1576,7 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
}
|
||||
match control {
|
||||
AppRunControl::Continue => {
|
||||
if app.reconnect.offline {
|
||||
if app.reconnect.offline && !app.pending_startup_thread_start {
|
||||
pending_startup_submission = false;
|
||||
app.chat_widget.cancel_startup_submission();
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
//! Offline editing, uncertain submissions, and stale events never consume local work.
|
||||
|
||||
use super::*;
|
||||
use crate::app::reconnect::ReconnectPresentation;
|
||||
use crate::app::reconnect::reconnect;
|
||||
use crate::app_server_session::ThreadParamsMode;
|
||||
use crate::bottom_pane::TerminalTitleItem;
|
||||
use crate::chatwidget::tests::helpers::normalize_agent_center_snapshot;
|
||||
use codex_app_server_client::AppServerEvent;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::JSONRPCMessage;
|
||||
use codex_app_server_protocol::JSONRPCRequest;
|
||||
use futures::SinkExt;
|
||||
@@ -414,6 +418,10 @@ async fn lost_initial_thread_reply_keeps_startup_draft_offline() -> Result<()> {
|
||||
for disconnect_first in [false, true] {
|
||||
let (mut app, _events, mut ops) = make_test_app_with_channels().await;
|
||||
app.pending_startup_thread_start = true;
|
||||
if disconnect_first {
|
||||
app.reconnect.presentation =
|
||||
ReconnectPresentation::Startup(tokio::time::Instant::now());
|
||||
}
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let endpoint = crate::resolve_remote_addr(&format!("ws://{}", listener.local_addr()?))?;
|
||||
app.app_server_target = AppServerTarget::Remote {
|
||||
@@ -446,7 +454,13 @@ async fn lost_initial_thread_reply_keeps_startup_draft_offline() -> Result<()> {
|
||||
.await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
if disconnect_first {
|
||||
app.begin_reconnect();
|
||||
app.handle_app_server_event(
|
||||
&session,
|
||||
AppServerEvent::Disconnected {
|
||||
message: "connection closed".into(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
@@ -455,6 +469,7 @@ async fn lost_initial_thread_reply_keeps_startup_draft_offline() -> Result<()> {
|
||||
)
|
||||
.await?;
|
||||
assert!(app.reconnect.offline);
|
||||
assert!(!app.pending_startup_thread_start);
|
||||
app.handle_tui_event(
|
||||
&mut tui,
|
||||
&mut session,
|
||||
@@ -473,3 +488,184 @@ async fn lost_initial_thread_reply_keeps_startup_draft_offline() -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejected_initial_thread_start_reconnects_and_submits_prompt_once() -> Result<()> {
|
||||
for reject_again in [false, true] {
|
||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
||||
app.pending_startup_thread_start = true;
|
||||
app.config.model = Some("gpt-retry".into());
|
||||
app.chat_widget.initial_user_message = Some("startup prompt".into());
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let endpoint = crate::resolve_remote_addr(&format!("ws://{}", listener.local_addr()?))?;
|
||||
app.app_server_target = AppServerTarget::Remote {
|
||||
endpoint: endpoint.clone(),
|
||||
};
|
||||
let thread_id = ThreadId::new();
|
||||
let cwd = app.config.cwd.clone();
|
||||
let server = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
serve_reconnect_requests(tokio_tungstenite::accept_async(stream).await?, |request| {
|
||||
let cwd = cwd.clone();
|
||||
async move {
|
||||
assert_eq!(request.method, "thread/start");
|
||||
let params = request.params.as_ref().expect("thread/start params");
|
||||
assert_eq!(params["model"], "gpt-retry");
|
||||
assert_eq!(params["config"]["model_reasoning_effort"], "high");
|
||||
if reject_again {
|
||||
return Some(json!({"error": {
|
||||
"code": -32600,
|
||||
"message": "Server is draining; retry after reconnecting",
|
||||
"data": {"reason": "serverShuttingDown"}
|
||||
}}));
|
||||
}
|
||||
Some(json!({"result": {
|
||||
"thread": {
|
||||
"id": thread_id,
|
||||
"sessionId": thread_id,
|
||||
"preview": "startup prompt",
|
||||
"ephemeral": false,
|
||||
"modelProvider": "test-provider",
|
||||
"createdAt": 1,
|
||||
"updatedAt": 1,
|
||||
"status": {"type": "idle"},
|
||||
"cwd": cwd,
|
||||
"cliVersion": "0.0.0",
|
||||
"source": "cli",
|
||||
"turns": []
|
||||
},
|
||||
"model": "gpt-retry",
|
||||
"modelProvider": "test-provider",
|
||||
"serviceTier": null,
|
||||
"cwd": cwd,
|
||||
"approvalPolicy": "never",
|
||||
"approvalsReviewer": "user",
|
||||
"sandbox": {"type": "dangerFullAccess"},
|
||||
"reasoningEffort": "high"
|
||||
}}))
|
||||
}
|
||||
})
|
||||
.await
|
||||
});
|
||||
let mut app_server = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
||||
// A close notification can arrive before the already received refusal is dispatched.
|
||||
app.handle_app_server_event(
|
||||
&app_server,
|
||||
AppServerEvent::Disconnected {
|
||||
message: "connection closed".into(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
app.handle_startup_thread_started(
|
||||
&mut app_server,
|
||||
Err(color_eyre::Report::new(TypedRequestError::Server {
|
||||
method: "thread/start".into(),
|
||||
source: JSONRPCErrorError {
|
||||
code: -32600,
|
||||
message: "not accepting new actions".into(),
|
||||
data: Some(json!({"reason": "serverShuttingDown"})),
|
||||
},
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
assert!(app.reconnect.offline);
|
||||
assert!(app.pending_startup_thread_start);
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
app.handle_tui_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
TuiEvent::Paste("startup draft".into()),
|
||||
)
|
||||
.await?;
|
||||
let reconnect_status =
|
||||
regex_lite::Regex::new(r"^[•◦] (Reconnecting to server… )\([\dhms ]+\)")?;
|
||||
assert_snapshot!(
|
||||
"rejected_startup_reconnecting",
|
||||
reconnect_status.replace(
|
||||
&render_bottom_popup(&app.chat_widget, /*width*/ 80),
|
||||
"• ${1}(<elapsed>)",
|
||||
)
|
||||
);
|
||||
|
||||
let mut launch_choices = crate::app_server_session::StartupLaunchChoices::default();
|
||||
launch_choices.model = Some("gpt-retry".into());
|
||||
launch_choices.effort = Some(json!("high"));
|
||||
let connected = reconnect(
|
||||
app_server.backend_id(),
|
||||
AppServerTarget::Remote { endpoint },
|
||||
app.config.clone(),
|
||||
app.local_settings.clone(),
|
||||
/*thread_id*/ None,
|
||||
/*remote_cwd*/ None,
|
||||
crate::dynamic_tools_mcp::ThreadToolTransport::Dynamic,
|
||||
app.reconnect.presentation,
|
||||
)
|
||||
.await?;
|
||||
app.finish_reconnect(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
&mut events,
|
||||
connected,
|
||||
CODEX_CLI_VERSION,
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert!(!app.reconnect.offline);
|
||||
assert!(app.pending_startup_thread_start);
|
||||
let result = crate::app_server_session::start_thread_with_request_handle(
|
||||
app_server.request_handle(),
|
||||
&app.local_settings,
|
||||
app.config.clone(),
|
||||
ThreadParamsMode::Remote,
|
||||
/*remote_cwd_override*/ None,
|
||||
app_server.thread_tool_transport(),
|
||||
launch_choices,
|
||||
)
|
||||
.await;
|
||||
app.handle_startup_thread_started(&mut app_server, result)
|
||||
.await?;
|
||||
assert!(!app.pending_startup_thread_start);
|
||||
if reject_again {
|
||||
assert!(app.reconnect.offline);
|
||||
assert!(app.reconnect.failed);
|
||||
assert!(
|
||||
app.chat_widget
|
||||
.composer_text_with_pending()
|
||||
.contains("startup prompt")
|
||||
);
|
||||
} else {
|
||||
assert_eq!(app.primary_thread_id, Some(thread_id));
|
||||
assert_snapshot!(
|
||||
"rejected_startup_reconnected",
|
||||
normalize_snapshot_paths(render_bottom_popup(&app.chat_widget, /*width*/ 80))
|
||||
);
|
||||
}
|
||||
let submitted = std::iter::from_fn(|| events.try_recv().ok())
|
||||
.filter_map(|event| match event {
|
||||
AppEvent::CodexOp(Op::UserTurn { items, .. }) => Some(items),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
submitted,
|
||||
if reject_again {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![vec![UserInput::Text {
|
||||
text: "startup prompt".into(),
|
||||
text_elements: Vec::new(),
|
||||
}]]
|
||||
}
|
||||
);
|
||||
app_server.shutdown().await?;
|
||||
let methods = server.await??;
|
||||
assert_eq!(
|
||||
methods
|
||||
.iter()
|
||||
.filter(|method| method.as_str() == "thread/start")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
---
|
||||
source: tui/src/app/tests/disconnect_tests.rs
|
||||
expression: "render_bottom_popup(&app.chat_widget, 80)"
|
||||
---
|
||||
› startup draft
|
||||
|
||||
gpt-retry high · /tmp/project
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
---
|
||||
source: tui/src/app/tests/disconnect_tests.rs
|
||||
expression: "reconnect_status.replace(&render_bottom_popup(&app.chat_widget, 80),\n\"• ${1}(<elapsed>)\",)"
|
||||
---
|
||||
• Reconnecting to server… (<elapsed>)
|
||||
|
||||
|
||||
› startup draft
|
||||
|
||||
⌃c quit
|
||||
@@ -387,6 +387,17 @@ pub(crate) fn is_active_writer_error(err: &color_eyre::eyre::Report) -> bool {
|
||||
.any(|cause| cause.to_string().contains("already has an active writer"))
|
||||
}
|
||||
|
||||
/// Recognizes a draining server's refusal, using the legacy message only when data is absent.
|
||||
pub(crate) fn is_server_shutting_down_error(error: &JSONRPCErrorError) -> bool {
|
||||
error.code == JSONRPC_INVALID_REQUEST
|
||||
&& match &error.data {
|
||||
Some(data) => {
|
||||
data.get("reason").and_then(serde_json::Value::as_str) == Some("serverShuttingDown")
|
||||
}
|
||||
None => error.message == "Server is draining; retry after reconnecting",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn source_agent_path(source: &SessionSource) -> Option<String> {
|
||||
match source {
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { agent_path, .. }) => {
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::legacy_core::config::ConfigOverrides;
|
||||
use codex_app_server_protocol::ThreadStartParams;
|
||||
use codex_config::LoaderOverrides;
|
||||
|
||||
#[derive(Default)]
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct StartupLaunchChoices {
|
||||
pub(crate) model: Option<String>,
|
||||
pub(crate) effort: Option<serde_json::Value>,
|
||||
|
||||
@@ -617,6 +617,8 @@ impl ChatWidget {
|
||||
.as_deref_mut()
|
||||
.map(crate::bottom_pane::AsyncQuestions::capture),
|
||||
pending_thread_settings: None,
|
||||
initial_user_message: self.initial_user_message.clone(),
|
||||
startup_submission: self.input_queue.startup_submission.clone(),
|
||||
composer: composer.has_content().then_some(composer),
|
||||
safety_buffering_prompt: self.safety_buffering_prompt.clone(),
|
||||
safety_buffering_source: self.safety_buffering_source,
|
||||
@@ -655,6 +657,14 @@ impl ChatWidget {
|
||||
preserve_in_flight_turn && input_state.as_ref().is_some_and(|state| state.task_running);
|
||||
if let Some(input_state) = input_state {
|
||||
self.bottom_pane.restore_questions(input_state.questions);
|
||||
self.initial_user_message = input_state.initial_user_message;
|
||||
self.input_queue.startup_submission = input_state.startup_submission;
|
||||
if self.input_queue.startup_submission.is_some() {
|
||||
self.bottom_pane.set_footer_hint_override(Some(vec![
|
||||
("Waiting for startup".into(), String::new()),
|
||||
("esc".into(), "cancel".into()),
|
||||
]));
|
||||
}
|
||||
self.input_queue.recovered_queue = input_state.recovered_queue;
|
||||
self.current_collaboration_mode = input_state.current_collaboration_mode;
|
||||
self.active_collaboration_mask = input_state.active_collaboration_mask;
|
||||
|
||||
@@ -17,9 +17,19 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
pub(crate) fn pause_for_disconnect(&mut self) {
|
||||
self.pause_for_disconnect_inner(/*preserve_startup_input*/ false);
|
||||
}
|
||||
|
||||
pub(crate) fn pause_for_rejected_startup(&mut self) {
|
||||
self.pause_for_disconnect_inner(/*preserve_startup_input*/ true);
|
||||
}
|
||||
|
||||
fn pause_for_disconnect_inner(&mut self, preserve_startup_input: bool) {
|
||||
self.permission_discovery = None;
|
||||
self.invalidate_permission_discovery();
|
||||
self.cancel_startup_submission();
|
||||
if !preserve_startup_input {
|
||||
self.cancel_startup_submission();
|
||||
}
|
||||
self.cancel_image_submission();
|
||||
// The app-server transport can fail while the separate WebRTC helper
|
||||
// still sends microphone audio. Retire local media before showing offline UI.
|
||||
@@ -29,9 +39,11 @@ impl ChatWidget {
|
||||
questions.delivery_enabled = false;
|
||||
}
|
||||
self.input_queue.suppress_queue_autosend = true;
|
||||
self.set_initial_user_message_submit_suppressed(/*suppressed*/ true);
|
||||
if let Some(message) = self.initial_user_message.take() {
|
||||
self.restore_user_message_to_composer(message);
|
||||
if !preserve_startup_input {
|
||||
self.set_initial_user_message_submit_suppressed(/*suppressed*/ true);
|
||||
if let Some(message) = self.initial_user_message.take() {
|
||||
self.restore_user_message_to_composer(message);
|
||||
}
|
||||
}
|
||||
self.bottom_pane.ensure_status_indicator();
|
||||
self.bottom_pane
|
||||
@@ -196,6 +208,26 @@ impl ChatWidget {
|
||||
if self.external_writer_view {
|
||||
return;
|
||||
}
|
||||
let startup_key_handled = self.input_queue.startup_submission.is_some()
|
||||
&& !self.startup_submission_has_protected_input()
|
||||
&& (key.code == KeyCode::Null || self.handle_startup_submission_key(key));
|
||||
if mode == RestrictedInputMode::Disconnected {
|
||||
self.set_footer_hint_override(Some(vec![(
|
||||
crate::key_hint::ctrl(KeyCode::Char('c')).display_label(),
|
||||
"quit".into(),
|
||||
)]));
|
||||
}
|
||||
if startup_key_handled {
|
||||
return;
|
||||
}
|
||||
if self.input_queue.startup_submission.is_some()
|
||||
&& !self.startup_submission_has_protected_input()
|
||||
{
|
||||
// Cursor movement must preserve the confirmed draft's paste provenance.
|
||||
let result = self.bottom_pane.handle_key_event(key);
|
||||
self.handle_composer_input_result(result, /*had_modal_or_popup*/ false);
|
||||
return;
|
||||
}
|
||||
if self.handle_question_key(key) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Carry one startup submission intent across draft handoff without consuming editable text early.
|
||||
//!
|
||||
//! Confirmation applies to the visible draft only. Editing, cancellation, or disconnect removes
|
||||
//! the intent; normal submission parsing runs once the session and protected-input gates are ready.
|
||||
//! Confirmation applies to the visible draft only. Editing, cancellation, or an uncertain disconnect
|
||||
//! removes the intent; a refused initial start can preserve it while reconnecting. Normal submission
|
||||
//! parsing runs once the session and protected-input gates are ready.
|
||||
|
||||
use super::*;
|
||||
use crate::bottom_pane::ComposerDraftSnapshot;
|
||||
|
||||
@@ -1872,6 +1872,8 @@ async fn restore_thread_input_state_applies_running_state_policy() {
|
||||
let input_state = ThreadInputState {
|
||||
questions: None,
|
||||
pending_thread_settings: None,
|
||||
initial_user_message: None,
|
||||
startup_submission: None,
|
||||
composer: Some(ThreadComposerState {
|
||||
text: "composer draft".to_string(),
|
||||
..Default::default()
|
||||
|
||||
@@ -418,6 +418,8 @@ async fn restore_thread_input_state_restores_pending_steers_without_downgrading_
|
||||
Some(ThreadInputState {
|
||||
pending_thread_settings: None,
|
||||
questions: None,
|
||||
initial_user_message: None,
|
||||
startup_submission: None,
|
||||
composer: None,
|
||||
safety_buffering_prompt: None,
|
||||
safety_buffering_source: UserMessageSource::Prompt,
|
||||
|
||||
@@ -270,19 +270,35 @@ async fn startup_submission_waits_for_session_and_sends_exactly_once() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_submission_escape_restores_editing_without_submitting() {
|
||||
let (mut source, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
source.bottom_pane.insert_str("keep the draft");
|
||||
source.bottom_pane.set_composer_cursor(/*cursor*/ 4);
|
||||
let mut draft = Some(source.bottom_pane.composer_draft_snapshot());
|
||||
let mut confirmed = true;
|
||||
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
chat.restore_startup_input_when_ready(&mut draft, &mut confirmed);
|
||||
let before = chat.bottom_pane.composer_draft_snapshot();
|
||||
chat.handle_key_event(KeyEvent::from(KeyCode::Esc));
|
||||
chat.thread_id = Some(ThreadId::new());
|
||||
chat.restore_startup_input_when_ready(&mut draft, &mut confirmed);
|
||||
assert_eq!(chat.bottom_pane.composer_draft_snapshot(), before);
|
||||
assert_no_submit_op(&mut op_rx);
|
||||
for rejected_startup in [false, true] {
|
||||
let (mut source, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
source.bottom_pane.insert_str("keep the draft");
|
||||
source.bottom_pane.set_composer_cursor(/*cursor*/ 4);
|
||||
let mut draft = Some(source.bottom_pane.composer_draft_snapshot());
|
||||
let mut confirmed = true;
|
||||
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
chat.restore_startup_input_when_ready(&mut draft, &mut confirmed);
|
||||
let before = chat.bottom_pane.composer_draft_snapshot();
|
||||
if rejected_startup {
|
||||
chat.pause_for_rejected_startup();
|
||||
chat.handle_restricted_key(
|
||||
KeyEvent::from(KeyCode::Esc),
|
||||
crate::bottom_pane::RestrictedInputMode::Disconnected,
|
||||
);
|
||||
assert_snapshot!(
|
||||
render_bottom_popup(&chat, /*width*/ 80).lines().last().unwrap(),
|
||||
@" ⌃c quit"
|
||||
);
|
||||
chat.input_queue.suppress_queue_autosend = false;
|
||||
} else {
|
||||
chat.handle_key_event(KeyEvent::from(KeyCode::Esc));
|
||||
}
|
||||
assert!(chat.input_queue.startup_submission.is_none());
|
||||
chat.thread_id = Some(ThreadId::new());
|
||||
chat.restore_startup_input_when_ready(&mut draft, &mut confirmed);
|
||||
assert_eq!(chat.bottom_pane.composer_draft_snapshot(), before);
|
||||
assert_no_submit_op(&mut op_rx);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -302,6 +318,18 @@ async fn startup_submission_waits_for_protected_view_and_preserves_paste_provena
|
||||
assert!(draft.is_some());
|
||||
assert_no_submit_op(&mut op_rx);
|
||||
chat.handle_key_event(KeyEvent::from(KeyCode::Esc));
|
||||
chat.thread_id = None;
|
||||
chat.restore_startup_input_when_ready(&mut draft, &mut confirmed);
|
||||
chat.pause_for_rejected_startup();
|
||||
for key in [KeyCode::Null, KeyCode::Left, KeyCode::Right, KeyCode::Enter] {
|
||||
chat.handle_restricted_key(
|
||||
KeyEvent::from(key),
|
||||
crate::bottom_pane::RestrictedInputMode::Disconnected,
|
||||
);
|
||||
}
|
||||
assert_no_submit_op(&mut op_rx);
|
||||
chat.input_queue.suppress_queue_autosend = false;
|
||||
chat.thread_id = Some(ThreadId::new());
|
||||
chat.restore_startup_input_when_ready(&mut draft, &mut confirmed);
|
||||
if payload.starts_with(' ') {
|
||||
assert!(op_rx.try_recv().is_err());
|
||||
@@ -320,7 +348,7 @@ async fn startup_submission_waits_for_protected_view_and_preserves_paste_provena
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_submission_edit_or_disconnect_cancels_without_losing_draft() {
|
||||
for action in ["edit", "disconnect", "parent-owned"] {
|
||||
for action in ["edit", "disconnect", "parent-owned", "rejected-edit-undo"] {
|
||||
let (mut source, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
source.bottom_pane.insert_str("confirmed draft");
|
||||
let mut draft = Some(source.bottom_pane.composer_draft_snapshot());
|
||||
@@ -334,6 +362,15 @@ async fn startup_submission_edit_or_disconnect_cancels_without_losing_draft() {
|
||||
chat.pause_for_disconnect();
|
||||
} else if action == "edit" {
|
||||
chat.handle_paste(" edited".into());
|
||||
} else if action == "rejected-edit-undo" {
|
||||
chat.pause_for_rejected_startup();
|
||||
for key in [KeyCode::Char('x'), KeyCode::Backspace] {
|
||||
chat.handle_restricted_key(
|
||||
KeyEvent::from(key),
|
||||
crate::bottom_pane::RestrictedInputMode::Disconnected,
|
||||
);
|
||||
}
|
||||
chat.input_queue.suppress_queue_autosend = false;
|
||||
}
|
||||
chat.thread_id = Some(ThreadId::new());
|
||||
chat.restore_startup_input_when_ready(&mut draft, &mut confirmed);
|
||||
|
||||
@@ -145,6 +145,8 @@ pub(crate) struct ThreadInputState {
|
||||
pub(crate) questions: Option<crate::bottom_pane::QuestionState>,
|
||||
pub(crate) pending_thread_settings:
|
||||
Option<codex_app_server_protocol::ThreadSettingsUpdatedNotification>,
|
||||
pub(super) initial_user_message: Option<UserMessage>,
|
||||
pub(super) startup_submission: Option<crate::bottom_pane::ComposerDraftSnapshot>,
|
||||
pub(super) composer: Option<ThreadComposerState>,
|
||||
pub(super) safety_buffering_prompt: Option<UserMessage>,
|
||||
pub(super) safety_buffering_source: UserMessageSource,
|
||||
|
||||
Reference in New Issue
Block a user